-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (89 loc) · 2.24 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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path"
"github.com/xanzy/go-gitlab"
"golang.org/x/time/rate"
)
const (
rateLimitR = rate.Limit(2)
rateLimitB = 1
)
type Config struct {
BaseURL string `json:"base_url"`
Token string `json:"token"`
UserID int `json:"user_id"`
ProjectIDs []int `json:"project_ids"`
}
func main() {
var _ Gitlab = (*XanzyGitlab)(nil)
homePath, err := os.UserConfigDir()
must(err)
config, err := loadConfig(path.Join(homePath, "glnotify", "config.json"))
must(err)
statePath := path.Join(homePath, "glnotify", "state.json")
state, err := loadState(statePath)
must(err)
client, err := gitlab.NewClient(
config.Token,
gitlab.WithBaseURL(config.BaseURL),
gitlab.WithCustomLimiter(rate.NewLimiter(rateLimitR, rateLimitB)),
)
must(err)
gitlab := NewXanzyGitlab(client, config.UserID, config.ProjectIDs)
app := NewApp(os.Stdout, gitlab)
state, err = app.Run(state)
must(err)
must(saveState(statePath, state))
}
func must(err error) {
if err != nil {
panic(err)
}
}
func loadConfig(path string) (Config, error) {
var config Config
file, err := os.Open(path)
if err != nil {
return config, fmt.Errorf("unable to open %q config file: %w", path, err)
}
defer file.Close()
err = json.NewDecoder(file).Decode(&config)
if err != nil {
return config, fmt.Errorf("unable to parse %q config file: %w", path, err)
}
return config, nil
}
func loadState(path string) (State, error) {
state := NewState()
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
return state, nil
}
file, err := os.Open(path)
if err != nil {
return state, fmt.Errorf("unable to open %q state file: %w", path, err)
}
defer file.Close()
err = json.NewDecoder(file).Decode(&state)
if err != nil {
return state, fmt.Errorf("unable to parse %q state file: %w", path, err)
}
return state, nil
}
func saveState(path string, state State) error {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("unable to create/truncate %q state file: %w", path, err)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
err = encoder.Encode(state)
if err != nil {
return fmt.Errorf("unable to save %q state file: %w", path, err)
}
return nil
}