File: files.go

package info (click to toggle)
kitty 0.42.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 28,564 kB
  • sloc: ansic: 82,787; python: 55,191; objc: 5,122; sh: 1,295; xml: 364; makefile: 143; javascript: 78
file content (333 lines) | stat: -rw-r--r-- 8,081 bytes parent folder | download
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>

package cli

import (
	"fmt"
	"mime"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/sys/unix"

	"github.com/kovidgoyal/kitty/tools/utils"
)

var _ = fmt.Print

func absolutize_path(path string) string {
	path = utils.Expanduser(path)
	q, err := filepath.Abs(path)
	if err == nil {
		path = q
	}
	return path
}

type FileEntry struct {
	Name, CompletionCandidate, Abspath string
	Mode                               os.FileMode
	IsDir, IsSymlink, IsEmptyDir       bool
}

func CompleteFiles(prefix string, callback func(*FileEntry), cwd string) error {
	if cwd == "" {
		var err error
		cwd, err = os.Getwd()
		if err != nil {
			return err
		}
	}
	location := absolutize_path(prefix)
	base_dir := ""
	joinable_prefix := ""
	switch prefix {
	case ".":
		base_dir = "."
		joinable_prefix = ""
	case "./":
		base_dir = "."
		joinable_prefix = "./"
	case "/":
		base_dir = "/"
		joinable_prefix = "/"
	case "~":
		base_dir = location
		joinable_prefix = "~/"
	case "":
		base_dir = cwd
		joinable_prefix = ""
	default:
		if strings.HasSuffix(prefix, utils.Sep) {
			base_dir = location
			joinable_prefix = prefix
		} else {
			idx := strings.LastIndex(prefix, utils.Sep)
			if idx > 0 {
				joinable_prefix = prefix[:idx+1]
				base_dir = filepath.Dir(location)
			}
		}
	}
	if base_dir == "" {
		base_dir = cwd
	}
	if !strings.HasPrefix(base_dir, "~") && !filepath.IsAbs(base_dir) {
		base_dir = filepath.Join(cwd, base_dir)
	}
	// fmt.Printf("prefix=%#v base_dir=%#v joinable_prefix=%#v\n", prefix, base_dir, joinable_prefix)
	entries, err := os.ReadDir(base_dir)
	if err != nil {
		return err
	}

	for _, entry := range entries {
		q := joinable_prefix + entry.Name()
		if !strings.HasPrefix(q, prefix) {
			continue
		}
		abspath := filepath.Join(base_dir, entry.Name())
		dir_to_check := ""
		data := FileEntry{
			Name: entry.Name(), Abspath: abspath, Mode: entry.Type(), IsDir: entry.IsDir(),
			IsSymlink: entry.Type()&os.ModeSymlink == os.ModeSymlink, CompletionCandidate: q}
		if data.IsSymlink {
			target, err := filepath.EvalSymlinks(abspath)
			if err == nil && target != base_dir {
				td, err := os.Stat(target)
				if err == nil && td.IsDir() {
					dir_to_check = target
					data.IsDir = true
				}
			}
		}
		if dir_to_check != "" {
			subentries, err := os.ReadDir(dir_to_check)
			data.IsEmptyDir = err != nil || len(subentries) == 0
		}
		if data.IsDir {
			data.CompletionCandidate += utils.Sep
		}
		callback(&data)
	}
	return nil
}

func CompleteExecutablesInPath(prefix string, paths ...string) []string {
	ans := make([]string, 0, 1024)
	if len(paths) == 0 {
		paths = filepath.SplitList(os.Getenv("PATH"))
	}
	for _, dir := range paths {
		entries, err := os.ReadDir(dir)
		if err == nil {
			for _, e := range entries {
				if strings.HasPrefix(e.Name(), prefix) && !e.IsDir() && unix.Access(filepath.Join(dir, e.Name()), unix.X_OK) == nil {
					ans = append(ans, e.Name())
				}
			}
		}
	}
	return ans
}

func is_dir_or_symlink_to_dir(entry os.DirEntry, path string) bool {
	if entry.IsDir() {
		return true
	}
	if entry.Type()&os.ModeSymlink == os.ModeSymlink {
		p, err := filepath.EvalSymlinks(path)
		if err == nil {
			s, err := os.Stat(p)
			if err == nil && s.IsDir() {
				return true
			}
		}
	}
	return false
}

func fname_based_completer(prefix, cwd string, is_match func(string) bool) []string {
	ans := make([]string, 0, 1024)
	_ = CompleteFiles(prefix, func(entry *FileEntry) {
		if entry.IsDir && !entry.IsEmptyDir {
			entries, err := os.ReadDir(entry.Abspath)
			if err == nil {
				for _, e := range entries {
					if is_match(e.Name()) || is_dir_or_symlink_to_dir(e, filepath.Join(entry.Abspath, e.Name())) {
						ans = append(ans, entry.CompletionCandidate)
						return
					}
				}
			}
			return
		}
		q := strings.ToLower(entry.Name)
		if is_match(q) {
			ans = append(ans, entry.CompletionCandidate)
		}
	}, cwd)
	return ans

}

func complete_by_fnmatch(prefix, cwd string, patterns []string) []string {
	return fname_based_completer(prefix, cwd, func(name string) bool {
		for _, pat := range patterns {
			matched, err := filepath.Match(pat, name)
			if err == nil && matched {
				return true
			}
		}
		return false
	})
}

func complete_by_mimepat(prefix, cwd string, patterns []string) []string {
	all_allowed := false
	for _, p := range patterns {
		if p == "*" {
			all_allowed = true
			break
		}
	}
	return fname_based_completer(prefix, cwd, func(name string) bool {
		if all_allowed {
			return true
		}
		idx := strings.Index(name, ".")
		if idx < 1 {
			return false
		}
		ext := name[idx:]
		mt := mime.TypeByExtension(ext)
		if mt == "" {
			ext = filepath.Ext(name)
			mt = mime.TypeByExtension(ext)
		}
		if mt == "" {
			return false
		}
		for _, pat := range patterns {
			matched, err := filepath.Match(pat, mt)
			if err == nil && matched {
				return true
			}
		}
		return false
	})
}

type relative_to int

const (
	CWD relative_to = iota
	CONFIG
)

func get_cwd_for_completion(relative_to relative_to) string {
	switch relative_to {
	case CONFIG:
		return utils.ConfigDir()
	}
	return ""
}

func make_completer(title string, relative_to relative_to, patterns []string, f func(string, string, []string) []string) CompletionFunc {
	lpats := make([]string, 0, len(patterns))
	for _, p := range patterns {
		lpats = append(lpats, strings.ToLower(p))
	}
	cwd := get_cwd_for_completion(relative_to)

	return func(completions *Completions, word string, arg_num int) {
		q := f(word, cwd, lpats)
		if len(q) > 0 {
			dirs, files := make([]string, 0, len(q)), make([]string, 0, len(q))
			for _, x := range q {
				if strings.HasSuffix(x, "/") {
					dirs = append(dirs, x)
				} else {
					files = append(files, x)
				}
			}
			if len(dirs) > 0 {
				mg := completions.AddMatchGroup("Directories")
				mg.IsFiles = true
				mg.NoTrailingSpace = true
				for _, c := range dirs {
					mg.AddMatch(c)
				}
			}
			mg := completions.AddMatchGroup(title)
			mg.IsFiles = true
			for _, c := range files {
				mg.AddMatch(c)
			}
		}
	}
}

func CompleteExecutableFirstArg(completions *Completions, word string, arg_num int) {
	if arg_num > 1 {
		completions.Delegate.NumToRemove = completions.CurrentCmd.IndexOfFirstArg + 1 // +1 because the first word is not present in all_words
		completions.Delegate.Command = completions.AllWords[completions.CurrentCmd.IndexOfFirstArg]
		return
	}
	exes := CompleteExecutablesInPath(word)
	if len(exes) > 0 {
		mg := completions.AddMatchGroup("Executables in PATH")
		for _, exe := range exes {
			mg.AddMatch(exe)
		}
	}

	if len(word) > 0 {
		mg := completions.AddMatchGroup("Executables")
		mg.IsFiles = true

		_ = CompleteFiles(word, func(entry *FileEntry) {
			if entry.IsDir && !entry.IsEmptyDir {
				// only allow directories that have sub-dirs or executable files in them
				entries, err := os.ReadDir(entry.Abspath)
				if err == nil {
					for _, x := range entries {
						if x.IsDir() || unix.Access(filepath.Join(entry.Abspath, x.Name()), unix.X_OK) == nil {
							mg.AddMatch(entry.CompletionCandidate)
							break
						}
					}
				}
			} else if unix.Access(entry.Abspath, unix.X_OK) == nil {
				mg.AddMatch(entry.CompletionCandidate)
			}
		}, "")
	}
}

func FnmatchCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
	return make_completer(title, relative_to, patterns, complete_by_fnmatch)
}

func MimepatCompleter(title string, relative_to relative_to, patterns ...string) CompletionFunc {
	return make_completer(title, relative_to, patterns, complete_by_mimepat)
}

func DirectoryCompleter(title string, relative_to relative_to) CompletionFunc {
	if title == "" {
		title = "Directories"
	}
	cwd := get_cwd_for_completion(relative_to)

	return func(completions *Completions, word string, arg_num int) {
		mg := completions.AddMatchGroup(title)
		mg.NoTrailingSpace = true
		mg.IsFiles = true
		_ = CompleteFiles(word, func(entry *FileEntry) {
			if entry.Mode.IsDir() {
				mg.AddMatch(entry.CompletionCandidate)
			}
		}, cwd)
	}
}