Debian Codegraph @

scripts/main.go

raw
1 package main
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/signal"
9 "strconv"
10 "strings"
11 )
12
13 const readmePath = "README.md"
14
15 const usage = `usage: go run ./scripts [-update] [-block N]
16
17 (no flags) re-align the benchmark tables in README.md
18 -update re-run each table's own "// go test ..." command and refresh its numbers
19 -block N restrict -update to the Nth table (1-based); it still has to be a
20 table this machine's architecture can measure
21 `
22
23 var errHelp = errors.New("help requested")
24
25 func main() {
26 if err := run(os.Args[1:]); err != nil {
27 _, _ = fmt.Fprintln(os.Stderr, err) //nolint:errcheck // printing error only
28 os.Exit(1)
29 }
30 }
31
32 func run(args []string) error {
33 update, block, err := parseFlags(args)
34 switch {
35 case errors.Is(err, errHelp):
36 logf("%s", usage)
37 return nil
38 case err != nil:
39 return fmt.Errorf("%w\n\n%s", err, usage)
40 }
41
42 if update {
43 // A Ctrl-C during a 15 minute measurement should take the go test child with it.
44 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
45 defer stop()
46 if err := updateBenchmarks(ctx, readmePath, block); err != nil {
47 return err
48 }
49 }
50
51 return formatBenchmarks(readmePath)
52 }
53
54 // Parsed by hand: the repo's depguard rules deny the flag package.
55 func parseFlags(args []string) (bool, int, error) {
56 update, block := false, 0
57 for i := 0; i < len(args); i++ {
58 name, value, hasValue := strings.Cut(args[i], "=")
59 if hasValue && name != "-block" && name != "--block" {
60 return false, 0, fmt.Errorf("%s takes no value", name)
61 }
62
63 switch name {
64 case "-h", "--help":
65 return false, 0, errHelp
66 case "-update", "--update":
67 update = true
68 case "-block", "--block":
69 if !hasValue {
70 rest := args[i+1:]
71 if len(rest) == 0 {
72 return false, 0, errors.New("-block needs a table number")
73 }
74 value = rest[0]
75 i++
76 }
77 n, err := strconv.Atoi(value)
78 if err != nil || n < 1 {
79 return false, 0, fmt.Errorf("-block wants a positive table number, got %q", value)
80 }
81 block = n
82 default:
83 return false, 0, fmt.Errorf("unknown argument %q", args[i])
84 }
85 }
86 if block > 0 && !update {
87 return false, 0, errors.New("-block only applies together with -update")
88 }
89 return update, block, nil
90 }