Debian Codegraph @

commands/z.go

raw
1 package commands
2
3 import (
4 "errors"
5 "os"
6 "os/exec"
7 "strings"
8
9 "git.sr.ht/~rjarry/aerc/lib/xdg"
10 )
11
12 type Zoxide struct {
13 Args []string `opt:"..." required:"false" metavar:"<query>..." complete:"CompleteFolder" desc:"Target folder."`
14 }
15
16 func ZoxideAdd(arg string) error {
17 zargs := []string{"add", arg}
18 cmd := exec.Command("zoxide", zargs...)
19 err := cmd.Run()
20 return err
21 }
22
23 func ZoxideQuery(args []string) (string, error) {
24 zargs := append([]string{"query"}, args...)
25 cmd := exec.Command("zoxide", zargs...)
26 res, err := cmd.Output()
27 return strings.TrimSuffix(string(res), "\n"), err
28 }
29
30 func init() {
31 _, err := exec.LookPath("zoxide")
32 if err == nil {
33 Register(Zoxide{})
34 }
35 }
36
37 func (Zoxide) Description() string {
38 return "Change aerc's current working directory using zoxide."
39 }
40
41 func (Zoxide) Context() CommandContext {
42 return GLOBAL
43 }
44
45 func (Zoxide) Aliases() []string {
46 return []string{"z"}
47 }
48
49 func (*Zoxide) CompleteFolder(arg string) []string {
50 return CompletePath(arg, true)
51 }
52
53 // Execute calls zoxide add and query and delegates actually changing the
54 // directory to ChangeDirectory
55 func (z Zoxide) Execute(args []string) error {
56 if len(z.Args) == 0 {
57 z.Args = []string{"~"}
58 }
59 if len(z.Args) == 1 && (z.Args[0] == "~" || z.Args[0] == "-") {
60 if previousDir != "" {
61 err := ZoxideAdd(previousDir)
62 if err != nil {
63 return err
64 }
65 }
66 return ChangeDirectory{Target: z.Args[0]}.Execute(args)
67 } else {
68 target := xdg.ExpandHome(z.Args[0])
69 _, err := os.Stat(target)
70 if err != nil || len(z.Args) > 1 {
71 // not a file, assume zoxide query
72 res, err := ZoxideQuery(z.Args)
73 if err != nil {
74 return errors.New("zoxide: no match found")
75 } else {
76 err := ZoxideAdd(res)
77 if err != nil {
78 return err
79 }
80 cd := ChangeDirectory{Target: res}
81 return cd.Execute([]string{"z", res})
82 }
83
84 } else {
85 err := ZoxideAdd(target)
86 if err != nil {
87 return err
88 }
89 return ChangeDirectory{Target: target}.Execute(args)
90 }
91
92 }
93 }