This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
next.go
78 lines (66 loc) · 1.92 KB
/
next.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
package main
import (
"flag"
"fmt"
"os"
"strconv"
"time"
)
var cmdNext = &Command{
UsageLine: "next n",
Short: "Fügt die nächsten Termine automatisch ein",
Long: `Fügt die nächsten n Termine automatisch ein.
Stammtische werden jeweils am ersten Donnerstag eines Monats ohne Ort angelegt,
alle anderen Termine werden ohne Stammtisch oder chaotische Viertelstunde
angelegt. Existente Termine werden nicht geändert.
Bei Erfolg gibt der Befehl nichts aus`,
NeedsDB: true,
RegenWebsite: true,
}
func init() {
cmdNext.Flag = flag.NewFlagSet("next", flag.ExitOnError)
cmdNext.Run = RunNext
}
func getNextThursdays(n int) (next []time.Time) {
cur := time.Now()
// 0 == Sonntag
wd := cur.Weekday()
// Wir bestimmen zuerst letzten Donnerstag, indem wir vom aktuellen Datum
// die richtige Anzahl an Tagen abziehen
date := cur.AddDate(0, 0, -((3 + int(wd)) % 7))
// Jetzt addieren wir immer 7 Tage auf dieses Datum drauf und erhalten so
// die nächsten n Donnerstage
for i := 0; i < n; i++ {
date = date.AddDate(0, 0, 7)
next = append(next, date)
}
return next
}
func RunNext() {
if cmdNext.Flag.NArg() < 1 {
fmt.Fprintf(os.Stderr, "Nicht genug Argumente. Siehe %s help next\n", os.Args[0])
return
}
n, err := strconv.Atoi(cmdNext.Flag.Arg(0))
if err != nil {
fmt.Fprintf(os.Stderr, "Kann \"%s\" nicht als Nummer parsen. Siehe %s help next\n", cmdNext.Flag.Arg(0), os.Args[0])
return
}
tx, err := db.Begin()
if err != nil {
fmt.Fprintln(os.Stderr, "SQL-Fehler:", err)
return
}
for _, d := range getNextThursdays(n) {
_, err := tx.Exec("INSERT INTO termine (stammtisch, date, override, location, override_long) SELECT $2, $1, '', '', '' WHERE NOT EXISTS (SELECT 1 FROM termine WHERE date = $1)", d, d.Day() < 8)
if err != nil {
fmt.Fprintln(os.Stderr, "SQL-Fehler:", err)
tx.Rollback()
return
}
}
err = tx.Commit()
if err != nil {
fmt.Fprintln(os.Stderr, "SQL-Fehler:", err)
}
}