last : filepath.Glob instead of exec.Command(ls)

This commit is contained in:
bth 2026-01-20 19:32:55 -08:00
commit 18eab3cb85
2 changed files with 11 additions and 21 deletions

View file

@ -1,46 +1,35 @@
package next package next
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"log" "log"
"os/exec" "path/filepath"
"regexp" "regexp"
"strings"
cmdpkg "github.com/brtholomy/um/go/cmd" cmdpkg "github.com/brtholomy/um/go/cmd"
) )
const ( const (
// NOTE: the -r flag: GLOB = "[0-9]*.md"
LS_CMD = `ls -r [0-9]*.md`
// we only care about the number group: // we only care about the number group:
FILE_REGEXP = `(?m)^([0-9]+)\.[[:alpha:]]*\.*md$` FILE_REGEXP = `(?m)^([0-9]+)\.[[:alpha:]]*\.*md$`
NOT_FOUND_MSG = "um files not found" NOT_FOUND_MSG = "um files not found: " + GLOB
) )
var fileRegexp *regexp.Regexp = regexp.MustCompile(FILE_REGEXP) var fileRegexp *regexp.Regexp = regexp.MustCompile(FILE_REGEXP)
// calls ls to get the lexical last file // get the lexical last file from GLOB
func last() (string, error) { func last() (string, error) {
// NOTE: globbing requires invoking the shell as cmd: // NOTE: filepath.Glob is more reliable than a manual ls call:
cmd := exec.Command("sh", "-c", LS_CMD) filelist, err := filepath.Glob(GLOB)
if err != nil {
// fine grained control: return "", err
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// the returned err is ExitStatus, which has stderr embedded, but i find this clearer:
if err := cmd.Run(); err != nil {
return "", errors.New(stderr.String())
} }
if len(filelist) == 0 {
lines := strings.Split(stdout.String(), "\n")
if len(lines) == 0 {
return "", errors.New(NOT_FOUND_MSG) return "", errors.New(NOT_FOUND_MSG)
} }
return lines[0], nil return filelist[len(filelist)-1], nil
} }
func Last() { func Last() {

View file

@ -5,6 +5,7 @@ import (
"testing" "testing"
"time" "time"
// TODO: switch to something lighter: https://github.com/alecthomas/assert
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )