blob: 8cd2845faef8933c16e87c6f16446c75c14db6a7 [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"
27 "go.starlark.net/starlarkstruct"
28)
29
Cole Faustc63ce1a2023-05-09 14:56:36 -070030type ExecutionMode int
31const (
32 ExecutionModeRbc ExecutionMode = iota
Cole Faust5b8dda02023-11-07 11:14:58 -080033 ExecutionModeScl ExecutionMode = iota
Cole Faustc63ce1a2023-05-09 14:56:36 -070034)
Sasha Smundak24159db2020-10-26 15:43:21 -070035
Cole Faust386b3742023-06-06 16:55:58 -070036const allowExternalEntrypointKey = "allowExternalEntrypoint"
Cole Faust5b8dda02023-11-07 11:14:58 -080037const callingFileKey = "callingFile"
Cole Faustc63ce1a2023-05-09 14:56:36 -070038const executionModeKey = "executionMode"
Cole Faust386b3742023-06-06 16:55:58 -070039const shellKey = "shell"
Sasha Smundak24159db2020-10-26 15:43:21 -070040
41type modentry struct {
42 globals starlark.StringDict
43 err error
44}
45
46var moduleCache = make(map[string]*modentry)
47
Cole Faustc63ce1a2023-05-09 14:56:36 -070048var rbcBuiltins starlark.StringDict = starlark.StringDict{
49 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make),
50 // To convert find-copy-subdir and product-copy-files-by pattern
51 "rblf_find_files": starlark.NewBuiltin("rblf_find_files", find),
52 // To convert makefile's $(shell cmd)
53 "rblf_shell": starlark.NewBuiltin("rblf_shell", shell),
54 // Output to stderr
55 "rblf_log": starlark.NewBuiltin("rblf_log", log),
56 // To convert makefile's $(wildcard foo*)
57 "rblf_wildcard": starlark.NewBuiltin("rblf_wildcard", wildcard),
58}
Sasha Smundak24159db2020-10-26 15:43:21 -070059
Cole Faust5b8dda02023-11-07 11:14:58 -080060var sclBuiltins starlark.StringDict = starlark.StringDict{
Cole Faustc63ce1a2023-05-09 14:56:36 -070061 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make),
Cole Faustc63ce1a2023-05-09 14:56:36 -070062}
63
Cole Faustccd26802023-11-09 14:28:34 -080064func isSymlink(filepath string) (bool, error) {
65 if info, err := os.Lstat(filepath); err == nil {
66 return info.Mode() & os.ModeSymlink != 0, nil
67 } else {
68 return false, err
69 }
70}
71
Cole Faustc63ce1a2023-05-09 14:56:36 -070072// Takes a module name (the first argument to the load() function) and returns the path
73// it's trying to load, stripping out leading //, and handling leading :s.
Cole Faust386b3742023-06-06 16:55:58 -070074func cleanModuleName(moduleName string, callerDir string, allowExternalPaths bool) (string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -070075 if strings.Count(moduleName, ":") > 1 {
76 return "", fmt.Errorf("at most 1 colon must be present in starlark path: %s", moduleName)
Sasha Smundak24159db2020-10-26 15:43:21 -070077 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070078
79 // We don't have full support for external repositories, but at least support skylib's dicts.
80 if moduleName == "@bazel_skylib//lib:dicts.bzl" {
81 return "external/bazel-skylib/lib/dicts.bzl", nil
82 }
83
84 localLoad := false
85 if strings.HasPrefix(moduleName, "@//") {
86 moduleName = moduleName[3:]
87 } else if strings.HasPrefix(moduleName, "//") {
88 moduleName = moduleName[2:]
Sasha Smundak24159db2020-10-26 15:43:21 -070089 } else if strings.HasPrefix(moduleName, ":") {
Cole Faustc63ce1a2023-05-09 14:56:36 -070090 moduleName = moduleName[1:]
91 localLoad = true
Cole Faust386b3742023-06-06 16:55:58 -070092 } else if !allowExternalPaths {
Cole Faustc63ce1a2023-05-09 14:56:36 -070093 return "", fmt.Errorf("load path must start with // or :")
Sasha Smundak24159db2020-10-26 15:43:21 -070094 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070095
96 if ix := strings.LastIndex(moduleName, ":"); ix >= 0 {
97 moduleName = moduleName[:ix] + string(os.PathSeparator) + moduleName[ix+1:]
98 }
99
100 if filepath.Clean(moduleName) != moduleName {
101 return "", fmt.Errorf("load path must be clean, found: %s, expected: %s", moduleName, filepath.Clean(moduleName))
102 }
Cole Faust386b3742023-06-06 16:55:58 -0700103 if !allowExternalPaths {
104 if strings.HasPrefix(moduleName, "../") {
105 return "", fmt.Errorf("load path must not start with ../: %s", moduleName)
106 }
107 if strings.HasPrefix(moduleName, "/") {
108 return "", fmt.Errorf("load path starts with /, use // for a absolute path: %s", moduleName)
109 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700110 }
111
112 if localLoad {
113 return filepath.Join(callerDir, moduleName), nil
114 }
115
116 return moduleName, nil
Sasha Smundak24159db2020-10-26 15:43:21 -0700117}
118
119// loader implements load statement. The format of the loaded module URI is
120// [//path]:base[|symbol]
121// The file path is $ROOT/path/base if path is present, <caller_dir>/base otherwise.
122// The presence of `|symbol` indicates that the loader should return a single 'symbol'
123// bound to None if file is missing.
124func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700125 mode := thread.Local(executionModeKey).(ExecutionMode)
Cole Faust386b3742023-06-06 16:55:58 -0700126 allowExternalEntrypoint := thread.Local(allowExternalEntrypointKey).(bool)
Sasha Smundak24159db2020-10-26 15:43:21 -0700127 var defaultSymbol string
Cole Faustc63ce1a2023-05-09 14:56:36 -0700128 mustLoad := true
129 if mode == ExecutionModeRbc {
130 pipePos := strings.LastIndex(module, "|")
Cole Faust386b3742023-06-06 16:55:58 -0700131 if pipePos >= 0 {
132 mustLoad = false
Cole Faustc63ce1a2023-05-09 14:56:36 -0700133 defaultSymbol = module[pipePos+1:]
134 module = module[:pipePos]
135 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700136 }
Cole Faust5b8dda02023-11-07 11:14:58 -0800137 callingFile := thread.Local(callingFileKey).(string)
138 modulePath, err := cleanModuleName(module, filepath.Dir(callingFile), allowExternalEntrypoint)
Sasha Smundak24159db2020-10-26 15:43:21 -0700139 if err != nil {
140 return nil, err
141 }
142 e, ok := moduleCache[modulePath]
143 if e == nil {
144 if ok {
145 return nil, fmt.Errorf("cycle in load graph")
146 }
147
148 // Add a placeholder to indicate "load in progress".
149 moduleCache[modulePath] = nil
150
151 // Decide if we should load.
152 if !mustLoad {
153 if _, err := os.Stat(modulePath); err == nil {
154 mustLoad = true
155 }
156 }
157
158 // Load or return default
159 if mustLoad {
Cole Faust5b8dda02023-11-07 11:14:58 -0800160 if strings.HasSuffix(callingFile, ".scl") && !strings.HasSuffix(modulePath, ".scl") {
161 return nil, fmt.Errorf(".scl files can only load other .scl files: %q loads %q", callingFile, modulePath)
162 }
163 // Switch into scl mode from here on
164 if strings.HasSuffix(modulePath, ".scl") {
165 mode = ExecutionModeScl
166 }
Cole Faustccd26802023-11-09 14:28:34 -0800167
168 if sym, err := isSymlink(modulePath); sym && err == nil {
169 return nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", modulePath)
170 } else if err != nil {
171 return nil, err
172 }
173
Sasha Smundak24159db2020-10-26 15:43:21 -0700174 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load}
175 // Cheating for the sake of testing:
176 // propagate starlarktest's Reporter key, otherwise testing
177 // the load function may cause panic in starlarktest code.
178 const testReporterKey = "Reporter"
179 if v := thread.Local(testReporterKey); v != nil {
180 childThread.SetLocal(testReporterKey, v)
181 }
182
Cole Faust386b3742023-06-06 16:55:58 -0700183 // Only the entrypoint starlark file allows external loads.
184 childThread.SetLocal(allowExternalEntrypointKey, false)
Cole Faust5b8dda02023-11-07 11:14:58 -0800185 childThread.SetLocal(callingFileKey, modulePath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700186 childThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700187 childThread.SetLocal(shellKey, thread.Local(shellKey))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700188 if mode == ExecutionModeRbc {
189 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins)
190 e = &modentry{globals, err}
Cole Faust5b8dda02023-11-07 11:14:58 -0800191 } else if mode == ExecutionModeScl {
192 globals, err := starlark.ExecFile(childThread, modulePath, nil, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700193 e = &modentry{globals, err}
194 } else {
195 return nil, fmt.Errorf("unknown executionMode %d", mode)
196 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700197 } else {
198 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil}
199 }
200
201 // Update the cache.
202 moduleCache[modulePath] = e
203 }
204 return e.globals, e.err
205}
206
Sasha Smundak24159db2020-10-26 15:43:21 -0700207// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present,
208// the 'top/pattern' is globbed and then 'top/' prefix is removed.
209func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
210 kwargs []starlark.Tuple) (starlark.Value, error) {
211 var pattern string
212 var top string
213
214 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil {
215 return starlark.None, err
216 }
217
218 var files []string
219 var err error
220 if top == "" {
221 if files, err = filepath.Glob(pattern); err != nil {
222 return starlark.None, err
223 }
224 } else {
225 prefix := top + string(filepath.Separator)
226 if files, err = filepath.Glob(prefix + pattern); err != nil {
227 return starlark.None, err
228 }
229 for i := range files {
230 files[i] = strings.TrimPrefix(files[i], prefix)
231 }
232 }
Cole Faustc7b8b6e2022-04-26 12:03:19 -0700233 // Kati uses glob(3) with no flags, which means it's sorted
234 // because GLOB_NOSORT is not passed. Go's glob is not
235 // guaranteed to sort the results.
236 sort.Strings(files)
Sasha Smundak24159db2020-10-26 15:43:21 -0700237 return makeStringList(files), nil
238}
239
Sasha Smundak6b795dc2021-08-18 16:32:19 -0700240// find(top, pattern, only_files = 0) returns all the paths under 'top'
241// whose basename matches 'pattern' (which is a shell's glob pattern).
242// If 'only_files' is non-zero, only the paths to the regular files are
243// returned. The returned paths are relative to 'top'.
244func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
245 kwargs []starlark.Tuple) (starlark.Value, error) {
246 var top, pattern string
247 var onlyFiles int
248 if err := starlark.UnpackArgs(b.Name(), args, kwargs,
249 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil {
250 return starlark.None, err
251 }
252 top = filepath.Clean(top)
253 pattern = filepath.Clean(pattern)
254 // Go's filepath.Walk is slow, consider using OS's find
255 var res []string
256 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error {
257 if err != nil {
258 if d != nil && d.IsDir() {
259 return fs.SkipDir
260 } else {
261 return nil
262 }
263 }
264 relPath := strings.TrimPrefix(path, top)
265 if len(relPath) > 0 && relPath[0] == os.PathSeparator {
266 relPath = relPath[1:]
267 }
268 // Do not return top-level dir
269 if len(relPath) == 0 {
270 return nil
271 }
272 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) {
273 res = append(res, relPath)
274 }
275 return nil
276 })
277 return makeStringList(res), err
278}
279
Sasha Smundak24159db2020-10-26 15:43:21 -0700280// shell(command) runs OS shell with given command and returns back
281// its output the same way as Make's $(shell ) function. The end-of-lines
282// ("\n" or "\r\n") are replaced with " " in the result, and the trailing
283// end-of-line is removed.
Cole Faustc63ce1a2023-05-09 14:56:36 -0700284func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
Sasha Smundak24159db2020-10-26 15:43:21 -0700285 kwargs []starlark.Tuple) (starlark.Value, error) {
286 var command string
287 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil {
288 return starlark.None, err
289 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700290 shellPath := thread.Local(shellKey).(string)
Sasha Smundak24159db2020-10-26 15:43:21 -0700291 if shellPath == "" {
292 return starlark.None,
Sasha Smundak57bb5082021-04-01 15:51:56 -0700293 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)")
Sasha Smundak24159db2020-10-26 15:43:21 -0700294 }
295 cmd := exec.Command(shellPath, "-c", command)
296 // We ignore command's status
297 bytes, _ := cmd.Output()
298 output := string(bytes)
299 if strings.HasSuffix(output, "\n") {
300 output = strings.TrimSuffix(output, "\n")
301 } else {
302 output = strings.TrimSuffix(output, "\r\n")
303 }
304
305 return starlark.String(
306 strings.ReplaceAll(
307 strings.ReplaceAll(output, "\r\n", " "),
308 "\n", " ")), nil
309}
310
311func makeStringList(items []string) *starlark.List {
312 elems := make([]starlark.Value, len(items))
313 for i, item := range items {
314 elems[i] = starlark.String(item)
315 }
316 return starlark.NewList(elems)
317}
318
Sasha Smundake8652d42021-09-24 08:25:17 -0700319func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
320 sep := " "
321 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil {
322 return nil, err
323 }
324 for i, v := range args {
325 if i > 0 {
326 fmt.Fprint(os.Stderr, sep)
327 }
328 if s, ok := starlark.AsString(v); ok {
329 fmt.Fprint(os.Stderr, s)
330 } else if b, ok := v.(starlark.Bytes); ok {
331 fmt.Fprint(os.Stderr, string(b))
332 } else {
333 fmt.Fprintf(os.Stderr, "%s", v)
334 }
335 }
336
337 fmt.Fprintln(os.Stderr)
338 return starlark.None, nil
339}
340
Sasha Smundak24159db2020-10-26 15:43:21 -0700341// Parses, resolves, and executes a Starlark file.
342// filename and src parameters are as for starlark.ExecFile:
343// * filename is the name of the file to execute,
344// and the name that appears in error messages;
345// * src is an optional source of bytes to use instead of filename
346// (it can be a string, or a byte array, or an io.Reader instance)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700347// Returns the top-level starlark variables, the list of starlark files loaded, and an error
Cole Faust386b3742023-06-06 16:55:58 -0700348func Run(filename string, src interface{}, mode ExecutionMode, allowExternalEntrypoint bool) (starlark.StringDict, []string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700349 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call,
350 // which always uses /bin/sh to run the command
351 shellPath := "/bin/sh"
352 if _, err := os.Stat(shellPath); err != nil {
353 shellPath = ""
354 }
355
Sasha Smundak24159db2020-10-26 15:43:21 -0700356 mainThread := &starlark.Thread{
357 Name: "main",
Cole Faustc63ce1a2023-05-09 14:56:36 -0700358 Print: func(_ *starlark.Thread, msg string) {
359 if mode == ExecutionModeRbc {
360 // In rbc mode, rblf_log is used to print to stderr
361 fmt.Println(msg)
Cole Faust5b8dda02023-11-07 11:14:58 -0800362 } else if mode == ExecutionModeScl {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700363 fmt.Fprintln(os.Stderr, msg)
364 }
365 },
Sasha Smundak24159db2020-10-26 15:43:21 -0700366 Load: loader,
367 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700368 filename, err := filepath.Abs(filename)
369 if err != nil {
370 return nil, nil, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700371 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700372 if wd, err := os.Getwd(); err == nil {
373 filename, err = filepath.Rel(wd, filename)
374 if err != nil {
375 return nil, nil, err
376 }
Cole Faust386b3742023-06-06 16:55:58 -0700377 if !allowExternalEntrypoint && strings.HasPrefix(filename, "../") {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700378 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename)
379 }
380 } else {
381 return nil, nil, err
382 }
383
Cole Faustccd26802023-11-09 14:28:34 -0800384 if sym, err := isSymlink(filename); sym && err == nil {
385 return nil, nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", filename)
386 } else if err != nil {
387 return nil, nil, err
388 }
389
Cole Faust63092342023-11-13 11:21:08 -0800390 if mode == ExecutionModeScl && !strings.HasSuffix(filename, ".scl") {
391 return nil, nil, fmt.Errorf("filename must end in .scl: %s", filename)
392 }
393
Cole Faustc63ce1a2023-05-09 14:56:36 -0700394 // Add top-level file to cache for cycle detection purposes
395 moduleCache[filename] = nil
396
397 var results starlark.StringDict
Cole Faust386b3742023-06-06 16:55:58 -0700398 mainThread.SetLocal(allowExternalEntrypointKey, allowExternalEntrypoint)
Cole Faust5b8dda02023-11-07 11:14:58 -0800399 mainThread.SetLocal(callingFileKey, filename)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700400 mainThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700401 mainThread.SetLocal(shellKey, shellPath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700402 if mode == ExecutionModeRbc {
403 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins)
Cole Faust5b8dda02023-11-07 11:14:58 -0800404 } else if mode == ExecutionModeScl {
405 results, err = starlark.ExecFile(mainThread, filename, src, sclBuiltins)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700406 } else {
407 return results, nil, fmt.Errorf("unknown executionMode %d", mode)
408 }
409 loadedStarlarkFiles := make([]string, 0, len(moduleCache))
410 for file := range moduleCache {
411 loadedStarlarkFiles = append(loadedStarlarkFiles, file)
412 }
413 sort.Strings(loadedStarlarkFiles)
414
415 return results, loadedStarlarkFiles, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700416}