Require .txt filename extension for entries, allow defining entry title via Title: ... in first line of the file, update examples
This commit is contained in:
parent
1db5336f35
commit
89fbb17ab7
6 changed files with 53 additions and 11 deletions
40
database.go
40
database.go
|
|
@ -44,20 +44,44 @@ func (db *Database) search(query string) []string { // returns keys (entry names
|
|||
func BuildDB(directory string) Database {
|
||||
logger := log.Default()
|
||||
logger.Println("Building database")
|
||||
// keys, entries
|
||||
var keys []string
|
||||
// files, entries
|
||||
var files []string
|
||||
entries := map[string]string{}
|
||||
// get files in directory and read them
|
||||
directory = strings.TrimRight(directory, "/") // we don't need that last /, don't use the root directory /
|
||||
entriesDirFs := os.DirFS(directory)
|
||||
keys, err := fs.Glob(entriesDirFs, "*")
|
||||
files, err := fs.Glob(entriesDirFs, "*.txt")
|
||||
if err != nil { logger.Panicln(err) }
|
||||
for _, k := range keys {
|
||||
contentB, err := os.ReadFile(directory + "/" + k)
|
||||
titles := []string{}
|
||||
for _, f := range files {
|
||||
fileData, err := os.ReadFile(directory + "/" + f)
|
||||
if err != nil { logger.Panicln(err) }
|
||||
content := string(contentB)
|
||||
entries[k] = content
|
||||
content := string(fileData)
|
||||
content = strings.Trim(content, "\n\r ")
|
||||
if strings.HasPrefix(content, "Title:") {
|
||||
len_content := len(content)
|
||||
title_start_idx := 6
|
||||
var title_stop_idx int
|
||||
if strings.Contains(content, "\n") {
|
||||
title_stop_idx = strings.Index(content, "\n")
|
||||
} else {
|
||||
title_stop_idx = len_content
|
||||
}
|
||||
title := content[title_start_idx:title_stop_idx]
|
||||
title = strings.Trim(title, " ")
|
||||
body := content[title_stop_idx:len_content]
|
||||
body = strings.TrimLeft(body, "\n\r")
|
||||
if len(body) < 1 {
|
||||
body = " "
|
||||
}
|
||||
titles = append(titles, title)
|
||||
entries[title] = body
|
||||
} else {
|
||||
title := f[:len(f)-4] // remove ".txt"
|
||||
titles = append(titles, title)
|
||||
entries[title] = content
|
||||
}
|
||||
}
|
||||
matcher := search.New(ContentLanguage, search.IgnoreCase, search.IgnoreDiacritics)
|
||||
return Database{Keys: keys, Entries: entries, matcher: matcher}
|
||||
return Database{Keys: titles, Entries: entries, matcher: matcher}
|
||||
}
|
||||
|
|
|
|||
Reference in a new issue