Sfoglia il codice sorgente

~/.bin/working-time.go: Track how long I work each day

Lu Stadler 7 anni fa
parent
commit
dc5c0770a4
2 ha cambiato i file con 79 aggiunte e 1 eliminazioni
  1. 4 1
      .bin/Makefile
  2. 75 0
      .bin/working-time.go

+ 4 - 1
.bin/Makefile

@ -1,4 +1,4 @@
1
all: rn since timely up ydl
1
all: rn since timely up working-time ydl
2 2
3 3
rn: rn.go
4 4
	go build $<
@ -12,5 +12,8 @@ timely: timely.go
12 12
up: up.c
13 13
	clang -Wall -o up up.c
14 14
15
working-time: working-time.go
16
	go build working-time.go
17
15 18
ydl: ydl.go
16 19
	go build ydl.go

+ 75 - 0
.bin/working-time.go

@ -0,0 +1,75 @@
1
// Command working-time tracks how much time you've spent working today.
2
//
3
// It doesn't do anything fancy, it just notes when you've logged in today,
4
// and then tracks how much time has passed since then.
5
package main
6
7
import (
8
	"encoding/json"
9
	"fmt"
10
	"os"
11
	"path"
12
	"time"
13
)
14
15
// Day contains information about how long you've worked today.
16
type Day struct {
17
	Start time.Time `json:"start"`
18
}
19
20
// modes:
21
//  - no such file or directory => record start
22
//  - start is not today => record start
23
//
24
// after, log time since start
25
26
func main() {
27
	dayFile := path.Join(os.Getenv("HOME"), ".cache/working-day.json")
28
	now := time.Now()
29
	day := readDay(dayFile)
30
31
	if day.Start.Day() != now.Day() {
32
		day = Day{Start: now}
33
		writeDay(dayFile, day)
34
	}
35
36
	dur := time.Since(day.Start)
37
	hours := dur.Hours()
38
	minutes := dur.Minutes() - float64(int(hours)*60)
39
	fmt.Printf("%d:%02d\n", int(hours), int(minutes))
40
}
41
42
func readDay(path string) Day {
43
	f, err := os.Open(path)
44
	if err != nil {
45
		fmt.Fprintln(os.Stderr, err)
46
		return Day{Start: time.Now()}
47
	}
48
	defer f.Close()
49
50
	var day Day
51
	dec := json.NewDecoder(f)
52
	err = dec.Decode(&day)
53
	if err != nil {
54
		fmt.Println("invalid json")
55
		os.Exit(1)
56
	}
57
58
	return day
59
}
60
61
func writeDay(path string, day Day) {
62
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640)
63
	if err != nil {
64
		fmt.Println("write error")
65
		os.Exit(1)
66
	}
67
	defer f.Close()
68
69
	enc := json.NewEncoder(f)
70
	err = enc.Encode(day)
71
	if err != nil {
72
		fmt.Println("write error")
73
		os.Exit(1)
74
	}
75
}