Skip to content

Update BSP connection build server config lookup path #1728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 65 additions & 2 deletions Sources/BuildSystemIntegration/ExternalBuildSystemAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ struct ExecutableNotFoundError: Error {
let executableName: String
}

enum BuildServerNotFoundError: Error {
case fileNotFound
}

private struct BuildServerConfig: Codable {
/// The name of the build tool.
let name: String
Expand Down Expand Up @@ -94,7 +98,7 @@ actor ExternalBuildSystemAdapter {
private var lastRestart: Date?

static package func projectRoot(for workspaceFolder: AbsolutePath, options: SourceKitLSPOptions) -> AbsolutePath? {
guard localFileSystem.isFile(workspaceFolder.appending(component: "buildServer.json")) else {
guard getConfigPath(for: workspaceFolder) != nil else {
return nil
}
return workspaceFolder
Expand Down Expand Up @@ -142,7 +146,10 @@ actor ExternalBuildSystemAdapter {

/// Create a new JSONRPCConnection to the build server.
private func createConnectionToBspServer() async throws -> JSONRPCConnection {
let configPath = projectRoot.appending(component: "buildServer.json")
guard let configPath = ExternalBuildSystemAdapter.getConfigPath(for: self.projectRoot) else {
throw BuildServerNotFoundError.fileNotFound
}

let serverConfig = try BuildServerConfig.load(from: configPath)
var serverPath = try AbsolutePath(validating: serverConfig.argv[0], relativeTo: projectRoot)
var serverArgs = Array(serverConfig.argv[1...])
Expand Down Expand Up @@ -178,6 +185,62 @@ actor ExternalBuildSystemAdapter {
).connection
}

private static func getConfigPath(for workspaceFolder: AbsolutePath? = nil) -> AbsolutePath? {
var buildServerConfigLocations: [URL?] = []
if let workspaceFolder = workspaceFolder {
buildServerConfigLocations.append(workspaceFolder.appending(component: ".bsp").asURL)
}

#if os(Windows)
if let localAppData = ProcessInfo.processInfo.environment["LOCALAPPDATA"] {
buildServerConfigLocations.append(URL(fileURLWithPath: localAppData).appendingPathComponent("bsp"))
}
if let programData = ProcessInfo.processInfo.environment["PROGRAMDATA"] {
buildServerConfigLocations.append(URL(fileURLWithPath: programData).appendingPathComponent("bsp"))
}
#else
if let xdgDataHome = ProcessInfo.processInfo.environment["XDG_DATA_HOME"] {
buildServerConfigLocations.append(URL(fileURLWithPath: xdgDataHome).appendingPathComponent("bsp"))
}

if let libraryUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
buildServerConfigLocations.append(libraryUrl.appendingPathComponent("bsp"))
}

if let xdgDataDirs = ProcessInfo.processInfo.environment["XDG_DATA_DIRS"] {
buildServerConfigLocations += xdgDataDirs.split(separator: ":").map { xdgDataDir in
URL(fileURLWithPath: String(xdgDataDir)).appendingPathComponent("bsp")
}
}

if let libraryUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .systemDomainMask).first {
buildServerConfigLocations.append(libraryUrl.appendingPathComponent("bsp"))
}
#endif

for case let buildServerConfigLocation? in buildServerConfigLocations {
let jsonFiles =
try? FileManager.default.contentsOfDirectory(at: buildServerConfigLocation, includingPropertiesForKeys: nil)
.filter { $0.pathExtension == "json" }

if let configFileURL = jsonFiles?.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }).first,
let configFilePath = AbsolutePath(validatingOrNil: configFileURL.path)
{
return configFilePath
}
}

// Pre Swift 6.1 SourceKit-LSP looked for `buildServer.json` in the project root. Maintain this search location for
// compatibility even though it's not a standard BSP search location.
if let workspaceFolder = workspaceFolder,
localFileSystem.isFile(workspaceFolder.appending(component: "buildServer.json"))
{
return workspaceFolder.appending(component: "buildServer.json")
}

return nil
}

/// Restart the BSP server after it has crashed.
private func handleBspServerCrash() async throws {
// Set `connectionToBuildServer` to `nil` to indicate that there is currently no BSP server running.
Expand Down
3 changes: 2 additions & 1 deletion Sources/SKTestSupport/BuildServerTestProject.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,12 @@ private let skTestSupportInputsDirectory: URL = {
package class BuildServerTestProject: MultiFileTestProject {
package init(
files: [RelativeFileLocation: String],
buildServerConfigLocation: RelativeFileLocation = ".bsp/sourcekit-lsp.json",
buildServer: String,
testName: String = #function
) async throws {
var files = files
files["buildServer.json"] = """
files[buildServerConfigLocation] = """
{
"name": "client name",
"version": "10",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,61 @@ final class BuildServerBuildSystemTests: XCTestCase {
)
return diagnostics.fullReport?.items.map(\.message) == ["DEBUG SET"]
}
}

func testBuildServerConfigAtLegacyLocation() async throws {
let project = try await BuildServerTestProject(
files: [
"Test.swift": """
#if DEBUG
#error("DEBUG SET")
#else
#error("DEBUG NOT SET")
#endif
"""
],
buildServerConfigLocation: "buildServer.json",
buildServer: """
class BuildServer(AbstractBuildServer):
def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, object]:
return {
"targets": [
{
"id": {"uri": "bsp://dummy"},
"tags": [],
"languageIds": [],
"dependencies": [],
"capabilities": {},
}
]
}

def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
return {
"items": [
{
"target": {"uri": "bsp://dummy"},
"sources": [
{"uri": "$TEST_DIR_URL/Test.swift", "kind": 1, "generated": False}
],
}
]
}

def textdocument_sourcekitoptions(self, request: Dict[str, object]) -> Dict[str, object]:
return {
"compilerArguments": ["$TEST_DIR/Test.swift", "-DDEBUG", $SDK_ARGS]
}
"""
)

let (uri, _) = try project.openDocument("Test.swift")

try await repeatUntilExpectedResult {
let diags = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
return diags.fullReport?.items.map(\.message) == ["DEBUG SET"]
}
}
}