From aac4f7f5cda6074b8a3cb803d96fbf46bc84e795 Mon Sep 17 00:00:00 2001 From: surdeus Date: Mon, 21 Nov 2022 03:27:21 +0500 Subject: [PATCH] Implemented basic useprog command. --- src/cmd/goblin/main.go | 2 ++ src/tool/useprog/main.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/tool/useprog/main.go diff --git a/src/cmd/goblin/main.go b/src/cmd/goblin/main.go index dd64cee..747fe3e 100644 --- a/src/cmd/goblin/main.go +++ b/src/cmd/goblin/main.go @@ -24,6 +24,7 @@ import( "github.com/surdeus/goblin/src/tool/ftest" "github.com/surdeus/goblin/src/tool/grange" "github.com/surdeus/goblin/src/tool/in" + "github.com/surdeus/goblin/src/tool/useprog" ) func main() { @@ -50,6 +51,7 @@ func main() { "ftest" : mtool.Tool{ftest.Run, "filter files by specified features"}, "range" : mtool.Tool{grange.Run, "too lazy"}, "in" : mtool.Tool{in.Run, "filter strings from stdin that aren not in arguments"}, + "useprog" : mtool.Tool{useprog.Run, "print the name of the first existing program in arg list"}, } mtool.Main("goblin", tools) diff --git a/src/tool/useprog/main.go b/src/tool/useprog/main.go new file mode 100644 index 0000000..97e5e81 --- /dev/null +++ b/src/tool/useprog/main.go @@ -0,0 +1,35 @@ +package useprog + +import ( + "os" + "os/exec" + "fmt" + "flag" +) + +func Run(args []string) { + arg0 := args[0] + args = args[1:] + flagSet := flag.NewFlagSet(arg0, flag.ExitOnError) + flagSet.Usage = func() { + fmt.Fprintf(os.Stderr, "usage: %s [prog2, ...prog3]\n", arg0) + flagSet.PrintDefaults() + os.Exit(1) + } + + flagSet.Parse(args) + args = flagSet.Args() + + if len(args) == 0 { + flagSet.Usage() + } + + for _, v := range args { + _, err := exec.LookPath(v) + if err != nil { + continue + } + fmt.Printf("%s", v) + break + } +}