example_test.go 933 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package cmdflag_test
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "github.com/pierrec/lz4/internal/cmdflag"
  7. )
  8. func ExampleParse() {
  9. // Declare the `split` cmdflag.
  10. cmdflag.New(
  11. "split",
  12. "argsdesc",
  13. "desc",
  14. flag.ExitOnError,
  15. func(fs *flag.FlagSet) cmdflag.Handler {
  16. // Declare the cmdflag specific flags.
  17. var s string
  18. fs.StringVar(&s, "s", "", "string to be split")
  19. // Return the handler to be executed when the cmdflag is found.
  20. return func(...string) error {
  21. i := len(s) / 2
  22. fmt.Println(s[:i], s[i:])
  23. return nil
  24. }
  25. })
  26. // The following is only used to emulate passing command line arguments to `program`.
  27. // It is equivalent to running:
  28. // ./program split -s hello
  29. args := os.Args
  30. defer func() { os.Args = args }()
  31. os.Args = []string{"program", "split", "-s", "hello"}
  32. // Process the command line arguments.
  33. if err := cmdflag.Parse(); err != nil {
  34. panic(err)
  35. }
  36. // Output:
  37. // he llo
  38. }