github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/cmds/elvish/program/shell/script.go (about) 1 package shell 2 3 import ( 4 "errors" 5 "fmt" 6 "io/ioutil" 7 "path/filepath" 8 "unicode/utf8" 9 10 "github.com/u-root/u-root/cmds/elvish/eval" 11 "github.com/u-root/u-root/cmds/elvish/parse" 12 ) 13 14 // script evaluates a script. The returned error contains enough context and can 15 // be printed as-is (with util.PprintError). 16 func script(ev *eval.Evaler, args []string, cmd, compileOnly bool) error { 17 arg0 := args[0] 18 ev.SetArgs(args[1:]) 19 20 var name, path, code string 21 if cmd { 22 name = "code from -c" 23 path = "" 24 code = arg0 25 } else { 26 var err error 27 name = arg0 28 path, err = filepath.Abs(name) 29 if err != nil { 30 return fmt.Errorf("cannot get full path of script %q: %v", name, err) 31 } 32 code, err = readFileUTF8(path) 33 if err != nil { 34 return fmt.Errorf("cannot read script %q: %v", name, err) 35 } 36 } 37 38 n, err := parse.Parse(name, code) 39 if err != nil { 40 return err 41 } 42 43 src := eval.NewScriptSource(name, path, code) 44 op, err := ev.Compile(n, src) 45 if err != nil { 46 return err 47 } 48 if compileOnly { 49 return nil 50 } 51 52 return ev.EvalWithStdPorts(op, src) 53 } 54 55 var errSourceNotUTF8 = errors.New("source is not UTF-8") 56 57 func readFileUTF8(fname string) (string, error) { 58 bytes, err := ioutil.ReadFile(fname) 59 if err != nil { 60 return "", err 61 } 62 if !utf8.Valid(bytes) { 63 return "", errSourceNotUTF8 64 } 65 return string(bytes), nil 66 }