1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 03:36:16 +00:00
mycorrhiza/hyphae/files.go

95 lines
2.5 KiB
Go
Raw Normal View History

package hyphae
import (
"log"
2021-07-02 08:29:55 +00:00
"os"
"path/filepath"
"github.com/bouncepaw/mycorrhiza/mimetype"
)
2021-02-17 18:41:35 +00:00
// Index finds all hypha files in the full `path` and saves them to the hypha storage.
func Index(path string) {
2022-02-19 08:26:38 +00:00
byNames = make(map[string]ExistingHypha)
ch := make(chan ExistingHypha, 5)
2021-02-17 18:41:35 +00:00
2022-02-19 08:26:38 +00:00
go func(ch chan ExistingHypha) {
2021-02-17 18:41:35 +00:00
indexHelper(path, 0, ch)
close(ch)
}(ch)
2022-02-19 08:26:38 +00:00
for foundHypha := range ch {
switch storedHypha := ByName(foundHypha.CanonicalName()).(type) {
case *EmptyHypha:
2022-02-19 08:26:38 +00:00
Insert(foundHypha)
2022-02-19 08:26:38 +00:00
case *TextualHypha:
switch foundHypha := foundHypha.(type) {
case *TextualHypha: // conflict! overwrite
storedHypha.mycoFilePath = foundHypha.mycoFilePath
log.Printf(
"File collision for hypha %s, using %s rather than %s\n",
foundHypha.CanonicalName(),
foundHypha.TextFilePath(),
storedHypha.TextFilePath(),
)
case *MediaHypha: // no conflict
Insert(ExtendTextualToMedia(storedHypha, foundHypha.mediaFilePath))
}
2022-02-19 08:26:38 +00:00
case *MediaHypha:
switch foundHypha := foundHypha.(type) {
case *TextualHypha: // no conflict
storedHypha.mycoFilePath = foundHypha.mycoFilePath
case *MediaHypha: // conflict! overwrite
storedHypha.mediaFilePath = foundHypha.mediaFilePath
log.Printf(
"File collision for hypha %s, using %s rather than %s\n",
foundHypha.CanonicalName(),
foundHypha.MediaFilePath(),
storedHypha.MediaFilePath(),
)
}
2021-02-17 18:41:35 +00:00
}
}
log.Println("Indexed", Count(), "hyphae")
2021-02-17 18:41:35 +00:00
}
// indexHelper finds all hypha files in the full `path` and sends them to the
2022-02-26 07:33:09 +00:00
// channel. Handling of duplicate entries and media and counting them is
// up to the caller.
2022-02-19 08:26:38 +00:00
func indexHelper(path string, nestLevel uint, ch chan ExistingHypha) {
2021-07-02 08:29:55 +00:00
nodes, err := os.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, node := range nodes {
// If this hypha looks like it can be a hypha path, go deeper. Do not
2022-02-03 22:39:21 +00:00
// touch the .git folders for it has an administrative importance!
if node.IsDir() && IsValidName(node.Name()) && node.Name() != ".git" {
2021-02-17 18:41:35 +00:00
indexHelper(filepath.Join(path, node.Name()), nestLevel+1, ch)
continue
}
var (
hyphaPartPath = filepath.Join(path, node.Name())
hyphaName, isText, skip = mimetype.DataFromFilename(hyphaPartPath)
)
if !skip {
if isText {
2022-02-19 08:26:38 +00:00
ch <- &TextualHypha{
canonicalName: hyphaName,
mycoFilePath: hyphaPartPath,
}
} else {
2022-02-19 08:26:38 +00:00
ch <- &MediaHypha{
canonicalName: hyphaName,
mycoFilePath: "",
mediaFilePath: hyphaPartPath,
}
}
}
}
}