cmd-zet/internal/zet/zet.go
Oliver Davies 4d11b5354c Refactor
Signed-off-by: Oliver Davies <oliver@oliverdavies.uk>
2025-10-05 00:57:15 +01:00

90 lines
1.5 KiB
Go

package zet
import (
"bufio"
"fmt"
"os"
"path"
"strconv"
"strings"
"code.oliverdavies.uk/opdavies/cmd-zet/internal/config"
"code.oliverdavies.uk/opdavies/cmd-zet/internal/git"
)
type ZetList struct {
Ids []int
UseColors bool
}
func CreateZetList(ids []int, useColors ...bool) *ZetList {
colorSetting := true
if len(useColors) > 0 {
colorSetting = useColors[0]
}
return &ZetList{
Ids: ids,
UseColors: colorSetting,
}
}
func (z *ZetList) Parse() []string {
var lines []string
green := "\033[32m"
reset := "\033[0m"
for _, num := range z.Ids {
line := fmt.Sprintf("%s %s", strconv.Itoa(num), getTitle(num))
if z.UseColors {
line = fmt.Sprintf("%s%s%s %s", green, strconv.Itoa(num), reset, getTitle(num))
}
lines = append(lines, line)
}
return lines
}
func getTitle(id int) string {
return getTitleFromFile(path.Join(strconv.Itoa(id), "index.adoc"))
}
func getTitleFromFile(filePath string) string {
filePath = path.Join(config.GetZetDir(), filePath)
file, err := os.Open(filePath)
if err != nil {
fmt.Println("Error opening file:", err)
return ""
}
defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
text := scanner.Text()
return strings.TrimPrefix(text, "= ")
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
}
return ""
}
func onSave(id int) {
title := getTitle(id)
git.CommitZettel(id, title)
// TODO: Or delete the file if empty.
}