-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.go
117 lines (94 loc) · 2.07 KB
/
file.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
package goc
import (
"encoding/json"
"io"
"log"
"os"
"time"
)
const SHARED_PATH = "/goc_cli"
const FILE_NAME = "/data.json"
type FileData struct {
CalendarId string
CurrentTask DataTask
TaskAlias map[string]string
DurationToday time.Duration
CurrentDate CurDate
StatusOneline bool
UpdateToken TokenStatus
Jira *JiraAuth
}
func (f *FileData) GetDurationToday(force bool) time.Duration {
if !force {
year, month, day := time.Now().Date()
date := f.CurrentDate
if date.Year == year && date.Month == month && date.Day == day {
return f.DurationToday // updated on new events to cal
}
}
client, source := GetClient()
updateTotalDuration(client, f)
updateToken(source)
writeToFile(f)
return f.DurationToday
}
type JiraAuth struct {
Username string
Token string
}
type TokenStatus struct {
DayNumber int
Done bool
}
type CurDate struct {
Year int
Month time.Month
Day int
}
type DataTask struct {
Name string
Start string
}
func (f *DataTask) Reset() {
f.Name = ""
f.Start = ""
}
func getSharedPath() string {
configPath, err := os.UserConfigDir()
if err != nil {
log.Fatalf("unable to get userConfigDir: %v", err)
}
sharedPath := configPath + SHARED_PATH
return sharedPath
}
func getFilePath() string {
commonPath := getSharedPath()
fullFilePath := commonPath + FILE_NAME
return fullFilePath
}
func readFile() *FileData {
filepath := getFilePath()
f, err := os.OpenFile(filepath, os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
log.Fatalf("unable to read/create file: %v", err)
}
defer f.Close()
data := &FileData{}
err = json.NewDecoder(f).Decode(data)
if err != nil && err != io.EOF {
log.Fatalf("unable to decode data from file: %v", err)
}
return data
}
func writeToFile(data *FileData) {
filepath := getFilePath()
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
log.Fatalf("unable to write/create file: %v", err)
}
defer f.Close()
err = json.NewEncoder(f).Encode(data)
if err != nil {
log.Fatalf("unable to encode data to file: %v", err)
}
}