summaryrefslogtreecommitdiff
path: root/cmds/cmds.go
blob: f61f2b85c7a60fc52ee93820b9e211fffa3ffd90 (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
package cmds

import (
	"errors"
	"os"
	"strings"
)

func Eval(cmd string) error {
	args := strings.Split(cmd, " ")
	switch args[0] {
	case "cd":
		if err := chDir(args); err != nil {
			return err
		}
		break
	case "export":
		if err := export(args); err != nil {
			return err
		}
		break
	case "unset":
		if len(args) == 1 || len(args) >= 3{
			return errors.New("unset: usage: name")
		}
		os.Unsetenv(args[1])
		break
	case ":":
		return nil
	}
	return nil
}

func chDir(args []string) error {
	var dir string
	if len(args) == 1 {
		dir, _ = os.UserHomeDir()
	} else {
		dir = args[1]
	}
	return os.Chdir(dir)
}

func export(args []string) error {
	if len(args) == 1 || len(args) >= 3 {
		return errors.New("export: usage: name=value")
	}
	tmp := strings.Split(args[1], "=")
	if len(tmp) != 2 {
		return errors.New("export: usage: name=value")
	}
	return os.Setenv(tmp[0], tmp[1])
}