blob: f36553e746fefd47297b6f9312d3d424e77cae96 [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
Cole Faustccd26802023-11-09 14:28:34 -080066func isSymlink(filepath string) (bool, error) {
67 if info, err := os.Lstat(filepath); err == nil {
68 return info.Mode() & os.ModeSymlink != 0, nil
69 } else {
70 return false, err
71 }
72}
73
Cole Faustc63ce1a2023-05-09 14:56:36 -070074// Takes a module name (the first argument to the load() function) and returns the path
75// it's trying to load, stripping out leading //, and handling leading :s.
Cole Faust386b3742023-06-06 16:55:58 -070076func cleanModuleName(moduleName string, callerDir string, allowExternalPaths bool) (string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -070077 if strings.Count(moduleName, ":") > 1 {
78 return "", fmt.Errorf("at most 1 colon must be present in starlark path: %s", moduleName)
Sasha Smundak24159db2020-10-26 15:43:21 -070079 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070080
81 // We don't have full support for external repositories, but at least support skylib's dicts.
82 if moduleName == "@bazel_skylib//lib:dicts.bzl" {
83 return "external/bazel-skylib/lib/dicts.bzl", nil
84 }
85
86 localLoad := false
87 if strings.HasPrefix(moduleName, "@//") {
88 moduleName = moduleName[3:]
89 } else if strings.HasPrefix(moduleName, "//") {
90 moduleName = moduleName[2:]
Sasha Smundak24159db2020-10-26 15:43:21 -070091 } else if strings.HasPrefix(moduleName, ":") {
Cole Faustc63ce1a2023-05-09 14:56:36 -070092 moduleName = moduleName[1:]
93 localLoad = true
Cole Faust386b3742023-06-06 16:55:58 -070094 } else if !allowExternalPaths {
Cole Faustc63ce1a2023-05-09 14:56:36 -070095 return "", fmt.Errorf("load path must start with // or :")
Sasha Smundak24159db2020-10-26 15:43:21 -070096 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070097
98 if ix := strings.LastIndex(moduleName, ":"); ix >= 0 {
99 moduleName = moduleName[:ix] + string(os.PathSeparator) + moduleName[ix+1:]
100 }
101
102 if filepath.Clean(moduleName) != moduleName {
103 return "", fmt.Errorf("load path must be clean, found: %s, expected: %s", moduleName, filepath.Clean(moduleName))
104 }
Cole Faust386b3742023-06-06 16:55:58 -0700105 if !allowExternalPaths {
106 if strings.HasPrefix(moduleName, "../") {
107 return "", fmt.Errorf("load path must not start with ../: %s", moduleName)
108 }
109 if strings.HasPrefix(moduleName, "/") {
110 return "", fmt.Errorf("load path starts with /, use // for a absolute path: %s", moduleName)
111 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700112 }
113
114 if localLoad {
115 return filepath.Join(callerDir, moduleName), nil
116 }
117
118 return moduleName, nil
Sasha Smundak24159db2020-10-26 15:43:21 -0700119}
120
121// loader implements load statement. The format of the loaded module URI is
122// [//path]:base[|symbol]
123// The file path is $ROOT/path/base if path is present, <caller_dir>/base otherwise.
124// The presence of `|symbol` indicates that the loader should return a single 'symbol'
125// bound to None if file is missing.
126func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700127 mode := thread.Local(executionModeKey).(ExecutionMode)
Cole Faust386b3742023-06-06 16:55:58 -0700128 allowExternalEntrypoint := thread.Local(allowExternalEntrypointKey).(bool)
Sasha Smundak24159db2020-10-26 15:43:21 -0700129 var defaultSymbol string
Cole Faustc63ce1a2023-05-09 14:56:36 -0700130 mustLoad := true
131 if mode == ExecutionModeRbc {
132 pipePos := strings.LastIndex(module, "|")
Cole Faust386b3742023-06-06 16:55:58 -0700133 if pipePos >= 0 {
134 mustLoad = false
Cole Faustc63ce1a2023-05-09 14:56:36 -0700135 defaultSymbol = module[pipePos+1:]
136 module = module[:pipePos]
137 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700138 }
Cole Faust5b8dda02023-11-07 11:14:58 -0800139 callingFile := thread.Local(callingFileKey).(string)
140 modulePath, err := cleanModuleName(module, filepath.Dir(callingFile), allowExternalEntrypoint)
Sasha Smundak24159db2020-10-26 15:43:21 -0700141 if err != nil {
142 return nil, err
143 }
144 e, ok := moduleCache[modulePath]
145 if e == nil {
146 if ok {
147 return nil, fmt.Errorf("cycle in load graph")
148 }
149
150 // Add a placeholder to indicate "load in progress".
151 moduleCache[modulePath] = nil
152
153 // Decide if we should load.
154 if !mustLoad {
155 if _, err := os.Stat(modulePath); err == nil {
156 mustLoad = true
157 }
158 }
159
160 // Load or return default
161 if mustLoad {
Cole Faust5b8dda02023-11-07 11:14:58 -0800162 if strings.HasSuffix(callingFile, ".scl") && !strings.HasSuffix(modulePath, ".scl") {
163 return nil, fmt.Errorf(".scl files can only load other .scl files: %q loads %q", callingFile, modulePath)
164 }
165 // Switch into scl mode from here on
166 if strings.HasSuffix(modulePath, ".scl") {
167 mode = ExecutionModeScl
168 }
Cole Faustccd26802023-11-09 14:28:34 -0800169
170 if sym, err := isSymlink(modulePath); sym && err == nil {
171 return nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", modulePath)
172 } else if err != nil {
173 return nil, err
174 }
175
Sasha Smundak24159db2020-10-26 15:43:21 -0700176 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load}
177 // Cheating for the sake of testing:
178 // propagate starlarktest's Reporter key, otherwise testing
179 // the load function may cause panic in starlarktest code.
180 const testReporterKey = "Reporter"
181 if v := thread.Local(testReporterKey); v != nil {
182 childThread.SetLocal(testReporterKey, v)
183 }
184
Cole Faust386b3742023-06-06 16:55:58 -0700185 // Only the entrypoint starlark file allows external loads.
186 childThread.SetLocal(allowExternalEntrypointKey, false)
Cole Faust5b8dda02023-11-07 11:14:58 -0800187 childThread.SetLocal(callingFileKey, modulePath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700188 childThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700189 childThread.SetLocal(shellKey, thread.Local(shellKey))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700190 if mode == ExecutionModeRbc {
191 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins)
192 e = &modentry{globals, err}
Cole Faust5b8dda02023-11-07 11:14:58 -0800193 } else if mode == ExecutionModeScl {
194 globals, err := starlark.ExecFile(childThread, modulePath, nil, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700195 e = &modentry{globals, err}
196 } else {
197 return nil, fmt.Errorf("unknown executionMode %d", mode)
198 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700199 } else {
200 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil}
201 }
202
203 // Update the cache.
204 moduleCache[modulePath] = e
205 }
206 return e.globals, e.err
207}
208
Sasha Smundak24159db2020-10-26 15:43:21 -0700209// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present,
210// the 'top/pattern' is globbed and then 'top/' prefix is removed.
211func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
212 kwargs []starlark.Tuple) (starlark.Value, error) {
213 var pattern string
214 var top string
215
216 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil {
217 return starlark.None, err
218 }
219
220 var files []string
221 var err error
222 if top == "" {
223 if files, err = filepath.Glob(pattern); err != nil {
224 return starlark.None, err
225 }
226 } else {
227 prefix := top + string(filepath.Separator)
228 if files, err = filepath.Glob(prefix + pattern); err != nil {
229 return starlark.None, err
230 }
231 for i := range files {
232 files[i] = strings.TrimPrefix(files[i], prefix)
233 }
234 }
Cole Faustc7b8b6e2022-04-26 12:03:19 -0700235 // Kati uses glob(3) with no flags, which means it's sorted
236 // because GLOB_NOSORT is not passed. Go's glob is not
237 // guaranteed to sort the results.
238 sort.Strings(files)
Sasha Smundak24159db2020-10-26 15:43:21 -0700239 return makeStringList(files), nil
240}
241
Sasha Smundak6b795dc2021-08-18 16:32:19 -0700242// find(top, pattern, only_files = 0) returns all the paths under 'top'
243// whose basename matches 'pattern' (which is a shell's glob pattern).
244// If 'only_files' is non-zero, only the paths to the regular files are
245// returned. The returned paths are relative to 'top'.
246func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
247 kwargs []starlark.Tuple) (starlark.Value, error) {
248 var top, pattern string
249 var onlyFiles int
250 if err := starlark.UnpackArgs(b.Name(), args, kwargs,
251 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil {
252 return starlark.None, err
253 }
254 top = filepath.Clean(top)
255 pattern = filepath.Clean(pattern)
256 // Go's filepath.Walk is slow, consider using OS's find
257 var res []string
258 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error {
259 if err != nil {
260 if d != nil && d.IsDir() {
261 return fs.SkipDir
262 } else {
263 return nil
264 }
265 }
266 relPath := strings.TrimPrefix(path, top)
267 if len(relPath) > 0 && relPath[0] == os.PathSeparator {
268 relPath = relPath[1:]
269 }
270 // Do not return top-level dir
271 if len(relPath) == 0 {
272 return nil
273 }
274 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) {
275 res = append(res, relPath)
276 }
277 return nil
278 })
279 return makeStringList(res), err
280}
281
Sasha Smundak24159db2020-10-26 15:43:21 -0700282// shell(command) runs OS shell with given command and returns back
283// its output the same way as Make's $(shell ) function. The end-of-lines
284// ("\n" or "\r\n") are replaced with " " in the result, and the trailing
285// end-of-line is removed.
Cole Faustc63ce1a2023-05-09 14:56:36 -0700286func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
Sasha Smundak24159db2020-10-26 15:43:21 -0700287 kwargs []starlark.Tuple) (starlark.Value, error) {
288 var command string
289 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil {
290 return starlark.None, err
291 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700292 shellPath := thread.Local(shellKey).(string)
Sasha Smundak24159db2020-10-26 15:43:21 -0700293 if shellPath == "" {
294 return starlark.None,
Sasha Smundak57bb5082021-04-01 15:51:56 -0700295 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)")
Sasha Smundak24159db2020-10-26 15:43:21 -0700296 }
297 cmd := exec.Command(shellPath, "-c", command)
298 // We ignore command's status
299 bytes, _ := cmd.Output()
300 output := string(bytes)
301 if strings.HasSuffix(output, "\n") {
302 output = strings.TrimSuffix(output, "\n")
303 } else {
304 output = strings.TrimSuffix(output, "\r\n")
305 }
306
307 return starlark.String(
308 strings.ReplaceAll(
309 strings.ReplaceAll(output, "\r\n", " "),
310 "\n", " ")), nil
311}
312
313func makeStringList(items []string) *starlark.List {
314 elems := make([]starlark.Value, len(items))
315 for i, item := range items {
316 elems[i] = starlark.String(item)
317 }
318 return starlark.NewList(elems)
319}
320
Sasha Smundake8652d42021-09-24 08:25:17 -0700321func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
322 sep := " "
323 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil {
324 return nil, err
325 }
326 for i, v := range args {
327 if i > 0 {
328 fmt.Fprint(os.Stderr, sep)
329 }
330 if s, ok := starlark.AsString(v); ok {
331 fmt.Fprint(os.Stderr, s)
332 } else if b, ok := v.(starlark.Bytes); ok {
333 fmt.Fprint(os.Stderr, string(b))
334 } else {
335 fmt.Fprintf(os.Stderr, "%s", v)
336 }
337 }
338
339 fmt.Fprintln(os.Stderr)
340 return starlark.None, nil
341}
342
Sasha Smundak24159db2020-10-26 15:43:21 -0700343// Parses, resolves, and executes a Starlark file.
344// filename and src parameters are as for starlark.ExecFile:
345// * filename is the name of the file to execute,
346// and the name that appears in error messages;
347// * src is an optional source of bytes to use instead of filename
348// (it can be a string, or a byte array, or an io.Reader instance)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700349// Returns the top-level starlark variables, the list of starlark files loaded, and an error
Cole Faust386b3742023-06-06 16:55:58 -0700350func Run(filename string, src interface{}, mode ExecutionMode, allowExternalEntrypoint bool) (starlark.StringDict, []string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700351 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call,
352 // which always uses /bin/sh to run the command
353 shellPath := "/bin/sh"
354 if _, err := os.Stat(shellPath); err != nil {
355 shellPath = ""
356 }
357
Sasha Smundak24159db2020-10-26 15:43:21 -0700358 mainThread := &starlark.Thread{
359 Name: "main",
Cole Faustc63ce1a2023-05-09 14:56:36 -0700360 Print: func(_ *starlark.Thread, msg string) {
361 if mode == ExecutionModeRbc {
362 // In rbc mode, rblf_log is used to print to stderr
363 fmt.Println(msg)
Cole Faust5b8dda02023-11-07 11:14:58 -0800364 } else if mode == ExecutionModeScl {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700365 fmt.Fprintln(os.Stderr, msg)
366 }
367 },
Sasha Smundak24159db2020-10-26 15:43:21 -0700368 Load: loader,
369 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700370 filename, err := filepath.Abs(filename)
371 if err != nil {
372 return nil, nil, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700373 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700374 if wd, err := os.Getwd(); err == nil {
375 filename, err = filepath.Rel(wd, filename)
376 if err != nil {
377 return nil, nil, err
378 }
Cole Faust386b3742023-06-06 16:55:58 -0700379 if !allowExternalEntrypoint && strings.HasPrefix(filename, "../") {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700380 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename)
381 }
382 } else {
383 return nil, nil, err
384 }
385
Cole Faustccd26802023-11-09 14:28:34 -0800386 if sym, err := isSymlink(filename); sym && err == nil {
387 return nil, nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", filename)
388 } else if err != nil {
389 return nil, nil, err
390 }
391
Cole Faustc63ce1a2023-05-09 14:56:36 -0700392 // Add top-level file to cache for cycle detection purposes
393 moduleCache[filename] = nil
394
395 var results starlark.StringDict
Cole Faust386b3742023-06-06 16:55:58 -0700396 mainThread.SetLocal(allowExternalEntrypointKey, allowExternalEntrypoint)
Cole Faust5b8dda02023-11-07 11:14:58 -0800397 mainThread.SetLocal(callingFileKey, filename)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700398 mainThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700399 mainThread.SetLocal(shellKey, shellPath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700400 if mode == ExecutionModeRbc {
401 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins)
Cole Faust5b8dda02023-11-07 11:14:58 -0800402 } else if mode == ExecutionModeScl {
403 results, err = starlark.ExecFile(mainThread, filename, src, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700404 } else {
405 return results, nil, fmt.Errorf("unknown executionMode %d", mode)
406 }
407 loadedStarlarkFiles := make([]string, 0, len(moduleCache))
408 for file := range moduleCache {
409 loadedStarlarkFiles = append(loadedStarlarkFiles, file)
410 }
411 sort.Strings(loadedStarlarkFiles)
412
413 return results, loadedStarlarkFiles, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700414}