wtt/work.go
work.goRaw
1package main
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io/ioutil"
8 "os"
9 "strconv"
10 "time"
11
12 "github.com/fatih/color"
13)
14
15type Project struct {
16 Name string `json:"name"`
17 Streaks []Streak `json:"streaks"`
18}
19type Streak struct {
20 Start time.Time `json:"start"`
21 End time.Time `json:"end"`
22 Duration time.Duration `json:"duration"`
23 Description string `json:"description"`
24}
25type Work struct {
26 Projects []Project `json:"projects"`
27 CurrentProjectName string `json:"currentProjectName"`
28}
29
30var work Work
31
32func readProjects() {
33 file, err := ioutil.ReadFile(filePath)
34 if err != nil {
35 //file not exists, create directory and file
36 color.Yellow(directoryPath + " not exists, creating directory")
37 _ = os.Mkdir(directoryPath, os.ModePerm)
38 saveWork()
39 }
40 content := string(file)
41 json.Unmarshal([]byte(content), &work)
42}
43
44func saveWork() {
45
46 jsonProjects, err := json.Marshal(work)
47 check(err)
48 err = ioutil.WriteFile(filePath, jsonProjects, 0644)
49 check(err)
50}
51func getProjectIByName(name string) int {
52 for i, project := range work.Projects {
53 if project.Name == name {
54 return i
55 }
56 }
57 return -1
58}
59func projectExist(name string) bool {
60 for _, project := range work.Projects {
61 if project.Name == name {
62 return true
63 }
64 }
65 return false
66}
67func newProject(name string) error {
68 //first, check if the project name is not taken yet
69 if projectExist(name) {
70 color.Red("Project name: " + name + ", already exists")
71 return errors.New("project name already exist")
72 }
73 var newProject Project
74 newProject.Name = name
75 work.Projects = append(work.Projects, newProject)
76 return nil
77}
78func listProjects() {
79 fmt.Println("")
80 fmt.Println("")
81 fmt.Println("Listing projects")
82 fmt.Println("")
83 for k, project := range work.Projects {
84 fmt.Println("project " + strconv.Itoa(k))
85 fmt.Print("name: ")
86 color.Blue(project.Name)
87 for k2, streak := range project.Streaks {
88 fmt.Println(" streak: " + strconv.Itoa(k2))
89 fmt.Print(" Start:")
90 fmt.Println(streak.Start)
91 fmt.Print(" End:")
92 fmt.Println(streak.End)
93 fmt.Print(" Duration:")
94 fmt.Println(streak.Duration)
95 }
96 fmt.Println("")
97 }
98}