all repos

viye @ 63835f5

my shot at reimplementing xiki

viye/plumbing/files/files.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
init, 2 months ago
1
package files
2
3
import (
4
	"os"
5
	"os/exec"
6
	"path/filepath"
7
	"strings"
8
9
	"github.com/olexsmir/viye/core"
10
	"github.com/olexsmir/viye/core/osutil"
11
)
12
13
type Tool struct{}
14
15
func (Tool) Name() string { return "files(~/..., /...)" }
16
func (Tool) Match(ctx *core.Context) bool {
17
	p := ctx.Path[0]
18
	if p == "~" || strings.HasPrefix(p, "/") {
19
		return true
20
	}
21
	_, err := os.Stat(filepath.Join(ctx.Dir, p))
22
	return err == nil
23
}
24
25
func (Tool) Execute(ctx *core.Context) (string, error) {
26
	path := resolve(ctx.Path[0], ctx.Dir)
27
28
	info, err := os.Stat(path)
29
	if err != nil {
30
		return "", err
31
	}
32
33
	switch {
34
	case info.IsDir():
35
		if len(ctx.Path) == 1 {
36
			return listDir(path)
37
		}
38
		ctx.Dir = path
39
		ctx.Path = ctx.Path[1:]
40
		return ctx.Next()
41
42
	case info.Mode()&0o111 != 0:
43
		return runExec(path)
44
45
	default:
46
		return "", osutil.Open(path)
47
	}
48
}
49
50
func resolve(p, dir string) string {
51
	if p == "~" {
52
		home, _ := os.UserHomeDir()
53
		return home
54
	}
55
	if strings.HasPrefix(p, "~/") {
56
		home, _ := os.UserHomeDir()
57
		return filepath.Join(home, p[2:])
58
	}
59
	if filepath.IsAbs(p) {
60
		return filepath.Clean(p)
61
	}
62
	return filepath.Join(dir, p)
63
}
64
65
func listDir(dir string) (string, error) {
66
	entries, err := os.ReadDir(dir)
67
	if err != nil {
68
		return "", err
69
	}
70
	var b strings.Builder
71
	for _, e := range entries {
72
		name := e.Name()
73
		if e.IsDir() {
74
			name += "/"
75
		}
76
		b.WriteString(name)
77
		b.WriteByte('\n')
78
	}
79
	return b.String(), nil
80
}
81
82
func runExec(path string) (string, error) {
83
	cmd := exec.Command(path)
84
	out, err := cmd.Output()
85
	if err != nil {
86
		return "", err
87
	}
88
	return string(out), nil
89
}