blob: 7f5e3327c0cd214baa37ec6a169c5b170e1359ec [file] [log] [blame]
Sasha Smundak24159db2020-10-26 15:43:21 -07001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package rbcrun
16
17import (
18 "fmt"
Sasha Smundak6b795dc2021-08-18 16:32:19 -070019 "io/fs"
Sasha Smundak24159db2020-10-26 15:43:21 -070020 "os"
21 "os/exec"
22 "path/filepath"
Cole Faustc7b8b6e2022-04-26 12:03:19 -070023 "sort"
Sasha Smundak24159db2020-10-26 15:43:21 -070024 "strings"
25
26 "go.starlark.net/starlark"
Cole Faustc63ce1a2023-05-09 14:56:36 -070027 "go.starlark.net/starlarkjson"
Sasha Smundak24159db2020-10-26 15:43:21 -070028 "go.starlark.net/starlarkstruct"
29)
30
Cole Faustc63ce1a2023-05-09 14:56:36 -070031type ExecutionMode int
32const (
33 ExecutionModeRbc ExecutionMode = iota
Cole Faust5b8dda02023-11-07 11:14:58 -080034 ExecutionModeScl ExecutionMode = iota
Cole Faustc63ce1a2023-05-09 14:56:36 -070035)
Sasha Smundak24159db2020-10-26 15:43:21 -070036
Cole Faust386b3742023-06-06 16:55:58 -070037const allowExternalEntrypointKey = "allowExternalEntrypoint"
Cole Faust5b8dda02023-11-07 11:14:58 -080038const callingFileKey = "callingFile"
Cole Faustc63ce1a2023-05-09 14:56:36 -070039const executionModeKey = "executionMode"
Cole Faust386b3742023-06-06 16:55:58 -070040const shellKey = "shell"
Sasha Smundak24159db2020-10-26 15:43:21 -070041
42type modentry struct {
43 globals starlark.StringDict
44 err error
45}
46
47var moduleCache = make(map[string]*modentry)
48
Cole Faustc63ce1a2023-05-09 14:56:36 -070049var rbcBuiltins starlark.StringDict = starlark.StringDict{
50 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make),
51 // To convert find-copy-subdir and product-copy-files-by pattern
52 "rblf_find_files": starlark.NewBuiltin("rblf_find_files", find),
53 // To convert makefile's $(shell cmd)
54 "rblf_shell": starlark.NewBuiltin("rblf_shell", shell),
55 // Output to stderr
56 "rblf_log": starlark.NewBuiltin("rblf_log", log),
57 // To convert makefile's $(wildcard foo*)
58 "rblf_wildcard": starlark.NewBuiltin("rblf_wildcard", wildcard),
59}
Sasha Smundak24159db2020-10-26 15:43:21 -070060
Cole Faust5b8dda02023-11-07 11:14:58 -080061var sclBuiltins starlark.StringDict = starlark.StringDict{
Cole Faustc63ce1a2023-05-09 14:56:36 -070062 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make),
63 "json": starlarkjson.Module,
64}
65
66// Takes a module name (the first argument to the load() function) and returns the path
67// it's trying to load, stripping out leading //, and handling leading :s.
Cole Faust386b3742023-06-06 16:55:58 -070068func cleanModuleName(moduleName string, callerDir string, allowExternalPaths bool) (string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -070069 if strings.Count(moduleName, ":") > 1 {
70 return "", fmt.Errorf("at most 1 colon must be present in starlark path: %s", moduleName)
Sasha Smundak24159db2020-10-26 15:43:21 -070071 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070072
73 // We don't have full support for external repositories, but at least support skylib's dicts.
74 if moduleName == "@bazel_skylib//lib:dicts.bzl" {
75 return "external/bazel-skylib/lib/dicts.bzl", nil
76 }
77
78 localLoad := false
79 if strings.HasPrefix(moduleName, "@//") {
80 moduleName = moduleName[3:]
81 } else if strings.HasPrefix(moduleName, "//") {
82 moduleName = moduleName[2:]
Sasha Smundak24159db2020-10-26 15:43:21 -070083 } else if strings.HasPrefix(moduleName, ":") {
Cole Faustc63ce1a2023-05-09 14:56:36 -070084 moduleName = moduleName[1:]
85 localLoad = true
Cole Faust386b3742023-06-06 16:55:58 -070086 } else if !allowExternalPaths {
Cole Faustc63ce1a2023-05-09 14:56:36 -070087 return "", fmt.Errorf("load path must start with // or :")
Sasha Smundak24159db2020-10-26 15:43:21 -070088 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070089
90 if ix := strings.LastIndex(moduleName, ":"); ix >= 0 {
91 moduleName = moduleName[:ix] + string(os.PathSeparator) + moduleName[ix+1:]
92 }
93
94 if filepath.Clean(moduleName) != moduleName {
95 return "", fmt.Errorf("load path must be clean, found: %s, expected: %s", moduleName, filepath.Clean(moduleName))
96 }
Cole Faust386b3742023-06-06 16:55:58 -070097 if !allowExternalPaths {
98 if strings.HasPrefix(moduleName, "../") {
99 return "", fmt.Errorf("load path must not start with ../: %s", moduleName)
100 }
101 if strings.HasPrefix(moduleName, "/") {
102 return "", fmt.Errorf("load path starts with /, use // for a absolute path: %s", moduleName)
103 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700104 }
105
106 if localLoad {
107 return filepath.Join(callerDir, moduleName), nil
108 }
109
110 return moduleName, nil
Sasha Smundak24159db2020-10-26 15:43:21 -0700111}
112
113// loader implements load statement. The format of the loaded module URI is
114// [//path]:base[|symbol]
115// The file path is $ROOT/path/base if path is present, <caller_dir>/base otherwise.
116// The presence of `|symbol` indicates that the loader should return a single 'symbol'
117// bound to None if file is missing.
118func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700119 mode := thread.Local(executionModeKey).(ExecutionMode)
Cole Faust386b3742023-06-06 16:55:58 -0700120 allowExternalEntrypoint := thread.Local(allowExternalEntrypointKey).(bool)
Sasha Smundak24159db2020-10-26 15:43:21 -0700121 var defaultSymbol string
Cole Faustc63ce1a2023-05-09 14:56:36 -0700122 mustLoad := true
123 if mode == ExecutionModeRbc {
124 pipePos := strings.LastIndex(module, "|")
Cole Faust386b3742023-06-06 16:55:58 -0700125 if pipePos >= 0 {
126 mustLoad = false
Cole Faustc63ce1a2023-05-09 14:56:36 -0700127 defaultSymbol = module[pipePos+1:]
128 module = module[:pipePos]
129 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700130 }
Cole Faust5b8dda02023-11-07 11:14:58 -0800131 callingFile := thread.Local(callingFileKey).(string)
132 modulePath, err := cleanModuleName(module, filepath.Dir(callingFile), allowExternalEntrypoint)
Sasha Smundak24159db2020-10-26 15:43:21 -0700133 if err != nil {
134 return nil, err
135 }
136 e, ok := moduleCache[modulePath]
137 if e == nil {
138 if ok {
139 return nil, fmt.Errorf("cycle in load graph")
140 }
141
142 // Add a placeholder to indicate "load in progress".
143 moduleCache[modulePath] = nil
144
145 // Decide if we should load.
146 if !mustLoad {
147 if _, err := os.Stat(modulePath); err == nil {
148 mustLoad = true
149 }
150 }
151
152 // Load or return default
153 if mustLoad {
Cole Faust5b8dda02023-11-07 11:14:58 -0800154 if strings.HasSuffix(callingFile, ".scl") && !strings.HasSuffix(modulePath, ".scl") {
155 return nil, fmt.Errorf(".scl files can only load other .scl files: %q loads %q", callingFile, modulePath)
156 }
157 // Switch into scl mode from here on
158 if strings.HasSuffix(modulePath, ".scl") {
159 mode = ExecutionModeScl
160 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700161 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load}
162 // Cheating for the sake of testing:
163 // propagate starlarktest's Reporter key, otherwise testing
164 // the load function may cause panic in starlarktest code.
165 const testReporterKey = "Reporter"
166 if v := thread.Local(testReporterKey); v != nil {
167 childThread.SetLocal(testReporterKey, v)
168 }
169
Cole Faust386b3742023-06-06 16:55:58 -0700170 // Only the entrypoint starlark file allows external loads.
171 childThread.SetLocal(allowExternalEntrypointKey, false)
Cole Faust5b8dda02023-11-07 11:14:58 -0800172 childThread.SetLocal(callingFileKey, modulePath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700173 childThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700174 childThread.SetLocal(shellKey, thread.Local(shellKey))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700175 if mode == ExecutionModeRbc {
176 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins)
177 e = &modentry{globals, err}
Cole Faust5b8dda02023-11-07 11:14:58 -0800178 } else if mode == ExecutionModeScl {
179 globals, err := starlark.ExecFile(childThread, modulePath, nil, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700180 e = &modentry{globals, err}
181 } else {
182 return nil, fmt.Errorf("unknown executionMode %d", mode)
183 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700184 } else {
185 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil}
186 }
187
188 // Update the cache.
189 moduleCache[modulePath] = e
190 }
191 return e.globals, e.err
192}
193
Sasha Smundak24159db2020-10-26 15:43:21 -0700194// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present,
195// the 'top/pattern' is globbed and then 'top/' prefix is removed.
196func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
197 kwargs []starlark.Tuple) (starlark.Value, error) {
198 var pattern string
199 var top string
200
201 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil {
202 return starlark.None, err
203 }
204
205 var files []string
206 var err error
207 if top == "" {
208 if files, err = filepath.Glob(pattern); err != nil {
209 return starlark.None, err
210 }
211 } else {
212 prefix := top + string(filepath.Separator)
213 if files, err = filepath.Glob(prefix + pattern); err != nil {
214 return starlark.None, err
215 }
216 for i := range files {
217 files[i] = strings.TrimPrefix(files[i], prefix)
218 }
219 }
Cole Faustc7b8b6e2022-04-26 12:03:19 -0700220 // Kati uses glob(3) with no flags, which means it's sorted
221 // because GLOB_NOSORT is not passed. Go's glob is not
222 // guaranteed to sort the results.
223 sort.Strings(files)
Sasha Smundak24159db2020-10-26 15:43:21 -0700224 return makeStringList(files), nil
225}
226
Sasha Smundak6b795dc2021-08-18 16:32:19 -0700227// find(top, pattern, only_files = 0) returns all the paths under 'top'
228// whose basename matches 'pattern' (which is a shell's glob pattern).
229// If 'only_files' is non-zero, only the paths to the regular files are
230// returned. The returned paths are relative to 'top'.
231func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
232 kwargs []starlark.Tuple) (starlark.Value, error) {
233 var top, pattern string
234 var onlyFiles int
235 if err := starlark.UnpackArgs(b.Name(), args, kwargs,
236 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil {
237 return starlark.None, err
238 }
239 top = filepath.Clean(top)
240 pattern = filepath.Clean(pattern)
241 // Go's filepath.Walk is slow, consider using OS's find
242 var res []string
243 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error {
244 if err != nil {
245 if d != nil && d.IsDir() {
246 return fs.SkipDir
247 } else {
248 return nil
249 }
250 }
251 relPath := strings.TrimPrefix(path, top)
252 if len(relPath) > 0 && relPath[0] == os.PathSeparator {
253 relPath = relPath[1:]
254 }
255 // Do not return top-level dir
256 if len(relPath) == 0 {
257 return nil
258 }
259 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) {
260 res = append(res, relPath)
261 }
262 return nil
263 })
264 return makeStringList(res), err
265}
266
Sasha Smundak24159db2020-10-26 15:43:21 -0700267// shell(command) runs OS shell with given command and returns back
268// its output the same way as Make's $(shell ) function. The end-of-lines
269// ("\n" or "\r\n") are replaced with " " in the result, and the trailing
270// end-of-line is removed.
Cole Faustc63ce1a2023-05-09 14:56:36 -0700271func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
Sasha Smundak24159db2020-10-26 15:43:21 -0700272 kwargs []starlark.Tuple) (starlark.Value, error) {
273 var command string
274 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil {
275 return starlark.None, err
276 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700277 shellPath := thread.Local(shellKey).(string)
Sasha Smundak24159db2020-10-26 15:43:21 -0700278 if shellPath == "" {
279 return starlark.None,
Sasha Smundak57bb5082021-04-01 15:51:56 -0700280 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)")
Sasha Smundak24159db2020-10-26 15:43:21 -0700281 }
282 cmd := exec.Command(shellPath, "-c", command)
283 // We ignore command's status
284 bytes, _ := cmd.Output()
285 output := string(bytes)
286 if strings.HasSuffix(output, "\n") {
287 output = strings.TrimSuffix(output, "\n")
288 } else {
289 output = strings.TrimSuffix(output, "\r\n")
290 }
291
292 return starlark.String(
293 strings.ReplaceAll(
294 strings.ReplaceAll(output, "\r\n", " "),
295 "\n", " ")), nil
296}
297
298func makeStringList(items []string) *starlark.List {
299 elems := make([]starlark.Value, len(items))
300 for i, item := range items {
301 elems[i] = starlark.String(item)
302 }
303 return starlark.NewList(elems)
304}
305
Sasha Smundake8652d42021-09-24 08:25:17 -0700306func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
307 sep := " "
308 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil {
309 return nil, err
310 }
311 for i, v := range args {
312 if i > 0 {
313 fmt.Fprint(os.Stderr, sep)
314 }
315 if s, ok := starlark.AsString(v); ok {
316 fmt.Fprint(os.Stderr, s)
317 } else if b, ok := v.(starlark.Bytes); ok {
318 fmt.Fprint(os.Stderr, string(b))
319 } else {
320 fmt.Fprintf(os.Stderr, "%s", v)
321 }
322 }
323
324 fmt.Fprintln(os.Stderr)
325 return starlark.None, nil
326}
327
Sasha Smundak24159db2020-10-26 15:43:21 -0700328// Parses, resolves, and executes a Starlark file.
329// filename and src parameters are as for starlark.ExecFile:
330// * filename is the name of the file to execute,
331// and the name that appears in error messages;
332// * src is an optional source of bytes to use instead of filename
333// (it can be a string, or a byte array, or an io.Reader instance)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700334// Returns the top-level starlark variables, the list of starlark files loaded, and an error
Cole Faust386b3742023-06-06 16:55:58 -0700335func Run(filename string, src interface{}, mode ExecutionMode, allowExternalEntrypoint bool) (starlark.StringDict, []string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700336 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call,
337 // which always uses /bin/sh to run the command
338 shellPath := "/bin/sh"
339 if _, err := os.Stat(shellPath); err != nil {
340 shellPath = ""
341 }
342
Sasha Smundak24159db2020-10-26 15:43:21 -0700343 mainThread := &starlark.Thread{
344 Name: "main",
Cole Faustc63ce1a2023-05-09 14:56:36 -0700345 Print: func(_ *starlark.Thread, msg string) {
346 if mode == ExecutionModeRbc {
347 // In rbc mode, rblf_log is used to print to stderr
348 fmt.Println(msg)
Cole Faust5b8dda02023-11-07 11:14:58 -0800349 } else if mode == ExecutionModeScl {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700350 fmt.Fprintln(os.Stderr, msg)
351 }
352 },
Sasha Smundak24159db2020-10-26 15:43:21 -0700353 Load: loader,
354 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700355 filename, err := filepath.Abs(filename)
356 if err != nil {
357 return nil, nil, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700358 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700359 if wd, err := os.Getwd(); err == nil {
360 filename, err = filepath.Rel(wd, filename)
361 if err != nil {
362 return nil, nil, err
363 }
Cole Faust386b3742023-06-06 16:55:58 -0700364 if !allowExternalEntrypoint && strings.HasPrefix(filename, "../") {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700365 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename)
366 }
367 } else {
368 return nil, nil, err
369 }
370
371 // Add top-level file to cache for cycle detection purposes
372 moduleCache[filename] = nil
373
374 var results starlark.StringDict
Cole Faust386b3742023-06-06 16:55:58 -0700375 mainThread.SetLocal(allowExternalEntrypointKey, allowExternalEntrypoint)
Cole Faust5b8dda02023-11-07 11:14:58 -0800376 mainThread.SetLocal(callingFileKey, filename)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700377 mainThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700378 mainThread.SetLocal(shellKey, shellPath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700379 if mode == ExecutionModeRbc {
380 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins)
Cole Faust5b8dda02023-11-07 11:14:58 -0800381 } else if mode == ExecutionModeScl {
382 results, err = starlark.ExecFile(mainThread, filename, src, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700383 } else {
384 return results, nil, fmt.Errorf("unknown executionMode %d", mode)
385 }
386 loadedStarlarkFiles := make([]string, 0, len(moduleCache))
387 for file := range moduleCache {
388 loadedStarlarkFiles = append(loadedStarlarkFiles, file)
389 }
390 sort.Strings(loadedStarlarkFiles)
391
392 return results, loadedStarlarkFiles, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700393}