計算機科学のブログ

Powerful Command-Line Applications in Go: Interacting with Your Users options, flag package, time

Powerful Command-Line Applications in Go(Ricardo Gerardi(著)、Pragmatic Bookshelf)のChapter 2(Interacting with Your Users)、Exercisesの2つ目の解答を求めてみる。

コード

main.go

package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"pragprog.com/rggo/interacting/todo"
)

const todoFileName = ".todo.json"

func main() {
	list := flag.Bool("list", false, "List all tasks")
	complete := flag.Int("complete", 0, "Item to be completed")
	del := flag.Int("del", 0, "Item to be deleted")
	verbose := flag.Bool("v", false, "list All tasks(verbose mode)")
	flag.Parse()
	l := &todo.List{}
	if err := l.Get(todoFileName); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	switch {
	case *list:
		for _, item := range *l {
			if !item.Done {
				fmt.Println(item.Task)
			}
		}
	case *verbose:
		for _, item := range *l {
			fmt.Print(item.Task)
			if item.Done {
				fmt.Printf(": compleated at %v\n", item.CompletedAt)
			} else {
				fmt.Println("")
			}
		}
	case *complete > 0:
		if err := l.Complete(*complete); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		if err := l.Save(todoFileName); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	case len(os.Args) == 1:
		for _, item := range *l {
			fmt.Println(item.Task)
		}
	case *del > 0:
		if err := l.Delete(*del); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		if err := l.Save(todoFileName); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	default:
		item := strings.Join(os.Args[1:], " ")
		l.Add(item)
		if err := l.Save(todoFileName); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	}
}

入出力結果(Terminal, Zsh)

% go run main.go -list    
tasks1
tasks2
tasks3
tasks4
tasks5
% go run main.go -complete
flag needs an argument: -complete
Usage of /var/folders/d5/bf58kt_s36q8p2lzvvvvyhbc0000gn/T/go-build147016877/b001/exe/main:
  -complete int
    	Item to be completed
  -del int
    	Item to be deleted
  -list
    	List all tasks
  -v	list All tasks(verbose mode)
exit status 2
% go run main.go -complete 2
% go run main.go -list      
tasks1
tasks3
tasks4
tasks5
% go run main.go -v   
tasks1
tasks2: compleated at 2022-04-08 12:47:10.365428 +0900 JST
tasks3
tasks4
tasks5
% go run main.go -del 2
% go run main.go -v    
tasks1
tasks3
tasks4
tasks5
%