-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
64 lines (51 loc) · 1.19 KB
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
)
type CmdFlags struct {
Add string
Del int
Edit string
Toggle int
List bool
}
func NewCmdFlags() *CmdFlags {
cf := CmdFlags{}
flag.StringVar(&cf.Add, "add", "", "Add a new todo specify title")
flag.StringVar(&cf.Edit, "edit", "", "Edit a todo by index & specify a new title. id:new_title")
flag.IntVar(&cf.Del, "del", -1, "Specify a todo by index to delete")
flag.IntVar(&cf.Toggle, "toggle", -1, "Specify a todo by index to toggle")
flag.BoolVar(&cf.List, "list", false, "List all todos")
flag.Parse()
return &cf
}
func (cf *CmdFlags) Execute(todos *Todos) {
switch {
case cf.List:
todos.print()
case cf.Add != "":
todos.add(cf.Add)
case cf.Edit != "":
parts := strings.SplitN(cf.Edit, ":", 2)
if len(parts) != 2 {
fmt.Println("Error, invalid format for edit. Please use id:new_title")
os.Exit(1)
}
index, err := strconv.Atoi(parts[0])
if err != nil {
fmt.Println("Error: invalid index for edit")
os.Exit(1)
}
todos.edit(index, parts[1])
case cf.Toggle != -1:
todos.toggle(cf.Toggle)
case cf.Del != -1:
todos.delete(cf.Del)
default:
fmt.Println("Invalid command")
}
}