-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
118 lines (104 loc) · 2.49 KB
/
Copy pathmain.go
File metadata and controls
118 lines (104 loc) · 2.49 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
113
114
115
116
117
118
package main
import (
"Project2/builtins"
"bufio"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strings"
)
var currenthistory []string
func main() {
exit := make(chan struct{}, 2) // buffer this so there's no deadlock.
runLoop(os.Stdin, os.Stdout, os.Stderr, exit)
}
func runLoop(r io.Reader, w, errW io.Writer, exit chan struct{}) {
var (
input string
err error
readLoop = bufio.NewReader(r)
)
for {
select {
case <-exit:
_, _ = fmt.Fprintln(w, "exiting gracefully...")
return
default:
if err := printPrompt(w); err != nil {
_, _ = fmt.Fprintln(errW, err)
continue
}
if input, err = readLoop.ReadString('\n'); err != nil {
_, _ = fmt.Fprintln(errW, err)
continue
}
if err = handleInput(w, input, exit); err != nil {
_, _ = fmt.Fprintln(errW, err)
}
}
}
}
func printPrompt(w io.Writer) error {
// Get current user.
// Don't prematurely memoize this because it might change due to `su`?
u, err := user.Current()
if err != nil {
return err
}
// Get current working directory.
wd, err := os.Getwd()
if err != nil {
return err
}
// /home/User [Username] $
_, err = fmt.Fprintf(w, "%v [%v] $ ", wd, u.Username)
return err
}
func handleInput(w io.Writer, input string, exit chan<- struct{}) error {
// Remove trailing spaces.
input = strings.TrimSpace(input)
// Split the input separate the command name and the command arguments.
args := strings.Split(input, " ")
currenthistory = append(currenthistory, input)
name, args := args[0], args[1:]
// Check for built-in commands.
// New builtin commands should be added here. Eventually this should be refactored to its own func.
switch name {
case "pwd":
return builtins.PrintWorkingDirectory(w, args...)
case "history":
histerr, hist := builtins.History(currenthistory, args...)
currenthistory = hist
return histerr
case "cd":
return builtins.ChangeDirectory(args...)
case "env":
return builtins.EnvironmentVariables(w, args...)
case "cat":
builtins.Cat(args...)
return nil
case "echo":
builtins.Echo(args...)
return nil
case "times":
return builtins.Times()
case "shift":
builtins.Shift()
return nil
case "exit":
exit <- struct{}{}
return nil
}
return executeCommand(name, args...)
}
func executeCommand(name string, arg ...string) error {
// Otherwise prep the command
cmd := exec.Command(name, arg...)
// Set the correct output device.
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
// Execute the command and return the error.
return cmd.Run()
}