-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
276 lines (226 loc) · 6.2 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
// Copyright 2022 The Firefly Authors.
//
// Use of this source code is governed by a BSD 3-clause
// license that can be found in the LICENSE file.
// Command update-deps helps identify and perform updates to Firefly's dependencies.
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"github.com/bazelbuild/buildtools/build"
"firefly-os.dev/tools/simplehttp"
)
func init() {
log.SetFlags(0)
log.SetOutput(os.Stderr)
log.SetPrefix("")
simplehttp.UserAgent = "Firefly-dependency-updates/1 (github.com/ProjectSerenity/firefly)"
}
type Command struct {
Name string
Description string
Func func(ctx context.Context, w io.Writer, args []string) error
}
var (
commandsNames = make([]string, 0, 10)
commandsMap = make(map[string]*Command)
program = filepath.Base(os.Args[0])
)
func RegisterCommand(name, description string, fun func(ctx context.Context, w io.Writer, args []string) error) {
if commandsMap[name] != nil {
panic("command " + name + " already registered")
}
if fun == nil {
panic("command " + name + " registered with nil implementation")
}
commandsNames = append(commandsNames, name)
commandsMap[name] = &Command{Name: name, Description: description, Func: fun}
}
func main() {
sort.Strings(commandsNames)
var help bool
flag.BoolVar(&help, "h", false, "Show this message and exit.")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage\n %s COMMAND [OPTIONS]\n\n", program)
fmt.Fprintf(os.Stderr, "Commands:\n")
maxWidth := 0
for _, name := range commandsNames {
if maxWidth < len(name) {
maxWidth = len(name)
}
}
for _, name := range commandsNames {
cmd := commandsMap[name]
fmt.Fprintf(os.Stderr, " %-*s %s\n", maxWidth, name, cmd.Description)
}
os.Exit(2)
}
flag.Parse()
args := flag.Args()
if help {
flag.Usage()
}
// If we're being run with `bazel run`, we're in
// a semi-random build directory, and need to move
// to the caller's working directory.
//
workspace := os.Getenv("BUILD_WORKSPACE_DIRECTORY")
if workspace != "" {
err := os.Chdir(workspace)
if err != nil {
log.Printf("Failed to change directory to %q: %v", workspace, err)
}
}
if len(args) == 0 {
// Run all the commands.
for _, name := range commandsNames {
log.SetPrefix(name + ": ")
cmd := commandsMap[name]
err := cmd.Func(context.Background(), os.Stdout, args)
if err != nil {
log.Fatal(err)
}
}
return
}
name := args[0]
cmd, ok := commandsMap[args[0]]
if !ok {
flag.Usage()
}
log.SetPrefix(name + ": ")
err := cmd.Func(context.Background(), os.Stdout, args[1:])
if err != nil {
log.Fatal(err)
}
}
// UnmarshalFields processes the AST node for a
// Starlark function call and stores its parameters
// into data.
//
// UnmarshalFields will return an error if any required
// fields were unset, or if any additional fields were
// found in the AST.
func UnmarshalFields(call *build.CallExpr, v any) error {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return fmt.Errorf("invalid set of fields: got %v, expected struct", val.Kind())
}
// Use reflection to extract the data for
// each field in a format we can process
// more easily as we iterate through the
// call.
type FieldData struct {
Name string
Optional bool
Ignore bool
Value *string
Ptr **string
}
valType := val.Type()
fieldType := reflect.TypeOf(StringField{})
numFields := val.NumField()
fields := make([]*FieldData, numFields)
fieldsMap := make(map[string]*FieldData)
for i := 0; i < numFields; i++ {
valField := val.Field(i)
typeField := valType.Field(i)
if valField.Type() != fieldType {
return fmt.Errorf("invalid set of fields: field %s has unexpected type %s, want %s", typeField.Name, valField.Type(), fieldType)
}
name, ok := typeField.Tag.Lookup("bzl")
optional := false
ignore := false
if strings.HasSuffix(name, ",optional") {
optional = true
name = strings.TrimSuffix(name, ",optional")
} else if strings.HasSuffix(name, ",ignore") {
ignore = true
name = strings.TrimSuffix(name, ",ignore")
}
if !ok {
name = typeField.Name
}
if name == "" {
return fmt.Errorf("invalid set of fields: field %s has no field name", typeField.Name)
}
// We already know valField is a struct.
valPtr := valField.Field(0).Addr().Interface().(*string)
ptrPtr := valField.Field(1).Addr().Interface().(**string)
field := &FieldData{
Name: name,
Optional: optional,
Ignore: ignore,
Value: valPtr,
Ptr: ptrPtr,
}
if fieldsMap[name] != nil {
return fmt.Errorf("invalid set of fields: multiple fields have the name %q", name)
}
fields[i] = field
fieldsMap[name] = field
}
// Now we have the field data ready, we can
// start parsing the call.
for i, expr := range call.List {
assign, ok := expr.(*build.AssignExpr)
if !ok {
return fmt.Errorf("field %d in the call is not an assignment", i)
}
lhs, ok := assign.LHS.(*build.Ident)
if !ok {
return fmt.Errorf("field %d in the call assigns to a non-identifier value %#v", i, assign.LHS)
}
field := fieldsMap[lhs.Name]
if field == nil {
return fmt.Errorf("field %d in the call has unexpected field %q", i, lhs.Name)
}
if field.Ignore {
continue
}
if *field.Ptr != nil {
return fmt.Errorf("field %d in the call assigns to %s for the second time", i, lhs.Name)
}
rhs, ok := assign.RHS.(*build.StringExpr)
if !ok {
return fmt.Errorf("field %d in the call (%s) has non-string value %#v", i, lhs.Name, assign.RHS)
}
*field.Value = rhs.Value
*field.Ptr = &rhs.Value
}
// Check we've got values for all required
// fields.
for _, field := range fields {
if field.Optional || field.Ignore {
continue
}
if *field.Ptr != nil {
continue
}
return fmt.Errorf("function call had no value for required field %s", field.Name)
}
return nil
}
// StringField represents a field in a Starlark
// function that receives a string literal.
type StringField struct {
// The parsed value.
Value string
// A pointer to the original AST node, which
// can be modified to update the AST.
Ptr *string
}
func (f StringField) String() string {
return f.Value
}