From faafc494712df9dd27e50d50935bf3a68474c316 Mon Sep 17 00:00:00 2001 From: Johan Walles Date: Fri, 29 Sep 2023 22:42:41 +0200 Subject: [PATCH] Accept +1234 argument in any place Fixes the issue reported with PR #158: https://github.com/walles/moar/pull/158#issue-1918313499 --- moar.go | 17 ++++++++--------- test.sh | 7 +++++++ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/moar.go b/moar.go index a18ef017..0dafc4fd 100644 --- a/moar.go +++ b/moar.go @@ -279,8 +279,7 @@ func tryOpen(filename string) error { // line number, and returns the remaining args. // // Returns 0 on no target line number specified. -func getTargetLineNumberOneBased(flagSet *flag.FlagSet) (int, []string) { - args := flagSet.Args() +func getTargetLineNumberOneBased(args []string) (int, []string) { for i, arg := range args { if !strings.HasPrefix(arg, "+") { continue @@ -378,7 +377,9 @@ func main() { flags = append(strings.Fields(moarEnv), flags...) } - err := flagSet.Parse(flags) + targetLineNumberOneBased, remainingArgs := getTargetLineNumberOneBased(flags) + + err := flagSet.Parse(remainingArgs) if err != nil { if err == flag.ErrHelp { printUsage(os.Stdout, flagSet, false) @@ -408,10 +409,8 @@ func main() { TimestampFormat: time.StampMicro, }) - targetLineNumberOneBased, remainingArgs := getTargetLineNumberOneBased(flagSet) - - if len(remainingArgs) > 1 { - fmt.Fprintln(os.Stderr, "ERROR: Expected exactly one filename, or data piped from stdin, got:", remainingArgs) + if len(flagSet.Args()) > 1 { + fmt.Fprintln(os.Stderr, "ERROR: Expected exactly one filename, or data piped from stdin, got:", flagSet.Args()) fmt.Fprintln(os.Stderr) printUsage(os.Stderr, flagSet, true) @@ -421,8 +420,8 @@ func main() { stdinIsRedirected := !term.IsTerminal(int(os.Stdin.Fd())) stdoutIsRedirected := !term.IsTerminal(int(os.Stdout.Fd())) var inputFilename *string - if len(remainingArgs) == 1 { - word := remainingArgs[0] + if len(flagSet.Args()) == 1 { + word := flagSet.Args()[0] inputFilename = &word // Need to check before twin.NewScreen() below, otherwise the screen diff --git a/test.sh b/test.sh index 6a8e0494..8476b789 100755 --- a/test.sh +++ b/test.sh @@ -61,6 +61,13 @@ if ./moar does-not-exist >&/dev/null; then exit 1 fi +echo Testing not crashing with different argument orders... +./moar +123 moar.go >/dev/null +./moar moar.go +123 >/dev/null +./moar +123 --trace moar.go >/dev/null +./moar --trace +123 moar.go >/dev/null +./moar --trace moar.go +123 >/dev/null + echo Test --version... ./moar --version >/dev/null # Should exit with code 0 diff -u <(./moar --version) <(git describe --tags --dirty --always)