...
1 package main
2
3 import (
4 "context"
5 "flag"
6 "fmt"
7 "os"
8
9 "github.com/peterbourgon/ff/v3/ffcli"
10 )
11
12
13
14
15
16
17 func main() {
18 var (
19 rootFlagSet = flag.NewFlagSet("textctl", flag.ExitOnError)
20 verbose = rootFlagSet.Bool("v", false, "increase log verbosity")
21 repeatFlagSet = flag.NewFlagSet("textctl repeat", flag.ExitOnError)
22 n = repeatFlagSet.Int("n", 3, "how many times to repeat")
23 )
24
25 repeat := &ffcli.Command{
26 Name: "repeat",
27 ShortUsage: "textctl repeat [-n times] <arg>",
28 ShortHelp: "Repeatedly print the argument to stdout.",
29 FlagSet: repeatFlagSet,
30 Exec: func(_ context.Context, args []string) error {
31 if n := len(args); n != 1 {
32 return fmt.Errorf("repeat requires exactly 1 argument, but you provided %d", n)
33 }
34 if *verbose {
35 fmt.Fprintf(os.Stderr, "repeat: will generate %dB of output\n", (*n)*len(args[0]))
36 }
37 for i := 0; i < *n; i++ {
38 fmt.Fprintf(os.Stdout, "%s\n", args[0])
39 }
40 return nil
41 },
42 }
43
44 count := &ffcli.Command{
45 Name: "count",
46 ShortUsage: "count [<arg> ...]",
47 ShortHelp: "Count the number of bytes in the arguments.",
48 Exec: func(_ context.Context, args []string) error {
49 if *verbose {
50 fmt.Fprintf(os.Stderr, "count: argument count %d\n", len(args))
51 }
52 var n int
53 for _, arg := range args {
54 n += len(arg)
55 }
56 fmt.Fprintf(os.Stdout, "%d\n", n)
57 return nil
58 },
59 }
60
61 root := &ffcli.Command{
62 ShortUsage: "textctl [flags] <subcommand>",
63 FlagSet: rootFlagSet,
64 Subcommands: []*ffcli.Command{repeat, count},
65 Exec: func(context.Context, []string) error {
66 return flag.ErrHelp
67 },
68 }
69
70 if err := root.ParseAndRun(context.Background(), os.Args[1:]); err != nil {
71 fmt.Fprintf(os.Stderr, "error: %v\n", err)
72 os.Exit(1)
73 }
74 }
75
View as plain text