-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.go
More file actions
120 lines (96 loc) · 2.11 KB
/
todo.go
File metadata and controls
120 lines (96 loc) · 2.11 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
package todo
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/alexeyco/simpletable"
)
type item struct {
Task string
Done bool
CreateAt time.Time
CompletedAt time.Time
}
type Todos [item]
func (t *Todos) Add(task string){
ls := *testing
if index <= 0 || index > len(ls){
return errors.New("index inválido")
}
ls[index-1].CompletedAt = time.Now()
ls[index-1].Done = true
return nil
}
func (t *Todos) Load(filename string) error{
file, err := ioutil.ReadFile(filename)
if err != nil {
if errors.Is(err, os.ErrNotExist){
return nil
}
return err
}
if len(file) == 0 {
return err
}
err = json.Unmarshal(file, t)
if err != nil {
return err
}
return nil
}
func (t *Todos) Store(filename string) error {
data, err := json.Marshal(t)
if err != nil {
return err
}
return ioutil.WriteFile(filename, data, 0644)
}
func (t *Todos) Print() {
table := simpletable.New()
table.Header = &simpletable.Header{
Cells: []*simpletable.Cell{
{Align: simpletable.AlignCenter, Text: "#"},
{Align: simpletable.AlignCenter, Text: "Task"},
{Align: simpletable.AlignCenter, Text: "Done?"},
{Align: simpletable.AlignRight, Text: "CreatedAt"},
{Align: simpletable.AlignRight, Text: "CompletedAt"},
},
}
var cells [][]*simpletable.Cell
for idx, item := range *t {
idx++
task := blue(item.Task)
done := blue("no")
if item.Done {
task = green(fmt.Sprintf("\u2705 %s", item.Task))
done = green("yes")
}
cells = append(cells, *&[]*simpletable.Cell{
{Text: fmt.Sprintf("%d", idx)},
{Text: task},
{Text: done},
{Text: item.CreatedAt.Format(time.RFC822)},
{Text: item.CompletedAt.Format(time.RFC822)},
})
}
table.Body = &simpletable.Body{Cells: cells}
table.Footer = &simpletable.Footer{Cells: []*simpletable.Cell{
{Align: simpletable.AlignCenter, Span: 5, Text: red(fmt.Sprintf("You have %d pending todos", t.CountPending()))},
}}
table.SetStyle(simpletable.StyleUnicode)
table.Println()
}
func (t *Todos) CountPending() int {
total := 0
for _, item := range *t {
if !item.Done {
total++
}
}
return total
}