-
Notifications
You must be signed in to change notification settings - Fork 10
/
util.go
67 lines (54 loc) · 1.08 KB
/
util.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
//
// Copyright (c) 2018 Dean Jackson <[email protected]>
//
// MIT Licence. See http://opensource.org/licenses/MIT
//
// Created on 2018-01-26
//
package main
import (
"os"
"path/filepath"
"strings"
)
// calculate the relative depth between base and dir.
//
// base itself has a depth of 0, its immediate children of 1 etc.
// If dir is not under base (and is not base itself), -1 is returned.
func reldepth(base, dir string) int {
base = filepath.Clean(base)
dir = filepath.Clean(dir)
if base == "." {
base = ""
}
if dir == "." {
dir = ""
}
if !strings.HasPrefix(dir, base) {
// log("no match: base=%s, dir=%s", base, dir)
return -1
}
if base == dir {
return 0
}
if strings.HasPrefix(dir, "/") {
base = base[1:]
dir = dir[1:]
}
db := len(strings.Split(base, "/"))
dd := len(strings.Split(dir, "/"))
if base == "" {
db = 0
}
if dir == "" {
dd = 0
}
return (dd - db)
}
// Replace ~ in a path with the home directory.
func expandPath(path string) string {
if strings.HasPrefix(path, "~") {
path = "${HOME}" + path[1:]
}
return os.ExpandEnv(path)
}