zk/core/note/index.go
2021-01-03 17:09:10 +01:00

105 lines
2.3 KiB
Go

package note
import (
"crypto/sha256"
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/mickael-menu/zk/core/file"
"github.com/mickael-menu/zk/core/zk"
"github.com/mickael-menu/zk/util"
"github.com/mickael-menu/zk/util/errors"
"gopkg.in/djherbis/times.v1"
)
// Metadata holds information about a particular note.
type Metadata struct {
Path file.Path
Title string
Body string
WordCount int
Created time.Time
Modified time.Time
Checksum string
}
// Indexer persists the notes index.
type Indexer interface {
// Indexed returns the list of indexed note file metadata.
Indexed() (<-chan file.Metadata, error)
// Add indexes a new note from its metadata.
Add(metadata Metadata) error
// Update updates the metadata of an already indexed note.
Update(metadata Metadata) error
// Remove deletes a note from the index.
Remove(path file.Path) error
}
// Index indexes the content of the notes in the given directory.
func Index(dir zk.Dir, indexer Indexer, logger util.Logger) error {
wrap := errors.Wrapper("indexation failed")
source := file.Walk(dir, logger)
target, err := indexer.Indexed()
if err != nil {
return wrap(err)
}
err = file.Diff(source, target, func(change file.DiffChange) error {
switch change.Kind {
case file.DiffAdded:
metadata, err := metadata(change.Path)
if err == nil {
err = indexer.Add(metadata)
}
logger.Err(err)
case file.DiffModified:
metadata, err := metadata(change.Path)
if err == nil {
err = indexer.Update(metadata)
}
logger.Err(err)
case file.DiffRemoved:
err := indexer.Remove(change.Path)
logger.Err(err)
}
return nil
})
return wrap(err)
}
// metadata retrieves note metadata for the given file.
func metadata(path file.Path) (Metadata, error) {
metadata := Metadata{
Path: path,
}
content, err := ioutil.ReadFile(path.Abs)
if err != nil {
return metadata, err
}
contentStr := string(content)
metadata.Body = contentStr
metadata.WordCount = len(strings.Fields(contentStr))
metadata.Checksum = fmt.Sprintf("%x", sha256.Sum256(content))
times, err := times.Stat(path.Abs)
if err != nil {
return metadata, err
}
metadata.Modified = times.ModTime()
if times.HasBirthTime() {
metadata.Created = times.BirthTime()
} else {
metadata.Created = time.Now()
}
return metadata, nil
}