blob: a0fb9e1687e580eaa012d5f18b6de7f0bbe435ff [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 Faustc63ce1a2023-05-09 14:56:36 -070037const callerDirKey = "callerDir"
38const shellKey = "shell"
39const executionModeKey = "executionMode"
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 Faustc63ce1a2023-05-09 14:56:36 -070060var makeBuiltins starlark.StringDict = starlark.StringDict{
61 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make),
62 "json": starlarkjson.Module,
63}
64
65// Takes a module name (the first argument to the load() function) and returns the path
66// it's trying to load, stripping out leading //, and handling leading :s.
67func cleanModuleName(moduleName string, callerDir string) (string, error) {
68 if strings.Count(moduleName, ":") > 1 {
69 return "", fmt.Errorf("at most 1 colon must be present in starlark path: %s", moduleName)
Sasha Smundak24159db2020-10-26 15:43:21 -070070 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070071
72 // We don't have full support for external repositories, but at least support skylib's dicts.
73 if moduleName == "@bazel_skylib//lib:dicts.bzl" {
74 return "external/bazel-skylib/lib/dicts.bzl", nil
75 }
76
77 localLoad := false
78 if strings.HasPrefix(moduleName, "@//") {
79 moduleName = moduleName[3:]
80 } else if strings.HasPrefix(moduleName, "//") {
81 moduleName = moduleName[2:]
Sasha Smundak24159db2020-10-26 15:43:21 -070082 } else if strings.HasPrefix(moduleName, ":") {
Cole Faustc63ce1a2023-05-09 14:56:36 -070083 moduleName = moduleName[1:]
84 localLoad = true
Sasha Smundak24159db2020-10-26 15:43:21 -070085 } else {
Cole Faustc63ce1a2023-05-09 14:56:36 -070086 return "", fmt.Errorf("load path must start with // or :")
Sasha Smundak24159db2020-10-26 15:43:21 -070087 }
Cole Faustc63ce1a2023-05-09 14:56:36 -070088
89 if ix := strings.LastIndex(moduleName, ":"); ix >= 0 {
90 moduleName = moduleName[:ix] + string(os.PathSeparator) + moduleName[ix+1:]
91 }
92
93 if filepath.Clean(moduleName) != moduleName {
94 return "", fmt.Errorf("load path must be clean, found: %s, expected: %s", moduleName, filepath.Clean(moduleName))
95 }
96 if strings.HasPrefix(moduleName, "../") {
97 return "", fmt.Errorf("load path must not start with ../: %s", moduleName)
98 }
99 if strings.HasPrefix(moduleName, "/") {
100 return "", fmt.Errorf("load path starts with /, use // for a absolute path: %s", moduleName)
101 }
102
103 if localLoad {
104 return filepath.Join(callerDir, moduleName), nil
105 }
106
107 return moduleName, nil
Sasha Smundak24159db2020-10-26 15:43:21 -0700108}
109
110// loader implements load statement. The format of the loaded module URI is
111// [//path]:base[|symbol]
112// The file path is $ROOT/path/base if path is present, <caller_dir>/base otherwise.
113// The presence of `|symbol` indicates that the loader should return a single 'symbol'
114// bound to None if file is missing.
115func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) {
Cole Faustc63ce1a2023-05-09 14:56:36 -0700116 mode := thread.Local(executionModeKey).(ExecutionMode)
Sasha Smundak24159db2020-10-26 15:43:21 -0700117 var defaultSymbol string
Cole Faustc63ce1a2023-05-09 14:56:36 -0700118 mustLoad := true
119 if mode == ExecutionModeRbc {
120 pipePos := strings.LastIndex(module, "|")
121 mustLoad = pipePos < 0
122 if !mustLoad {
123 defaultSymbol = module[pipePos+1:]
124 module = module[:pipePos]
125 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700126 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700127 modulePath, err := cleanModuleName(module, thread.Local(callerDirKey).(string))
Sasha Smundak24159db2020-10-26 15:43:21 -0700128 if err != nil {
129 return nil, err
130 }
131 e, ok := moduleCache[modulePath]
132 if e == nil {
133 if ok {
134 return nil, fmt.Errorf("cycle in load graph")
135 }
136
137 // Add a placeholder to indicate "load in progress".
138 moduleCache[modulePath] = nil
139
140 // Decide if we should load.
141 if !mustLoad {
142 if _, err := os.Stat(modulePath); err == nil {
143 mustLoad = true
144 }
145 }
146
147 // Load or return default
148 if mustLoad {
149 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load}
150 // Cheating for the sake of testing:
151 // propagate starlarktest's Reporter key, otherwise testing
152 // the load function may cause panic in starlarktest code.
153 const testReporterKey = "Reporter"
154 if v := thread.Local(testReporterKey); v != nil {
155 childThread.SetLocal(testReporterKey, v)
156 }
157
158 childThread.SetLocal(callerDirKey, filepath.Dir(modulePath))
Cole Faustc63ce1a2023-05-09 14:56:36 -0700159 childThread.SetLocal(shellKey, thread.Local(shellKey))
160 childThread.SetLocal(executionModeKey, mode)
161 if mode == ExecutionModeRbc {
162 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins)
163 e = &modentry{globals, err}
164 } else if mode == ExecutionModeMake {
165 globals, err := starlark.ExecFile(childThread, modulePath, nil, makeBuiltins)
166 e = &modentry{globals, err}
167 } else {
168 return nil, fmt.Errorf("unknown executionMode %d", mode)
169 }
Sasha Smundak24159db2020-10-26 15:43:21 -0700170 } else {
171 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil}
172 }
173
174 // Update the cache.
175 moduleCache[modulePath] = e
176 }
177 return e.globals, e.err
178}
179
Sasha Smundak24159db2020-10-26 15:43:21 -0700180// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present,
181// the 'top/pattern' is globbed and then 'top/' prefix is removed.
182func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
183 kwargs []starlark.Tuple) (starlark.Value, error) {
184 var pattern string
185 var top string
186
187 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil {
188 return starlark.None, err
189 }
190
191 var files []string
192 var err error
193 if top == "" {
194 if files, err = filepath.Glob(pattern); err != nil {
195 return starlark.None, err
196 }
197 } else {
198 prefix := top + string(filepath.Separator)
199 if files, err = filepath.Glob(prefix + pattern); err != nil {
200 return starlark.None, err
201 }
202 for i := range files {
203 files[i] = strings.TrimPrefix(files[i], prefix)
204 }
205 }
Cole Faustc7b8b6e2022-04-26 12:03:19 -0700206 // Kati uses glob(3) with no flags, which means it's sorted
207 // because GLOB_NOSORT is not passed. Go's glob is not
208 // guaranteed to sort the results.
209 sort.Strings(files)
Sasha Smundak24159db2020-10-26 15:43:21 -0700210 return makeStringList(files), nil
211}
212
Sasha Smundak6b795dc2021-08-18 16:32:19 -0700213// find(top, pattern, only_files = 0) returns all the paths under 'top'
214// whose basename matches 'pattern' (which is a shell's glob pattern).
215// If 'only_files' is non-zero, only the paths to the regular files are
216// returned. The returned paths are relative to 'top'.
217func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
218 kwargs []starlark.Tuple) (starlark.Value, error) {
219 var top, pattern string
220 var onlyFiles int
221 if err := starlark.UnpackArgs(b.Name(), args, kwargs,
222 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil {
223 return starlark.None, err
224 }
225 top = filepath.Clean(top)
226 pattern = filepath.Clean(pattern)
227 // Go's filepath.Walk is slow, consider using OS's find
228 var res []string
229 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error {
230 if err != nil {
231 if d != nil && d.IsDir() {
232 return fs.SkipDir
233 } else {
234 return nil
235 }
236 }
237 relPath := strings.TrimPrefix(path, top)
238 if len(relPath) > 0 && relPath[0] == os.PathSeparator {
239 relPath = relPath[1:]
240 }
241 // Do not return top-level dir
242 if len(relPath) == 0 {
243 return nil
244 }
245 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) {
246 res = append(res, relPath)
247 }
248 return nil
249 })
250 return makeStringList(res), err
251}
252
Sasha Smundak24159db2020-10-26 15:43:21 -0700253// shell(command) runs OS shell with given command and returns back
254// its output the same way as Make's $(shell ) function. The end-of-lines
255// ("\n" or "\r\n") are replaced with " " in the result, and the trailing
256// end-of-line is removed.
Cole Faustc63ce1a2023-05-09 14:56:36 -0700257func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple,
Sasha Smundak24159db2020-10-26 15:43:21 -0700258 kwargs []starlark.Tuple) (starlark.Value, error) {
259 var command string
260 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil {
261 return starlark.None, err
262 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700263 shellPath := thread.Local(shellKey).(string)
Sasha Smundak24159db2020-10-26 15:43:21 -0700264 if shellPath == "" {
265 return starlark.None,
Sasha Smundak57bb5082021-04-01 15:51:56 -0700266 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)")
Sasha Smundak24159db2020-10-26 15:43:21 -0700267 }
268 cmd := exec.Command(shellPath, "-c", command)
269 // We ignore command's status
270 bytes, _ := cmd.Output()
271 output := string(bytes)
272 if strings.HasSuffix(output, "\n") {
273 output = strings.TrimSuffix(output, "\n")
274 } else {
275 output = strings.TrimSuffix(output, "\r\n")
276 }
277
278 return starlark.String(
279 strings.ReplaceAll(
280 strings.ReplaceAll(output, "\r\n", " "),
281 "\n", " ")), nil
282}
283
284func makeStringList(items []string) *starlark.List {
285 elems := make([]starlark.Value, len(items))
286 for i, item := range items {
287 elems[i] = starlark.String(item)
288 }
289 return starlark.NewList(elems)
290}
291
Sasha Smundake8652d42021-09-24 08:25:17 -0700292func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
293 sep := " "
294 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil {
295 return nil, err
296 }
297 for i, v := range args {
298 if i > 0 {
299 fmt.Fprint(os.Stderr, sep)
300 }
301 if s, ok := starlark.AsString(v); ok {
302 fmt.Fprint(os.Stderr, s)
303 } else if b, ok := v.(starlark.Bytes); ok {
304 fmt.Fprint(os.Stderr, string(b))
305 } else {
306 fmt.Fprintf(os.Stderr, "%s", v)
307 }
308 }
309
310 fmt.Fprintln(os.Stderr)
311 return starlark.None, nil
312}
313
Sasha Smundak24159db2020-10-26 15:43:21 -0700314// Parses, resolves, and executes a Starlark file.
315// filename and src parameters are as for starlark.ExecFile:
316// * filename is the name of the file to execute,
317// and the name that appears in error messages;
318// * src is an optional source of bytes to use instead of filename
319// (it can be a string, or a byte array, or an io.Reader instance)
Cole Faustc63ce1a2023-05-09 14:56:36 -0700320// Returns the top-level starlark variables, the list of starlark files loaded, and an error
321func Run(filename string, src interface{}, mode ExecutionMode) (starlark.StringDict, []string, error) {
322 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call,
323 // which always uses /bin/sh to run the command
324 shellPath := "/bin/sh"
325 if _, err := os.Stat(shellPath); err != nil {
326 shellPath = ""
327 }
328
Sasha Smundak24159db2020-10-26 15:43:21 -0700329 mainThread := &starlark.Thread{
330 Name: "main",
Cole Faustc63ce1a2023-05-09 14:56:36 -0700331 Print: func(_ *starlark.Thread, msg string) {
332 if mode == ExecutionModeRbc {
333 // In rbc mode, rblf_log is used to print to stderr
334 fmt.Println(msg)
335 } else if mode == ExecutionModeMake {
336 fmt.Fprintln(os.Stderr, msg)
337 }
338 },
Sasha Smundak24159db2020-10-26 15:43:21 -0700339 Load: loader,
340 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700341 filename, err := filepath.Abs(filename)
342 if err != nil {
343 return nil, nil, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700344 }
Cole Faustc63ce1a2023-05-09 14:56:36 -0700345 if wd, err := os.Getwd(); err == nil {
346 filename, err = filepath.Rel(wd, filename)
347 if err != nil {
348 return nil, nil, err
349 }
350 if strings.HasPrefix(filename, "../") {
351 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename)
352 }
353 } else {
354 return nil, nil, err
355 }
356
357 // Add top-level file to cache for cycle detection purposes
358 moduleCache[filename] = nil
359
360 var results starlark.StringDict
361 mainThread.SetLocal(callerDirKey, filepath.Dir(filename))
362 mainThread.SetLocal(shellKey, shellPath)
363 mainThread.SetLocal(executionModeKey, mode)
364 if mode == ExecutionModeRbc {
365 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins)
366 } else if mode == ExecutionModeMake {
367 results, err = starlark.ExecFile(mainThread, filename, src, makeBuiltins)
368 } else {
369 return results, nil, fmt.Errorf("unknown executionMode %d", mode)
370 }
371 loadedStarlarkFiles := make([]string, 0, len(moduleCache))
372 for file := range moduleCache {
373 loadedStarlarkFiles = append(loadedStarlarkFiles, file)
374 }
375 sort.Strings(loadedStarlarkFiles)
376
377 return results, loadedStarlarkFiles, err
Sasha Smundak24159db2020-10-26 15:43:21 -0700378}