blob: 4db6a0bf3814f6fd97bf3212c7bcdef947d8381c [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 main
16
17import (
18 "flag"
19 "fmt"
20 "go.starlark.net/starlark"
21 "os"
22 "rbcrun"
23 "strings"
24)
25
26var (
27 execprog = flag.String("c", "", "execute program `prog`")
28 rootdir = flag.String("d", ".", "the value of // for load paths")
29 file = flag.String("f", "", "file to execute")
30 perfFile = flag.String("perf", "", "save performance data")
31)
32
33func main() {
34 flag.Parse()
35 filename := *file
36 var src interface{}
37 var env []string
38
39 rc := 0
40 for _, arg := range flag.Args() {
41 if strings.Contains(arg, "=") {
42 env = append(env, arg)
43 } else if filename == "" {
44 filename = arg
45 } else {
46 quit("only one file can be executed\n")
47 }
48 }
49 if *execprog != "" {
50 if filename != "" {
51 quit("either -c or file name should be present\n")
52 }
53 filename = "<cmdline>"
54 src = *execprog
55 }
56 if filename == "" {
57 if len(env) > 0 {
58 fmt.Fprintln(os.Stderr,
59 "no file to run -- if your file's name contains '=', use -f to specify it")
60 }
61 flag.Usage()
62 os.Exit(1)
63 }
64 if stat, err := os.Stat(*rootdir); os.IsNotExist(err) || !stat.IsDir() {
65 quit("%s is not a directory\n", *rootdir)
66 }
67 if *perfFile != "" {
68 pprof, err := os.Create(*perfFile)
69 if err != nil {
70 quit("%s: err", *perfFile)
71 }
72 defer pprof.Close()
73 if err := starlark.StartProfile(pprof); err != nil {
74 quit("%s\n", err)
75 }
76 }
77 rbcrun.LoadPathRoot = *rootdir
78 err := rbcrun.Run(filename, src, env)
79 if *perfFile != "" {
80 if err2 := starlark.StopProfile(); err2 != nil {
81 fmt.Fprintln(os.Stderr, err2)
82 rc = 1
83 }
84 }
85 if err != nil {
86 if evalErr, ok := err.(*starlark.EvalError); ok {
87 quit("%s\n", evalErr.Backtrace())
88 } else {
89 quit("%s\n", err)
90 }
91 }
92 os.Exit(rc)
93}
94
95func quit(format string, s ...interface{}) {
Cole Fauste95122e2021-10-13 12:15:21 -070096 fmt.Fprintf(os.Stderr, format, s...)
Sasha Smundak24159db2020-10-26 15:43:21 -070097 os.Exit(2)
98}