-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.go
More file actions
394 lines (343 loc) · 7.74 KB
/
utils.go
File metadata and controls
394 lines (343 loc) · 7.74 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"github.com/go-pkgz/fileutils"
"golang.org/x/sys/windows"
)
func isUNC(path string) bool {
p := filepath.ToSlash(path)
return strings.HasPrefix(p, "//") &&
len(p) > 2 &&
p[2] != '/' // not three slashes (///) or more
}
func isUNCRoot(path string) bool {
if !isUNC(path) {
return false
}
if len(splitPath(path)) == 1 {
return true
}
return false
}
func splitPath(path string) []string {
return strings.FieldsFunc(path, func(r rune) bool {
return r == '\\' || r == '/'
})
}
func isDisk(path string) bool {
pattern := `^[A-Za-z]:\\$`
driveRegex := regexp.MustCompile(pattern)
if driveRegex.MatchString(path) {
return true
}
return false
}
func filepathDir(path string) string {
if path == "" {
return path
}
if isUNC(path) {
parts := splitPath(path)
if len(parts) > 1 {
return `\\` + strings.Join(parts[:len(parts)-1], `\`)
}
}
dir := filepath.Dir(path)
if dir == path && isDisk(path) {
return ""
}
return dir
}
// DirExists checks if a path exists and is a directory
func dirExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
}
// PathExists checks if a path exists (file or directory)
func pathExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// IsFile checks if a path exists and is a file (not directory)
func isFile(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
func numberOfDigits(n int) int {
if n == 0 {
return 1
}
if n < 0 {
n = -n
}
count := 0
for n > 0 {
n /= 10
count++
}
return count
}
func fillAutocomplete(m *model) {
switch m.mode {
case pathMode:
path := m.pathInput.Value()
if m.getTab().dir == "" {
m.pathInput.ShowSuggestions = false // TODO: autocomplete drives maybe
return
}
if isUNC(path) { // because network is slow T_T
m.pathInput.ShowSuggestions = false
return
}
if strings.HasSuffix(path, ":") {
path = path + "\\"
}
dir := filepath.Dir(path)
if dir == m.pathInputDir {
return
} else {
m.pathInputDir = dir
}
entries, err := os.ReadDir(dir)
if err != nil {
m.pathInput.ShowSuggestions = false
return
}
var suggestions []string
for i := range entries {
if entries[i].IsDir() {
name := entries[i].Name()
if !checkName(name) {
continue
}
suggestions = append(suggestions, filepath.Join(dir, name))
}
}
m.pathInput.ShowSuggestions = true
m.pathInput.SetSuggestions(suggestions)
case shellMode:
items := m.getPage().getItems()
suggestions := make([]string, len(items)+1)
cmd := m.input.Value()
lastSpaceIndex := strings.LastIndex(cmd, " ")
if lastSpaceIndex == -1 {
for i := range items {
suggestions[i] = items[i].getName()
}
suggestions[len(suggestions)-1] = "#sl"
m.input.ShowSuggestions = true
m.input.SetSuggestions(suggestions)
} else {
prefix := cmd[:lastSpaceIndex+1]
for i := range items {
suggestions[i] = prefix + items[i].getName()
}
suggestions[len(suggestions)-1] = prefix + "#sl"
m.input.ShowSuggestions = true
m.input.SetSuggestions(suggestions)
}
}
}
// true - ok
func checkName(name string) bool {
lowerName := strings.ToLower(name)
// Skip Windows/system files and folders
switch lowerName {
// System files
case "thumbs.db":
return false
case "desktop.ini":
return false
case "dumpstack.log.tmp":
return false
// System folders (legacy and modern)
case "$recycle.bin":
return false
case "system volume information":
return false
case "documents and settings": // XP legacy junction
return false
case "recovery": // Windows Recovery folder
return false
case "config.msi": // Windows Installer temp
return false
// Windows system files
case "pagefile.sys":
return false
case "hiberfil.sys":
return false
case "swapfile.sys":
return false
case "bootmgr":
return false
case "bootnxt":
return false
}
return true
}
func expandWindowsEnv(path string) (string, error) {
if strings.ContainsRune(path, '~') {
home, err := os.UserHomeDir()
if err == nil {
path = strings.ReplaceAll(path, "~", home+"\\")
}
}
src, err := windows.UTF16PtrFromString(path)
if err != nil {
return "", err
}
// First call: get required size (includes null terminator)
n, err := windows.ExpandEnvironmentStrings(src, nil, 0)
if err != nil {
return "", err
}
buf := make([]uint16, n)
// Second call: expand into buffer
_, err = windows.ExpandEnvironmentStrings(src, &buf[0], n)
if err != nil {
return "", err
}
// Trim trailing null
return windows.UTF16ToString(buf[:n-1]), nil
}
func realWindowsPath(p string) (string, error) {
abs, err := filepath.Abs(p)
if err != nil {
return "", err
}
return filepath.EvalSymlinks(abs)
}
// uniquePath returns the next available numbered path
// Like Maya's naming: if test01, test02 exist, returns test03
func uniquePath(reserved []string, exclude []string, path string) string {
dir := filepath.Dir(path)
base := filepath.Base(path)
ext := filepath.Ext(base)
name := strings.TrimSuffix(base, ext)
baseName, number, width, hasNumber := parseName(name)
if !hasNumber {
if !pathExists(path) && !slices.Contains(reserved, path) {
return path
}
}
existing := findExistingNumbers(reserved, exclude, dir, baseName, ext)
used := map[int]struct{}{}
for _, n := range existing {
used[n] = struct{}{}
}
next := number
if !hasNumber {
next = 1
}
for {
if _, ok := used[next]; !ok {
candidate := filepath.Join(dir,
fmt.Sprintf("%s%0*d%s", baseName, width, next, ext))
if !pathExists(candidate) && !slices.Contains(reserved, candidate) {
return candidate
}
}
next++
}
}
func parseName(name string) (baseName string, number int, width int, hasNumber bool) {
re := regexp.MustCompile(`^(.*?)(\d+)$`)
m := re.FindStringSubmatch(name)
if len(m) == 3 {
n, _ := strconv.Atoi(m[2])
return m[1], n, len(m[2]), true
}
return name, 0, 1, false
}
func findExistingNumbers(reserved []string, exclude []string, dir, baseName, ext string) []int {
var nums []int
pattern := regexp.MustCompile(`^` + regexp.QuoteMeta(baseName) + `(\d+)` + regexp.QuoteMeta(ext) + `$`)
entries, err := os.ReadDir(dir)
if err != nil {
return nums
}
for _, entry := range entries {
name := entry.Name()
path := filepath.Join(dir, name)
if slices.Contains(exclude, path) {
continue
}
matches := pattern.FindStringSubmatch(entry.Name())
if len(matches) == 2 {
num, _ := strconv.Atoi(matches[1])
if num > 0 {
nums = append(nums, num)
}
}
}
for _, path := range reserved {
name := filepath.Base(path)
matches := pattern.FindStringSubmatch(name)
if len(matches) == 2 {
num, _ := strconv.Atoi(matches[1])
if num > 0 {
nums = append(nums, num)
}
}
}
sort.Ints(nums)
return nums
}
func calcDirSize(path string) (uint64, error) {
var size uint64
err := filepath.WalkDir(path, func(_ string, entry os.DirEntry, err error) error {
if err != nil {
return nil // skip unreadable entries
}
if entry.Type()&os.ModeSymlink != 0 {
return nil
}
if !entry.IsDir() {
info, err := entry.Info()
if err != nil {
return nil
}
size += uint64(info.Size())
}
return nil
})
return size, err
}
func isDirEmpty(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1)
if err == io.EOF {
return true, nil // empty
}
return false, err // not empty or actual error
}
func copyDir(src, dst string) error {
empty, err := isDirEmpty(src)
if err != nil {
return err
}
if empty {
err := os.MkdirAll(dst, 0755)
if err != nil {
return err
}
} else {
err := fileutils.CopyDir(src, dst)
if err != nil {
return err
}
}
return nil
}