-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (87 loc) · 2.13 KB
/
main.go
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
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strings"
"github.com/Shashi42/CSCE4600_Project2Shell/builtins"
)
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, " ")
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 "cd":
return builtins.ChangeDirectory(args...)
case "env":
return builtins.EnvironmentVariables(w, args...)
case "ls":
return builtins.ListDirectory(args...)
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()
}