Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 1 | // 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 | |
| 15 | package rbcrun |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
Sasha Smundak | 6b795dc | 2021-08-18 16:32:19 -0700 | [diff] [blame] | 19 | "io/fs" |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 20 | "os" |
| 21 | "os/exec" |
| 22 | "path/filepath" |
Cole Faust | c7b8b6e | 2022-04-26 12:03:19 -0700 | [diff] [blame] | 23 | "sort" |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 24 | "strings" |
| 25 | |
| 26 | "go.starlark.net/starlark" |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 27 | "go.starlark.net/starlarkjson" |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 28 | "go.starlark.net/starlarkstruct" |
| 29 | ) |
| 30 | |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 31 | type ExecutionMode int |
| 32 | const ( |
| 33 | ExecutionModeRbc ExecutionMode = iota |
| 34 | ExecutionModeMake ExecutionMode = iota |
| 35 | ) |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 36 | |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 37 | const callerDirKey = "callerDir" |
| 38 | const shellKey = "shell" |
| 39 | const executionModeKey = "executionMode" |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 40 | |
| 41 | type modentry struct { |
| 42 | globals starlark.StringDict |
| 43 | err error |
| 44 | } |
| 45 | |
| 46 | var moduleCache = make(map[string]*modentry) |
| 47 | |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 48 | var 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 59 | |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 60 | var 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. |
| 67 | func 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 70 | } |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 71 | |
| 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 82 | } else if strings.HasPrefix(moduleName, ":") { |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 83 | moduleName = moduleName[1:] |
| 84 | localLoad = true |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 85 | } else { |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 86 | return "", fmt.Errorf("load path must start with // or :") |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 87 | } |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 88 | |
| 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 108 | } |
| 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. |
| 115 | func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) { |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 116 | mode := thread.Local(executionModeKey).(ExecutionMode) |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 117 | var defaultSymbol string |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 118 | 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 126 | } |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 127 | modulePath, err := cleanModuleName(module, thread.Local(callerDirKey).(string)) |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 128 | 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 Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 159 | 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 170 | } 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 180 | // 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. |
| 182 | func 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 Faust | c7b8b6e | 2022-04-26 12:03:19 -0700 | [diff] [blame] | 206 | // 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 210 | return makeStringList(files), nil |
| 211 | } |
| 212 | |
Sasha Smundak | 6b795dc | 2021-08-18 16:32:19 -0700 | [diff] [blame] | 213 | // 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'. |
| 217 | func 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 253 | // 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 Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 257 | func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 258 | 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 Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 263 | shellPath := thread.Local(shellKey).(string) |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 264 | if shellPath == "" { |
| 265 | return starlark.None, |
Sasha Smundak | 57bb508 | 2021-04-01 15:51:56 -0700 | [diff] [blame] | 266 | fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)") |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 267 | } |
| 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 | |
| 284 | func 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 Smundak | e8652d4 | 2021-09-24 08:25:17 -0700 | [diff] [blame] | 292 | func 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 314 | // 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 Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 320 | // Returns the top-level starlark variables, the list of starlark files loaded, and an error |
| 321 | func 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 329 | mainThread := &starlark.Thread{ |
| 330 | Name: "main", |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 331 | 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 339 | Load: loader, |
| 340 | } |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 341 | filename, err := filepath.Abs(filename) |
| 342 | if err != nil { |
| 343 | return nil, nil, err |
Sasha Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 344 | } |
Cole Faust | c63ce1a | 2023-05-09 14:56:36 -0700 | [diff] [blame^] | 345 | 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 Smundak | 24159db | 2020-10-26 15:43:21 -0700 | [diff] [blame] | 378 | } |