-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
309 lines (287 loc) · 7.06 KB
/
main.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
package main
import (
"bytes"
"encoding/binary"
"encoding/gob"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"time"
)
const (
bufSize = 16 * 1024
sunDataDir = ".sun.d"
sunDataFileExtension = ".sun"
tagPrefix = "@"
dateFormat = "2006-01-02"
weekdayFormat = "Mon"
timeFormat = "15:04:05"
dateDivider = "\t ---\t ----------\t --------\t \t \t"
rowFormat = "\t %s\t %s\t %s\t %s\t %s\t"
)
var (
ErrInsufficientSize = errors.New("buffer is to small")
ErrFileCorrupt = errors.New("corrupt file")
Version string
CommitHash string
)
type entry struct {
Note string
CreatedAt time.Time
Tags []string
}
type entryReader struct {
toProcess []byte
}
func NewReader(r io.Reader) (*entryReader, error) {
buf, err := ioutil.ReadAll(r)
if err != nil {
return &entryReader{}, err
}
return &entryReader{toProcess: buf}, nil
}
func (reader *entryReader) Read() (*entry, error) {
if len(reader.toProcess) == 0 {
return &entry{}, io.EOF
}
sizeSizePos := len(reader.toProcess) - 1
sizeSize := reader.toProcess[sizeSizePos]
sansSizeSize := reader.toProcess[:sizeSizePos]
varintStart := len(sansSizeSize) - int(sizeSize)
if varintStart < 0 {
return &entry{}, io.EOF
}
gobStart, err := readGobStart(sansSizeSize, varintStart)
if err != nil {
return &entry{}, err
}
if gobStart < 0 {
return &entry{}, io.EOF
}
sansSize := sansSizeSize[gobStart:varintStart]
result, err := decode(sansSize)
reader.toProcess = reader.toProcess[:gobStart]
return result, err
}
func readGobStart(slice []byte, varIntStart int) (int, error) {
slice = slice[varIntStart:]
dec, n := binary.Uvarint(slice)
if n <= 0 {
return 0, ErrFileCorrupt
}
gobStart := varIntStart - int(dec)
return gobStart, nil
}
func decode(slice []byte) (*entry, error) {
rr := bytes.NewReader(slice)
decoder := gob.NewDecoder(rr)
var result entry
err := decoder.Decode(&result)
if err != nil {
return &entry{}, err
}
return &result, nil
}
func (entry *entry) Write(w io.Writer) error {
var buf bytes.Buffer
size, err := writeGob(&buf, entry)
if err != nil {
return err
}
n, err := writeSize(&buf, size)
if err != nil {
return err
}
if err := writeSizeSize(&buf, n); err != nil {
return err
}
_, err = w.Write(buf.Bytes())
return err
}
func writeSizeSize(buf *bytes.Buffer, sizeSize int) error {
if written, errwr := buf.Write([]byte{byte(sizeSize)}); errwr != nil {
return errwr
} else if written != 1 {
return ErrInsufficientSize
}
return nil
}
func writeSize(buf *bytes.Buffer, size uint64) (int, error) {
lenBuf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(lenBuf, size)
reduced := lenBuf[:n]
if _, errwr := buf.Write(reduced); errwr != nil {
return 0, errwr
}
return n, nil
}
func writeGob(buf *bytes.Buffer, entry *entry) (uint64, error) {
enc := gob.NewEncoder(buf)
err := enc.Encode(entry)
size := uint64(buf.Len())
return size, err
}
func ensureDataDir() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
dataDir := filepath.Join(home, sunDataDir)
err = os.MkdirAll(dataDir, 0700)
if err != nil {
return "", err
}
return dataDir, nil
}
func openDataFile(dataDir string) (*os.File, error) {
filename, err := calculateFilename(dataDir)
if err != nil {
return nil, err
}
f, err := os.OpenFile(filename, os.O_RDONLY, 0600)
if err != nil {
log.Fatalf("could not open file %v", err)
}
fileInf, errrr := f.Stat()
if errrr != nil {
log.Fatalf("could not stat file %v", errrr)
}
if bufSize < fileInf.Size() {
_, errr := f.Seek(-1*bufSize, io.SeekEnd)
if errr != nil {
log.Fatalf("could not seek in file %v", errr)
}
}
return f, nil
}
func printLastEntries(dataDir string) {
f, err := openDataFile(dataDir)
if err != nil {
return
}
defer f.Close()
er, err := NewReader(f)
if err != nil {
log.Fatalf("could not create entry reader %v", err)
}
writeTable(er)
}
func writeTable(er *entryReader) {
w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', tabwriter.Debug)
prevDate := ""
dayCounter := 0
for entry, err := er.Read(); err != io.EOF && dayCounter < 2; entry, err = er.Read() {
prevDate, dayCounter = writeRow(w, entry, prevDate, dayCounter)
}
w.Flush()
}
func writeRow(w *tabwriter.Writer, entry *entry, prevDate string, dayCount int) (string, int) {
nextDayCount := dayCount
curDate := entry.CreatedAt.Format(dateFormat)
if prevDate == "" {
prevDate = curDate
}
if prevDate != curDate {
fmt.Fprintln(w, dateDivider)
nextDayCount++
}
fmt.Fprintln(
w,
fmt.Sprintf(
rowFormat,
entry.CreatedAt.Format(weekdayFormat),
curDate,
entry.CreatedAt.Format(timeFormat),
strings.Join(entry.Tags, " "),
entry.Note))
return curDate, nextDayCount
}
func writeNewEntry(dataDir string, args []string) {
filename := calculateSunFilename(dataDir, time.Now().Year())
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatalf("could not open file %f", err)
}
defer f.Close()
entry := convertArgsToEntry(args)
err = entry.Write(f)
if err != nil {
log.Fatalf("could not write entry %v", err)
}
}
func calculateSunFilename(dataDir string, year int) string {
return filepath.Join(
dataDir,
fmt.Sprintf(
"%d%s",
year,
sunDataFileExtension))
}
func calculateFilename(dataDir string) (string, error) {
currentYear := time.Now().Year()
filename := calculateSunFilename(dataDir, currentYear)
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
previousYear := currentYear - 1
filename = calculateSunFilename(dataDir, previousYear)
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
return "", err
}
return filename, nil
}
return filename, nil
}
func convertArgsToEntry(args []string) entry {
tags := make([]string, 0, len(args))
nonTagfields := make([]string, 0, len(args))
for _, arg := range args {
for _, field := range strings.Fields(arg) {
if strings.HasPrefix(field, tagPrefix) {
tags = append(tags, strings.TrimPrefix(field, tagPrefix))
} else {
nonTagfields = append(nonTagfields, field)
}
}
}
sort.Strings(tags)
note := strings.Join(nonTagfields, " ")
entry := entry{Note: note, Tags: tags, CreatedAt: time.Now()}
return entry
}
func usage() {
fmt.Fprintf(
flag.CommandLine.Output(),
"Usage of %s: [option] [sentence describing activity to note, words beginning with an @ are taken to be tags]\n",
os.Args[0])
fmt.Fprintln(
flag.CommandLine.Output(),
"If no arguments are given, a table with the latest notes is shown.")
flag.PrintDefaults()
}
func main() {
showVersion := false
flag.Usage = usage
flag.BoolVar(&showVersion, "version", false, "show version and exit")
flag.BoolVar(&showVersion, "v", false, "show version and exit")
flag.Parse()
if showVersion {
fmt.Println(os.Args[0], " version: ", Version, CommitHash)
os.Exit(0)
}
dataDir, err := ensureDataDir()
if err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 {
writeNewEntry(dataDir, os.Args[1:])
} else {
printLastEntries(dataDir)
}
}