pttodo/cmd/config.go

107 lines
2.7 KiB
Go

package main
import (
"flag"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
)
type config struct {
target string
target2 string
root string
tags []string
search string
edit bool
add string
addSchedule string
addTags string
dryRun bool
archive string
dedupe bool
}
func getConfig() config {
defaultFilepath := os.Getenv("PTTODO_FILE")
if defaultFilepath == "" {
defaultFilepath = "./todo.yaml"
}
var config config
flag.StringVar(&config.target, "f", defaultFilepath, "($PTTODO_FILE) path to yaml file or dir (starting with root then alphabetical for dir)")
flag.StringVar(&config.target2, "g", "", "path to yaml file to merge into root of -f")
flag.StringVar(&config.archive, "archive", "", "path to yaml file to migrate done")
flag.StringVar(&config.root, "root", DUMP_TODO, "path to pretty print ("+fmt.Sprint([]string{DUMP_ALL, DUMP_TODO, DUMP_SCHEDULED, DUMP_DONE})+")")
var tagss string
flag.StringVar(&tagss, "tags", "", "csv of all tags to find, -x to invert")
flag.StringVar(&config.search, "search", "", "fts case insensitive")
flag.BoolVar(&config.edit, "e", false, "edit file")
flag.BoolVar(&config.dedupe, "dedupe", false, "dedupe file")
flag.BoolVar(&config.dryRun, "dry-run", false, "dry run")
flag.StringVar(&config.add, "add", "", "todo to add")
flag.StringVar(&config.addSchedule, "add-schedule", "", "todo to add schedule")
flag.StringVar(&config.addTags, "add-tags", "", "todo to add csv tags")
flag.Parse()
config.tags = strings.Split(tagss, ",")
config.Targets()
return config
}
func (config config) Targets() []string {
result, err := config.targets()
if err != nil {
panic(err)
}
sort.Strings(result)
for i := range result {
if path.Base(result[i]) == "root.yaml" {
newresult := append([]string{result[i]}, result[:i]...)
newresult = append(newresult, result[i+1:]...)
result = newresult
break
}
}
return result
}
func (config config) targets() ([]string, error) {
patterns := []string{config.target, fmt.Sprintf("%s.*", config.target)}
isDir := false
if stat, err := os.Stat(config.target); err == nil {
isDir = stat.IsDir()
}
if isDir {
patterns = []string{fmt.Sprintf("%s/*", config.target)}
}
result := make([]string, 0, 1)
for _, pattern := range patterns {
results, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for i := range results {
if stat, err := os.Stat(results[i]); err != nil {
return nil, err
} else if !stat.IsDir() {
result = append(result, results[i])
}
}
}
if len(result) == 0 {
if isDir {
return []string{path.Join(config.target, "root.yaml")}, nil
}
return []string{config.target}, nil
}
return result, nil
}