-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtodo-list-v1.go
107 lines (92 loc) · 1.88 KB
/
todo-list-v1.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
type todo struct {
description string
done bool
}
var fileName = "todo.txt"
var todos = make([]todo, 0)
func loadFile() {
var todoFile *os.File
_, err := os.Stat(fileName)
if errors.Is(err, os.ErrNotExist) {
todoFile, _ = os.Create(fileName)
} else {
todoFile, _ = os.Open(fileName)
}
defer todoFile.Close()
todoFileScanner := bufio.NewScanner(todoFile)
todoFileScanner.Split(bufio.ScanLines)
for todoFileScanner.Scan() {
todoLine := todoFileScanner.Text()
todoSplit := strings.Split(todoLine, ":::")
t := todo{description: todoSplit[0]}
t.done, _ = strconv.ParseBool(todoSplit[1])
todos = append(todos, t)
}
}
func list() {
for i, e := range todos {
// https://stackoverflow.com/a/31483763/420096
check := map[bool]string{true: "✓", false: " "}
fmt.Printf("%d) [%s] %s\n", i, check[e.done], e.description)
}
}
func add() {
fmt.Println("provide the new todo description")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
todos = append(todos, todo{input, false})
}
func resolve() {
list()
fmt.Println("choose a number to resolve")
var i int
fmt.Scanln(&i)
todos[i].done = true
}
func save() {
todoFile, _ := os.OpenFile(fileName, os.O_WRONLY, 666)
defer todoFile.Close()
for _, e := range todos {
line := fmt.Sprintf("%s:::%t", e.description, e.done)
fmt.Fprintln(todoFile, line)
}
todoFile.Sync()
}
func main() {
loadFile()
var op string
for op != "quit" {
fmt.Println("choose an option:")
fmt.Println("list")
fmt.Println("add")
fmt.Println("resolve")
fmt.Println("quit")
fmt.Println()
fmt.Scanln(&op)
fmt.Println()
switch op {
case "list":
list()
case "add":
add()
case "resolve":
resolve()
case "quit":
op = "quit"
save()
default:
fmt.Println("invalid option")
}
fmt.Println()
}
}