aboutsummaryrefslogtreecommitdiffstats
path: root/commands/z.go
blob: 966e2ce9368c1a49e2c5d40ceec10fcd2ddd6f85 (plain) (blame)
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
package commands

import (
	"errors"
	"os"
	"os/exec"
	"strings"
)

type Zoxide struct{}

func ZoxideAdd(arg string) error {
	zargs := []string{"add", arg}
	cmd := exec.Command("zoxide", zargs...)
	err := cmd.Run()
	return err
}

func ZoxideQuery(args []string) (string, error) {
	zargs := append([]string{"query"}, args[1:]...)
	cmd := exec.Command("zoxide", zargs...)
	res, err := cmd.Output()
	return strings.TrimSuffix(string(res), "\n"), err
}

func init() {
	_, err := exec.LookPath("zoxide")
	if err == nil {
		register(Zoxide{})
	}
}

func (Zoxide) Aliases() []string {
	return []string{"z"}
}

func (Zoxide) Complete(args []string) []string {
	return ChangeDirectory{}.Complete(args)
}

// Execute calls zoxide add and query and delegates actually changing the
// directory to ChangeDirectory
func (Zoxide) Execute(args []string) error {
	if len(args) < 1 {
		return errors.New("Usage: z [directory or zoxide query]")
	}
	target := strings.Join(args[1:], " ")
	switch target {
	case "":
		return ChangeDirectory{}.Execute(args)
	case "-":
		if previousDir != "" {
			err := ZoxideAdd(previousDir)
			if err != nil {
				return err
			}
		}
		return ChangeDirectory{}.Execute(args)
	default:
		_, err := os.Stat(target)
		if err != nil {
			// not a file, assume zoxide query
			res, err := ZoxideQuery(args)
			if err != nil {
				return errors.New("zoxide: no match found")
			} else {
				err := ZoxideAdd(res)
				if err != nil {
					return err
				}
				return ChangeDirectory{}.Execute([]string{"z", res})
			}

		} else {
			err := ZoxideAdd(target)
			if err != nil {
				return err
			}
			return ChangeDirectory{}.Execute(args)
		}

	}
}