-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
315 lines (298 loc) · 7.79 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
310
311
312
313
314
315
package main
import (
"bufio"
"bytes"
"context"
"database/sql"
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"sort"
"strings"
"time"
"github.com/jreut/pager/v2/pkg/cli"
"github.com/jreut/pager/v2/pkg/cmd"
"github.com/jreut/pager/v2/pkg/global"
"github.com/jreut/pager/v2/pkg/interval"
"github.com/jreut/pager/v2/pkg/og"
"github.com/jreut/pager/v2/pkg/save"
)
var (
dbpath = "db.sqlite3"
)
func init() {
if global.Deterministic() {
log.SetFlags(0)
} else {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
if v, ok := os.LookupEnv("DB"); ok {
dbpath = v
}
}
func main() {
var names []string
for k := range cmds {
names = append(names, k)
}
names = append(names, "help")
if global.Deterministic() {
sort.Strings(names)
}
if len(os.Args) <= 1 {
log.Fatalf("no command given: choose one of %s", names)
}
if os.Args[1] == "help" || os.Args[1] == "-h" {
if err := help(names); err != nil {
log.Fatal(err)
}
return
}
command, ok := cmds[os.Args[1]]
if !ok {
log.Fatalf("unhandled command %q: choose one of %s", os.Args[1], names)
}
db, err := save.Open(dbpath, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
err = save.WithTx(db, func(tx *sql.Tx) error {
return command.f(ctx, os.Args[2:], opts{
q: save.New(tx),
})
})
if err != nil {
log.Println(err)
switch {
case errors.Is(err, cmd.ErrConflict):
os.Exit(17)
default:
os.Exit(1)
}
}
log.Println("ok")
}
type opts struct{ q *save.Queries }
type command struct {
help string
f func(context.Context, []string, opts) error
}
func help(names []string) error {
// Iterate over this slice of names instead of cmds directly.
// This lets us pass a sorted list during tests.
for _, k := range names {
if k == "help" {
continue
}
v, ok := cmds[k]
if !ok {
return fmt.Errorf("no command found for %q", k)
}
if v.help == "" {
return fmt.Errorf("TODO: %q is undocumented", k)
}
var buf bytes.Buffer
cmd := exec.Command(os.Args[0], k, "-h")
cmd.Stdout = &buf
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
return fmt.Errorf("could not generate help for %q: %w\nout=%s", k, err, buf.String())
}
s := bufio.NewScanner(&buf)
for s.Scan() {
if strings.HasPrefix(s.Text(), "Usage of") {
continue
}
v.help += "\n " + s.Text()
}
if s.Err() != nil {
return fmt.Errorf("could not scan output of %q -h: %w", k, s.Err())
}
fmt.Fprintf(os.Stderr, "%s\n %s\n", k, v.help)
}
return nil
}
var cmds = map[string]command{
"add-schedule": {
help: "Initialize a new schedule",
f: func(ctx context.Context, args []string, opts opts) error {
name := flag.String("name", "", "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
return opts.q.AddSchedule(ctx, *name)
},
},
"add-interval": {
help: "Add an ad hoc shift or an exclusion to the schedule. This is useful for things like covering someone for an hour.",
f: func(ctx context.Context, args []string, opts opts) error {
times := cli.TimeFlags()
who := flag.String("who", "", "who")
kind := flag.String("kind", save.IntervalKindShift, fmt.Sprintf("one of %s", []string{save.IntervalKindShift, save.IntervalKindExclusion}))
schedule := flag.String("schedule", "", "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
if *who == "" {
return fmt.Errorf("provide -who")
}
if !(*kind == save.IntervalKindExclusion || *kind == save.IntervalKindShift) {
return fmt.Errorf("provide -kind=%s or -kind=%s", save.IntervalKindShift, save.IntervalKindExclusion)
}
start, end, err := times.Times()
if err != nil {
return err
}
return cmd.AddInterval(ctx, opts.q, save.AddIntervalParams{
Person: *who,
Schedule: *schedule,
StartAt: start,
EndBefore: end,
Kind: *kind,
}, false)
},
},
"show-schedule": {
help: "Print the schedule for the given time interval as a CSV.",
f: func(ctx context.Context, args []string, opts opts) error {
schedule := flag.String("schedule", "", "")
times := cli.TimeFlags()
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
start, end, err := times.Times()
if err != nil {
return err
}
out, err := cmd.ShowSchedule(ctx, opts.q, *schedule, start, end)
if err != nil {
return err
}
return interval.WriteCSV(os.Stdout, out)
},
},
"edit": {
help: "Add or remove people from a schedule. Adding a person makes them eligible for shifts generated by `generate`, and removing them does the opposite.",
f: func(ctx context.Context, args []string, opts opts) error {
schedule := flag.String("schedule", "", "")
var actions []cmd.Action
flag.Var(actionsflag{save.EventKindAdd, &actions}, "add", "")
flag.Var(actionsflag{save.EventKindRemove, &actions}, "remove", "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
return cmd.EditSchedule(ctx, opts.q, *schedule, actions)
}},
"generate": {
help: "Generate shifts for a schedule",
f: func(ctx context.Context, args []string, opts opts) error {
schedule := flag.String("schedule", "", "")
times := cli.TimeFlags()
style := flag.String("style", "", "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
start, end, err := times.Times()
if err != nil {
return err
}
return cmd.Generate(ctx, opts.q, *schedule, *style, start, end)
},
},
"import": {
help: "Overwrite the schedule with the given CSV of shifts.",
f: func(ctx context.Context, args []string, opts opts) error {
f := flag.String("file", "-", "csv file containing intervals, or stdin if '-'")
schedule := flag.String("schedule", "", "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
if *schedule == "" {
return fmt.Errorf("provide nonempty -schedule")
}
r := os.Stdin
if *f != "-" {
var err error
r, err = os.Open(*f)
if err != nil {
return err
}
defer r.Close()
}
is, err := interval.ReadCSV(r, *schedule, save.IntervalKindShift)
if err != nil {
return err
}
for i := range is {
if err := cmd.AddInterval(ctx, opts.q, save.AddIntervalParams(is[i]), true); err != nil {
return fmt.Errorf("AddInterval[%d]: %w\n%s", i, err, is[i])
}
}
return nil
},
},
"apply": {
help: "Write the schedule to the pager provider.",
f: func(ctx context.Context, args []string, opts opts) error {
f := flag.String("file", "-", "csv file containing intervals, or stdin if '-'")
d := flag.String("dst", "stderr", "write to this external destination")
schedule := flag.String("schedule", "", "")
debug := flag.Bool("debug", false, "")
if err := flag.CommandLine.Parse(args); err != nil {
return err
}
if *schedule == "" {
return fmt.Errorf("provide nonempty -schedule")
}
r := os.Stdin
if *f != "-" {
var err error
r, err = os.Open(*f)
if err != nil {
return err
}
defer r.Close()
}
var dst cmd.Destination
switch *d {
case "opsgenie":
dst = og.NewHTTPClient(og.DomainDefault, "TODO-KEY", *debug)
case "stderr":
dst = cmd.FakeDestination{Writer: os.Stderr}
default:
return fmt.Errorf("unhandled destination %q", *d)
}
return cmd.Apply(ctx, r, dst, *schedule)
},
},
}
type actionsflag struct {
kind string
val *[]cmd.Action
}
func (f actionsflag) Set(v string) error {
before, after, ok := strings.Cut(v, "=")
if !ok {
return fmt.Errorf("cannot parse %v: does not contain %q", v, "=")
}
at, err := time.Parse(time.RFC3339, after)
if err != nil {
return err
}
*f.val = append(*f.val, cmd.Action{
Kind: f.kind,
Who: before,
At: at,
})
return nil
}
func (f actionsflag) String() string {
return fmt.Sprintf("%s: %s", f.kind, f.val)
}