Skip to content

BridgeJS: Rename which override env-var format to JAVASCRIPTKIT_<EXECUTABLE>_EXEC #415

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
Aug 17, 2025
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
13 changes: 8 additions & 5 deletions Plugins/BridgeJS/Sources/TS2Skeleton/TS2Skeleton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,20 @@ import BridgeJSCore
import BridgeJSSkeleton
#endif

internal func which(_ executable: String) throws -> URL {
internal func which(
_ executable: String,
environment: [String: String] = ProcessInfo.processInfo.environment
) throws -> URL {
func checkCandidate(_ candidate: URL) -> Bool {
var isDirectory: ObjCBool = false
let fileExists = FileManager.default.fileExists(atPath: candidate.path, isDirectory: &isDirectory)
return fileExists && !isDirectory.boolValue && FileManager.default.isExecutableFile(atPath: candidate.path)
}
do {
// Check overriding environment variable
let envVariable = executable.uppercased().replacingOccurrences(of: "-", with: "_") + "_PATH"
if let path = ProcessInfo.processInfo.environment[envVariable] {
let url = URL(fileURLWithPath: path).appendingPathComponent(executable)
let envVariable = "JAVASCRIPTKIT_" + executable.uppercased().replacingOccurrences(of: "-", with: "_") + "_EXEC"
if let executablePath = environment[envVariable] {
let url = URL(fileURLWithPath: executablePath)
if checkCandidate(url) {
return url
}
Expand All @@ -41,7 +44,7 @@ internal func which(_ executable: String) throws -> URL {
#else
pathSeparator = ":"
#endif
let paths = ProcessInfo.processInfo.environment["PATH"]!.split(separator: pathSeparator)
let paths = environment["PATH"]?.split(separator: pathSeparator) ?? []
for path in paths {
let url = URL(fileURLWithPath: String(path)).appendingPathComponent(executable)
if checkCandidate(url) {
Expand Down
190 changes: 190 additions & 0 deletions Plugins/BridgeJS/Tests/BridgeJSToolTests/WhichTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import Testing
import Foundation
@testable import TS2Skeleton
@testable import BridgeJSCore

@Suite struct WhichTests {

// MARK: - Helper Functions

private static var pathSeparator: String {
#if os(Windows)
return ";"
#else
return ":"
#endif
}

// MARK: - Successful Path Resolution Tests

@Test func whichFindsExecutableInPath() throws {
try withTemporaryDirectory { tempDir, _ in
let execFile = tempDir.appendingPathComponent("testexec")
try "#!/bin/sh\necho 'test'".write(to: execFile, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: execFile.path)

let environment = ["PATH": tempDir.path]

let result = try which("testexec", environment: environment)

#expect(result.path == execFile.path)
}
}

@Test func whichReturnsFirstMatchInPath() throws {
try withTemporaryDirectory { tempDir1, _ in
try withTemporaryDirectory { tempDir2, _ in
let exec1 = tempDir1.appendingPathComponent("testexec")
let exec2 = tempDir2.appendingPathComponent("testexec")

// Create executable files in both directories
try "#!/bin/sh\necho 'first'".write(to: exec1, atomically: true, encoding: .utf8)
try "#!/bin/sh\necho 'second'".write(to: exec2, atomically: true, encoding: .utf8)

// Make files executable
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: exec1.path)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: exec2.path)

let pathEnv = "\(tempDir1.path)\(Self.pathSeparator)\(tempDir2.path)"
let environment = ["PATH": pathEnv]

let result = try which("testexec", environment: environment)

// Should return the first one found
#expect(result.path == exec1.path)
}
}
}

// MARK: - Environment Variable Override Tests

@Test func whichUsesEnvironmentVariableOverride() throws {
try withTemporaryDirectory { tempDir, _ in
let customExec = tempDir.appendingPathComponent("mynode")
try "#!/bin/sh\necho 'custom node'".write(to: customExec, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: customExec.path)

let environment = [
"PATH": "/nonexistent/path",
"JAVASCRIPTKIT_NODE_EXEC": customExec.path,
]

let result = try which("node", environment: environment)

#expect(result.path == customExec.path)
}
}

@Test func whichHandlesHyphenatedExecutableNames() throws {
try withTemporaryDirectory { tempDir, _ in
let customExec = tempDir.appendingPathComponent("my-exec")
try "#!/bin/sh\necho 'hyphenated'".write(to: customExec, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: customExec.path)

let environment = [
"PATH": "/nonexistent/path",
"JAVASCRIPTKIT_MY_EXEC_EXEC": customExec.path,
]

let result = try which("my-exec", environment: environment)

#expect(result.path == customExec.path)
}
}

@Test func whichPrefersEnvironmentOverridePath() throws {
try withTemporaryDirectory { tempDir1, _ in
try withTemporaryDirectory { tempDir2, _ in
let pathExec = tempDir1.appendingPathComponent("testexec")
let envExec = tempDir2.appendingPathComponent("testexec")

try "#!/bin/sh\necho 'from path'".write(to: pathExec, atomically: true, encoding: .utf8)
try "#!/bin/sh\necho 'from env'".write(to: envExec, atomically: true, encoding: .utf8)

try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: pathExec.path)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: envExec.path)

let environment = [
"PATH": tempDir1.path,
"JAVASCRIPTKIT_TESTEXEC_EXEC": envExec.path,
]

let result = try which("testexec", environment: environment)

// Should prefer environment variable over PATH
#expect(result.path == envExec.path)
}
}
}

// MARK: - Error Handling Tests

@Test func whichThrowsWhenExecutableNotFound() throws {
let environment = ["PATH": "/nonexistent\(Self.pathSeparator)/also/nonexistent"]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("nonexistent_executable_12345", environment: environment)
}
}

@Test func whichThrowsWhenEnvironmentPathIsInvalid() throws {
try withTemporaryDirectory { tempDir, _ in
let nonExecFile = tempDir.appendingPathComponent("notexecutable")
try "not executable".write(to: nonExecFile, atomically: true, encoding: .utf8)

let environment = [
"PATH": tempDir.path,
"JAVASCRIPTKIT_NOTEXECUTABLE_EXEC": nonExecFile.path,
]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("notexecutable", environment: environment)
}
}
}

@Test func whichThrowsWhenPathPointsToDirectory() throws {
try withTemporaryDirectory { tempDir, _ in
let environment = [
"PATH": "/nonexistent/path",
"JAVASCRIPTKIT_TESTEXEC_EXEC": tempDir.path,
]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("testexec", environment: environment)
}
}
}

// MARK: - Edge Case Tests

@Test func whichHandlesEmptyPath() throws {
let environment = ["PATH": ""]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("anyexec", environment: environment)
}
}

@Test func whichHandlesMissingPathEnvironment() throws {
let environment: [String: String] = [:]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("anyexec", environment: environment)
}
}

@Test func whichIgnoresNonExecutableFiles() throws {
try withTemporaryDirectory { tempDir, _ in
let nonExecFile = tempDir.appendingPathComponent("testfile")
try "content".write(to: nonExecFile, atomically: true, encoding: .utf8)
// Don't set executable permissions

let environment = ["PATH": tempDir.path]

#expect(throws: BridgeJSCoreError.self) {
_ = try which("testfile", environment: environment)
}
}
}
}
11 changes: 6 additions & 5 deletions Plugins/PackageToJS/Sources/PackageToJS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ final class DefaultPackagingSystem: PackagingSystem {
private let printWarning: (String) -> Void
private let which: (String) throws -> URL

init(printWarning: @escaping (String) -> Void, which: @escaping (String) throws -> URL = which(_:)) {
init(printWarning: @escaping (String) -> Void, which: @escaping (String) throws -> URL) {
self.printWarning = printWarning
self.which = which
}
Expand Down Expand Up @@ -323,16 +323,17 @@ final class DefaultPackagingSystem: PackagingSystem {
}

internal func which(_ executable: String) throws -> URL {
let environment = ProcessInfo.processInfo.environment
func checkCandidate(_ candidate: URL) -> Bool {
var isDirectory: ObjCBool = false
let fileExists = FileManager.default.fileExists(atPath: candidate.path, isDirectory: &isDirectory)
return fileExists && !isDirectory.boolValue && FileManager.default.isExecutableFile(atPath: candidate.path)
}
do {
// Check overriding environment variable
let envVariable = executable.uppercased().replacingOccurrences(of: "-", with: "_") + "_PATH"
if let path = ProcessInfo.processInfo.environment[envVariable] {
let url = URL(fileURLWithPath: path).appendingPathComponent(executable)
let envVariable = "JAVASCRIPTKIT_" + executable.uppercased().replacingOccurrences(of: "-", with: "_") + "_EXEC"
if let executablePath = environment[envVariable] {
let url = URL(fileURLWithPath: executablePath)
if checkCandidate(url) {
return url
}
Expand All @@ -344,7 +345,7 @@ internal func which(_ executable: String) throws -> URL {
#else
pathSeparator = ":"
#endif
let paths = ProcessInfo.processInfo.environment["PATH"]!.split(separator: pathSeparator)
let paths = environment["PATH"]?.split(separator: pathSeparator) ?? []
for path in paths {
let url = URL(fileURLWithPath: String(path)).appendingPathComponent(executable)
if checkCandidate(url) {
Expand Down
2 changes: 1 addition & 1 deletion Plugins/PackageToJS/Sources/PackageToJSPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -762,7 +762,7 @@ extension PackagingPlanner {
) {
let outputBaseName = outputDir.lastPathComponent
let (configuration, triple) = PackageToJS.deriveBuildConfiguration(wasmProductArtifact: wasmProductArtifact)
let system = DefaultPackagingSystem(printWarning: printStderr)
let system = DefaultPackagingSystem(printWarning: printStderr, which: which(_:))
self.init(
options: options,
packageId: context.package.id,
Expand Down