瀏覽代碼

Implement #RA6

Alois Mahdal 6 天之前
父節點
當前提交
50551d3ec6
共有 1 個檔案被更改,包括 37 行新增0 行删除
  1. 37
    0
      app/main.go

+ 37
- 0
app/main.go 查看文件

87
 	CommandTypeBuiltinEcho
87
 	CommandTypeBuiltinEcho
88
 	CommandTypeBuiltinType
88
 	CommandTypeBuiltinType
89
 	CommandTypeBuiltinPwd
89
 	CommandTypeBuiltinPwd
90
+	CommandTypeBuiltinCd
90
 )
91
 )
91
 
92
 
92
 func getCommand(ctx *Context) (Command, error) {
93
 func getCommand(ctx *Context) (Command, error) {
139
 	if tokens[0] == "pwd" {
140
 	if tokens[0] == "pwd" {
140
 		return makeCommandBuiltin(CommandTypeBuiltinPwd, tokens), nil
141
 		return makeCommandBuiltin(CommandTypeBuiltinPwd, tokens), nil
141
 	}
142
 	}
143
+	if tokens[0] == "cd" {
144
+		return makeCommandBuiltin(CommandTypeBuiltinCd, tokens), nil
145
+	}
142
 	if tokens[0] == "echo" {
146
 	if tokens[0] == "echo" {
143
 		return makeCommandBuiltin(CommandTypeBuiltinEcho, tokens), nil
147
 		return makeCommandBuiltin(CommandTypeBuiltinEcho, tokens), nil
144
 	}
148
 	}
152
 	return makeCommandExternal(tokens, exec_path), nil
156
 	return makeCommandExternal(tokens, exec_path), nil
153
 }
157
 }
154
 
158
 
159
+func bltnChdir(ctx Context, path string) ExitStatus {
160
+	err := os.Chdir(path)
161
+	if err != nil {
162
+		fmt.Fprintf(ctx.stderr, "cd: %s: No such file or directory\n", path)
163
+		return 4
164
+	}
165
+	return 0
166
+}
167
+
155
 func handleCommand(ctx Context, command Command) ExitStatus {
168
 func handleCommand(ctx Context, command Command) ExitStatus {
156
 	// fmt.Printf("handleCommand():command=%#v\n", command)
169
 	// fmt.Printf("handleCommand():command=%#v\n", command)
157
 	switch command.command_type {
170
 	switch command.command_type {
166
 		fmt.Fprintln(ctx.stdout, strings.Join(command.args, " "))
179
 		fmt.Fprintln(ctx.stdout, strings.Join(command.args, " "))
167
 		return 0
180
 		return 0
168
 
181
 
182
+	case CommandTypeBuiltinCd:
183
+		switch len(command.args) {
184
+		case 0:
185
+			home_path := os.Getenv("HOME")
186
+			if len(home_path) == 0 {
187
+				fmt.Fprintln(ctx.stderr, "error: $HOME environment variable is empty or unset")
188
+				return 4
189
+			}
190
+			return bltnChdir(ctx, home_path)
191
+		case 1:
192
+			if command.args[0] == "~" {
193
+				home_path := os.Getenv("HOME")
194
+				if len(home_path) == 0 {
195
+					fmt.Fprintln(ctx.stderr, "error: $HOME environment variable is empty or unset")
196
+					return 4
197
+				}
198
+				return bltnChdir(ctx, home_path)
199
+			}
200
+			return bltnChdir(ctx, command.args[0])
201
+		default:
202
+			fmt.Fprintln(ctx.stderr, "usage: cd PATH")
203
+			return 2
204
+		}
205
+
169
 	case CommandTypeBuiltinPwd:
206
 	case CommandTypeBuiltinPwd:
170
 		if len(command.args) != 0 {
207
 		if len(command.args) != 0 {
171
 			fmt.Fprintln(ctx.stderr, "usage: pwd")
208
 			fmt.Fprintln(ctx.stderr, "usage: pwd")