| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | |
| 8 | "reasonix/internal/pathidentity" |
| 9 | ) |
| 10 | |
| 11 | func cleanDesktopPath(path string) string { |
| 12 | path = strings.TrimSpace(path) |
| 13 | if path == "" { |
| 14 | return "" |
| 15 | } |
| 16 | if abs, err := filepath.Abs(path); err == nil { |
| 17 | path = abs |
| 18 | } |
| 19 | return filepath.Clean(path) |
| 20 | } |
| 21 | |
| 22 | func sameDesktopPath(a, b string) bool { |
| 23 | same, err := sameDesktopPathStrict(a, b) |
| 24 | return err == nil && same |
| 25 | } |
| 26 | |
| 27 | func sameDesktopPathStrict(a, b string) (bool, error) { |
| 28 | return newDesktopPathMatcher().sameStrict(a, b) |
| 29 | } |
| 30 | |
| 31 | // resolveDesktopPathIdentity is the one filesystem probe behind every desktop |
| 32 | // path comparison. |
| 33 | var resolveDesktopPathIdentity = pathidentity.Resolve |
| 34 | |
| 35 | // desktopPathMatcher resolves each distinct path once for the pass that owns |
| 36 | // it. A pass comparing many roots against each other shares one matcher. |
| 37 | type desktopPathMatcher struct{ matcher *pathidentity.Matcher } |
| 38 | |
| 39 | func newDesktopPathMatcher() desktopPathMatcher { |
| 40 | return desktopPathMatcher{pathidentity.NewMatcher(pathidentity.Options{FollowLeaf: true}, resolveDesktopPathIdentity)} |
| 41 | } |
| 42 | |
| 43 | func (m desktopPathMatcher) same(a, b string) bool { |
| 44 | same, err := m.sameStrict(a, b) |
| 45 | return err == nil && same |
| 46 | } |
| 47 | |
| 48 | func (m desktopPathMatcher) sameStrict(a, b string) (bool, error) { |
| 49 | a, b = cleanDesktopPath(a), cleanDesktopPath(b) |
| 50 | if a == "" || b == "" { |
| 51 | return false, &pathidentity.Error{Kind: pathidentity.ErrorInvalid, Stage: "input", Err: errors.New("desktop path is empty")} |
| 52 | } |
| 53 | return m.matcher.Same(a, b) |
| 54 | } |
| 55 | |
| 56 | func projectRootKey(root string) string { |
| 57 | root = cleanDesktopPath(root) |
| 58 | if root == "" { |
| 59 | return "" |
| 60 | } |
| 61 | identity, err := resolveDesktopPathIdentity(root, pathidentity.Options{FollowLeaf: true}) |
| 62 | if err != nil { |
| 63 | return "" |
| 64 | } |
| 65 | return identity.Key |
| 66 | } |
| 67 |