aboutsummaryrefslogtreecommitdiff
path: root/cmd/myshell/main.go
blob: 97cf8dc90f31b4e1cdc23e3c3e29b1093e6d2e87 (plain)
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
119
package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"
)

func main() {
	stdin := bufio.NewReader(os.Stdin)
	for {
		fmt.Fprint(os.Stdout, "$ ")

		in, err := stdin.ReadString('\n')
		if err != nil {
			fmt.Println(err.Error())
		}

		trim := strings.TrimSpace(in)

		command := strings.Split(trim, " ")

		switch command[0] {
		case "exit":
			Exit(command[1])
		case "echo":
			Echo(command[1:])
		case "type":
			Type(command[1])
		case "pwd":
			Pwd()
		case "cd":
			Cd(command[1])
		default:
			executable := exec.Command(command[0], command[1:]...)
			executable.Stderr = os.Stderr
			executable.Stdout = os.Stdout

			err := executable.Run()

			if err != nil {
				fmt.Printf("%s: command not found\n", command[0])
			}
		}
	}
}

func Cd(dir string) {
	if len(dir) < 1 {
		fmt.Println("path expected")
		return
	}

	p := path.Clean(dir)

	if !path.IsAbs(p) && dir != "~" {
		dir, _ := os.Getwd()
		p = path.Join(dir, p)
	}

	if dir == "~" {
		home, _ := os.UserHomeDir()
		p = home + "/"
	}

	err := os.Chdir(p)

	if err != nil {
		fmt.Printf("%s: No such file or directory\n", p)
	}
}

func Pwd() {
	dir, err := os.Getwd()

	if err != nil {
		fmt.Println(err.Error())
	}

	fmt.Println(dir)
}

func Echo(message []string) {
	fmt.Println(strings.Join(message, " "))
}

func Exit(code string) {
	exitCode, err := strconv.Atoi(code)

	if err != nil {
		fmt.Println(err.Error())
	}

	os.Exit(exitCode)
}

func Type(command string) {
	switch command {
	case "exit", "echo", "type":
		fmt.Printf("%s is a shell builtin\n", command)
	default:
		env := os.Getenv("PATH")
		paths := strings.Split(env, ":")

		for _, path := range paths {
			exec := path + "/" + command

			if _, err := os.Stat(exec); err == nil {
				fmt.Printf("%s is %s\n", command, exec)
				return
			}
		}
		fmt.Printf("%s not found\n", command)
	}
}