Skip to content

Commit c05ea2d

Browse files
committed
Enable cross-PR testing
1 parent d82d736 commit c05ea2d

File tree

4 files changed

+222
-10
lines changed

4 files changed

+222
-10
lines changed

.github/workflows/pull_request.yml

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ jobs:
88
tests:
99
name: Test
1010
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
11-
soundness:
12-
name: Soundness
13-
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
1411
with:
15-
license_header_check_enabled: false
16-
license_header_check_project_name: "Swift.org"
12+
enable_windows_checks: false
13+
linux_pre_build_command: |
14+
swiftc cross-pr-checkout.swift -o /tmp/cross-pr-checkout
15+
/tmp/cross-pr-checkout "${{ github.repository }}" "${{ github.event.number }}"
16+
# soundness:
17+
# name: Soundness
18+
# uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
19+
# with:
20+
# license_header_check_enabled: false
21+
# license_header_check_project_name: "Swift.org"

Sources/SwiftFormat/Rules/UseShorthandTypeNames.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
4848
switch node.name.text {
4949
case "Array":
5050
guard let argument = genericArgumentList.firstAndOnly,
51-
case .type(let typeArgument) = argument else {
51+
case .type(let typeArgument) = argument.argument else {
5252
newNode = nil
5353
break
5454
}
@@ -62,7 +62,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
6262
case "Dictionary":
6363
guard let arguments = exactlyTwoChildren(of: genericArgumentList),
6464
case .type(let type0Argument) = arguments.0.argument,
65-
caes .type(let type1Argument) = arguments.1.argument else {
65+
case .type(let type1Argument) = arguments.1.argument else {
6666
newNode = nil
6767
break
6868
}
@@ -79,7 +79,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
7979
break
8080
}
8181
guard let argument = genericArgumentList.firstAndOnly,
82-
case .type(let typeArgument) = argument else {
82+
case .type(let typeArgument) = argument.argument else {
8383
newNode = nil
8484
break
8585
}
@@ -143,7 +143,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
143143
switch expression.baseName.text {
144144
case "Array":
145145
guard let argument = genericArgumentList.firstAndOnly,
146-
case .type(let typeArgument) = argument else {
146+
case .type(let typeArgument) = argument.argument else {
147147
newNode = nil
148148
break
149149
}
@@ -172,7 +172,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
172172

173173
case "Optional":
174174
guard let argument = genericArgumentList.firstAndOnly,
175-
case .type(let typeArgument) = argument else {
175+
case .type(let typeArgument) = argument.argument else {
176176
newNode = nil
177177
break
178178
}

cross-pr-checkout.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import subprocess
2+
import pathlib
3+
import requests
4+
5+
class CrossRepoPR:
6+
org: str
7+
repo: str
8+
pr_num: str
9+
10+
def __init__(self, org: str, repo: str, pr_num: str) -> None:
11+
self.org = org
12+
self.repo = repo
13+
self.pr_num = pr_num
14+
15+
def cross_repo_prs() -> list[CrossRepoPR]:
16+
return [
17+
CrossRepoPR("swiftlang", "swift-syntax", "2859")
18+
]
19+
20+
def run(cmd: list[str], cwd: str|None = None):
21+
print(" ".join(cmd))
22+
subprocess.check_call(cmd, cwd=cwd)
23+
24+
def main():
25+
for cross_repo_pr in cross_repo_prs():
26+
run(["git", "clone", f"https://github.com/{cross_repo_pr.org}/{cross_repo_pr.repo}.git", f"{cross_repo_pr.repo}"], cwd="..")
27+
run(["git", "fetch", "origin", f"pull/{cross_repo_pr.pr_num}/merge:pr_merge"], cwd="../swift-syntax")
28+
run(["git", "checkout", "main"], cwd="../swift-syntax")
29+
run(["git", "reset", "--hard", "pr_merge"], cwd="../swift-syntax")
30+
run(["swift", "package", "config", "set-mirror", "--package-url", "https://github.com/swiftlang/swift-syntax.git", "--mirror-url", str(pathlib.Path("../swift-syntax").resolve())])
31+
32+
if __name__ == "__main__":
33+
main()

cross-pr-checkout.swift

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
import Foundation
2+
import RegexBuilder
3+
4+
#if canImport(FoundationNetworking)
5+
import FoundationNetworking
6+
#endif
7+
8+
struct GenericError: Error, CustomStringConvertible {
9+
var description: String
10+
11+
init(_ description: String) {
12+
self.description = description
13+
}
14+
}
15+
16+
/// Launch a subprocess with the given command and wait for it to finish
17+
func run(_ executable: URL, _ arguments: String..., workingDirectory: URL? = nil) throws {
18+
print("Running " + ([executable.path] + arguments).joined(separator: " "))
19+
let process = Process()
20+
process.executableURL = executable
21+
process.arguments = arguments
22+
if let workingDirectory {
23+
process.currentDirectoryURL = workingDirectory
24+
}
25+
26+
try process.run()
27+
process.waitUntilExit()
28+
guard process.terminationStatus == 0 else {
29+
throw GenericError("")
30+
}
31+
}
32+
33+
/// Find the executable with the given name
34+
public func lookup(executable: String) throws -> URL {
35+
// Compute search paths from PATH variable.
36+
#if os(Windows)
37+
let pathSeparator: Character = ";"
38+
let pathVariable = "Path"
39+
#else
40+
let pathSeparator: Character = ":"
41+
let pathVariable = "PATH"
42+
#endif
43+
guard let pathString = ProcessInfo.processInfo.environment[pathVariable] else {
44+
throw GenericError("Failed to read path environment variable")
45+
}
46+
for searchPath in pathString.split(separator: pathSeparator) {
47+
let candidateUrl = URL(fileURLWithPath: String(searchPath)).appendingPathComponent(executable)
48+
if FileManager.default.isExecutableFile(atPath: candidateUrl.path) {
49+
return candidateUrl
50+
}
51+
}
52+
throw GenericError("Did not find \(executable)")
53+
}
54+
55+
struct CrossRepoPR {
56+
let repositoryOwner: String
57+
let repositoryName: String
58+
let prNumber: String
59+
}
60+
61+
/// The JSON fields of the `https://api.github.com/repos/\(repository)/pulls/\(prNumber)` endpoint that we care about.
62+
struct PRInfo: Codable {
63+
struct Base: Codable {
64+
let ref: String
65+
}
66+
let base: Base
67+
let body: String
68+
}
69+
70+
/// - Parameters:
71+
/// - repository: The repository's name, eg. `swiftlang/swift-syntax`
72+
func getPRInfo(repository: String, prNumber: String) throws -> PRInfo {
73+
guard let prInfoUrl = URL(string: "https://api.github.com/repos/\(repository)/pulls/\(prNumber)") else {
74+
throw GenericError("Failed to form URL for GitHub API")
75+
}
76+
77+
do {
78+
let data = try Data(contentsOf: prInfoUrl)
79+
return try JSONDecoder().decode(PRInfo.self, from: data)
80+
} catch {
81+
throw GenericError("Failed to load PR info from \(prInfoUrl): \(error)")
82+
}
83+
}
84+
85+
func getCrossRepoPrs(repository: String, prNumber: String) throws -> [CrossRepoPR] {
86+
var result: [CrossRepoPR] = []
87+
let prInfo = try getPRInfo(repository: repository, prNumber: prNumber)
88+
for line in prInfo.body.split(separator: "\n") {
89+
guard line.lowercased().starts(with: "linked pr:") else {
90+
continue
91+
}
92+
let repoRegex = Regex {
93+
Capture {
94+
#/swiftlang|apple/#
95+
}
96+
"/"
97+
Capture {
98+
#/[-a-zA-Z0-9_]+/#
99+
}
100+
ChoiceOf {
101+
"/pull/"
102+
"#"
103+
}
104+
Capture {
105+
OneOrMore(.digit)
106+
}
107+
}
108+
for match in line.matches(of: repoRegex) {
109+
result.append(
110+
CrossRepoPR(repositoryOwner: String(match.1), repositoryName: String(match.2), prNumber: String(match.3))
111+
)
112+
}
113+
}
114+
return result
115+
}
116+
117+
func main() throws {
118+
print("Start")
119+
print(ProcessInfo.processInfo.arguments)
120+
121+
guard ProcessInfo.processInfo.arguments.count >= 3 else {
122+
throw GenericError(
123+
"""
124+
Expected two arguments:
125+
- Repository name, eg. `swiftlang/swift-syntax
126+
- PR number
127+
"""
128+
)
129+
}
130+
let repository = ProcessInfo.processInfo.arguments[1]
131+
let prNumber = ProcessInfo.processInfo.arguments[2]
132+
133+
let crossRepoPrs = try getCrossRepoPrs(repository: repository, prNumber: prNumber)
134+
print("Detected cross-repo PRs: \(crossRepoPrs)")
135+
136+
for crossRepoPr in crossRepoPrs {
137+
let git = try lookup(executable: "git")
138+
let swift = try lookup(executable: "swift")
139+
let baseBranch = try getPRInfo(
140+
repository: "\(crossRepoPr.repositoryOwner)/\(crossRepoPr.repositoryName)",
141+
prNumber: crossRepoPr.prNumber
142+
).base.ref
143+
144+
let workspaceDir = URL(fileURLWithPath: "..")
145+
let repoDir = workspaceDir.appendingPathComponent(crossRepoPr.repositoryName)
146+
try run(
147+
git,
148+
"clone",
149+
"https://github.com/\(crossRepoPr.repositoryOwner)/\(crossRepoPr.repositoryName).git",
150+
"\(crossRepoPr.repositoryName)",
151+
workingDirectory: workspaceDir
152+
)
153+
try run(git, "fetch", "origin", "pull/\(crossRepoPr.prNumber)/merge:pr_merge", workingDirectory: repoDir)
154+
try run(git, "checkout", baseBranch, workingDirectory: repoDir)
155+
try run(git, "reset", "--hard", "pr_merge", workingDirectory: repoDir)
156+
try run(
157+
swift,
158+
"package",
159+
"config",
160+
"set-mirror",
161+
"--package-url",
162+
"https://github.com/\(crossRepoPr.repositoryOwner)/\(crossRepoPr.repositoryName).git",
163+
"--mirror-url",
164+
repoDir.resolvingSymlinksInPath().path
165+
)
166+
}
167+
}
168+
169+
do {
170+
try main()
171+
} catch {
172+
print(error)
173+
exit(1)
174+
}

0 commit comments

Comments
 (0)