Bladeren bron

Implement #RA6

Alois Mahdal 6 dagen geleden
bovenliggende
commit
50551d3ec6
1 gewijzigde bestanden met toevoegingen van 37 en 0 verwijderingen
  1. 37
    0
      app/main.go

+ 37
- 0
app/main.go Bestand weergeven

@@ -87,6 +87,7 @@ const (
87 87
 	CommandTypeBuiltinEcho
88 88
 	CommandTypeBuiltinType
89 89
 	CommandTypeBuiltinPwd
90
+	CommandTypeBuiltinCd
90 91
 )
91 92
 
92 93
 func getCommand(ctx *Context) (Command, error) {
@@ -139,6 +140,9 @@ func parseCommand(command_line string) (Command, error) {
139 140
 	if tokens[0] == "pwd" {
140 141
 		return makeCommandBuiltin(CommandTypeBuiltinPwd, tokens), nil
141 142
 	}
143
+	if tokens[0] == "cd" {
144
+		return makeCommandBuiltin(CommandTypeBuiltinCd, tokens), nil
145
+	}
142 146
 	if tokens[0] == "echo" {
143 147
 		return makeCommandBuiltin(CommandTypeBuiltinEcho, tokens), nil
144 148
 	}
@@ -152,6 +156,15 @@ func parseCommand(command_line string) (Command, error) {
152 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 168
 func handleCommand(ctx Context, command Command) ExitStatus {
156 169
 	// fmt.Printf("handleCommand():command=%#v\n", command)
157 170
 	switch command.command_type {
@@ -166,6 +179,30 @@ func handleCommand(ctx Context, command Command) ExitStatus {
166 179
 		fmt.Fprintln(ctx.stdout, strings.Join(command.args, " "))
167 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 206
 	case CommandTypeBuiltinPwd:
170 207
 		if len(command.args) != 0 {
171 208
 			fmt.Fprintln(ctx.stderr, "usage: pwd")