-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuiltins.go
More file actions
112 lines (104 loc) · 2.14 KB
/
builtins.go
File metadata and controls
112 lines (104 loc) · 2.14 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"errors"
"os"
"strconv"
)
type builtinFunc func(sh *Shell, std StdStreams, args []string) (RunningJob, error)
var builtins map[string]builtinFunc
func init() {
builtins = map[string]builtinFunc{
"cd": builtinCd,
"exit": builtinExit,
"return": builtinReturn,
"shift": builtinShift,
}
}
func builtinCd(sh *Shell, std StdStreams, args []string) (RunningJob, error) {
var (
dir = ""
err error
)
switch len(args) {
case 0:
dir, err = os.UserHomeDir()
case 1:
dir = args[0]
default:
err = errors.New("cd: wrong number of arguments")
}
if err != nil {
return nil, err
}
err = sh.SetCwd(dir)
if err != nil {
return nil, err
}
return &ImmediateRunningJob{name: "cd"}, nil
}
func builtinExit(sh *Shell, std StdStreams, args []string) (RunningJob, error) {
var (
code int64
err error
)
switch len(args) {
case 0:
// default exit code
case 1:
codeStr := args[0]
code, err = strconv.ParseInt(codeStr, 10, 64)
if err != nil {
return nil, err
}
default:
return nil, errors.New("exit: wrong number of arguments")
}
sh.Exit(int(code))
return &ImmediateRunningJob{name: "exit"}, nil
}
func builtinReturn(sh *Shell, std StdStreams, args []string) (RunningJob, error) {
var (
code int64
err error
)
switch len(args) {
case 0:
// default return code
case 1:
codeStr := args[0]
code, err = strconv.ParseInt(codeStr, 10, 64)
if err != nil {
return nil, err
}
default:
return nil, errors.New("return: wrong number of arguments")
}
err = sh.Return(int(code))
if err != nil {
return nil, err
}
return &ImmediateRunningJob{name: "return"}, nil
}
func builtinShift(sh *Shell, std StdStreams, args []string) (RunningJob, error) {
var (
shift uint64
err error
)
switch len(args) {
case 0:
shift = 1
case 1:
codeStr := args[0]
shift, err = strconv.ParseUint(codeStr, 10, 64)
if err != nil {
return nil, err
}
default:
return nil, errors.New("return: wrong number of arguments")
}
if sh.ArgCount() < int(shift) {
return nil, errors.New("shift count must be at most $#")
}
sh.ShiftArgs(int(shift))
return &ImmediateRunningJob{name: "shift"}, nil
}