Files
donniemarko/internal/scanner/handler.go
2026-02-03 09:15:29 +01:00

69 lines
1.5 KiB
Go

package scanner
import (
"path/filepath"
"donniemarko/internal/note"
"donniemarko/internal/storage"
"log"
"os"
)
type NotesHandler struct {
storage storage.Storage
}
func NewNotesHandler(storage storage.Storage) *NotesHandler {
return &NotesHandler{storage: storage}
}
func (h *NotesHandler) HandleCreate(path string) error {
note, err := ParseNoteFile(path)
if err != nil {
return err
}
h.storage.Create(note)
log.Printf("Created or updated note '%s'\n", path)
return nil
}
func (h *NotesHandler) HandleModify(path string) error {
return h.HandleCreate(path)
}
func (h *NotesHandler) HandleDelete(path string) error {
id := note.GenerateNoteID(path)
h.storage.Delete(id)
log.Printf("Deleted note '%s' from index\n", path)
return nil
}
// ParseNoteFile reads a note file on the file system and returns a note struct
// populated with the metadata and content extracted from the file
func ParseNoteFile(path string) (*note.Note, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
// Get file info to get modification time
fileInfo, err := os.Stat(path)
if err != nil {
return nil, err
}
id := note.GenerateNoteID(path)
nn := note.NewNote()
nn.ID = id
nn.Path = path
nn.Content = string(content)
nn.Title = note.ExtractTitle(nn.Content)
// Use filename as title if no heading found
if nn.Title == "" {
nn.Title = filepath.Base(path)
}
nn.UpdatedAt = fileInfo.ModTime()
nn.Size = fileInfo.Size()
return nn, nil
}