1
+import fs from 'node:fs/promises';
2
+import path from 'node:path';
3
+
4
+const swiftSystemAtResolveBeneathGuard = '#if canImport(Darwin, _version: 346) || os(FreeBSD)';
5
+const swiftSystemFreeBsdOnlyGuard = '#if os(FreeBSD)';
6
+
7
+// swift-system 1.7.x exposes AT_RESOLVE_BENEATH on Darwin when compiling with
8
+// Swift 6.2, but GitHub's macOS SDK currently omits the C constant.
9
+const swiftSystemAtResolveBeneathFiles = [
10
+ 'Sources/System/Internals/Constants.swift',
11
+ 'Sources/System/FileSystem/Stat.swift',
12
+] as const;
13
+
14
+const countOccurrences = (source: string, pattern: string): number =>
15
+ source.split(pattern).length - 1;
16
+
17
+export const patchSwiftSystemAtResolveBeneathGuardInSource = (
18
+ source: string,
19
+ filePath: string
20
+): { source: string; replacementCount: number } => {
21
+ const replacementCount = countOccurrences(source, swiftSystemAtResolveBeneathGuard);
22
+ if (replacementCount > 0) {
23
+ return {
24
+ source: source.replaceAll(swiftSystemAtResolveBeneathGuard, swiftSystemFreeBsdOnlyGuard),
25
+ replacementCount,
26
+ };
27
+ }
28
+
29
+ if (source.includes(swiftSystemFreeBsdOnlyGuard) && source.includes('AT_RESOLVE_BENEATH')) {
30
+ return { source, replacementCount: 0 };
31
+ }
32
+
33
+ throw new Error(`Unable to patch swift-system AT_RESOLVE_BENEATH guard in ${filePath}`);
34
+};
35
+
36
+export const patchSwiftSystemAtResolveBeneathGuard = async (
37
+ checkoutRoot: string,
38
+ exists: (filePath: string) => Promise<boolean>
39
+): Promise<number> => {
40
+ let replacementCount = 0;
41
+
42
+ for (const filePath of swiftSystemAtResolveBeneathFiles) {
43
+ const sourcePath = path.join(checkoutRoot, filePath);
44
+ if (!(await exists(sourcePath))) {
45
+ throw new Error(
46
+ `Swift package resolution completed but swift-system ${filePath} was not found.`
47
+ );
48
+ }
49
+
50
+ const source = await fs.readFile(sourcePath, 'utf8');
51
+ const patched = patchSwiftSystemAtResolveBeneathGuardInSource(source, filePath);
52
+ if (patched.replacementCount === 0) continue;
53
+
54
+ await fs.chmod(sourcePath, 0o644).catch(() => undefined);
55
+ await fs.writeFile(sourcePath, patched.source, 'utf8');
56
+ replacementCount += patched.replacementCount;
57
+ }
58
+
59
+ return replacementCount;
60
+};