/
TimeKeeper.go
881 lines (802 loc) · 19.3 KB
/
TimeKeeper.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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
package main
//
// Program: TimeKeeper.go
//
// Description: This program runs the feedback logic for selecting the on/off state for
// the currently timed project.
//
//
// Import the libraries we use for this program.
//
import (
"fmt"
"github.com/raguay/goAlfred"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"time"
)
//
// Setup and constants that are used.
//
// MAXPROJECTS This is the maximum number of projects allowed.
// TSDir This keeps the directory name for the time sheets. It is a complete path.
//
const (
MAXPROJECTS int = 20
)
var TSDir = ""
//
// Function: main
//
// Description: This is the main function for the TimeKeeper program. It takes the command line
// and parses it for the proper functionality.
//
func main() {
if len(os.Args) > 1 {
switch os.Args[1][0] {
case 'm':
//
// atk:month
//
SystemViewMonth()
case 'l':
//
// atk:lastmonth
//
SystemViewLastMonth()
case 'w':
//
// atk:week
//
SystemViewWeek()
case 't':
//
// atk:current
//
SystemViewDate()
case 'r':
//
// atk:remove
//
RemoveProject()
case 'c':
//
// atk:project
//
ChangeProject()
case 'b':
//
// atk:current
//
SystemViewDay()
case 'a':
//
// atk:addproject
//
AddProject()
case 'o':
//
// atk:state
//
StopStart()
case 'p':
//
// Used for atk:project script filter
//
project()
case 'T':
//
// atk:time
//
SystemAllProjects()
case 's':
fallthrough
default:
//
// Used for the script filter on atk:state
//
state()
}
}
}
//
// Function: getTimeSheetDir
//
// Description: This function is used to cache a copy of the time
// sheet directory and give it in the return.
//
func getTimeSheetDir() string {
if strings.Contains("", TSDir) {
Filename := goAlfred.Data() + "/dir.txt"
buf, err := ioutil.ReadFile(Filename)
if err == nil {
//
// Convert the directory path to a string and trim it.
//
TSDir = strings.TrimSpace(string(buf))
} else {
//
// The Directory has not been set. Make it the default location.
//
TSDir = goAlfred.Data()
err = ioutil.WriteFile(Filename, []byte(TSDir), 0666)
}
}
//
// Return the directory to the time sheets.
//
return (TSDir)
}
//
// Function: SystemAllProjects
//
// Description: This function will display to the terminal the time for all projects on
// the day given on the command line next.
//
func SystemAllProjects() {
//
// Get the current date in case there isn't one on the command line.
//
tm := time.Now()
if len(os.Args) > 2 {
if strings.Contains("today", os.Args[2]) {
//
// Today's date.
//
tm = time.Now()
} else if strings.Contains("yesterday", os.Args[2]) {
//
// Yesterday is today minus one day.
//
tm = time.Now()
tm = tm.AddDate(0, 0, -1)
} else {
//
// Parse the date string given.
//
tm, _ = time.Parse("2006-Jan-02", os.Args[2])
}
}
//
// Get the list of project names.
//
proj := GetListOfProjects()
//
// For each project, get the time spent on it for the given day.
//
numproj := len(proj) - 1
for i := 0; i < numproj; i++ {
fmt.Printf("%s: %s\n", proj[i], formatTimeString(GetTimeAtDate(proj[i], tm)))
}
}
//
// Function: SystemViewMonth
//
// Description: This function will calculate the time the current month for all the projects.
//
func SystemViewMonth() {
//
// Get the current project.
//
currentProject := GetCurrentProject()
//
// Get the time on that project for this month. The current time gives the current month.
//
now := time.Now()
year, month, _ := now.Date()
tm := GetTimeAtMonth(currentProject, year, month)
//
// format the time string and print it out.
//
fmt.Print(formatTimeString(tm))
}
//
// Function: SystemViewLastMonth
//
// Description: This function will calculate the time last
// month for the current project.
//
func SystemViewLastMonth() {
//
// Get the current project.
//
currentProject := GetCurrentProject()
//
// Get the time on that project for this month. The current time gives the current month.
//
now := time.Now()
year, month, _ := now.Date()
month = month - 1
tm := GetTimeAtMonth(currentProject, year, month)
//
// format the time string and print it out.
//
fmt.Print(formatTimeString(tm))
}
//
// Function: GetTimeAtMonth
//
// Description: This function will take a project and calculate
// the time spent on that project for a particular
// month.
//
func GetTimeAtMonth(project string, year int, month time.Month) int64 {
tm := int64(0)
dateStart := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
dateEnd := time.Date(year, month, 32, 0, 0, 0, 0, time.UTC)
lastDay := 32 - dateEnd.Day()
//
// Get the time added up for the whole month.
//
for i := 0; i < lastDay; i++ {
tm += GetTimeAtDate(project, dateStart.AddDate(0, 0, i))
}
//
// Return the amount of time calculated.
//
return (tm)
}
//
// Function: SystemViewWeek
//
// Description: This function will calculate the time the current week for all the projects.
//
// Inputs:
// variable description
//
func SystemViewWeek() {
currentProject := GetCurrentProject()
tm := GetTimeAtWeek(currentProject, time.Now())
fmt.Print(formatTimeString(tm))
}
//
// Function: GetTimeAtDate
//
// Description: This function will take a project and calculate the time spent
// on that project for a particular date.
//
func GetTimeAtWeek(project string, date time.Time) int64 {
tm := int64(0)
dateStart := date
dateEnd := date
switch date.Weekday() {
case 0:
{
dateEnd = dateEnd.AddDate(0, 0, 6)
}
case 1:
{
dateStart = dateStart.AddDate(0, 0, -1)
dateEnd = dateEnd.AddDate(0, 0, 5)
}
case 2:
{
dateStart = dateStart.AddDate(0, 0, -2)
dateEnd = dateEnd.AddDate(0, 0, 4)
}
case 3:
{
dateStart = dateStart.AddDate(0, 0, -3)
dateEnd = dateEnd.AddDate(0, 0, 3)
}
case 4:
{
dateStart = dateStart.AddDate(0, 0, -4)
dateEnd = dateEnd.AddDate(0, 0, 2)
}
case 5:
{
dateStart = dateStart.AddDate(0, 0, -5)
dateEnd = dateEnd.AddDate(0, 0, 1)
}
case 6:
{
dateStart = dateStart.AddDate(0, 0, -6)
}
}
//
// Get the time added up for th whole week.
//
for i := 0; i < 7; i++ {
tm += GetTimeAtDate(project, dateStart.AddDate(0, 0, i))
}
return (tm)
}
//
// Function: SystemViewDate
//
// Description: This function will calculate the time for projects at a certain date.
//
func SystemViewDate() {
currentProject := GetCurrentProject()
tm := GetTimeAtDate(currentProject, time.Now())
fmt.Print(formatTimeString(tm))
}
//
// function: SystemViewDay
//
// Description: This function is for displaying a nice time for the current project.
//
func SystemViewDay() {
currentProject := GetCurrentProject()
tm := GetTimeAtDate(currentProject, time.Now())
ctime := formatTimeString(tm)
state := GetCurrentState()
fmt.Printf("The current time on %s is %s. Current state is %s.", currentProject, ctime, state)
}
//
// Function: GetTimeAtDate
//
// Description: This function will take a project and calculate the time spent
// on that project for a particular date.
//
func GetTimeAtDate(project string, date time.Time) int64 {
//
// Get the current project.
//
filename := generateTimeLogFileName(project, date)
tm := readDayTime(filename)
return tm
}
//
// Function: formatTimeString
//
// Description: This function takes the number of seconds and returns a string
// in hour:minute:seconds format with zero padding.
//
// Input:
// tm time in seconds (an int64)
//
func formatTimeString(tm int64) string {
min := int(tm / 60)
sec := tm - int64(min*60)
hr := min / 60
min = min - (hr * 60)
return fmt.Sprintf("%02d:%02d:%02d", hr, min, sec)
}
//
// Function: readDayTime
//
// Description: This function reads a time sheet file and calculates the time
// represented in that file.
func readDayTime(filename string) int64 {
buf, _ := ioutil.ReadFile(filename)
times := regexp.MustCompile("\n|\r").Split(string(buf), -1)
//
// Loop through all the time lines.
//
tmwork := int64(0)
firsttime := int64(0)
first := false
for i := 0; i < len(times); i++ {
if !strings.Contains("", times[i]) {
//
// Split by colon to time and action.
//
parts := strings.Split(times[i], ":")
if strings.Contains("start", parts[1]) {
firsttime, _ = strconv.ParseInt(parts[0], 10, 64)
first = true
} else {
tm, _ := strconv.ParseInt(parts[0], 10, 64)
tmwork += tm - firsttime
first = false
}
}
}
//
// If a start was the last thing processed, that means it is still being timed. Get the
// current time to see the overall time. firsttime is the time stamp when the start
// was given.
//
if first {
currentTime := time.Now()
ctime := currentTime.Unix()
tmwork += ctime - firsttime
}
//
// Return the final Time.
//
return tmwork
}
//
// Function: RemoveProject
//
// Description: This function will remove a project from the list a valid projects.
//
func RemoveProject() {
//
// Get the project name from the command line.
//
proj := GetCommandLineString()
//
// Get the list of project names.
//
projects := GetListOfProjects()
//
// Open the projects file in truncation mode to remove all the old stuff.
//
Filename := getTimeSheetDir() + "/projects.txt"
Fh, err := os.OpenFile(Filename, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
//
// The file would not open. Error out.
//
fmt.Print("Could not open the projects file: ", Filename, "\n")
os.Exit(1)
}
//
// Loop through all the projects.
//
for i := 0; i < len(projects); i++ {
if !strings.Contains(proj, projects[i]) {
//
// It is not the project to be removed. Put it into the file.
//
Fh.WriteString(projects[i] + "\n")
}
}
//
// Close the file.
//
Fh.Close()
//
// Tell the user that the project has been removed.
//
fmt.Print(proj + " has been removed!")
}
//
// Function: ChangeProject
//
// Description: This function will change the currently active project. If the old
// project was started, it will stop it first, then set the new project
// and start it.
//
func ChangeProject() {
//
// Get the project name from the command line.
//
proj := GetCommandLineString()
//
// Change to the specified project.
//
ChangeNamedProject(proj)
}
func ChangeNamedProject(proj string) {
//
// Get the current project.
//
currentProject := GetCurrentProject()
//
// Stop the current project.
//
StopStartProject(currentProject, "stop")
//
// Save the new project to the data file.
//
SaveProject(proj)
//
// Start the new project.
//
StopStartProject(proj, "start")
//
// Tell the user it is started.
//
fmt.Print("The current project is now " + proj + " and is started.")
}
//
// Function: GetCommandLineString
//
// Description: This function is used to get the after the function if there is one.
// If not, then just return nothing.
//
func GetCommandLineString() string {
//
// See if we have any input other then the command.
//
clstring := ""
if len(os.Args) > 2 {
clstring = strings.TrimSpace(os.Args[2])
}
//
// Return the the string.
//
return (clstring)
}
//
// Function: AddProject
//
// Description: This function will add a new project to the list of current projects.
//
func AddProject() {
//
// Get the project name from the command line.
//
proj := GetCommandLineString()
//
// Create the file name that contains all the projects.
//
projectFile := getTimeSheetDir() + "/projects.txt"
Fh, err := os.OpenFile(projectFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
Fh, err = os.Create(projectFile)
if err != nil {
//
// The file would not open. Error out.
//
fmt.Print("Could not open the projects file: ", projectFile, "\n")
os.Exit(1)
}
}
//
// Write the new command with the time stamp to the buffer.
//
_, err = io.WriteString(Fh, proj+"\n")
//
// Lose the file.
//
Fh.Close()
//
// Make it the new current project.
//
ChangeNamedProject(proj)
//
// Tell the user that the project is added.
//
fmt.Print("Added project " + proj + " to the list.")
}
//
// Function: state
//
// Description: This function gives the proper output for changing the state. The state
// first is the one opposite from the current state.
//
func state() {
//
// Get the last state of the current project.
//
stateFile := getTimeSheetDir() + "/laststate.txt"
buf, _ := ioutil.ReadFile(stateFile)
curState := string(buf)
//
// Set the first command to the opposite of the current state. That way
// the user simply pushes return to toggle states.
//
if strings.Contains(curState, "start") {
goAlfred.AddResult("stop", "stop", "stop", "", "icon.png", "yes", "", "")
goAlfred.AddResult("start", "start", "start", "", "icon.png", "yes", "", "")
} else {
goAlfred.AddResult("start", "start", "start", "", "icon.png", "yes", "", "")
goAlfred.AddResult("stop", "stop", "stop", "", "icon.png", "yes", "", "")
}
//
// Print out the xml string.
//
fmt.Print(goAlfred.ToXML())
}
//
// Function: project
//
// Description: This function creates a list of the projects and displays the ones
// similar to the input.
//
func project() {
//
// Get the project name from the command line.
//
proj := GetCommandLineString()
//
// Set our default string.
//
goAlfred.SetDefaultString("Alfred Time Keeper: Sorry, no match...")
//
// Get the latest project.
//
latestproject := GetCurrentProject()
//
// Get the list of projects.
//
projects := make([]string, MAXPROJECTS)
projects = GetListOfProjects()
//
// The regexp split statement gives one string more than was split out. The last
// string is a catchall. It does not need to be included.
//
numproj := len(projects) - 1
//
// For each project, create a result line. Show all put the current project.
//
for i := 0; i < numproj; i++ {
if !strings.Contains(projects[i], latestproject) || (latestproject == "") {
goAlfred.AddResultsSimilar(proj, projects[i], projects[i], projects[i], "", "icon.png", "yes", "", "")
}
}
//
// Print out the xml string.
//
fmt.Print(goAlfred.ToXML())
}
//
// Function: GetListOfProjects
//
// Description: This function will return an array of string with the names of the project.
//
func GetListOfProjects() []string {
//
// Create the projects array and populate it.
//
projectFile := getTimeSheetDir() + "/projects.txt"
buf, _ := ioutil.ReadFile(projectFile)
//
// Split out the different project names into separate strings.
//
return (regexp.MustCompile("\n|\r").Split(string(buf), -1))
}
//
// Function: StopStart
//
// Description: This will place a start or stop time stamp for the current project and
// current date.
//
func StopStart() {
//
// See if we have any input other then the command. If not, assume a stop command.
//
cmd := "stop"
if len(os.Args) > 2 {
cmd = strings.ToLower(os.Args[2])
}
//
// Get the current project.
//
currentProject := GetCurrentProject()
//
// Run the appropriate function and print the results.
//
fmt.Print(StopStartProject(currentProject, cmd))
}
//
// Function: GetCurrentProject
//
// Description: This function will retrieve the current project from the
// state file.
//
func GetCurrentProject() string {
//
// Get the current project.
//
Filename := getTimeSheetDir() + "/project.txt"
buf, _ := ioutil.ReadFile(Filename)
//
// Convert the current project to a string, trim it, and return it.
//
return (strings.TrimSpace(string(buf)))
}
//
// Function: SaveProject
//
// Description: This function will save the given project name to the
// current project file.
//
// Inputs:
// proj Name of the new project
//
func SaveProject(proj string) {
//
// Write the new project.
//
Filename := getTimeSheetDir() + "/project.txt"
err := ioutil.WriteFile(Filename, []byte(proj), 0666)
if err != nil {
fmt.Print("Can not write the project file: " + Filename)
os.Exit(1)
}
}
//
// Function: StopStartProject
//
// Description: This function is used to set the state for the given project.
//
// Inputs:
// currentProject The project to effect the state of.
// cmd The start or stop command.
//
func StopStartProject(currentProject string, cmd string) string {
//
// Setup the result string.
//
resultStr := ""
currentState := GetCurrentState()
//
// Is the current state the same as the new state?
//
if strings.Contains(cmd, currentState) {
//
// It is already in that state. Do nothing, but give a message.
//
resultStr = "Already " + cmd + "\n"
} else {
//
// Okay, we can proceed with writing the new state into the
// dated project file. Open the file for writing.
//
currentTime := time.Now()
Filename := generateTimeLogFileName(currentProject, currentTime)
Fh, err := os.OpenFile(Filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
//
// The file would not open. Error out.
//
fmt.Print("Could not open the dated project file: ", Filename, "\n")
os.Exit(1)
}
//
// Write the new command with the time stamp to the buffer.
//
str := fmt.Sprintf("%d:%s\n", currentTime.Unix(), cmd)
_, err = io.WriteString(Fh, str)
//
// Lose the file.
//
Fh.Close()
//
// Write the laststate file with the new state.
//
ioutil.WriteFile(getTimeSheetDir()+"/laststate.txt", []byte(cmd), 0666)
//
// Tell the user it is set.
//
resultStr = currentProject + " is now " + cmd
}
//
// Return the resulting string.
//
return (resultStr)
}
//
// function: GetCurrentState
//
// Description: This function gets the current state of the project.
//
func GetCurrentState() string {
//
// Get the current state.
//
Filename := getTimeSheetDir() + "/laststate.txt"
buf, err := ioutil.ReadFile(Filename)
currentState := "stop"
if err == nil {
//
// Convert the current project to a string and trim it.
//
currentState = strings.TrimSpace(string(buf))
} else {
//
// The current state is stop if the file does not exist. Create the file
// with that state.
//
err = ioutil.WriteFile(Filename, []byte(currentState), 0666)
}
return currentState
}
//
// Function: generateTimeLogFileName
//
// Description: This functions creates the time log file based on the project name and
// date.
//
// Inputs:
// proj Name of the project
// dt Date in question
//
func generateTimeLogFileName(proj string, dt time.Time) string {
//
// Generate the proper file name based on the project name and date.
//
filename := getTimeSheetDir() + "/" + proj + "_" + dt.Format("2006-01-02") + ".txt"
return (filename)
}