Files

87 lines
2.3 KiB
Go

// business-hours holds actions that change something outside working hours at
// propose and wait. Settings: timezone (IANA name, default UTC), start and end
// (hour of day, default 9 and 17), and days (comma-separated weekday numbers
// with Sunday as 0, default 1,2,3,4,5).
package main
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/samcharles93/archipelago/sdk/guard"
)
type hours struct {
loc *time.Location
start, end int
days map[time.Weekday]bool
}
func build(cfg guard.Config) (guard.Guard, error) {
h := hours{start: 9, end: 17, days: map[time.Weekday]bool{}}
var err error
if h.loc, err = time.LoadLocation(or(cfg.Settings["timezone"], "UTC")); err != nil {
return nil, fmt.Errorf("timezone: %w", err)
}
if h.start, err = hour(cfg.Settings["start"], 9); err != nil {
return nil, fmt.Errorf("start: %w", err)
}
if h.end, err = hour(cfg.Settings["end"], 17); err != nil {
return nil, fmt.Errorf("end: %w", err)
}
for _, d := range strings.Split(or(cfg.Settings["days"], "1,2,3,4,5"), ",") {
n, err := strconv.Atoi(strings.TrimSpace(d))
if err != nil || n < 0 || n > 6 {
return nil, fmt.Errorf("days: %q is not a weekday number", d)
}
h.days[time.Weekday(n)] = true
}
return h, nil
}
func or(s, fallback string) string {
if s == "" {
return fallback
}
return s
}
func hour(s string, fallback int) (int, error) {
if s == "" {
return fallback, nil
}
n, err := strconv.Atoi(s)
if err != nil || n < 0 || n > 24 {
return 0, fmt.Errorf("%q is not an hour of the day", s)
}
return n, nil
}
func (hours) Describe() guard.Description {
return guard.Description{Name: "business-hours", Version: "1.0.1"}
}
func (h hours) Judge(_ context.Context, a guard.Action) (guard.Verdict, error) {
if a.Effect.ReadOnly {
return guard.Verdict{Ceiling: guard.ActQuietly}, nil
}
at := a.At.In(h.loc)
if h.days[at.Weekday()] && at.Hour() >= h.start && at.Hour() < h.end {
return guard.Verdict{Ceiling: guard.ActQuietly}, nil
}
return guard.Verdict{
Ceiling: guard.ProposeAndWait,
Findings: []guard.Finding{{
Text: "the action changes something outside business hours",
Evidence: "the host's clock reads " + at.Format("Mon 15:04 MST"),
Strength: guard.Strong,
}},
BlindSpots: []string{"public holidays"},
}, nil
}
func main() { guard.Serve(build) }