forked from wakatara/harsh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
harsh.go
executable file
·818 lines (724 loc) · 23.1 KB
/
harsh.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"cloud.google.com/go/civil"
"github.com/gookit/color"
"github.com/urfave/cli/v2"
)
var configDir string
type Days int
type Habit struct {
Heading string
Name string
Frequency Days
}
// Outcome is the explicit recorded result of a habit
// on a day (y, n, or s) and an optional amount and comment
type Outcome struct {
Result string
Amount float64
Comment string
}
// DailyHabit combines Day and Habit with an Outcome to yield Entries
type DailyHabit struct {
Day civil.Date
Habit string
}
// HabitStats holds total stats for a Habit in the file
type HabitStats struct {
DaysTracked int
Total float64
Streaks int
Breaks int
Skips int
}
// Entries maps DailyHabit{ISO date + habit}: Outcome and log format
type Entries map[DailyHabit]Outcome
type Harsh struct {
Habits []Habit
MaxHabitNameLength int
Entries *Entries
FirstRecords map[Habit]civil.Date
}
func main() {
app := &cli.App{
Name: "Harsh",
Usage: "habit tracking for geeks",
Description: "A simple, minimalist CLI for tracking and understanding habits.",
Version: "0.9.2",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "no-color",
Aliases: []string{"n"},
Usage: "no colors in output",
},
},
Commands: []*cli.Command{
{
Name: "ask",
Aliases: []string{"a"},
Usage: "Asks and records your undone habits",
Action: func(_ *cli.Context) error {
harsh := newHarsh()
harsh.askHabits()
return nil
},
},
{
Name: "todo",
Aliases: []string{"t"},
Usage: "Shows undone habits for today.",
Action: func(_ *cli.Context) error {
harsh := newHarsh()
to := civil.DateOf(time.Now())
undone := harsh.getTodos(to, 0)
heading := ""
if len(undone) == 0 {
fmt.Println("All todos logged up to today.")
} else {
for date, todos := range undone {
color.Bold.Println(date + ":")
for _, habit := range harsh.Habits {
for _, todo := range todos {
if heading != habit.Heading && habit.Heading == todo.Heading {
color.Bold.Printf("\n" + habit.Heading + "\n")
heading = habit.Heading
}
if habit.Name == todo.Name {
fmt.Printf("%*v", harsh.MaxHabitNameLength, todo.Name+"\n")
}
}
}
}
}
return nil
},
},
{
Name: "log",
Aliases: []string{"l"},
Usage: "Shows graph of logged habits",
Action: func(_ *cli.Context) error {
harsh := newHarsh()
to := civil.DateOf(time.Now())
from := to.AddDays(-100)
consistency := map[string][]string{}
undone := harsh.getTodos(to, 0)
sparkline := harsh.buildSpark(from, to)
fmt.Printf("%*v", harsh.MaxHabitNameLength, "")
fmt.Print(strings.Join(sparkline, ""))
fmt.Printf("\n")
heading := ""
for _, habit := range harsh.Habits {
consistency[habit.Name] = append(consistency[habit.Name], harsh.buildGraph(&habit, harsh.FirstRecords[habit], from, to))
if heading != habit.Heading {
color.Bold.Printf(habit.Heading + "\n")
heading = habit.Heading
}
fmt.Printf("%*v", harsh.MaxHabitNameLength, habit.Name+" ")
fmt.Print(strings.Join(consistency[habit.Name], ""))
fmt.Printf("\n")
}
undone_num := strconv.Itoa(len(undone[to.String()]))
scoring := fmt.Sprintf("%.1f", harsh.score(civil.DateOf(time.Now()).AddDays(-1)))
fmt.Printf("\n" + "Yesterday's Score: ")
fmt.Printf("%9v", scoring)
fmt.Printf("%%\n")
if undone_num == "0" {
fmt.Printf("All todos logged for today.")
} else {
fmt.Printf("Today's unlogged todos: ")
fmt.Printf("%2v", undone_num)
}
fmt.Printf("\n")
return nil
},
Subcommands: []*cli.Command{
{
Name: "stats",
Aliases: []string{"s"},
Usage: "Shows habit stats for entire log file",
Action: func(c *cli.Context) error {
harsh := newHarsh()
to := civil.DateOf(time.Now())
// from := to.AddDays(-(365 * 5))
// firstRecords := harsh.firstRecords(from, to)
stats := map[string]HabitStats{}
heading := ""
for _, habit := range harsh.Habits {
if c.Bool("no-color") {
color.Disable()
}
if heading != habit.Heading {
color.Bold.Printf("\n" + habit.Heading + "\n")
heading = habit.Heading
}
stats[habit.Name] = harsh.buildStats(&habit, harsh.FirstRecords[habit], to)
fmt.Printf("%*v", harsh.MaxHabitNameLength, habit.Name+" ")
color.FgGreen.Printf("Streaks ")
color.FgGreen.Printf("%4v", strconv.Itoa(stats[habit.Name].Streaks))
color.FgGreen.Printf(" days")
fmt.Printf("%4v", "")
// if stats[habit.Name].Total == 0 {
// color.FgGray.Printf(" ")
// color.FgGray.Printf("%4v", " ")
// color.FgGray.Printf(" ")
// } else {
// color.FgGray.Printf("Total ")
// color.FgGray.Printf("%4v", (stats[habit.Name].Total))
// color.FgGray.Printf(" ")
// }
// fmt.Printf("%4v", "")
color.FgRed.Printf("Breaks ")
color.FgRed.Printf("%4v", strconv.Itoa(stats[habit.Name].Breaks))
color.FgRed.Printf(" days")
fmt.Printf("%4v", "")
color.FgYellow.Printf("Skips ")
color.FgYellow.Printf("%4v", strconv.Itoa(stats[habit.Name].Skips))
color.FgYellow.Printf(" days")
fmt.Printf("%4v", "")
fmt.Printf("Tracked ")
fmt.Printf("%4v", strconv.Itoa(stats[habit.Name].DaysTracked))
fmt.Printf(" days")
if stats[habit.Name].Total == 0 {
fmt.Printf("%4v", "")
fmt.Printf(" ")
fmt.Printf("%5v", "")
fmt.Printf(" \n")
} else {
fmt.Printf("%4v", "")
color.FgBlue.Printf("Total ")
color.FgBlue.Printf("%5v", (stats[habit.Name].Total))
color.FgBlue.Printf(" \n")
}
}
return nil
},
},
{
Name: "check",
Aliases: []string{"c"},
Usage: "Checks and compares a matched habit against overall sparklines and scoring.",
Action: func(cCtx *cli.Context) error {
harsh := newHarsh()
habit_fragment := cCtx.Args().First()
check := Habit{}
for _, habit := range harsh.Habits {
if strings.Contains(strings.ToLower(habit.Name), strings.ToLower(habit_fragment)) {
check = habit
}
}
to := civil.DateOf(time.Now())
from := to.AddDays(-100)
consistency := map[string][]string{}
sparkline := harsh.buildSpark(from, to)
fmt.Printf("%*v", harsh.MaxHabitNameLength, "")
fmt.Print(strings.Join(sparkline, ""))
fmt.Printf("\n")
consistency[check.Name] = append(consistency[check.Name], harsh.buildGraph(&check, harsh.FirstRecords[check], from, to))
fmt.Printf("%*v", harsh.MaxHabitNameLength, check.Name+" ")
fmt.Print(strings.Join(consistency[check.Name], ""))
fmt.Printf("\n")
fmt.Println(habit_fragment)
return nil
},
},
},
},
},
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func newHarsh() *Harsh {
config := findConfigFiles()
habits, maxHabitNameLength := loadHabitsConfig(config)
entries := loadLog(config)
to := civil.DateOf(time.Now())
from := to.AddDays(-100)
firstRecords := entries.firstRecords(from, to, habits)
return &Harsh{habits, maxHabitNameLength, entries, firstRecords}
}
// Ask function prompts
func (h *Harsh) askHabits() {
to := civil.DateOf(time.Now())
from := to.AddDays(-60)
// Goes back 8 days to check unresolved entries
checkBackDays := 10
// If log file is empty, we onboard the user
// For onboarding, we ask how many days to start tracking from
if len(*h.Entries) == 0 {
checkBackDays = onboard()
for _, habit := range h.Habits {
h.FirstRecords[habit] = to.AddDays(-(checkBackDays + 1))
}
}
dayHabits := h.getTodos(to, checkBackDays)
for dt := from; !dt.After(to); dt = dt.AddDays(1) {
if dayhabit, ok := dayHabits[dt.String()]; ok {
color.Bold.Println(dt.String() + ":")
// Go through habit file ordered habits,
// Check if in returned todos for day and prompt
heading := ""
for _, habit := range h.Habits {
for _, dh := range dayhabit {
if habit.Name == dh.Name && dt.After(h.FirstRecords[habit]) {
if heading != dh.Heading {
color.Bold.Printf("\n" + habit.Heading + "\n")
heading = habit.Heading
}
for {
fmt.Printf("%*v", h.MaxHabitNameLength, habit.Name+" ")
fmt.Print(h.buildGraph(&habit, h.FirstRecords[habit], from, to))
fmt.Printf(" [y/n/s/⏎] ")
reader := bufio.NewReader(os.Stdin)
habitResultInput, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
// No input
if len(habitResultInput) == 1 {
break
}
// Sanitize : colons out of string for log files
habitResultInput = strings.ReplaceAll(habitResultInput, ":", "")
var result, amount, comment string
atIndex := strings.Index(habitResultInput, "@")
hashIndex := strings.Index(habitResultInput, "#")
if atIndex > 0 && hashIndex > 0 && atIndex < hashIndex {
parts := strings.SplitN(habitResultInput, "@", 2)
secondParts := strings.SplitN(parts[1], "#", 2)
result = strings.TrimSpace(parts[0])
amount = strings.TrimSpace(secondParts[0])
comment = strings.TrimSpace(secondParts[1])
}
// only has an @ Amount
if hashIndex == -1 && atIndex > 0 {
parts := strings.SplitN(habitResultInput, "@", 2)
result = strings.TrimSpace(parts[0])
amount = strings.TrimSpace(parts[1])
comment = ""
}
// only has a # comment
if atIndex == -1 && hashIndex > 0 {
parts := strings.SplitN(habitResultInput, "#", 2)
result = strings.TrimSpace(parts[0])
amount = ""
comment = strings.TrimSpace(parts[1])
}
if atIndex == -1 && hashIndex == -1 {
result = strings.TrimSpace(habitResultInput)
}
if strings.ContainsAny(result, "yns") && len(result) == 1 {
writeHabitLog(dt, habit.Name, result, comment, amount)
// Updates the Entries map to get updated buildGraph across days
famount, _ := strconv.ParseFloat(amount, 64)
(*h.Entries)[DailyHabit{dt, habit.Name}] = Outcome{Result: result, Amount: famount, Comment: comment}
break
}
color.FgRed.Printf("%*v", h.MaxHabitNameLength+22, "Sorry! Please choose from")
color.FgRed.Printf(" [y/n/s/⏎] " + "(+ optional @ amounts then # comments)" + "\n")
}
}
}
}
}
}
}
func (e *Entries) firstRecords(from civil.Date, to civil.Date, habits []Habit) map[Habit]civil.Date {
firstRecords := map[Habit]civil.Date{}
for dt := to; !dt.Before(from); dt = dt.AddDays(-1) {
for _, habit := range habits {
if _, ok := (*e)[DailyHabit{Day: dt, Habit: habit.Name}]; ok {
firstRecords[habit] = dt
}
}
}
return firstRecords
}
func (h *Harsh) getTodos(to civil.Date, daysBack int) map[string][]Habit {
tasksUndone := map[string][]Habit{}
dayHabits := map[Habit]bool{}
from := to.AddDays(-daysBack)
for dt := to; !dt.Before(from); dt = dt.AddDays(-1) {
// build map of habit array to make deletions cleaner
// +more efficient than linear search array deletes
for _, habit := range h.Habits {
dayHabits[habit] = true
}
for _, habit := range h.Habits {
if _, ok := (*h.Entries)[DailyHabit{Day: dt, Habit: habit.Name}]; ok {
delete(dayHabits, habit)
}
if dt.Before(h.FirstRecords[habit]) {
delete(dayHabits, habit)
}
}
for habit := range dayHabits {
tasksUndone[dt.String()] = append(tasksUndone[dt.String()], habit)
}
}
return tasksUndone
}
// Consistency graph, sparkline, and scoring functions
func (h *Harsh) buildSpark(from civil.Date, to civil.Date) []string {
sparkline := []string{}
sparks := []string{" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"}
i := 0
for d := from; !d.After(to); d = d.AddDays(1) {
dailyScore := h.score(d)
// divide score into score to map to sparks slice graphic for sparkline
if dailyScore == 100 {
i = 8
} else {
i = int(math.Ceil(dailyScore / float64(100/(len(sparks)-1))))
}
sparkline = append(sparkline, sparks[i])
}
return sparkline
}
func (h *Harsh) buildGraph(habit *Habit, firstRecord civil.Date, from civil.Date, to civil.Date) string {
var graphDay string
var consistency []string
for d := from; !d.After(to); d = d.AddDays(1) {
if outcome, ok := (*h.Entries)[DailyHabit{Day: d, Habit: habit.Name}]; ok {
switch {
case outcome.Result == "y":
graphDay = "━"
case outcome.Result == "s":
graphDay = "•"
// look at cases of "n" being entered but
// within bounds of the habit every x days
case satisfied(d, habit, *h.Entries):
graphDay = "─"
case skipified(d, habit, *h.Entries):
graphDay = "·"
case outcome.Result == "n":
graphDay = " "
}
} else {
if warning(d, habit, *h.Entries, firstRecord) && (to.DaysSince(d) < 14) {
// warning: sigils max out at 2 weeks (~90 day habit in formula)
graphDay = "!"
} else {
graphDay = " "
}
}
consistency = append(consistency, graphDay)
}
return strings.Join(consistency, "")
}
func (h *Harsh) buildStats(habit *Habit, firstRecord civil.Date, to civil.Date) HabitStats {
var streaks, breaks, skips int
var total float64
for d := firstRecord; !d.After(to); d = d.AddDays(1) {
if outcome, ok := (*h.Entries)[DailyHabit{Day: d, Habit: habit.Name}]; ok {
switch {
case outcome.Result == "y":
streaks += 1
case outcome.Result == "s":
skips += 1
// look at cases of "n" being entered but
// within bounds of the habit every x days
case satisfied(d, habit, *h.Entries):
streaks += 1
case skipified(d, habit, *h.Entries):
skips += 1
case outcome.Result == "n":
breaks += 1
}
total += outcome.Amount
}
}
return HabitStats{DaysTracked: int((to.DaysSince(firstRecord)) + 1), Streaks: streaks, Breaks: breaks, Skips: skips, Total: total}
}
func satisfied(d civil.Date, habit *Habit, entries Entries) bool {
if habit.Frequency <= 1 {
return false
}
from := d
to := d.AddDays(-int(habit.Frequency))
for dt := from; !dt.Before(to); dt = dt.AddDays(-1) {
if v, ok := entries[DailyHabit{Day: dt, Habit: habit.Name}]; ok {
if v.Result == "y" {
return true
}
}
}
return false
}
func skipified(d civil.Date, habit *Habit, entries Entries) bool {
if habit.Frequency <= 1 {
return false
}
from := d
to := d.AddDays(-int(habit.Frequency))
for dt := from; !dt.Before(to); dt = dt.AddDays(-1) {
if v, ok := entries[DailyHabit{Day: dt, Habit: habit.Name}]; ok {
if v.Result == "s" {
return true
}
}
}
return false
}
func warning(d civil.Date, habit *Habit, entries Entries, firstRecord civil.Date) bool {
if habit.Frequency < 1 {
return false
}
warningDays := int(habit.Frequency)/7 + 1
to := d
from := d.AddDays(-int(habit.Frequency) + warningDays)
for dt := from; !dt.After(to); dt = dt.AddDays(1) {
if v, ok := entries[DailyHabit{Day: dt, Habit: habit.Name}]; ok {
switch v.Result {
case "y":
return false
case "s":
return false
}
}
if dt.Before(firstRecord) {
return false
}
}
return true
}
func (h *Harsh) score(d civil.Date) float64 {
scored := 0.0
skipped := 0.0
scorableHabits := 0.0
for _, habit := range h.Habits {
if habit.Frequency > 0 && !d.Before(h.FirstRecords[habit]) {
scorableHabits++
if outcome, ok := (*h.Entries)[DailyHabit{Day: d, Habit: habit.Name}]; ok {
switch {
case outcome.Result == "y":
scored++
case outcome.Result == "s":
skipped++
// look at cases of n being entered but
// within bounds of the habit every x days
case satisfied(d, &habit, *h.Entries):
scored++
case skipified(d, &habit, *h.Entries):
skipped++
}
}
}
}
score := 100.0 // deal with scorable habits - skipped == 0 causing divide by zero issue
if scorableHabits-skipped != 0 {
score = (scored / (scorableHabits - skipped)) * 100
}
return score
}
//////////////////////////////////////
// Loading and writing file functions
//////////////////////////////////////
// loadHabitsConfig loads habits in config file ordered slice
func loadHabitsConfig(configDir string) ([]Habit, int) {
file, err := os.Open(filepath.Join(configDir, "/habits"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var heading string
var habits []Habit
for scanner.Scan() {
if len(scanner.Text()) > 0 {
if scanner.Text()[0] == '!' {
result := strings.Split(scanner.Text(), "! ")
heading = result[1]
} else if scanner.Text()[0] != '#' {
result := strings.Split(scanner.Text(), ": ")
r1, _ := strconv.Atoi(result[1])
h := Habit{Heading: heading, Name: result[0], Frequency: Days(r1)}
habits = append(habits, h)
}
}
}
maxHabitNameLength := 0
for _, h := range habits {
if len(h.Name) > maxHabitNameLength {
maxHabitNameLength = len(h.Name)
}
}
return habits, maxHabitNameLength + 10
}
// loadLog reads entries from log file
func loadLog(configDir string) *Entries {
file, err := os.Open(filepath.Join(configDir, "/log"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
entries := Entries{}
for scanner.Scan() {
if len(scanner.Text()) > 0 {
if scanner.Text()[0] != '#' {
// Discards comments from read record read as result[3]
result := strings.Split(scanner.Text(), " : ")
cd, err := civil.ParseDate(result[0])
if err != nil {
fmt.Println("Error parsing log date format.")
}
switch len(result) {
case 5:
if result[4] == "" {
result[4] = "0"
}
amount, err := strconv.ParseFloat(result[4], 64)
if err != nil {
fmt.Println("Error: there is a non-number in your log file where we expect a number.")
}
entries[DailyHabit{Day: cd, Habit: result[1]}] = Outcome{Result: result[2], Comment: result[3], Amount: amount}
case 4:
entries[DailyHabit{Day: cd, Habit: result[1]}] = Outcome{Result: result[2], Comment: result[3], Amount: 0.0}
default:
entries[DailyHabit{Day: cd, Habit: result[1]}] = Outcome{Result: result[2], Comment: "", Amount: 0.0}
}
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return &entries
}
// writeHabitLog writes the log entry for a habit to file
func writeHabitLog(d civil.Date, habit string, result string, comment string, amount string) {
fileName := filepath.Join(configDir, "/log")
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
if _, err := f.Write([]byte(d.String() + " : " + habit + " : " + result + " : " + comment + " : " + amount + "\n")); err != nil {
f.Close() // ignore error; Write error takes precedence
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
// findConfigFile checks os relevant habits and log file exist, returns path
// If they do not exist, calls writeNewHabits and writeNewLog
func findConfigFiles() string {
configDir = os.Getenv("HARSHPATH")
if len(configDir) == 0 {
if runtime.GOOS == "windows" {
configDir = filepath.Join(os.Getenv("APPDATA"), "harsh")
} else {
configDir = filepath.Join(os.Getenv("HOME"), ".config/harsh")
}
}
if _, err := os.Stat(filepath.Join(configDir, "habits")); err == nil {
} else {
welcome(configDir)
}
return configDir
}
// welcome a new user and creates example habits and log files
func welcome(configDir string) {
createExampleHabitsFile(configDir)
createNewLogFile(configDir)
fmt.Println("Welcome to harsh!")
fmt.Println("Created " + filepath.Join(configDir, "/habits") + " This file lists your habits.")
fmt.Println("Created " + filepath.Join(configDir, "/log") + " This file is your habit log.")
fmt.Println("")
fmt.Println("No habits of your own yet?")
fmt.Println("Open your habits file @ " + filepath.Join(configDir, "/habits"))
fmt.Println("with a text editor (nano, vim, VS Code, Atom, emacs) and modify and save the habits list.")
fmt.Println("Then:")
fmt.Println("Run harsh ask to start tracking")
fmt.Println("Running harsh todo will show you undone habits for today.")
fmt.Println("Running harsh log will show you a consistency graph of your efforts.")
fmt.Println(" (the graph gets way cooler looking over time.")
fmt.Println("For more depth, you can read https://github.com/wakatara/harsh#usage")
fmt.Println("")
fmt.Println("Happy tracking! I genuinely hope this helps you with your goals. Buena suerte!")
os.Exit(0)
}
// first time ask is used and log empty asks user how far back to track
func onboard() int {
fmt.Println("Your log file looks empty. Let's setup your tracking.")
fmt.Println("How many days back shall we start tracking from in days?")
fmt.Println("harsh will ask you about each habit for every day back.")
fmt.Println("Starting today would be 0. Choose. (0-7) ")
var numberOfDays int
for {
reader := bufio.NewReader(os.Stdin)
dayResult, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
dayResult = strings.TrimSpace(dayResult)
dayNum, err := strconv.Atoi(dayResult)
if err == nil {
if dayNum >= 0 && dayNum <= 7 {
numberOfDays = dayNum
break
}
}
color.FgRed.Printf("Sorry! Please choose a valid number (0-7) ")
}
return numberOfDays
}
// createExampleHabitsFile writes a fresh Habits file for people to follow
func createExampleHabitsFile(configDir string) {
fileName := filepath.Join(configDir, "/habits")
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
if _, err := os.Stat(configDir); os.IsNotExist(err) {
os.MkdirAll(configDir, os.ModePerm)
}
f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
f.WriteString("# This is your habits file.\n")
f.WriteString("# It tells harsh what to track and how frequently.\n")
f.WriteString("# 1 means daily, 7 means weekly, 14 every two weeks.\n")
f.WriteString("# 0 is for tracking a habit. 0 frequency habits will not warn or score.\n")
f.WriteString("# Examples:\n\n")
f.WriteString("Gymmed: 2\n")
f.WriteString("Bed by midnight: 1\n")
f.WriteString("Cleaned House: 7\n")
f.WriteString("Called Mom: 7\n")
f.WriteString("Tracked Finances: 15\n")
f.WriteString("New Skill: 90\n")
f.WriteString("Too much coffee: 0\n")
f.WriteString("Used harsh: 0\n")
f.Close()
}
}
// createNewLogFile writes an empty log file for people to start tracking into
func createNewLogFile(configDir string) {
fileName := filepath.Join(configDir, "/log")
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
if _, err := os.Stat(configDir); os.IsNotExist(err) {
os.MkdirAll(configDir, os.ModePerm)
}
_, err := os.OpenFile(fileName, os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
}
}