2021-02-08 14:59:00 +00:00
package hyphae
import (
"io/ioutil"
"log"
"path/filepath"
"github.com/bouncepaw/mycorrhiza/mimetype"
"github.com/bouncepaw/mycorrhiza/util"
)
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 ) {
2021-02-18 15:16:15 +00:00
byNames = make ( map [ string ] * Hypha )
2021-02-17 18:41:35 +00:00
ch := make ( chan * Hypha , 5 )
go func ( ch chan * Hypha ) {
indexHelper ( path , 0 , ch )
close ( ch )
} ( ch )
for h := range ch {
// At this time it is safe to ignore the mutex, because there is only one worker.
2021-03-14 13:16:30 +00:00
if oh := ByName ( h . Name ) ; oh . Exists {
oh . MergeIn ( h )
2021-02-17 18:41:35 +00:00
} else {
2021-03-14 13:16:30 +00:00
h . Insert ( )
2021-02-17 18:41:35 +00:00
}
}
}
// indexHelper finds all hypha files in the full `path` and sends them to the channel. Handling of duplicate entries and attachment and counting them is up to the caller.
func indexHelper ( path string , nestLevel uint , ch chan * Hypha ) {
2021-02-08 14:59:00 +00:00
nodes , err := ioutil . ReadDir ( path )
if err != nil {
log . Fatal ( err )
}
for _ , node := range nodes {
2021-03-06 09:44:20 +00:00
// If this hypha looks like it can be a hypha path, go deeper. Do not touch the .git and static folders for they have an administrative importance!
2021-02-08 14:59:00 +00:00
if node . IsDir ( ) &&
util . IsCanonicalName ( node . Name ( ) ) &&
node . Name ( ) != ".git" &&
! ( nestLevel == 0 && node . Name ( ) == "static" ) {
2021-02-17 18:41:35 +00:00
indexHelper ( filepath . Join ( path , node . Name ( ) ) , nestLevel + 1 , ch )
2021-02-08 14:59:00 +00:00
continue
}
var (
hyphaPartPath = filepath . Join ( path , node . Name ( ) )
hyphaName , isText , skip = mimetype . DataFromFilename ( hyphaPartPath )
2021-02-17 18:41:35 +00:00
hypha = & Hypha { Name : hyphaName , Exists : true }
2021-02-08 14:59:00 +00:00
)
if ! skip {
if isText {
hypha . TextPath = hyphaPartPath
} else {
hypha . BinaryPath = hyphaPartPath
}
ch <- hypha
}
}
}