Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Find the caches npm, Yarn, pnpm and Go were told to keep elsewhere

Țugui Dragoș96d0f98d300f
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
index a956b0f3..f048165b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
@@ -143,9 +143,8 @@ public enum DeveloperCaches {
let rowsAreDerivedData: Bool
/// True for an editor's `workspaceStorage`, whose rows are listed only when `goneProject(at:)` names one.
let rowsAreProjectState: Bool
- /// The Xcode setting that moves the folder elsewhere when it holds an absolute path. The folder is looked
- /// for there as well as at `path`, where an earlier Xcode may have left it.
- let movedByXcodeSetting: String?
+ /// The setting that moves the folder elsewhere: Xcode's, or one in the tool's own configuration file.
+ let movedBy: Relocation?
let base: Base
/// The links, relative to the home folder, a tool's installer puts on the path to the version it runs. When
/// set, the folder's rows are the versions it keeps beside that one (`olderVersions(in:home:)`).
@@ -154,7 +153,7 @@ public enum DeveloperCaches {
init(
_ path: String, _ kind: DeveloperEnvironment.ContentKind, source: String, storeInside: String? = nil,
rowsDepth: Int = 0, rowEnding: String? = nil, rowsAreDerivedData: Bool = false,
- rowsAreProjectState: Bool = false, movedByXcodeSetting: String? = nil, base: Base = .home,
+ rowsAreProjectState: Bool = false, movedBy: Relocation? = nil, base: Base = .home,
launchers: [String] = []
) {
self.path = path
@@ -165,7 +164,7 @@ public enum DeveloperCaches {
self.rowEnding = rowEnding
self.rowsAreDerivedData = rowsAreDerivedData
self.rowsAreProjectState = rowsAreProjectState
- self.movedByXcodeSetting = movedByXcodeSetting
+ self.movedBy = movedBy
self.base = base
self.launchers = launchers
}
@@ -198,8 +197,10 @@ public enum DeveloperCaches {
.filter { !running.contains(PathComponents.of(PathPattern.comparablePath(of: $0)).last ?? "") }
}
- /// Where the folder is: at `path` in its base, and where the Xcode setting that moves it says.
- func places(home: URL, userCache: URL?, userTemporary: URL?, preference: (String) -> String?) -> [URL] {
+ /// Where the folder is: at `path` in its base, and where the setting that moves it says.
+ func places(
+ home: URL, userCache: URL?, userTemporary: URL?, preference: (String) -> String?, settings: ToolSettings
+ ) -> [URL] {
let root = switch base {
case .home: home
case .userCache: userCache
@@ -207,11 +208,7 @@ public enum DeveloperCaches {
}
guard let root else { return [] }
var places = PathPattern.expand(path, home: root)
- if let setting = movedByXcodeSetting.flatMap(preference).map({ NSString(string: $0).expandingTildeInPath }),
- setting.hasPrefix("/") {
- let moved = URL(filePath: setting, directoryHint: .isDirectory)
- if moved.isRealFolder { places.append(moved) }
- }
+ places += movedBy?.places(preference: preference, settings: settings).map(\.place) ?? []
var seen: Set<String> = []
return places.filter { seen.insert(PathPattern.comparablePath(of: $0)).inserted }
}
@@ -299,10 +296,22 @@ public enum DeveloperCaches {
init(home: URL) {
// Not through `comparablePath`: standardizing drops `/private` only from a path that exists, and most
// paths in the table don't.
- let home = PathComponents.of(PathPattern.canonical(home).path(percentEncoded: false))
+ let names = { (url: URL) in PathComponents.of(PathPattern.canonical(url).path(percentEncoded: false)) }
+ let homeNames = names(home)
+ // A tool's configuration can move a cache into a place Space shows, and the folder it names is the
+ // tool's own there.
+ let settings = ToolSettings(home: home)
folders = DeveloperCaches.definitions.flatMap { definition in
- let own = definition.ownFolders.map { home + PathComponents.of($0) }
- return definition.folders.filter { $0.base == .home }.map { (home + PathComponents.of($0.path), own) }
+ let own = definition.ownFolders.map { homeNames + PathComponents.of($0) }
+ let usual = definition.folders.filter { $0.base == .home }.map {
+ (homeNames + PathComponents.of($0.path), own)
+ }
+ let moved = definition.folders.compactMap(\.movedBy).flatMap { relocation in
+ relocation.places(preference: { _ in nil }, settings: settings).map {
+ (names($0.place), [names($0.named)])
+ }
+ }
+ return usual + moved
}
}
@@ -328,7 +337,7 @@ public enum DeveloperCaches {
Folder(
"Library/Developer/Xcode/DerivedData", .buildData,
source: "https://developer.apple.com/documentation/xcode-release-notes/xcode-26-release-notes",
- rowsDepth: 1, rowsAreDerivedData: true, movedByXcodeSetting: "IDECustomDerivedDataLocation"
+ rowsDepth: 1, rowsAreDerivedData: true, movedBy: .xcodeSetting("IDECustomDerivedDataLocation")
),
Folder("Library/Developer/Xcode/UserData/Previews/Simulator Devices", .buildData, source: "Xcode 27: DVTSystemPrerequisites.framework, beside DVTSimulatorDeviceRemover"),
Folder("Library/Developer/Xcode/UserData-Tests/Previews/Simulator Devices", .buildData, source: "Xcode 27: DVTSystemPrerequisites.framework, beside DVTSimulatorDeviceRemover"),
@@ -349,7 +358,7 @@ public enum DeveloperCaches {
Folder(
"Library/Developer/Xcode/Archives", .archives,
source: "Xcode 27: IDEFoundation.framework, -[IDEDeveloperPaths defaultDistributionArchivesLocation]",
- rowsDepth: 2, rowEnding: ".xcarchive", movedByXcodeSetting: "IDECustomDistributionArchivesLocation"
+ rowsDepth: 2, rowEnding: ".xcarchive", movedBy: .xcodeSetting("IDECustomDistributionArchivesLocation")
),
]),
Definition(id: "swiftpm", name: "Swift Package Manager", systemImage: "swift", appBundleIdentifiers: [], folders: [
@@ -381,20 +390,20 @@ public enum DeveloperCaches {
]),
// JavaScript
Definition(id: "npm", name: "npm", systemImage: "cube", appBundleIdentifiers: [], folders: [
- Folder(".npm/_cacache", .downloads, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L443"),
- Folder(".npm/_npx", .downloads, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L444"),
- Folder(".npm/_logs", .logs, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L1481-L1486"),
- Folder(".npm/_prebuilds", .downloads, source: "https://github.com/prebuild/prebuild-install/blob/8e4dbad54ac92c480e2ff213d46140b5fd9a3545/README.md#L148-L154"),
+ Folder(".npm/_cacache", .downloads, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L443", movedBy: .npmCache(inside: "_cacache")),
+ Folder(".npm/_npx", .downloads, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L444", movedBy: .npmCache(inside: "_npx")),
+ Folder(".npm/_logs", .logs, source: "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L1481-L1486", movedBy: .npmCache(inside: "_logs")),
+ Folder(".npm/_prebuilds", .downloads, source: "https://github.com/prebuild/prebuild-install/blob/8e4dbad54ac92c480e2ff213d46140b5fd9a3545/README.md#L148-L154", movedBy: .npmCache(inside: "_prebuilds")),
]),
Definition(id: "yarn", name: "Yarn", systemImage: "cube", appBundleIdentifiers: [], folders: [
- Folder("Library/Caches/Yarn", .downloads, source: "https://github.com/yarnpkg/yarn/blob/c2dda503f3759b5be5f0e24ecd9cf5c97a540147/src/util/user-dirs.js#L32-L33"),
+ Folder("Library/Caches/Yarn", .downloads, source: "https://github.com/yarnpkg/yarn/blob/c2dda503f3759b5be5f0e24ecd9cf5c97a540147/src/util/user-dirs.js#L32-L33", movedBy: .yarnCache),
// Yarn's Plug'n'Play projects load every package from this cache, so it is listed and never selected:
// moving it breaks each such project until `yarn install` runs in it again.
- Folder(".yarn/berry/cache", .environments, source: "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/yarnpkg-core/sources/Configuration.ts"),
- Folder(".yarn/berry/metadata", .cache, source: "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/plugin-npm/sources/npmHttpUtils.ts#L317"),
+ Folder(".yarn/berry/cache", .environments, source: "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/yarnpkg-core/sources/Configuration.ts", movedBy: .yarnGlobalFolder(inside: "cache")),
+ Folder(".yarn/berry/metadata", .cache, source: "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/plugin-npm/sources/npmHttpUtils.ts#L317", movedBy: .yarnGlobalFolder(inside: "metadata")),
]),
Definition(id: "pnpm", name: "pnpm", systemImage: "cube", appBundleIdentifiers: [], folders: [
- Folder("Library/pnpm/store", .environments, source: "https://github.com/pnpm/pnpm.io/blob/ae60a09ef4fe5929d937a24df02e21ecd08c3edc/docs/settings/store.md#L15"),
+ Folder("Library/pnpm/store", .environments, source: "https://github.com/pnpm/pnpm.io/blob/ae60a09ef4fe5929d937a24df02e21ecd08c3edc/docs/settings/store.md#L15", movedBy: .pnpmStore),
Folder(".pnpm-store", .environments, source: "https://github.com/pnpm/pnpm.io/blob/ae60a09ef4fe5929d937a24df02e21ecd08c3edc/versioned_docs_archived/version-6.x/npmrc.md#L95-L100"),
Folder("Library/Caches/pnpm", .cache, source: "https://github.com/pnpm/pnpm.io/blob/ae60a09ef4fe5929d937a24df02e21ecd08c3edc/docs/settings/other.md#L175"),
]),
@@ -566,9 +575,9 @@ public enum DeveloperCaches {
Folder(".cargo/git/db", .downloads, source: "https://github.com/rust-lang/cargo/blob/bb2126cffae48394a37db8728dc50a17bbfe54d4/doc/book/src/guide/cargo-home.md#L33-L34"),
]),
Definition(id: "go", name: "Go", systemImage: "chevron.left.forwardslash.chevron.right", appBundleIdentifiers: [], folders: [
- Folder("Library/Caches/go-build", .buildData, source: "https://github.com/golang/go/blob/6f5c275ebdc454197fff5f1496521c8f81e20eef/src/cmd/go/alldocs.go#L2372-L2373"),
- Folder("go/pkg/mod/cache/download", .downloads, source: "https://github.com/golang/website/blob/32881aa55f0d81413cda4fe43e0236d0cae2b2ec/_content/ref/mod.md#L4020-L4028"),
- Folder("go/pkg/mod/cache/vcs", .downloads, source: "https://github.com/golang/website/blob/32881aa55f0d81413cda4fe43e0236d0cae2b2ec/_content/ref/mod.md#L4088-L4095"),
+ Folder("Library/Caches/go-build", .buildData, source: "https://github.com/golang/go/blob/6f5c275ebdc454197fff5f1496521c8f81e20eef/src/cmd/go/alldocs.go#L2372-L2373", movedBy: .goBuildCache),
+ Folder("go/pkg/mod/cache/download", .downloads, source: "https://github.com/golang/website/blob/32881aa55f0d81413cda4fe43e0236d0cae2b2ec/_content/ref/mod.md#L4020-L4028", movedBy: .goModuleCache(inside: "cache/download")),
+ Folder("go/pkg/mod/cache/vcs", .downloads, source: "https://github.com/golang/website/blob/32881aa55f0d81413cda4fe43e0236d0cae2b2ec/_content/ref/mod.md#L4088-L4095", movedBy: .goModuleCache(inside: "cache/vcs")),
]),
Definition(id: "sccache", name: "sccache", systemImage: "gearshape.2", appBundleIdentifiers: [], folders: [
Folder("Library/Caches/Mozilla.sccache", .buildData, source: "https://github.com/mozilla/sccache/blob/50b329680bec2c01e84bc7b78a5a5cc41cffee82/docs/Local.md#L3"),
@@ -1152,13 +1161,14 @@ public enum DeveloperCaches {
preference: @escaping @Sendable (String) -> String? = Self.xcodePreference,
openFiles: OpenFiles = OpenFiles()
) async -> [DeveloperEnvironment] {
+ let settings = ToolSettings(home: homeDirectory)
// Four tools at a time: measured all at once, their big folders would share the disk and each run out of
// the time `FileSize` gives a walk, where alone they would finish.
- await definitions.concurrentMap(width: 4) { definition in
+ return await definitions.concurrentMap(width: 4) { definition in
await environment(
for: definition, homeDirectory: homeDirectory, userCacheDirectory: userCacheDirectory,
userTemporaryDirectory: userTemporaryDirectory, exclusions: exclusions, measure: measure,
- preference: preference, openFiles: openFiles
+ preference: preference, settings: settings, openFiles: openFiles
)
}
.compactMap(\.self)
@@ -1173,13 +1183,14 @@ public enum DeveloperCaches {
exclusions: Exclusions,
measure: @escaping LeftoverScanner.Measure,
preference: @escaping @Sendable (String) -> String?,
+ settings: ToolSettings,
openFiles: OpenFiles
) async -> DeveloperEnvironment? {
var found: [(url: URL, folder: Folder, project: String?)] = []
for folder in definition.folders {
let places = folder.places(
home: homeDirectory, userCache: userCacheDirectory, userTemporary: userTemporaryDirectory,
- preference: preference
+ preference: preference, settings: settings
)
let rows = places.flatMap { place in
folder.launchers.isEmpty
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/Relocation.swift b/Packages/PeelCore/Sources/PeelCore/Developer/Relocation.swift
new file mode 100644
index 00000000..9b52a4d6
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/Relocation.swift
@@ -0,0 +1,108 @@
+import Foundation
+
+extension DeveloperCaches {
+ /// A setting that moves a folder of the table elsewhere. The folder is looked for there as well as at its usual
+ /// place, where an earlier setting may have left it.
+ enum Relocation: Sendable {
+ /// An Xcode preference that holds the folder's absolute path.
+ case xcodeSetting(String)
+ /// npm's cache, with the folder inside it.
+ case npmCache(inside: String)
+ /// Yarn 1's cache root, whose cache is a folder named for its cache version (`v6`).
+ case yarnCache
+ /// Yarn 2 and later's global folder, with the folder inside it.
+ case yarnGlobalFolder(inside: String)
+ /// pnpm's store folder, whose store is a folder named for its store version (`v10`, `v11`).
+ case pnpmStore
+ /// Go's module cache, with the folder inside it.
+ case goModuleCache(inside: String)
+ /// Go's build cache, which holds the `README` Go writes in it.
+ case goBuildCache
+
+ /// Where the tool says which file holds the setting and where the setting puts the folder.
+ var sources: [String] {
+ switch self {
+ case .xcodeSetting: []
+ case .npmCache: [
+ "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/docs/lib/content/configuring-npm/npmrc.md#L17-L20",
+ "https://github.com/npm/cli/blob/b317f16c80df02ea3628cfa77170d5ae9b59720c/workspaces/config/lib/definitions/definitions.js#L433-L444",
+ ]
+ case .yarnCache: [
+ "https://github.com/yarnpkg/yarn/blob/c2dda503f3759b5be5f0e24ecd9cf5c97a540147/src/registries/yarn-registry.js#L34-L56",
+ "https://github.com/yarnpkg/yarn/blob/c2dda503f3759b5be5f0e24ecd9cf5c97a540147/src/config.js#L352-L431",
+ ]
+ case .yarnGlobalFolder: [
+ "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/yarnpkg-core/sources/Configuration.ts#L250-L254",
+ "https://github.com/yarnpkg/berry/blob/e4e423a1eb117b5129f20ac626a03eb7a97aedff/packages/yarnpkg-core/sources/Configuration.ts#L1416-L1417",
+ ]
+ case .pnpmStore: [
+ "https://github.com/pnpm/pnpm.io/blob/e36dcc555c137a77cd8c3fe5d62ba8d44636b33c/docs/cli/config.md#L19-L23",
+ "https://github.com/pnpm/pnpm.io/blob/e36dcc555c137a77cd8c3fe5d62ba8d44636b33c/versioned_docs/version-10.x/cli/config.md#L14-L19",
+ "https://github.com/pnpm/pnpm/blob/9287c31cea69206c4eeca7f21cd21df81d0b93e7/config/config/src/index.ts#L231-L236",
+ "https://github.com/pnpm/pnpm/blob/fca2d32621419e34897a114a2f14199344bdb8fc/pnpm11/store/path/src/index.ts#L39-L42",
+ ]
+ case .goModuleCache: [
+ "https://github.com/golang/go/blob/a90c4a7a586c70f0de61f5507d5c347702432e39/src/cmd/go/internal/cfg/cfg.go#L347-L363",
+ "https://github.com/golang/go/blob/a90c4a7a586c70f0de61f5507d5c347702432e39/src/cmd/go/internal/cfg/cfg.go#L470",
+ ]
+ case .goBuildCache: [
+ "https://github.com/golang/go/blob/a90c4a7a586c70f0de61f5507d5c347702432e39/src/cmd/go/internal/cfg/cfg.go#L347-L363",
+ "https://github.com/golang/go/blob/a90c4a7a586c70f0de61f5507d5c347702432e39/src/cmd/go/internal/cache/default.go#L25-L31",
+ ]
+ }
+ }
+
+ /// The places the setting moves the folder to, each with the folder the setting names, which is the tool's
+ /// own. Only real folders count: a link moves nothing.
+ func places(preference: (String) -> String?, settings: ToolSettings) -> [(place: URL, named: URL)] {
+ let found: [(place: URL, named: URL)] = switch self {
+ case .xcodeSetting(let key):
+ preference(key).map { NSString(string: $0).expandingTildeInPath }.flatMap { path in
+ path.hasPrefix("/") ? URL(filePath: path, directoryHint: .isDirectory) : nil
+ }.map { [($0, $0)] } ?? []
+ case .npmCache(let inside):
+ settings.npmCache.map { [($0.appending(path: inside, directoryHint: .isDirectory), $0)] } ?? []
+ case .yarnCache:
+ settings.yarnCacheRoot.map { root in Self.versions(in: root).map { ($0, root) } } ?? []
+ case .yarnGlobalFolder(let inside):
+ settings.yarnGlobalFolder.map { [($0.appending(path: inside, directoryHint: .isDirectory), $0)] } ?? []
+ case .pnpmStore:
+ // A store folder that already ends with the store's version is the store itself.
+ settings.pnpmStoreFolders.flatMap { folder in
+ Self.isAVersion(folder.lastPathComponent)
+ ? [(folder, folder)] : Self.versions(in: folder).map { ($0, folder) }
+ }
+ case .goModuleCache(let inside):
+ settings.goModuleCache.map { [($0.appending(path: inside, directoryHint: .isDirectory), $0)] } ?? []
+ case .goBuildCache:
+ settings.goBuildCache.flatMap { Self.holdsGosReadme($0) ? [($0, $0)] : nil } ?? []
+ }
+ return found.map { (Self.entry($0.place), Self.entry($0.named)) }.filter(\.place.isRealFolder)
+ }
+
+ /// The entry a place names, without a final `/`: with one, the kernel follows a link to what it leads to.
+ private static func entry(_ url: URL) -> URL {
+ let path = url.path(percentEncoded: false)
+ return URL(filePath: path.count > 1 && path.hasSuffix("/") ? String(path.dropLast()) : path)
+ }
+
+ /// The folders in `root` named for a version of the tool's layout, such as `v6`.
+ private static func versions(in root: URL) -> [URL] {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path(percentEncoded: false))) ?? []
+ return names.filter(isAVersion).sorted().map { root.appending(path: $0, directoryHint: .isDirectory) }
+ }
+
+ private static func isAVersion(_ name: String) -> Bool {
+ name.count > 1 && name.first == "v" && name.dropFirst().allSatisfy { $0.isASCII && $0.isNumber }
+ }
+
+ /// The first line of the `README` Go writes in its build cache, which no other folder holds.
+ private static let goReadme = "This directory holds cached build artifacts from the Go build system."
+
+ private static func holdsGosReadme(_ folder: URL) -> Bool {
+ let readme = folder.appending(path: "README")
+ guard let start = BoundedRead.prefix(of: readme, count: goReadme.utf8.count) else { return false }
+ return String(decoding: start, as: UTF8.self) == goReadme
+ }
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift
new file mode 100644
index 00000000..6de92cd9
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ToolSettings.swift
@@ -0,0 +1,258 @@
+import Foundation
+
+/// Where the tools' own configuration files say a cache Developer lists has moved: the files each tool reads, which
+/// its own `config set` writes, read here and never by running a tool. A value counts only when it names a place
+/// without the environment the tool runs in, such as an absolute path or one from the home folder.
+struct ToolSettings: Sendable {
+ /// npm's `cache` in `~/.npmrc`.
+ let npmCache: URL?
+ /// Yarn 1's cache root: `--cache-folder` or `cache-folder` in `~/.yarnrc`, then `cache-folder` in `~/.npmrc`.
+ let yarnCacheRoot: URL?
+ /// Yarn 2 and later's `globalFolder` in `~/.yarnrc.yml`.
+ let yarnGlobalFolder: URL?
+ /// pnpm's store folders: `storeDir` in the `config.yaml` pnpm 11 reads, and `store-dir` in the `rc` file and in
+ /// `~/.npmrc` pnpm 10 reads.
+ let pnpmStoreFolders: [URL]
+ /// Go's module cache: `GOMODCACHE` in the file `go env -w` writes, else `pkg/mod` in the first folder of its
+ /// `GOPATH`.
+ let goModuleCache: URL?
+ /// Go's build cache: `GOCACHE` in the same file.
+ let goBuildCache: URL?
+
+ init(home: URL) {
+ let npmrc = Self.text(at: home.appending(path: ".npmrc"))
+ let yarnrc = Self.text(at: home.appending(path: ".yarnrc"))
+ let pnpm = home.appending(path: "Library/Preferences/pnpm", directoryHint: .isDirectory)
+ let goEnvironment = Self.text(at: home.appending(path: "Library/Application Support/go/env"))
+
+ npmCache = npmrc.flatMap { Self.iniValue(of: "cache", in: $0) }.flatMap { Self.npmPlace($0, home: home) }
+
+ // An argument in `.yarnrc` is taken as typed on the command line, so only an absolute one names a place. A
+ // setting there is taken from the folder of the file, and one in `.npmrc` as npm takes a path.
+ let argument = yarnrc.flatMap { Self.yarnrcValue(of: "--cache-folder", in: $0) }.flatMap(Self.absolute)
+ let setting = yarnrc.flatMap { Self.yarnrcValue(of: "cache-folder", in: $0) }
+ .map { Self.folder($0, from: home) }
+ let fromNpm = npmrc.flatMap { Self.iniValue(of: "cache-folder", in: $0) }
+ .flatMap { Self.npmPlace($0, home: home) }
+ yarnCacheRoot = argument ?? setting ?? fromNpm
+
+ yarnGlobalFolder = Self.text(at: home.appending(path: ".yarnrc.yml"))
+ .flatMap { Self.yamlValue(of: "globalFolder", in: $0) }
+ .flatMap { Self.replacingHome(in: $0, home: home, defaults: true) }
+ .map { Self.folder($0, from: home) }
+
+ let pnpmEleven = Self.text(at: pnpm.appending(path: "config.yaml"))
+ .flatMap { Self.yamlValue(of: "storeDir", in: $0) }
+ .flatMap { $0.contains("${") ? nil : Self.place($0, home: home) }
+ let pnpmTen = [Self.text(at: pnpm.appending(path: "rc")), npmrc].compactMap { text in
+ text.flatMap { Self.iniValue(of: "store-dir", in: $0) }.flatMap { Self.npmPlace($0, home: home) }
+ }
+ pnpmStoreFolders = [pnpmEleven].compactMap(\.self) + pnpmTen
+
+ // Go takes an empty value as unset, and a relative one as an error.
+ let goValue = { (key: String) in
+ goEnvironment.flatMap { Self.goEnvironmentValue(of: key, in: $0) }.flatMap { $0.isEmpty ? nil : $0 }
+ }
+ let goPath = goValue("GOPATH")?.split(separator: ":", omittingEmptySubsequences: false).first
+ .flatMap { $0.isEmpty ? nil : String($0) + "/pkg/mod" }
+ goModuleCache = (goValue("GOMODCACHE") ?? goPath).flatMap(Self.absolute)
+ goBuildCache = goValue("GOCACHE").flatMap(Self.absolute)
+ }
+
+ /// A configuration file is a few lines; a megabyte is far beyond any real one.
+ private static func text(at url: URL) -> String? {
+ BoundedRead.data(at: url, maximum: 1_048_576).map { String(decoding: $0, as: UTF8.self) }
+ }
+
+ private static func absolute(_ path: String) -> URL? {
+ path.hasPrefix("/") ? URL(filePath: path, directoryHint: .isDirectory).standardized : nil
+ }
+
+ /// A path as a tool takes it from its configuration file: relative to the folder the file is in.
+ private static func folder(_ path: String, from base: URL) -> URL {
+ URL(filePath: path, directoryHint: .isDirectory, relativeTo: base).absoluteURL.standardized
+ }
+
+ /// An absolute path, or one that starts from the home folder with `~/`.
+ private static func place(_ path: String, home: URL) -> URL? {
+ guard path.hasPrefix("~/") else { return absolute(path) }
+ return home.appending(path: String(path.dropFirst(2)), directoryHint: .isDirectory).standardized
+ }
+
+ /// A path as npm and pnpm 10 take it (`@npmcli/config`'s `parse-field.js`): `${NAME}` from the environment, then
+ /// `~/` from the home folder. A relative path is taken from the folder the tool runs in, which is not known here.
+ private static func npmPlace(_ value: String, home: URL) -> URL? {
+ replacingHome(in: value, home: home, defaults: false).flatMap { place($0, home: home) }
+ }
+
+ /// `value` with `${HOME}` taken as the home folder, or nil when it names another variable, whose value is the
+ /// environment's the tool runs in. npm writes `${HOME?}` for an empty value when unset, and Yarn, with `defaults`,
+ /// `${HOME:-fallback}` and `${HOME-fallback}` for a fallback: the home folder is always set.
+ static func replacingHome(in value: String, home: URL, defaults: Bool) -> String? {
+ guard !value.contains("\\") else { return nil }
+ var homePath = home.path(percentEncoded: false)
+ while homePath.count > 1, homePath.hasSuffix("/") { homePath.removeLast() }
+ var result = ""
+ var rest = Substring(value)
+ while let start = rest.range(of: "${") {
+ result += rest[..<start.lowerBound]
+ guard let end = rest[start.upperBound...].firstIndex(of: "}") else { return nil }
+ let expression = rest[start.upperBound..<end]
+ let namesHome = defaults
+ ? expression == "HOME" || expression.hasPrefix("HOME:-") || expression.hasPrefix("HOME-")
+ : expression == "HOME" || expression == "HOME?"
+ guard namesHome, !expression.contains("$") else { return nil }
+ result += homePath
+ rest = rest[rest.index(after: end)...]
+ }
+ return result + rest
+ }
+
+ // MARK: - The formats
+
+ /// The value of a top-level `key` in an INI file as npm reads `.npmrc` (`ini` 7, `decode`): the last one before
+ /// any `[section]`. A quoted value is decoded, and an unquoted one ends at the first `;` or `#` not escaped.
+ static func iniValue(of key: String, in text: String) -> String? {
+ var found: String?
+ for line in text.split(whereSeparator: { $0 == "\n" || $0 == "\r" }) {
+ let content = line.drop { $0.isWhitespace }
+ if content.isEmpty || content.first == ";" || content.first == "#" { continue }
+ // Every line after a section belongs to it.
+ if line.first == "[", let close = line.firstIndex(of: "]"),
+ line[line.index(after: close)...].allSatisfy(\.isWhitespace) {
+ break
+ }
+ guard let equals = line.firstIndex(of: "="), iniUnquoted(line[..<equals]) == key else { continue }
+ found = iniUnquoted(line[line.index(after: equals)...])
+ }
+ return found
+ }
+
+ private static func iniUnquoted(_ raw: Substring) -> String {
+ let value = raw.trimmingCharacters(in: .whitespaces)
+ if value.count > 1, value.hasPrefix("\""), value.hasSuffix("\"") {
+ return jsonString(value) ?? value
+ }
+ if value.count > 1, value.hasPrefix("'"), value.hasSuffix("'") {
+ return String(value.dropFirst().dropLast())
+ }
+ var result = ""
+ var isEscaped = false
+ for character in value {
+ if isEscaped {
+ result += ";#\\".contains(character) ? String(character) : "\\" + String(character)
+ isEscaped = false
+ } else if character == ";" || character == "#" {
+ break
+ } else if character == "\\" {
+ isEscaped = true
+ } else {
+ result.append(character)
+ }
+ }
+ return (isEscaped ? result + "\\" : result).trimmingCharacters(in: .whitespaces)
+ }
+
+ /// The value of a top-level `key` in Yarn 1's `.yarnrc` (its `lockfile/parse.js`): `key value` on one line, the
+ /// value a quoted string or a word that ends at a space, a colon or a comma. The last one counts.
+ static func yarnrcValue(of key: String, in text: String) -> String? {
+ var found: String?
+ for line in text.split(whereSeparator: { $0 == "\n" || $0 == "\r" }) {
+ guard let (name, rest) = yarnToken(line), name == key,
+ let (value, _) = yarnToken(rest.drop { $0 == " " })
+ else { continue }
+ found = value
+ }
+ return found
+ }
+
+ /// The string a line starts with in Yarn 1's syntax, and what follows it. A line that starts with a space is
+ /// inside a block, and one that starts with `#` is a comment.
+ private static func yarnToken(_ text: Substring) -> (String, Substring)? {
+ if text.first == "\"" {
+ guard let end = closingQuote(in: text), let string = jsonString(String(text[...end])) else { return nil }
+ return (string, text[text.index(after: end)...])
+ }
+ guard let first = text.first, first.isASCII, first.isLetter || "/.-".contains(first) else { return nil }
+ let end = text.firstIndex { " :,".contains($0) } ?? text.endIndex
+ return (String(text[..<end]), text[end...])
+ }
+
+ /// The value of a top-level `key: value` line of a YAML file: a plain, single quoted or double quoted scalar,
+ /// with a comment after it or not. A nested block, a flow collection or anything else is no path, and gives nil.
+ static func yamlValue(of key: String, in text: String) -> String? {
+ var found: String?
+ for line in text.split(whereSeparator: { $0 == "\n" || $0 == "\r" }) {
+ guard line.hasPrefix(key + ":") else { continue }
+ let value = line.dropFirst(key.count + 1)
+ guard value.isEmpty || value.first == " " || value.first == "\t" else { continue }
+ found = yamlScalar(Substring(value.trimmingCharacters(in: .whitespaces)))
+ }
+ return found
+ }
+
+ private static func yamlScalar(_ value: Substring) -> String? {
+ if value.first == "\"" {
+ guard let end = closingQuote(in: value), isComment(value[value.index(after: end)...]) else { return nil }
+ return jsonString(String(value[...end]))
+ }
+ if value.first == "'" {
+ // A quote inside is written twice.
+ var result = ""
+ var index = value.index(after: value.startIndex)
+ while index < value.endIndex {
+ let next = value.index(after: index)
+ if value[index] != "'" {
+ result.append(value[index])
+ index = next
+ } else if next < value.endIndex, value[next] == "'" {
+ result.append("'")
+ index = value.index(after: next)
+ } else {
+ return isComment(value[next...]) ? result : nil
+ }
+ }
+ return nil
+ }
+ guard let first = value.first, !"[]{}&*!|>%@`#,?\"'".contains(first) else { return nil }
+ let plain = value.range(of: " #").map { value[..<$0.lowerBound] } ?? value
+ return plain.trimmingCharacters(in: .whitespaces)
+ }
+
+ /// The double quote that closes the string `text` opens, past any quote a backslash escapes.
+ private static func closingQuote(in text: Substring) -> Substring.Index? {
+ var index = text.index(after: text.startIndex)
+ while index < text.endIndex {
+ if text[index] == "\\" {
+ index = text.index(after: index)
+ guard index < text.endIndex else { return nil }
+ } else if text[index] == "\"" {
+ return index
+ }
+ index = text.index(after: index)
+ }
+ return nil
+ }
+
+ private static func isComment(_ rest: Substring) -> Bool {
+ let rest = rest.drop { $0 == " " || $0 == "\t" }
+ return rest.isEmpty || rest.first == "#"
+ }
+
+ /// The value of `KEY` in the file `go env -w` writes, as Go reads it (`cmd/go/internal/cfg`, `readEnvFile`): a
+ /// line `KEY=value` whose name starts with a capital letter, the value taken as written. The last one counts.
+ static func goEnvironmentValue(of key: String, in text: String) -> String? {
+ var found: String?
+ for line in text.split(separator: "\n") {
+ guard let first = line.first, first.isASCII, first.isUppercase, let equals = line.firstIndex(of: "="),
+ line[..<equals] == key
+ else { continue }
+ found = String(line[line.index(after: equals)...])
+ }
+ return found
+ }
+
+ private static func jsonString(_ quoted: String) -> String? {
+ try? JSONSerialization.jsonObject(with: Data(quoted.utf8), options: .fragmentsAllowed) as? String
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
index 6b00e619..26a0e544 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
@@ -381,10 +381,15 @@ struct DeveloperCachesTests {
/// Every folder the table offers names where its tool documents it: a page, or the file inside Xcode that names
/// it, for the folders Apple documents nowhere else.
@Test func everyFolderNamesItsSource() {
+ let isAPage = { (source: String) in source.hasPrefix("https://") && URL(string: source)?.host() != nil }
for definition in DeveloperCaches.definitions {
for folder in definition.folders {
- let isAPage = folder.source.hasPrefix("https://") && URL(string: folder.source)?.host() != nil
- #expect(isAPage || folder.source.hasPrefix("Xcode 27: "), "\(definition.id)'s \(folder.path) names \(folder.source)")
+ #expect(isAPage(folder.source) || folder.source.hasPrefix("Xcode 27: "), "\(definition.id)'s \(folder.path) names \(folder.source)")
+ // What moves a folder is named too, except Xcode's setting, which its folder's source names.
+ if case .xcodeSetting? = folder.movedBy { continue }
+ let sources = folder.movedBy?.sources ?? []
+ #expect(folder.movedBy == nil || !sources.isEmpty, "\(definition.id)'s \(folder.path) moves unnamed")
+ #expect(sources.allSatisfy(isAPage), "\(definition.id)'s \(folder.path) moves by \(sources)")
}
}
}
@@ -402,6 +407,7 @@ struct DeveloperCachesTests {
let electron = DeveloperCaches.electronDefinitions(for: [chat], home: directory.url.appending(path: "home"))
try #require(!electron.isEmpty)
let sources = (DeveloperCaches.definitions + electron).flatMap { $0.folders.map(\.source) }
+ + DeveloperCaches.definitions.flatMap { $0.folders.compactMap(\.movedBy).flatMap(\.sources) }
+ ProjectArtifacts.definitions.map(\.source)
for source in sources {
@@ -829,6 +835,65 @@ struct DeveloperCachesTests {
#expect(byName["Notes 17.09.2026, 10.00.xcarchive"]?.kind == .archives)
}
+ /// npm, Yarn, pnpm and Go each write where a cache moved into a configuration file of their own, with their
+ /// own `config set`; Developer reads those files, never runs a tool, and finds the cache there.
+ @Test func findsTheCachesEachToolsOwnConfigurationMovedElsewhere() async throws {
+ let directory = try TemporaryDirectory()
+ let fast = directory.url.appending(path: "Fast", directoryHint: .isDirectory).path(percentEncoded: false)
+ try directory.file("home/.npmrc", contents: Data("registry=https://registry.npmjs.org/\ncache = \(fast)npm ; moved\n".utf8))
+ try directory.file("Fast/npm/_cacache/index-v5/00/entry")
+ try directory.file("home/.yarnrc", contents: Data("# yarn lockfile v1\ncache-folder \"\(fast)yarn\"\n".utf8))
+ try directory.file("Fast/yarn/v6/npm-left-pad-1.3.0/package.json")
+ try directory.file("home/.yarnrc.yml", contents: Data("globalFolder: \"\(fast)berry\"\n".utf8))
+ try directory.file("Fast/berry/cache/left-pad.zip")
+ try directory.file("home/Library/Preferences/pnpm/config.yaml", contents: Data("storeDir: \(fast)pnpm # moved\n".utf8))
+ try directory.file("Fast/pnpm/v11/index.db")
+ try directory.file("Fast/pnpm/Notes/todo.txt")
+ let goEnvironment = "GOMODCACHE=\(fast)gomod\nGOCACHE=\(fast)gobuild\n"
+ try directory.file("home/Library/Application Support/go/env", contents: Data(goEnvironment.utf8))
+ try directory.file("Fast/gomod/cache/download/example.com/@v/list")
+ let readme = "This directory holds cached build artifacts from the Go build system.\n"
+ try directory.file("Fast/gobuild/README", contents: Data(readme.utf8))
+ try directory.file("Fast/gobuild/00/0a1b-d")
+ let tools = DeveloperCaches.definitions.filter { ["npm", "yarn", "pnpm", "go"].contains($0.id) }
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+
+ let found = await DeveloperCaches.scan(tools, homeDirectory: home).flatMap(\.locations)
+
+ let temporary = directory.url.path(percentEncoded: false)
+ #expect(Set(found.map { $0.url.path(percentEncoded: false).replacingOccurrences(of: temporary, with: "") }) == [
+ "Fast/npm/_cacache", "Fast/yarn/v6", "Fast/berry/cache", "Fast/pnpm/v11", "Fast/gomod/cache/download",
+ "Fast/gobuild",
+ ])
+ }
+
+ /// What a tool would read with its own environment (another variable, its working folder), or a folder that does
+ /// not show the tool's own mark, is no place Peel can name, so it is passed over.
+ @Test func aConfigurationThatNamesNoPlaceOfItsOwnMovesNothing() async throws {
+ let directory = try TemporaryDirectory()
+ let fast = directory.url.appending(path: "Fast", directoryHint: .isDirectory).path(percentEncoded: false)
+ try directory.file("home/.npmrc", contents: Data("cache = ${NPM_FAST}/npm\n[section]\ncache = \(fast)npm\n".utf8))
+ try directory.file("Fast/npm/_cacache/index-v5/00/entry")
+ try directory.file("home/npm/_cacache/index-v5/00/entry")
+ try directory.file("home/berry/cache/left-pad.zip")
+ try directory.file("home/.yarnrc.yml", contents: Data("globalFolder: ${YARN_FAST}/berry\n".utf8))
+ try directory.file("Fast/berry/cache/left-pad.zip")
+ try directory.file("home/.yarnrc", contents: Data("cache-folder \"\(fast)yarn\"\n".utf8))
+ try directory.file("Elsewhere/v6/npm-left-pad-1.3.0/package.json")
+ try directory.directory("Fast/yarn")
+ try FileManager.default.createSymbolicLink(
+ at: directory.url.appending(path: "Fast/yarn/v6"), withDestinationURL: directory.url.appending(path: "Elsewhere/v6")
+ )
+ let goEnvironment = "GOMODCACHE=gomod\nGOCACHE=\(fast)gobuild\n"
+ try directory.file("home/Library/Application Support/go/env", contents: Data(goEnvironment.utf8))
+ try directory.file("Fast/gobuild/00/0a1b-d")
+ let tools = DeveloperCaches.definitions.filter { ["npm", "yarn", "go"].contains($0.id) }
+
+ let found = await DeveloperCaches.scan(tools, homeDirectory: directory.url.appending(path: "home"))
+
+ #expect(found.isEmpty)
+ }
+
@Test func aSettingThatIsNotAnAbsolutePathMovesNothing() async throws {
let directory = try TemporaryDirectory()
let xcode = DeveloperCaches.definitions.filter { $0.id == "xcode" }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift
new file mode 100644
index 00000000..d7485e8d
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ToolSettingsTests.swift
@@ -0,0 +1,156 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct ToolSettingsTests {
+ @Test func readsAnNpmrcAsNpmDoes() {
+ let npmrc = """
+ ; written by npm config set
+ # and edited by hand
+ cache=/first
+ cache = "/Volumes/Fast/npm cache"
+ store-dir = /Volumes/Fast/pnpm ; moved to the fast disk
+ escaped = /a\\#b
+ quoted = '/single'
+ [section]
+ cache = /inside/a/section
+ """
+
+ #expect(ToolSettings.iniValue(of: "cache", in: npmrc) == "/Volumes/Fast/npm cache")
+ #expect(ToolSettings.iniValue(of: "store-dir", in: npmrc) == "/Volumes/Fast/pnpm")
+ #expect(ToolSettings.iniValue(of: "escaped", in: npmrc) == "/a#b")
+ #expect(ToolSettings.iniValue(of: "quoted", in: npmrc) == "/single")
+ #expect(ToolSettings.iniValue(of: "registry", in: npmrc) == nil)
+ }
+
+ @Test func readsAYarnrcAsYarnOneDoes() {
+ let yarnrc = """
+ # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
+ # yarn lockfile v1
+
+
+ cache-folder "/Volumes/Fast/yarn cache"
+ lastUpdateCheck 1791158856071
+ --cache-folder /Volumes/Faster/yarn
+ indented "/is/inside/a/block"
+ """
+
+ #expect(ToolSettings.yarnrcValue(of: "cache-folder", in: yarnrc) == "/Volumes/Fast/yarn cache")
+ #expect(ToolSettings.yarnrcValue(of: "--cache-folder", in: yarnrc) == "/Volumes/Faster/yarn")
+ #expect(ToolSettings.yarnrcValue(of: "lastUpdateCheck", in: yarnrc) == nil)
+ #expect(ToolSettings.yarnrcValue(of: "indented", in: yarnrc) == nil)
+ }
+
+ @Test func readsATopLevelYamlScalar() {
+ let yaml = """
+ # global settings
+ storeDir: /Volumes/Fast/pnpm # moved
+ globalFolder: "/Volumes/Fast/yarn berry"
+ cacheFolder: '/it''s here'
+ packageExtensions:
+ storeDir: /nested/is/no/setting/of/the/top
+ npmScopes: { example: { npmRegistryServer: "https://example.com" } }
+ """
+
+ #expect(ToolSettings.yamlValue(of: "storeDir", in: yaml) == "/Volumes/Fast/pnpm")
+ #expect(ToolSettings.yamlValue(of: "globalFolder", in: yaml) == "/Volumes/Fast/yarn berry")
+ #expect(ToolSettings.yamlValue(of: "cacheFolder", in: yaml) == "/it's here")
+ #expect(ToolSettings.yamlValue(of: "packageExtensions", in: yaml) == nil)
+ #expect(ToolSettings.yamlValue(of: "npmScopes", in: yaml) == nil)
+ }
+
+ @Test func readsTheFileGoEnvWritesAsGoDoes() {
+ let environment = "GOMODCACHE=/first\ngoproxy=a name in lowercase is no setting\nGOMODCACHE=/Volumes/Fast/go mod\n"
+
+ #expect(ToolSettings.goEnvironmentValue(of: "GOMODCACHE", in: environment) == "/Volumes/Fast/go mod")
+ #expect(ToolSettings.goEnvironmentValue(of: "goproxy", in: environment) == nil)
+ }
+
+ /// Each tool takes the path it reads its own way: npm and pnpm 10 with `${HOME}` and `~/`, Yarn from the folder of
+ /// its file with `${HOME}` and a fallback, pnpm 11 with `~/`, and Go with only an absolute path, an empty value
+ /// being unset.
+ @Test func takesEachToolsPathAsTheToolDoes() throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/.npmrc", contents: Data("cache=${HOME}/npm-cache\nstore-dir=~/pnpm-ten\n".utf8))
+ try directory.file("home/.yarnrc", contents: Data("cache-folder relative/yarn\n".utf8))
+ try directory.file("home/.yarnrc.yml", contents: Data("globalFolder: ${HOME:-/nowhere}/berry\n".utf8))
+ try directory.file("home/Library/Preferences/pnpm/config.yaml", contents: Data("storeDir: ~/pnpm-eleven\n".utf8))
+ try directory.file("home/Library/Preferences/pnpm/rc", contents: Data("store-dir=/Volumes/Fast/pnpm\n".utf8))
+ let go = "GOPATH=/Volumes/Fast/go:/Volumes/Other/go\nGOMODCACHE=\nGOCACHE=off\n"
+ try directory.file("home/Library/Application Support/go/env", contents: Data(go.utf8))
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let inHome = { (path: String) in home.appending(path: path).path(percentEncoded: false) }
+
+ let settings = ToolSettings(home: home)
+
+ #expect(Self.path(settings.npmCache) == inHome("npm-cache"))
+ #expect(Self.path(settings.yarnCacheRoot) == inHome("relative/yarn"))
+ #expect(Self.path(settings.yarnGlobalFolder) == inHome("berry"))
+ #expect(settings.pnpmStoreFolders.map { Self.path($0) } == [
+ inHome("pnpm-eleven"), "/Volumes/Fast/pnpm", inHome("pnpm-ten"),
+ ])
+ #expect(Self.path(settings.goModuleCache) == "/Volumes/Fast/go/pkg/mod")
+ #expect(settings.goBuildCache == nil)
+ }
+
+ /// Yarn 1 takes `--cache-folder` in `.yarnrc` as typed on the command line, then its own setting, then npm's.
+ @Test func findsYarnOnesCacheWhereYarnOneLooksFirst() throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ try directory.file("home/.npmrc", contents: Data("cache-folder=/from/npm\n".utf8))
+ #expect(Self.path(ToolSettings(home: home).yarnCacheRoot) == "/from/npm")
+
+ try directory.file("home/.yarnrc", contents: Data("--cache-folder relative/argument\ncache-folder /from/yarn\n".utf8))
+ #expect(Self.path(ToolSettings(home: home).yarnCacheRoot) == "/from/yarn", "a relative argument is no place")
+
+ try directory.file("home/.yarnrc", contents: Data("--cache-folder /from/argument\ncache-folder /from/yarn\n".utf8))
+ #expect(Self.path(ToolSettings(home: home).yarnCacheRoot) == "/from/argument")
+ }
+
+ /// A value whose place depends on the tool's own environment, another variable or the folder it runs in, names
+ /// no place.
+ @Test func passesOverWhatOnlyTheToolsEnvironmentCouldName() throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/.npmrc", contents: Data("cache=${XDG_CACHE_HOME}/npm\nstore-dir=relative/pnpm\n".utf8))
+ try directory.file("home/.yarnrc.yml", contents: Data("globalFolder: ${XDG_DATA_HOME:-${HOME}}/berry\n".utf8))
+ try directory.file("home/Library/Preferences/pnpm/config.yaml", contents: Data("storeDir: ${HOME}/pnpm\n".utf8))
+ try directory.file("home/Library/Application Support/go/env", contents: Data("GOMODCACHE=go/mod\n".utf8))
+
+ let settings = ToolSettings(home: directory.url.appending(path: "home", directoryHint: .isDirectory))
+
+ #expect(settings.npmCache == nil)
+ #expect(settings.yarnGlobalFolder == nil)
+ #expect(settings.pnpmStoreFolders.isEmpty)
+ #expect(settings.goModuleCache == nil)
+ }
+
+ /// pnpm takes a store folder that already ends with its version as the store itself.
+ @Test func aStoreFolderNamedForItsVersionIsTheStore() async throws {
+ let directory = try TemporaryDirectory()
+ let store = directory.url.appending(path: "Fast/pnpm/v11").path(percentEncoded: false)
+ try directory.file("home/Library/Preferences/pnpm/config.yaml", contents: Data("storeDir: \(store)\n".utf8))
+ try directory.file("Fast/pnpm/v11/index.db")
+ let pnpm = DeveloperCaches.definitions.filter { $0.id == "pnpm" }
+
+ let found = await DeveloperCaches.scan(pnpm, homeDirectory: directory.url.appending(path: "home"))
+
+ #expect(found.flatMap(\.locations).map(\.url.path) == [store])
+ }
+
+ /// Space leaves to Developer the folder a tool's configuration moved a cache into, as it leaves the usual one.
+ @Test func spaceLeavesToDeveloperACacheMovedIntoItsCaches() throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let moved = home.appending(path: "Library/Caches/npm").path(percentEncoded: false)
+ try directory.file("home/.npmrc", contents: Data("cache = \(moved)\n".utf8))
+ try directory.file("home/Library/Caches/npm/_cacache/index-v5/00/entry")
+
+ let left = DeveloperCaches.FoldersLeftToDeveloper(home: home)
+
+ #expect(left.inside(home.appending(path: "Library/Caches", directoryHint: .isDirectory)).contains(["npm"]))
+ }
+
+ private static func path(_ url: URL?) -> String? {
+ url.map { $0.path(percentEncoded: false) }.map { $0.count > 1 && $0.hasSuffix("/") ? String($0.dropLast()) : $0 }
+ }
+}