// Chapter 32 example: a tool with subcommands, each with its own flags. // It keeps the notes in notes.txt, in the folder you run it from. // Run with: go run exercises/32/06-notes.go add Buy rice // and: go run exercises/32/06-notes.go list -last 2 package main import ( "bufio" "errors" "flag" "fmt" "os" "strings" ) const notesFile = "notes.txt" func usage() { fmt.Fprintln(os.Stderr, "usage:") fmt.Fprintln(os.Stderr, " notes add TEXT... add a note") fmt.Fprintln(os.Stderr, " notes list [-last N] show the notes") } func main() { if len(os.Args) < 2 { usage() os.Exit(2) } var err error switch os.Args[1] { case "add": err = addCommand(os.Args[2:]) case "list": err = listCommand(os.Args[2:]) default: fmt.Fprintf(os.Stderr, "unknown command %q\n", os.Args[1]) usage() os.Exit(2) } if err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } } func addCommand(args []string) error { flags := flag.NewFlagSet("add", flag.ExitOnError) flags.Parse(args) if flags.NArg() == 0 { return errors.New("add needs the text of the note") } text := strings.Join(flags.Args(), " ") f, err := os.OpenFile(notesFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() _, err = fmt.Fprintln(f, text) if err != nil { return err } err = f.Close() if err != nil { return err } fmt.Println("Added:", text) return nil } func listCommand(args []string) error { flags := flag.NewFlagSet("list", flag.ExitOnError) last := flags.Int("last", 0, "show only the last n notes (0 shows all)") flags.Parse(args) notes, err := readNotes() if err != nil { return err } if len(notes) == 0 { fmt.Println("No notes yet.") return nil } start := 0 if *last > 0 && *last < len(notes) { start = len(notes) - *last } for i := start; i < len(notes); i++ { fmt.Printf("%d. %s\n", i+1, notes[i]) } return nil } // readNotes returns the lines of the notes file. No file means no notes. func readNotes() ([]string, error) { f, err := os.Open(notesFile) if errors.Is(err, os.ErrNotExist) { return []string{}, nil } if err != nil { return nil, err } defer f.Close() notes := []string{} scanner := bufio.NewScanner(f) for scanner.Scan() { notes = append(notes, scanner.Text()) } return notes, scanner.Err() }