/
name.go
82 lines (66 loc) Β· 1.65 KB
/
name.go
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
package fs
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// FileName returns the relative filename with the same base and a given extension in a directory.
func FileName(fileName, dirName, baseDir, fileExt string) string {
dir := filepath.Dir(fileName)
if dirName == "" || dirName == "." {
dirName = dir
} else if dir != dirName {
if filepath.IsAbs(dirName) {
dirName = filepath.Join(dirName, RelName(dir, baseDir))
} else {
dirName = filepath.Join(dir, dirName)
}
}
if err := MkdirAll(dirName); err != nil {
fmt.Println(err.Error())
return ""
}
result := filepath.Join(dirName, filepath.Base(fileName)) + fileExt
return result
}
// RelName returns the file name relative to a directory.
func RelName(fileName, dir string) string {
if fileName == dir {
return ""
}
if dir == "" {
return fileName
}
if index := strings.Index(fileName, dir); index == 0 {
if index := strings.LastIndex(dir, string(os.PathSeparator)); index == len(dir)-1 {
pos := len(dir)
return fileName[pos:]
} else if index := strings.LastIndex(dir, string(os.PathSeparator)); index != len(dir) {
pos := len(dir) + 1
return fileName[pos:]
}
}
return fileName
}
// FileNameHidden tests is a file name belongs to a hidden file.
func FileNameHidden(name string) bool {
if len(name) == 0 {
return false
}
name = filepath.Base(name)
// Hidden files and folders starting with "." or "@" should be ignored.
switch name[0:1] {
case ".", "@":
return true
}
if len(name) == 1 {
return false
}
// File paths starting with _. and __ like __MACOSX should be ignored.
switch name[0:2] {
case "_.", "__":
return true
}
return false
}