forked from jreisinger/gokatas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gokatas.go
312 lines (279 loc) · 6.95 KB
/
gokatas.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package gokatas
import (
"bufio"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"text/tabwriter"
"time"
)
// KatasFile is a MarkDown file to track katas you've done. It looks like this:
//
// - 2022-09-13: boring/boring, boring/channel
// - 2022-09-10: areader
const KatasFile = "katas.md"
// Kata represents a programming kata.
type Kata struct {
Name string
LastDone time.Time
TimesDone int
Level string
Topics []string
}
// Get returns all existing katas and adds info about those you have done, i.e.
// written to KatasFile.
func Get() ([]Kata, error) {
existing, err := getExisting()
if err != nil {
return nil, fmt.Errorf("getting all existing katas: %v", err)
}
done, err := getDone()
if err != nil {
return nil, fmt.Errorf("getting done katas: %v", err)
}
// Check kata you put in KatasFile file really exists.
for _, d := range done {
var exists bool
for _, e := range existing {
if d.Name == e.Name {
exists = true
break
}
}
if !exists {
log.Printf("kata '%s' stated in %s does not exist in this repo", d.Name, KatasFile)
}
}
var katas []Kata
// Enrich existing katas with done info.
for _, e := range existing {
for _, d := range done {
if e.Name == d.Name {
e.LastDone = d.LastDone
e.TimesDone = d.TimesDone
}
}
katas = append(katas, e)
}
return katas, nil
}
// getExisting returns all existing katas.
func getExisting() ([]Kata, error) {
cmd := exec.Command("go", "list", "-f", "{{.Dir}}", "./...")
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%s", out)
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
var katas []Kata
for _, line := range strings.Split(string(out), "\n") {
name := strings.TrimPrefix(line, cwd)
name = strings.TrimPrefix(name, "/")
if name == "" || strings.HasSuffix(name, "cmd") {
continue
}
level, topics, err := parseKata(name)
if err != nil {
return nil, err
}
katas = append(katas, Kata{Name: name, Level: level, Topics: uniq(topics)})
}
return katas, err
}
// uniq removes duplicates from topics.
func uniq(topics []string) []string {
seen := make(map[string]bool)
var unique []string
for _, topic := range topics {
if _, ok := seen[topic]; !ok {
seen[topic] = true
unique = append(unique, topic)
}
}
return unique
}
// getDone returns katas from the KatasFile.
func getDone() ([]Kata, error) {
f, err := os.Open(KatasFile)
if err != nil {
return nil, err
}
// Regexes
kataLineRE := regexp.MustCompile(`^\s*[\*\-]\s*([0-9]{4}\-[0-9]{2}\-[0-9]{2}):\s*(.+)$`)
comaRE := regexp.MustCompile(`\s*,\s*`) // works both with w1,w2 and w1, w2
katas := make(map[string]Kata) // name to Kata
s := bufio.NewScanner(f)
for s.Scan() {
lineParts := kataLineRE.FindStringSubmatch(s.Text())
if lineParts == nil {
continue
}
date, katasStr := lineParts[1], lineParts[2]
doneOn, err := time.Parse("2006-01-02", date)
if err != nil {
return nil, err
}
for _, name := range comaRE.Split(katasStr, -1) {
if name == "" {
continue
}
name = strings.TrimSpace(name)
if kata, ok := katas[name]; ok {
kata.TimesDone++
if doneOn.After(kata.LastDone) {
kata.LastDone = doneOn
}
katas[name] = kata
} else {
kata.Name = name
kata.TimesDone = 1
kata.LastDone = doneOn
katas[name] = kata
}
}
}
if s.Err() != nil {
return nil, s.Err()
}
var ks []Kata
for name := range katas {
ks = append(ks, katas[name])
}
return ks, nil
}
func parseKata(name string) (level string, topics []string, err error) {
fn := func(path string, d fs.DirEntry, err error) error {
if filepath.Ext(path) == ".go" {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
var inCommentBlock bool
levelRE := regexp.MustCompile(`Level:\s*\w+`)
topicsRE := regexp.MustCompile(`Topics:\s*\w+`)
for s.Scan() {
line := s.Text()
if strings.HasPrefix(line, "/*") {
inCommentBlock = true
}
if strings.HasPrefix(line, "*/") {
inCommentBlock = false
}
if inCommentBlock || strings.HasPrefix(line, "//") {
if levelRE.MatchString(line) {
level = cutLevel(s.Text())
}
if topicsRE.MatchString(line) {
topics = append(topics, cutTopics(s.Text())...)
}
}
}
if err := s.Err(); err != nil {
return err
}
}
return nil
}
absPath, err := filepath.Abs(name)
if err != nil {
return "", nil, err
}
err = filepath.WalkDir(absPath, fn)
if err != nil {
return "", nil, err
}
return level, topics, err
}
func cutLevel(line string) string {
_, level, _ := strings.Cut(line, ":")
return strings.TrimSpace(level)
}
func cutTopics(line string) []string {
_, topicsStr, _ := strings.Cut(line, ":")
topics := strings.Split(topicsStr, ",")
for i := range topics {
topics[i] = strings.TrimSpace(topics[i])
}
return topics
}
// Print prints table with statistics about katas sorted by column.
func Print(katas []Kata, column int) {
const format = "%v\t%v\t%5v\t%v\t%v\n"
// Print header.
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
fmt.Fprintf(tw, format, "Kata", "Last done", "Done", "Level", "Topics")
fmt.Fprintf(tw, format, "----", "---------", "----", "-----", "------")
// Print lines.
var katasCount int
var doneCount int
sortKatas(katas, &column)
for _, k := range katas {
katasCount++
doneCount += k.TimesDone
fmt.Fprintf(tw, format, k.Name, humanize(k.LastDone), fmt.Sprintf("%dx", k.TimesDone), k.Level, strings.Join(k.Topics, ", "))
}
// Print footer.
fmt.Fprintf(tw, format, "----", "", "----", "", "")
fmt.Fprintf(tw, format, katasCount, "", fmt.Sprintf("%dx", doneCount), "", "")
tw.Flush() // calculate column widths and print table
}
// humanize make the time easier to read for humans.
func humanize(t time.Time) string {
if t.IsZero() {
return "never"
}
daysAgo := int(time.Since(t).Hours() / 24)
w := "day"
if daysAgo != 1 {
w += "s"
}
return fmt.Sprintf("%d %s ago", daysAgo, w)
}
type customSort struct {
katas []Kata
less func(x, y Kata) bool
}
func (x customSort) Len() int { return len(x.katas) }
func (x customSort) Less(i, j int) bool { return x.less(x.katas[i], x.katas[j]) }
func (x customSort) Swap(i, j int) { x.katas[i], x.katas[j] = x.katas[j], x.katas[i] }
// sortKatas sorts katas by column. Not all columns are sortable. Secondary sort
// orders is always by kata name.
func sortKatas(katas []Kata, column *int) {
sort.Sort(customSort{katas, func(x, y Kata) bool {
switch *column {
case 1:
if x.Name != y.Name {
return x.Name < y.Name
}
case 2:
if x.LastDone != y.LastDone {
return x.LastDone.After(y.LastDone)
}
case 3:
if x.TimesDone != y.TimesDone {
return x.TimesDone < y.TimesDone
}
case 4:
if x.Level != y.Level {
return x.Level > y.Level
}
default:
log.Fatalf("can't sort by column %d", *column)
}
if x.Name != y.Name {
return x.Name < y.Name
}
return false
}})
}