blob: 1d68d43fb5f81f2bab17c8870332c4b39bdb416e [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
34 ExecutionModeMake ExecutionMode = iota
35)
Sasha Smundak24159db2020-10-26 15:43:21 -070036
Cole Faust386b3742023-06-06 16:55:58 -070037const allowExternalEntrypointKey = "allowExternalEntrypoint"
Cole Faustc63ce1a2023-05-09 14:56:36 -070038const callerDirKey = "callerDir"
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 Faustc63ce1a2023-05-09 14:56:36 -070061var makeBuiltins starlark.StringDict = starlark.StringDict{
62 "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 Faust386b3742023-06-06 16:55:58 -0700131 modulePath, err := cleanModuleName(module, thread.Local(callerDirKey).(string), allowExternalEntrypoint)
Sasha Smundak24159db2020-10-26 15:43:21 -0700132 if err != nil {
133 return nil, err
134 }
135 e, ok := moduleCache[modulePath]
136 if e == nil {
137 if ok {
138 return nil, fmt.Errorf("cycle in load graph")
139 }
140
141 // Add a placeholder to indicate "load in progress".
142 moduleCache[modulePath] = nil
143
144 // Decide if we should load.
145 if !mustLoad {
146 if _, err := os.Stat(modulePath); err == nil {
147 mustLoad = true
148 }
149 }
150
151 // Load or return default
152 if mustLoad {
153 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load}
154 // Cheating for the sake of testing:
155 // propagate starlarktest's Reporter key, otherwise testing
156 // the load function may cause panic in starlarktest code.
157 const testReporterKey = "Reporter"
158 if v := thread.Local(testReporterKey); v != nil {
159 childThread.SetLocal(testReporterKey, v)
160 }
161
Cole Faust386b3742023-06-06 16:55:58 -0700162 // Only the entrypoint starlark file allows external loads.
163 childThread.SetLocal(allowExternalEntrypointKey, false)
Sasha Smundak24159db2020-10-26 15:43:21 -0700164 childThread.SetLocal(callerDirKey, filepath.Dir(modulePath))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700165 childThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700166 childThread.SetLocal(shellKey, thread.Local(shellKey))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700167 if mode == ExecutionModeRbc {
168 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins)
169 e = &modentry{globals, err}
170 } else if mode == ExecutionModeMake {
171 globals, err := starlark.ExecFile(childThread, modulePath, nil, makeBuiltins)
172 e = &modentry{globals, err}
173 } else {
174 return nil, fmt.Errorf("unknown executionMode %d", mode)
175 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700176 } else {
177 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil}
178 }
179
180 // Update the cache.
181 moduleCache[modulePath] = e
182 }
183 return e.globals, e.err
184}
185
Sasha Smundak24159db2020-10-26 15:43:21 -0700186// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present,
187// the 'top/pattern' is globbed and then 'top/' prefix is removed.
188func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
189 kwargs []starlark.Tuple) (starlark.Value, error) {
190 var pattern string
191 var top string
192
193 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil {
194 return starlark.None, err
195 }
196
197 var files []string
198 var err error
199 if top == "" {
200 if files, err = filepath.Glob(pattern); err != nil {
201 return starlark.None, err
202 }
203 } else {
204 prefix := top + string(filepath.Separator)
205 if files, err = filepath.Glob(prefix + pattern); err != nil {
206 return starlark.None, err
207 }
208 for i := range files {
209 files[i] = strings.TrimPrefix(files[i], prefix)
210 }
211 }
Cole Faustc7b8b6e2022-04-26 12:03:19 -0700212 // Kati uses glob(3) with no flags, which means it's sorted
213 // because GLOB_NOSORT is not passed. Go's glob is not
214 // guaranteed to sort the results.
215 sort.Strings(files)
Sasha Smundak24159db2020-10-26 15:43:21 -0700216 return makeStringList(files), nil
217}
218
Sasha Smundak6b795dc2021-08-18 16:32:19 -0700219// find(top, pattern, only_files = 0) returns all the paths under 'top'
220// whose basename matches 'pattern' (which is a shell's glob pattern).
221// If 'only_files' is non-zero, only the paths to the regular files are
222// returned. The returned paths are relative to 'top'.
223func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
224 kwargs []starlark.Tuple) (starlark.Value, error) {
225 var top, pattern string
226 var onlyFiles int
227 if err := starlark.UnpackArgs(b.Name(), args, kwargs,
228 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil {
229 return starlark.None, err
230 }
231 top = filepath.Clean(top)
232 pattern = filepath.Clean(pattern)
233 // Go's filepath.Walk is slow, consider using OS's find
234 var res []string
235 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error {
236 if err != nil {
237 if d != nil && d.IsDir() {
238 return fs.SkipDir
239 } else {
240 return nil
241 }
242 }
243 relPath := strings.TrimPrefix(path, top)
244 if len(relPath) > 0 && relPath[0] == os.PathSeparator {
245 relPath = relPath[1:]
246 }
247 // Do not return top-level dir
248 if len(relPath) == 0 {
249 return nil
250 }
251 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) {
252 res = append(res, relPath)
253 }
254 return nil
255 })
256 return makeStringList(res), err
257}
258
Sasha Smundak24159db2020-10-26 15:43:21 -0700259// shell(command) runs OS shell with given command and returns back
260// its output the same way as Make's $(shell ) function. The end-of-lines
261// ("\n" or "\r\n") are replaced with " " in the result, and the trailing
262// end-of-line is removed.
Cole Faustc63ce1a2023-05-09 14:56:36 -0700263func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
Sasha Smundak24159db2020-10-26 15:43:21 -0700264 kwargs []starlark.Tuple) (starlark.Value, error) {
265 var command string
266 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil {
267 return starlark.None, err
268 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700269 shellPath := thread.Local(shellKey).(string)
Sasha Smundak24159db2020-10-26 15:43:21 -0700270 if shellPath == "" {
271 return starlark.None,
Sasha Smundak57bb5082021-04-01 15:51:56 -0700272 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)")
Sasha Smundak24159db2020-10-26 15:43:21 -0700273 }
274 cmd := exec.Command(shellPath, "-c", command)
275 // We ignore command's status
276 bytes, _ := cmd.Output()
277 output := string(bytes)
278 if strings.HasSuffix(output, "\n") {
279 output = strings.TrimSuffix(output, "\n")
280 } else {
281 output = strings.TrimSuffix(output, "\r\n")
282 }
283
284 return starlark.String(
285 strings.ReplaceAll(
286 strings.ReplaceAll(output, "\r\n", " "),
287 "\n", " ")), nil
288}
289
290func makeStringList(items []string) *starlark.List {
291 elems := make([]starlark.Value, len(items))
292 for i, item := range items {
293 elems[i] = starlark.String(item)
294 }
295 return starlark.NewList(elems)
296}
297
Sasha Smundake8652d42021-09-24 08:25:17 -0700298func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
299 sep := " "
300 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil {
301 return nil, err
302 }
303 for i, v := range args {
304 if i > 0 {
305 fmt.Fprint(os.Stderr, sep)
306 }
307 if s, ok := starlark.AsString(v); ok {
308 fmt.Fprint(os.Stderr, s)
309 } else if b, ok := v.(starlark.Bytes); ok {
310 fmt.Fprint(os.Stderr, string(b))
311 } else {
312 fmt.Fprintf(os.Stderr, "%s", v)
313 }
314 }
315
316 fmt.Fprintln(os.Stderr)
317 return starlark.None, nil
318}
319
Sasha Smundak24159db2020-10-26 15:43:21 -0700320// Parses, resolves, and executes a Starlark file.
321// filename and src parameters are as for starlark.ExecFile:
322// * filename is the name of the file to execute,
323// and the name that appears in error messages;
324// * src is an optional source of bytes to use instead of filename
325// (it can be a string, or a byte array, or an io.Reader instance)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700326// Returns the top-level starlark variables, the list of starlark files loaded, and an error
Cole Faust386b3742023-06-06 16:55:58 -0700327func Run(filename string, src interface{}, mode ExecutionMode, allowExternalEntrypoint bool) (starlark.StringDict, []string, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700328 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call,
329 // which always uses /bin/sh to run the command
330 shellPath := "/bin/sh"
331 if _, err := os.Stat(shellPath); err != nil {
332 shellPath = ""
333 }
334
Sasha Smundak24159db2020-10-26 15:43:21 -0700335 mainThread := &starlark.Thread{
336 Name: "main",
Cole Faustc63ce1a2023-05-09 14:56:36 -0700337 Print: func(_ *starlark.Thread, msg string) {
338 if mode == ExecutionModeRbc {
339 // In rbc mode, rblf_log is used to print to stderr
340 fmt.Println(msg)
341 } else if mode == ExecutionModeMake {
342 fmt.Fprintln(os.Stderr, msg)
343 }
344 },
Sasha Smundak24159db2020-10-26 15:43:21 -0700345 Load: loader,
346 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700347 filename, err := filepath.Abs(filename)
348 if err != nil {
349 return nil, nil, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700350 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700351 if wd, err := os.Getwd(); err == nil {
352 filename, err = filepath.Rel(wd, filename)
353 if err != nil {
354 return nil, nil, err
355 }
Cole Faust386b3742023-06-06 16:55:58 -0700356 if !allowExternalEntrypoint && strings.HasPrefix(filename, "../") {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700357 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename)
358 }
359 } else {
360 return nil, nil, err
361 }
362
363 // Add top-level file to cache for cycle detection purposes
364 moduleCache[filename] = nil
365
366 var results starlark.StringDict
Cole Faust386b3742023-06-06 16:55:58 -0700367 mainThread.SetLocal(allowExternalEntrypointKey, allowExternalEntrypoint)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700368 mainThread.SetLocal(callerDirKey, filepath.Dir(filename))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700369 mainThread.SetLocal(executionModeKey, mode)
Cole Faust386b3742023-06-06 16:55:58 -0700370 mainThread.SetLocal(shellKey, shellPath)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700371 if mode == ExecutionModeRbc {
372 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins)
373 } else if mode == ExecutionModeMake {
374 results, err = starlark.ExecFile(mainThread, filename, src, makeBuiltins)
375 } else {
376 return results, nil, fmt.Errorf("unknown executionMode %d", mode)
377 }
378 loadedStarlarkFiles := make([]string, 0, len(moduleCache))
379 for file := range moduleCache {
380 loadedStarlarkFiles = append(loadedStarlarkFiles, file)
381 }
382 sort.Strings(loadedStarlarkFiles)
383
384 return results, loadedStarlarkFiles, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700385}