From 9a08b03b83ff28a26b0c20ccebc178df29cf7312 Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Thu, 23 Oct 2025 21:19:00 -0700 Subject: Use one binary with subcommands --- sym.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sym.go (limited to 'sym.go') diff --git a/sym.go b/sym.go new file mode 100644 index 0000000..2405feb --- /dev/null +++ b/sym.go @@ -0,0 +1,48 @@ +package main + +import ( + "flag" + "fmt" + "os" + "path/filepath" +) + +type subcommand interface { + registerFlags(*flag.FlagSet) + run(...string) error +} + +func whichSubcommand(name string) (subcommand, bool) { + switch filepath.Base(name) { + case "enc": + return &defaultEncryptOptions, true + case "dec": + return &defaultDecryptOptions, true + default: + return nil, false + } +} + +func run(args []string) error { + cmd, ok := whichSubcommand(args[0]) + if !ok { + if len(args) < 2 { + return fmt.Errorf("missing subcommand") + } + cmd, ok = whichSubcommand(args[1]) + if !ok { + return fmt.Errorf("invalid subcommand %q", args[1]) + } + args = args[1:] + } + cmd.registerFlags(flag.CommandLine) + flag.CommandLine.Parse(args[1:]) + return cmd.run(flag.Args()...) +} + +func main() { + if err := run(os.Args); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} -- cgit v1.3.1