Browse Source

Implement #EZ5

Alois Mahdal 1 week ago
parent
commit
ceaebda29d
1 changed files with 28 additions and 4 deletions
  1. 28
    4
      app/main.go

+ 28
- 4
app/main.go View File

@@ -54,6 +54,7 @@ const (
54 54
 	CommandTypeExternal
55 55
 	CommandTypeBuiltinExit
56 56
 	CommandTypeBuiltinEcho
57
+	CommandTypeBuiltinType
57 58
 )
58 59
 
59 60
 func getCommand(ctx *Context) (Command, error) {
@@ -71,24 +72,29 @@ func getCommand(ctx *Context) (Command, error) {
71 72
 }
72 73
 
73 74
 func tokenize(str string) []string {
74
-	tokens := make([]string, 2)
75
-	tokens = strings.Fields(str)
75
+	tokens := strings.Fields(str)
76 76
 	return tokens
77 77
 }
78 78
 
79 79
 func parseCommand(command_line string) (Command, error) {
80 80
 	tokens := tokenize(command_line)
81
+	if len(tokens) == 0 {
82
+		return makeCommandNone(), nil
83
+	}
81 84
 	if tokens[0] == "exit" {
82 85
 		return makeCommand(CommandTypeBuiltinExit, tokens), nil
83 86
 	}
84 87
 	if tokens[0] == "echo" {
85 88
 		return makeCommand(CommandTypeBuiltinEcho, tokens), nil
86 89
 	}
87
-	return makeCommandNone(), fmt.Errorf("%s: command not found", tokens[0])
90
+	if tokens[0] == "type" {
91
+		return makeCommand(CommandTypeBuiltinType, tokens), nil
92
+	}
93
+	return makeCommandNone(), fmt.Errorf("%s: not found", tokens[0])
88 94
 }
89 95
 
90 96
 func handleCommand(ctx Context, command Command) {
91
-	_ = ctx
97
+	// fmt.Printf("handleCommand():command=%#v\n", command)
92 98
 	switch command.command_type {
93 99
 	case CommandTypeNone:
94 100
 		return
@@ -96,6 +102,24 @@ func handleCommand(ctx Context, command Command) {
96 102
 		os.Exit(0)
97 103
 	case CommandTypeBuiltinEcho:
98 104
 		fmt.Fprintln(ctx.stdout, strings.Join(command.tokens[1:], " "))
105
+	case CommandTypeBuiltinType:
106
+		if len(command.tokens) != 2 {
107
+			fmt.Fprintln(ctx.stderr, "usage: type COMMAND")
108
+			return
109
+		}
110
+		parsed, err := parseCommand(command.tokens[1])
111
+		if err != nil {
112
+			fmt.Fprintln(ctx.stderr, err)
113
+			return
114
+		}
115
+		switch parsed.command_type {
116
+		case CommandTypeNone:
117
+			panic("impossible parseCommand() result")
118
+		case CommandTypeExternal:
119
+			fmt.Fprintf(ctx.stdout, "%s is an external command\n", parsed.tokens[0])
120
+		default:
121
+			fmt.Fprintf(ctx.stdout, "%s is a shell builtin\n", parsed.tokens[0])
122
+		}
99 123
 	}
100 124
 }
101 125