Bläddra i källkod

Implement #FF0

Alois Mahdal 1 vecka sedan
förälder
incheckning
0c380b3206
1 ändrade filer med 46 tillägg och 7 borttagningar
  1. 46
    7
      app/main.go

+ 46
- 7
app/main.go Visa fil

@@ -3,18 +3,57 @@ package main
3 3
 import (
4 4
 	"bufio"
5 5
 	"fmt"
6
+	"io"
6 7
 	"os"
7 8
 )
8 9
 
9
-// Ensures gofmt doesn't remove the "fmt" import in stage 1 (feel free to remove this!)
10
-var _ = fmt.Print
10
+type Context struct {
11
+	stdout io.Writer
12
+	stderr io.Writer
13
+	stdin  io.Reader
14
+}
11 15
 
12
-func main() {
16
+type GetCommandResult int
17
+
18
+const (
19
+	GetCommandResultOk GetCommandResult = iota
20
+	GetCommandResultError
21
+)
22
+
23
+func getCommand(ctx *Context) (string, error) {
13 24
 	fmt.Print("$ ")
14
-	command, err := bufio.NewReader(os.Stdin).ReadString('\n')
25
+	command_line, err := bufio.NewReader(ctx.stdin).ReadString('\n')
26
+	if err != nil {
27
+		return "", err
28
+	}
29
+	command, err := parseCommand(ctx, command_line)
15 30
 	if err != nil {
16
-		fmt.Fprintln(os.Stderr, "Error reading input: ", err)
17
-		os.Exit(1)
31
+		return "", err
32
+	}
33
+	return command, nil
34
+}
35
+
36
+func parseCommand(ctx *Context, command_line string) (string, error) {
37
+	_ = ctx
38
+	return command_line[:len(command_line)-1], nil
39
+}
40
+
41
+func handleCommand(ctx Context, command string) {
42
+	fmt.Fprintln(ctx.stderr, command+": command not found")
43
+}
44
+
45
+func main() {
46
+	ctx := Context{
47
+		stdout: os.Stdout,
48
+		stderr: os.Stderr,
49
+		stdin:  os.Stdin,
50
+	}
51
+	for {
52
+		command, err := getCommand(&ctx)
53
+		if err != nil {
54
+			fmt.Fprintln(os.Stderr, "Error reading input: ", err)
55
+			os.Exit(1)
56
+		}
57
+		handleCommand(ctx, command)
18 58
 	}
19
-	fmt.Println(command[:len(command)-1] + ": command not found")
20 59
 }