package paths import "strings" // Path joining is implemented per address-family (unix "/" vs. windows // "\") rather than via package path/filepath, deliberately: filepath's // behavior depends on the host GOOS, but a Resolver must be able to // compute Windows paths while running on Linux/macOS (and vice versa) so // that platform logic is unit-testable on every host -- see // WithPlatform and AGENTS.md's "OS specific logic isolated" rule. // unixJoin joins elements with "/", collapsing empty elements and // duplicate slashes at the seams. The first element determines whether // the result is absolute. func unixJoin(elems ...string) string { parts := make([]string, 0, len(elems)) for i, e := range elems { e = strings.Trim(e, "/") if e == "" { continue } if i == 0 && strings.HasPrefix(elems[0], "/") { e = "/" + e } parts = append(parts, e) } joined := strings.Join(parts, "/") if len(elems) > 0 && strings.HasPrefix(elems[0], "/") && !strings.HasPrefix(joined, "/") { joined = "/" + joined } if joined == "" && len(elems) > 0 && elems[0] == "/" { return "/" } return joined } // windowsJoin joins elements with "\", preserving a leading drive letter // or UNC prefix on the first element. func windowsJoin(elems ...string) string { if len(elems) == 0 { return "" } // A UNC prefix ("\\server\share") is two significant leading // backslashes; strip and preserve it separately so the trim loop // below (which treats a run of backslashes as a plain separator) // doesn't collapse it down to zero, losing the UNC-ness of the path. uncPrefix := "" first := elems[0] if rest, ok := strings.CutPrefix(first, `\\`); ok { uncPrefix = `\\` first = rest } nonEmpty := make([]string, 0, len(elems)) for i, e := range elems { if i == 0 { e = first } e = strings.Trim(e, `\`) if e != "" { nonEmpty = append(nonEmpty, e) } } return uncPrefix + strings.Join(nonEmpty, `\`) } // JoinFamily joins elems using platform's address family ("windows": // backslash; anything else: forward slash) rather than the *dir*-content // heuristic JoinDirFile uses -- needed when an element (e.g. a bare ".") // carries no separator of its own to infer a family from, such as // core/config's default working-directory layer. func JoinFamily(platform string, elems ...string) string { if platform == "windows" { return windowsJoin(elems...) } return unixJoin(elems...) } // JoinDirFileFamily joins dir and name like JoinDirFile (inferring the // family from dir's own content when it contains a separator of either // kind), falling back to platform's family (as JoinFamily does) only // when dir is ambiguous -- has no separator of its own to infer from, // such as a bare "." (core/config's default working-directory layer // before WithWorkdirPath overrides it). Prefer this over JoinFamily // whenever dir might come from a real filesystem path (e.g. WithRoot's // root, or a caller-supplied override) rather than always being a // hardcoded literal in platform's own family. func JoinDirFileFamily(platform, dir, name string) string { if !strings.ContainsRune(dir, '/') && !strings.ContainsRune(dir, '\\') { return JoinFamily(platform, dir, name) } return JoinDirFile(dir, name) } // JoinDirFile joins a directory (as produced by ConfigSearchDirs/ // DataSearchDirs/ExecutableSearchDirs, in either address family) with a // plain file name, picking the join style from the directory's own // separators rather than the host OS. Exported so core/config can build // file paths from these directories without re-implementing the // address-family detection. func JoinDirFile(dir, name string) string { if strings.ContainsRune(dir, '\\') && !strings.ContainsRune(dir, '/') { return windowsJoin(dir, name) } return unixJoin(dir, name) } // splitWindowsRoot separates a Windows absolute path's root (a drive // letter like "C:" or a UNC share like "\\server\share") from the // remainder, so WithRoot can rebase the remainder under a portable root. // It returns ok=false for a path it doesn't recognize as rooted. func splitWindowsRoot(p string) (root, rest string, ok bool) { if trimmed, ok := strings.CutPrefix(p, `\\`); ok { // UNC: \\server\share\rest... parts := strings.SplitN(trimmed, `\`, 3) switch len(parts) { case 0, 1: return "", "", false case 2: return `\\` + parts[0] + `\` + parts[1], "", true default: return `\\` + parts[0] + `\` + parts[1], parts[2], true } } if len(p) >= 2 && p[1] == ':' { rest := strings.TrimPrefix(p[2:], `\`) return p[:2], rest, true } return "", "", false } // isWindowsPath reports whether p looks like a Windows-family path // (backslash-separated, no forward slash) -- the same content-based // heuristic JoinDirFile uses, applied here to root rather than to a // resolved category directory. func isWindowsPath(p string) bool { return strings.ContainsRune(p, '\\') && !strings.ContainsRune(p, '/') } // pathSegments splits an absolute path p (in the given family) into its // plain path components, discarding p's own absolute-path root marker // (a leading "/" for Unix; a drive letter or UNC share for Windows). func pathSegments(p string, windowsFamily bool) []string { if windowsFamily { rest := p if _, r, ok := splitWindowsRoot(p); ok { rest = r } return splitNonEmpty(rest, '\\') } return splitNonEmpty(strings.TrimPrefix(p, "/"), '/') } // dirName returns p's parent directory, picking "/"- or "\"-based // splitting from p's own content (the same heuristic JoinDirFile uses) // rather than the host OS's path/filepath conventions -- a resolved // path's family depends on WithRoot's root, not on the host this code // happens to run on (see applyRootRebase), so path/filepath (or the // stdlib "path" package) would silently pick the wrong separator, or // none at all, whenever the two differ. func dirName(p string) string { sep := byte('/') if isWindowsPath(p) { sep = '\\' } if i := strings.LastIndexByte(p, sep); i >= 0 { return p[:i] } return "." } func splitNonEmpty(s string, sep byte) []string { var out []string for part := range strings.SplitSeq(s, string(sep)) { if part != "" { out = append(out, part) } } return out } // applyRootRebase rebases p -- an absolute path in the family denoted by // pIsWindows (r.platform's *simulated* family) -- under root, when root // is set. root is always in the REAL host's native family (e.g. // t.TempDir()'s result, or a literal caller-chosen path), which need not // match pIsWindows: WithRoot exists precisely to sandbox real filesystem // I/O while a *different* platform's path logic is being simulated (see // README's "Testing on any host"). p is decomposed into plain segments // and re-joined onto root using root's own family -- inferred from its // content via isWindowsPath, not from pIsWindows -- so the result is a // single, valid, host-usable path regardless of which platform is being // simulated. An empty root leaves p untouched. func applyRootRebase(root, p string, pIsWindows bool) string { if root == "" { return p } segments := pathSegments(p, pIsWindows) elems := append([]string{root}, segments...) if isWindowsPath(root) { return windowsJoin(elems...) } return unixJoin(elems...) }