|
| 1 | +package common |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "path" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +const pathSeparator = "/" |
| 10 | + |
| 11 | +func CorrectPaths(paths []string) []string { |
| 12 | + for i := range paths { |
| 13 | + folderPath := paths[i] |
| 14 | + |
| 15 | + if strings.Index(folderPath, pathSeparator) != 0 { |
| 16 | + folderPath = fmt.Sprintf("%s%s", pathSeparator, folderPath) |
| 17 | + } |
| 18 | + folderPath = path.Clean(folderPath) |
| 19 | + |
| 20 | + if len(folderPath) == 0 { |
| 21 | + folderPath = pathSeparator |
| 22 | + } |
| 23 | + |
| 24 | + paths[i] = folderPath |
| 25 | + } |
| 26 | + return paths |
| 27 | +} |
| 28 | + |
| 29 | +func CorrectPath(folderPath string) string { |
| 30 | + return CorrectPaths([]string{folderPath})[0] |
| 31 | +} |
| 32 | + |
| 33 | +func PathTree(folderPath string) []string { |
| 34 | + folderPath = CorrectPath(folderPath) |
| 35 | + |
| 36 | + folderTree := make([]string, 0) |
| 37 | + split := strings.Split(folderPath, pathSeparator) |
| 38 | + for len(split) > 0 { |
| 39 | + p := strings.Join(split, pathSeparator) |
| 40 | + folderTree = append([]string{CorrectPath(p)}, folderTree...) |
| 41 | + |
| 42 | + split = split[:len(split)-1] |
| 43 | + } |
| 44 | + |
| 45 | + return folderTree |
| 46 | +} |
| 47 | + |
| 48 | +func Split(path string) (string, string) { |
| 49 | + path = CorrectPath(path) |
| 50 | + if strings.Compare(path, pathSeparator) == 0 { |
| 51 | + return pathSeparator, "" |
| 52 | + } |
| 53 | + |
| 54 | + idx := strings.LastIndex(path, pathSeparator) |
| 55 | + if idx == 0 { |
| 56 | + return pathSeparator, path[1:] |
| 57 | + } |
| 58 | + |
| 59 | + return path[:idx], path[idx+1:] |
| 60 | +} |
| 61 | + |
| 62 | +func Join(inputs ...string) string { |
| 63 | + for i, p := range inputs { |
| 64 | + if strings.Index(p, pathSeparator) == 0 { |
| 65 | + p = p[1:] |
| 66 | + } |
| 67 | + inputs[i] = p |
| 68 | + } |
| 69 | + return CorrectPath(strings.Join(inputs, pathSeparator)) |
| 70 | +} |
| 71 | + |
| 72 | +func DivideParts(folderPath string) []string { |
| 73 | + return strings.Split(folderPath, pathSeparator) |
| 74 | +} |
| 75 | + |
| 76 | +func Absolute(basePath string, folderPath string) string { |
| 77 | + if strings.Index(folderPath, pathSeparator) == 0 { |
| 78 | + basePath = pathSeparator |
| 79 | + } |
| 80 | + |
| 81 | + targetParts := DivideParts(folderPath) |
| 82 | + for len(targetParts) > 0 { |
| 83 | + if strings.Compare(targetParts[0], "..") != 0 { |
| 84 | + basePath = Join(basePath, targetParts[0]) |
| 85 | + targetParts = targetParts[1:] |
| 86 | + continue |
| 87 | + } |
| 88 | + parentPath, _ := Split(basePath) |
| 89 | + basePath = parentPath |
| 90 | + targetParts = targetParts[1:] |
| 91 | + } |
| 92 | + return basePath |
| 93 | +} |
0 commit comments