Handle wiki style links

This commit is contained in:
2024-09-30 19:01:27 +02:00
parent 43d647c9ea
commit b64c13442b
8 changed files with 211 additions and 10 deletions

View File

@@ -28,6 +28,27 @@ func ListFiles(fs *filesystem.FileSystem) http.HandlerFunc {
}
}
func LookupFileByName(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
filenameOrPath := r.URL.Query().Get("filename")
if filenameOrPath == "" {
http.Error(w, "Filename or path is required", http.StatusBadRequest)
return
}
filePaths, err := fs.FindFileByName(filenameOrPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string][]string{"paths": filePaths}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
}
func GetFileContent(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
filePath := strings.TrimPrefix(r.URL.Path, "/api/v1/files/")

View File

@@ -18,6 +18,7 @@ func SetupRoutes(r chi.Router, db *db.DB, fs *filesystem.FileSystem) {
r.Get("/*", GetFileContent(fs))
r.Post("/*", SaveFile(fs))
r.Delete("/*", DeleteFile(fs))
r.Get("/lookup", LookupFileByName(fs))
})
r.Route("/git", func(r chi.Router) {
r.Post("/commit", StageCommitAndPush(fs))

View File

@@ -103,6 +103,47 @@ func (fs *FileSystem) walkDirectory(dir string) ([]FileNode, error) {
return nodes, nil
}
func (fs *FileSystem) FindFileByName(filenameOrPath string) ([]string, error) {
var foundPaths []string
var searchPattern string
// If no extension is provided, assume .md
if !strings.Contains(filenameOrPath, ".") {
searchPattern = filenameOrPath + ".md"
} else {
searchPattern = filenameOrPath
}
err := filepath.Walk(fs.RootDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
relPath, err := filepath.Rel(fs.RootDir, path)
if err != nil {
return err
}
// Check if the file matches the search pattern
if strings.HasSuffix(relPath, searchPattern) ||
strings.EqualFold(info.Name(), searchPattern) {
foundPaths = append(foundPaths, relPath)
}
}
return nil
})
if err != nil {
return nil, err
}
if len(foundPaths) == 0 {
return nil, errors.New("file not found")
}
return foundPaths, nil
}
func (fs *FileSystem) GetFileContent(filePath string) ([]byte, error) {
fullPath, err := fs.validatePath(filePath)
if err != nil {