-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (89 loc) · 1.99 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
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"regexp"
"strconv"
"strings"
"github.com/fatih/color"
)
var history []string
func main() {
reader := bufio.NewReader(os.Stdin)
var pwd string
var currentUser *user.User
var username string
var userHome string
var hostname string
var input string
var err error
for {
if currentUser, err = user.Current(); err == nil {
username = currentUser.Name
userHome = currentUser.HomeDir
} else {
username = "Donkey"
}
if hostname, err = os.Hostname(); err != nil {
hostname = "localhost"
}
if pwd, err = os.Getwd(); err != nil {
pwd = ""
}
c := color.New(color.BgCyan, color.FgBlack, color.Bold)
c.Printf("%s@%s=>%s$", username, hostname, pwd)
input, err = reader.ReadString('\n')
if err != nil {
fmt.Fprint(os.Stderr, err)
}
if err = runCmd(input, userHome); err != nil {
fmt.Fprint(os.Stderr, err, "\n")
}
}
}
func runCmd(input string, userHome string) (err error) {
input = strings.TrimSuffix(input, "\n")
history = append(history, input)
args := strings.Split(input, " ")
histroyR, _ := regexp.Compile("^![0-9]+")
//histroyUP, _ := regexp.Compile("|")
//histroyDOWN, _ := regexp.Compile("^[[B]")
//fmt.Print(args[0])
//fmt.Print(r.MatchString(args[0]))
switch args[0] {
case "cd":
if len(args) < 2 {
return os.Chdir(userHome)
}
return os.Chdir(args[1])
case "exit":
os.Exit(1)
case "":
return
case "history":
if len(args) < 2 {
for i, his := range history {
fmt.Printf("%d %s \n", i+1, his)
}
} else if len(args) == 2 && args[1] == "-c" {
history = nil
fmt.Fprintf(os.Stdout, "History cleared \n")
} else {
return errors.New("sub-command not supported")
}
return
}
if histroyR.MatchString(args[0]) {
num, _ := strconv.Atoi(strings.TrimPrefix(args[0], "!"))
fmt.Fprintln(os.Stdout, history[num-1])
return
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
return cmd.Run()
}