From af2f2032f17ca244998b70f36ddf4f36a3159f54 Mon Sep 17 00:00:00 2001 From: bth Date: Sun, 18 Jan 2026 21:38:18 -0800 Subject: [PATCH] next, last : glob and regexp --- next/last.go | 33 +++++++++++++++++++++++++++++---- next/next.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/next/last.go b/next/last.go index 70537dc..ecafc99 100644 --- a/next/last.go +++ b/next/last.go @@ -1,14 +1,39 @@ package next import ( + "errors" "fmt" "os/exec" + "regexp" + "strings" ) -func Last() { - ls, err := exec.Command("ls").Output() +const ( + LS_CMD = `ls -r [0-9]*.md` + LS_GREP_PIPE = `ls -r | grep -E '^[[:digit:]].*\.md'` + FILE_REGEXP = `(?m)^([0-9]+)\.([[:alpha:]]*)\.*md$` +) + +var fileRegexp *regexp.Regexp = regexp.MustCompile(FILE_REGEXP) + +func last() (string, error) { + // NOTE: globbing requires invoking the shell as cmd: + cmd := exec.Command("sh", "-c", LS_CMD) + ls, err := cmd.Output() if err != nil { - fmt.Print(err) + return "", err } - fmt.Printf("ls\n%s\n", string(ls)) + lines := strings.Split(string(ls), "\n") + if len(lines) == 0 { + return "", errors.New("no um files in current dir") + } + return lines[0], nil +} + +func Last() { + s, err := last() + if err != nil { + fmt.Printf("err: %v\n", err) + } + fmt.Println(s) } diff --git a/next/next.go b/next/next.go index fbfa19a..84241ba 100644 --- a/next/next.go +++ b/next/next.go @@ -1,7 +1,9 @@ package next import ( + "errors" "fmt" + "strconv" "github.com/brtholomy/um/go/flags" ) @@ -38,7 +40,49 @@ func parseArgs(args []string) options { return opts } +func parseFile(last string) (string, string, error) { + res := fileRegexp.FindStringSubmatch(last) + num := "" + desc := "" + if len(res) < 2 { + return num, desc, errors.New("no um files in current dir") + } + num = res[1] + if len(res) > 2 { + desc = res[2] + } + return num, desc, nil +} + +func next(last string) (string, error) { + num, desc, err := parseFile(last) + if err != nil { + return "", err + } + i, err := strconv.Atoi(num) + if err != nil { + return "", err + } + if desc != "" { + desc = desc + "." + } + width := len(num) + fmtstr := fmt.Sprintf("%%0%dd.%%smd", width) + n := fmt.Sprintf(fmtstr, i+1, desc) + return n, nil +} + func Next(args []string) { opts := parseArgs(args) fmt.Println(opts) + + l, err := last() + if err != nil { + fmt.Printf("err: %v\n", err) + } + n, err := next(l) + if err != nil { + fmt.Printf("err: %v\n", err) + } + fmt.Println(n) }