File: script.go

package info (click to toggle)
elvish 0.12%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,532 kB
  • sloc: python: 108; makefile: 94; sh: 72; xml: 9
file content (66 lines) | stat: -rw-r--r-- 1,299 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package shell

import (
	"errors"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"unicode/utf8"

	"github.com/elves/elvish/eval"
	"github.com/elves/elvish/parse"
)

// script evaluates a script. The returned error contains enough context and can
// be printed as-is (with util.PprintError).
func script(ev *eval.Evaler, args []string, cmd, compileOnly bool) error {
	arg0 := args[0]
	ev.SetArgs(args[1:])

	var name, path, code string
	if cmd {
		name = "code from -c"
		path = ""
		code = arg0
	} else {
		var err error
		name = arg0
		path, err = filepath.Abs(name)
		if err != nil {
			return fmt.Errorf("cannot get full path of script %q: %v", name, err)
		}
		code, err = readFileUTF8(path)
		if err != nil {
			return fmt.Errorf("cannot read script %q: %v", name, err)
		}
	}

	n, err := parse.Parse(name, code)
	if err != nil {
		return err
	}

	src := eval.NewScriptSource(name, path, code)
	op, err := ev.Compile(n, src)
	if err != nil {
		return err
	}
	if compileOnly {
		return nil
	}

	return ev.EvalWithStdPorts(op, src)
}

var errSourceNotUTF8 = errors.New("source is not UTF-8")

func readFileUTF8(fname string) (string, error) {
	bytes, err := ioutil.ReadFile(fname)
	if err != nil {
		return "", err
	}
	if !utf8.Valid(bytes) {
		return "", errSourceNotUTF8
	}
	return string(bytes), nil
}