Debian Codegraph @

infra/bots/format_jobs_json/format_jobs_json.go

raw
1 /*
2 * Copyright 2025 Google LLC.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 package main
9
10 /*
11 Reformat the jobs.json file, sorting the jobs by name.
12 */
13
14 import (
15 "encoding/json"
16 "os"
17 "path/filepath"
18 "regexp"
19 "runtime"
20 "sort"
21
22 "go.skia.org/infra/go/skerr"
23 "go.skia.org/infra/task_scheduler/go/specs"
24 )
25
26 func main() {
27 jobsJsonPath := findJobsJSON()
28 b, err := os.ReadFile(jobsJsonPath)
29 if err != nil {
30 panic(err)
31 }
32 b, err = updateJobsJSON(b)
33 if err != nil {
34 panic(err)
35 }
36 if err := os.WriteFile(jobsJsonPath, b, 0644); err != nil {
37 panic(err)
38 }
39 }
40
41 // findJobsJSON attempts to find the jobs.json path based on the location of
42 // this file. If that fails, fall back to assuming that this is being run from
43 // the root of the checkout.
44 func findJobsJSON() string {
45 _, filename, _, ok := runtime.Caller(0)
46 if ok {
47 return filepath.Join(filepath.Dir(filepath.Dir(filename)), "jobs.json")
48 }
49 return filepath.Join("infra", "bots", "jobs.json")
50 }
51
52 // job represents a single entry in jobs.json.
53 type job struct {
54 Name string `json:"name"`
55 CqConfig *specs.CommitQueueJobConfig `json:"cq_config"`
56 }
57
58 // jobSlice implements sort.Interface to sort jobs by name.
59 type jobSlice ([]*job)
60
61 func (s jobSlice) Less(i, j int) bool {
62 return s[i].Name < s[j].Name
63 }
64
65 func (s jobSlice) Len() int {
66 return len(s)
67 }
68
69 func (s jobSlice) Swap(i, j int) {
70 s[i], s[j] = s[j], s[i]
71 }
72
73 func updateJobsJSON(oldJobsContents []byte) ([]byte, error) {
74 var jobs []*job
75 if err := json.Unmarshal(oldJobsContents, &jobs); err != nil {
76 return nil, skerr.Wrapf(err, "failed to decode jobs.json")
77 }
78
79 sort.Sort(jobSlice(jobs))
80
81 newJobsContents, err := json.MarshalIndent(jobs, "", " ")
82 if err != nil {
83 return nil, skerr.Wrapf(err, "failed to encode jobs.json")
84 }
85
86 // Replace instances of `"cq_config": null`; these are cluttery and
87 // unnecessary, but we can't use omitempty because that causes the Marshaler
88 // to also omit `"cq_config": {}` which indicates that a job *should* be on
89 // the CQ. We also omit some whitespace to keep things relatively compact.
90 jobsJSONReplaceRegex := regexp.MustCompile(`(?m)\{\n\s*"name":\s*"(\S+)",\n\s*"cq_config":\s*null\n\s*}`)
91 jobsJSONReplaceContents := []byte(`{"name": "$1"}`)
92 return jobsJSONReplaceRegex.ReplaceAll(newJobsContents, jobsJSONReplaceContents), nil
93 }