Update SwiftPM branch to 5.8 and fix build errors (#395)

* Update SwiftPM branch to 5.8 and fix build errors

* Make swift-format 5.8 happy :)

* Make swift-format 5.8 happy for Tests

* Fix wrong formatting

* Resolve AbsolutePath(validating:) rename warnings

* Fix wrong formatting

* Resolve remaining deprecation warnings

* Fix Linux build failure
This commit is contained in:
Yuta Saito 2023-05-04 18:40:16 +09:00 committed by GitHub
parent f2a83a28bb
commit b79fe9a260
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 918 additions and 731 deletions

View File

@ -105,16 +105,16 @@
"repositoryURL": "https://github.com/apple/swift-crypto.git",
"state": {
"branch": null,
"revision": "ddb07e896a2a8af79512543b1c7eb9797f8898a5",
"version": "1.1.7"
"revision": "75ec60b8b4cc0f085c3ac414f3dca5625fa3588e",
"version": "2.2.4"
}
},
{
"package": "swift-driver",
"repositoryURL": "https://github.com/apple/swift-driver.git",
"state": {
"branch": "release/5.7",
"revision": "719426df790661020de657bf38beb2a8b1de5ad3",
"branch": "release/5.8",
"revision": "7cfe0c0b6e6297efe88a3ce34e6138ee7eda969e",
"version": null
}
},
@ -122,8 +122,8 @@
"package": "llbuild",
"repositoryURL": "https://github.com/apple/swift-llbuild.git",
"state": {
"branch": "release/5.7",
"revision": "564424db5fdb62dcb5d863bdf7212500ef03a87b",
"branch": "release/5.8",
"revision": "dccfc2e127a34b89a849407594cf2d604b598ba9",
"version": null
}
},
@ -203,8 +203,8 @@
"package": "SwiftPM",
"repositoryURL": "https://github.com/apple/swift-package-manager.git",
"state": {
"branch": "release/5.7",
"revision": "63c14b84dc12c943a9d4c102648b7617d8b92f67",
"branch": "release/5.8",
"revision": "fe383ccb099ff65ca1403137e7383aedaf99af87",
"version": null
}
},
@ -221,8 +221,8 @@
"package": "swift-tools-support-core",
"repositoryURL": "https://github.com/apple/swift-tools-support-core.git",
"state": {
"branch": "release/5.7",
"revision": "184eba382f6abbb362ffc02942d790ff35019ad4",
"branch": "release/5.8",
"revision": "ac4871e01ef338cb95b5d28328cab0ec1dfae935",
"version": null
}
},
@ -258,8 +258,8 @@
"repositoryURL": "https://github.com/jpsim/Yams.git",
"state": {
"branch": null,
"revision": "9ff1cc9327586db4e0c8f46f064b6a82ec1566fa",
"version": "4.0.6"
"revision": "f47ba4838c30dbd59998a4e4c87ab620ff959e8a",
"version": "5.0.5"
}
}
]

View File

@ -27,14 +27,14 @@ let package = Package(
.package(
name: "SwiftPM",
url: "https://github.com/apple/swift-package-manager.git",
.branch("release/5.7")
.branch("release/5.8")
),
.package(
url: "https://github.com/apple/swift-tools-support-core.git",
.branch("release/5.7")
.branch("release/5.8")
),
.package(url: "https://github.com/vapor/vapor.git", from: "4.57.1"),
.package(url: "https://github.com/apple/swift-crypto.git", from: "1.1.0"),
.package(url: "https://github.com/apple/swift-crypto.git", from: "2.2.0"),
.package(url: "https://github.com/JohnSundell/Splash.git", from: "0.16.0"),
.package(
url: "https://github.com/swiftwasm/WasmTransformer",

View File

@ -122,7 +122,9 @@ struct Bundle: AsyncParsableCommand {
terminal.write("Bundle generation finished successfully\n", inColor: .green, bold: true)
}
func optimize(_ inputPath: AbsolutePath, outputPath: AbsolutePath, terminal: InteractiveWriter) async throws {
func optimize(_ inputPath: AbsolutePath, outputPath: AbsolutePath, terminal: InteractiveWriter)
async throws
{
var wasmOptArgs = ["wasm-opt", "-Os", inputPath.pathString, "-o", outputPath.pathString]
if debugInfo {
wasmOptArgs.append("--debuginfo")
@ -156,7 +158,7 @@ struct Bundle: AsyncParsableCommand {
try localFileSystem.move(from: wasmOutputFilePath, to: mainModulePath)
// Copy the bundle entrypoint, point to the binary, and give it a cachebuster name.
let (_, _, entrypointPath) = dependency.paths(on: localFileSystem)
let (_, _, entrypointPath) = try dependency.paths(on: localFileSystem)
let entrypoint = try ByteString(
encodingAsUTF8: localFileSystem.readFileContents(entrypointPath)
.description
@ -173,7 +175,8 @@ struct Bundle: AsyncParsableCommand {
try localFileSystem.writeFileContents(
AbsolutePath(bundleDirectory, "index.html"),
bytes: ByteString(encodingAsUTF8: HTML.indexPage(
bytes: ByteString(
encodingAsUTF8: HTML.indexPage(
customContent: HTML.readCustomIndexPage(at: customIndexPage, on: localFileSystem),
entrypointName: entrypointName
))

View File

@ -126,7 +126,9 @@ struct Dev: AsyncParsableCommand {
verbose: verbose,
port: port,
host: host,
customIndexPath: customIndexPage.map { AbsolutePath($0, relativeTo: localFileSystem.currentWorkingDirectory!) },
customIndexPath: customIndexPage.map {
try AbsolutePath(validating: $0, relativeTo: localFileSystem.currentWorkingDirectory!)
},
// swiftlint:disable:next force_try
manifest: try! toolchain.manifest.get(),
product: build.product,

View File

@ -25,12 +25,14 @@ struct Init: AsyncParsableCommand {
subcommands: [ListTemplates.self]
)
@Option(name: .long,
@Option(
name: .long,
help: "The template to base the project on.",
transform: { Templates(rawValue: $0.lowercased()) })
var template: Templates?
@Option(name: .long,
@Option(
name: .long,
help: "The name of the project") var name: String?
func run() async throws {
@ -50,9 +52,10 @@ struct Init: AsyncParsableCommand {
terminal.write(" in ")
terminal.write("\(name)\n", inColor: .cyan)
guard let packagePath = self.name == nil ?
localFileSystem.currentWorkingDirectory :
AbsolutePath(name, relativeTo: currentDir)
guard
let packagePath = try self.name == nil
? localFileSystem.currentWorkingDirectory
: AbsolutePath(validating: name, relativeTo: currentDir)
else {
terminal.write("Path to project could be created.\n", inColor: .red)
return

View File

@ -15,7 +15,8 @@
import ArgumentParser
struct BuildOptions: ParsableArguments {
@Option(name: .customLong("Xswiftc", withSingleDash: true),
@Option(
name: .customLong("Xswiftc", withSingleDash: true),
parsing: .unconditionalSingleValue,
help: "Pass flag through to all Swift compiler invocations")
var swiftCompilerFlags: [String] = []

View File

@ -20,7 +20,8 @@ import TSCBasic
/// Proxy swift-package command to locally pinned toolchain version.
struct Package: AsyncParsableCommand {
static let configuration = CommandConfiguration(abstract: """
static let configuration = CommandConfiguration(
abstract: """
Perform operations on Swift packages.
""")

View File

@ -18,7 +18,8 @@ import SwiftToolchain
import TSCBasic
struct Local: ParsableCommand {
static let configuration = CommandConfiguration(abstract: """
static let configuration = CommandConfiguration(
abstract: """
Prints SDK version used for the current project or saves it \
in the `.swift-version` file if a version is passed as an argument.
""")
@ -27,7 +28,7 @@ struct Local: ParsableCommand {
func run() throws {
let terminal = InteractiveWriter.stdout
let toolchainSystem = ToolchainSystem(fileSystem: localFileSystem)
let toolchainSystem = try ToolchainSystem(fileSystem: localFileSystem)
if let version = version {
let versions = try toolchainSystem.fetchAllSwiftVersions()

View File

@ -25,7 +25,7 @@ struct Versions: ParsableCommand {
func run() throws {
let terminal = InteractiveWriter.stdout
let toolchainSystem = ToolchainSystem(fileSystem: localFileSystem)
let toolchainSystem = try ToolchainSystem(fileSystem: localFileSystem)
let versions = try toolchainSystem.fetchAllSwiftVersions()
let localVersion = try toolchainSystem.fetchLocalSwiftVersion()
if versions.count > 0 {

View File

@ -83,7 +83,8 @@ struct Test: AsyncParsableCommand {
func validate() throws {
if headless && environment != .defaultBrowser {
throw TestError(description: "The `--headless` flag can be applied only for browser environments")
throw TestError(
description: "The `--headless` flag can be applied only for browser environments")
}
}
@ -92,7 +93,8 @@ struct Test: AsyncParsableCommand {
let toolchain = try await Toolchain(localFileSystem, terminal)
let bundlePath: AbsolutePath
if let preBundlePath = self.prebuiltTestBundlePath {
bundlePath = AbsolutePath(preBundlePath, relativeTo: localFileSystem.currentWorkingDirectory!)
bundlePath = try AbsolutePath(
validating: preBundlePath, relativeTo: localFileSystem.currentWorkingDirectory!)
guard localFileSystem.exists(bundlePath) else {
terminal.write(
"No prebuilt binary found at \(bundlePath)\n",

View File

@ -72,7 +72,7 @@ struct BrowserTestRunner: TestRunner {
httpClient = HTTPClient(eventLoopGroupProvider: .shared(eventLoopGroup))
}
typealias Disposer = () -> ()
typealias Disposer = () -> Void
func findAvailablePort() async throws -> SocketAddress {
let bootstrap = ServerBootstrap(group: eventLoopGroup)
@ -118,8 +118,10 @@ struct BrowserTestRunner: TestRunner {
let driverCandidates = [
"chromedriver", "geckodriver", "safaridriver", "msedgedriver",
]
terminal.logLookup("- checking WebDriver executable in PATH: ", driverCandidates.joined(separator: ", "))
guard let found = driverCandidates.lazy.compactMap({ Process.findExecutable($0) }).first else {
terminal.logLookup(
"- checking WebDriver executable in PATH: ", driverCandidates.joined(separator: ", "))
guard let found = driverCandidates.lazy.compactMap({ Process.findExecutable($0) }).first
else {
return nil
}
return try await launchDriver(executablePath: found.pathString)
@ -153,11 +155,12 @@ struct BrowserTestRunner: TestRunner {
.shared(eventLoopGroup)
)
let localURL = try await server.start()
var disposer: () async throws -> () = {}
var disposer: () async throws -> Void = {}
do {
if headless {
let (endpoint, clientDisposer) = try await selectWebDriver()
let client = try await WebDriverClient.newSession(endpoint: endpoint, httpClient: httpClient)
let client = try await WebDriverClient.newSession(
endpoint: endpoint, httpClient: httpClient)
disposer = {
try await client.closeSession()
clientDisposer()

View File

@ -32,18 +32,20 @@ struct NodeTestRunner: TestRunner {
terminal.write("\nRunning the test bundle with Node.js:\n", inColor: .yellow)
try Constants.entrypoint.check(on: localFileSystem, terminal)
let (_, _, entrypointPath) = Constants.entrypoint.paths(on: localFileSystem)
let (_, _, entrypointPath) = try Constants.entrypoint.paths(on: localFileSystem)
// Allow Node.js to resolve modules from resource directories by making them relative to the entrypoint path.
let buildDirectory = testFilePath.parentDirectory
let staticDirectory = entrypointPath.parentDirectory
// Clean up existing symlinks before creating new ones.
for existingSymlink in try localFileSystem.resourcesDirectoryNames(relativeTo: staticDirectory) {
for existingSymlink in try localFileSystem.resourcesDirectoryNames(relativeTo: staticDirectory)
{
try localFileSystem.removeFileTree(staticDirectory.appending(component: existingSymlink))
}
let resourceDirectories = try localFileSystem.resourcesDirectoryNames(relativeTo: buildDirectory)
let resourceDirectories = try localFileSystem.resourcesDirectoryNames(
relativeTo: buildDirectory)
// Create new symlink for each resource directory.
for resourcesDirectoryName in resourceDirectories {

View File

@ -14,8 +14,8 @@
import ArgumentParser
public extension Sequence {
func asyncMap<T>(
extension Sequence {
public func asyncMap<T>(
_ transform: (Element) async throws -> T
) async rethrows -> [T] {
var values = [T]()
@ -33,8 +33,8 @@ public protocol AsyncParsableCommand: ParsableCommand {
mutating func run() async throws
}
public extension AsyncParsableCommand {
mutating func run() throws {
extension AsyncParsableCommand {
public mutating func run() throws {
throw CleanExit.helpRequest(self)
}
}
@ -43,8 +43,8 @@ public protocol AsyncMain {
associatedtype Command: ParsableCommand
}
public extension AsyncMain {
static func main() async {
extension AsyncMain {
public static func main() async {
do {
var command = try Command.parseAsRoot()
if var command = command as? AsyncParsableCommand {

View File

@ -28,7 +28,8 @@ public struct InvalidResponseCode: Error {
public final class AsyncFileDownload {
public let progressStream: AsyncThrowingStream<FileDownloadDelegate.Progress, Error>
public init(path: String, _ url: URL, _ client: HTTPClient, onTotalBytes: @escaping (Int) -> ()) {
public init(path: String, _ url: URL, _ client: HTTPClient, onTotalBytes: @escaping (Int) -> Void)
{
progressStream = .init { continuation in
do {
let request = try HTTPClient.Request.get(url: url)

View File

@ -15,12 +15,12 @@
import Foundation
import TSCBasic
public extension String {
var isAbsolutePath: Bool { first == "/" }
extension String {
public var isAbsolutePath: Bool { first == "/" }
}
public extension FileSystem {
func traverseRecursively(_ traversalRoot: AbsolutePath) throws -> [AbsolutePath] {
extension FileSystem {
public func traverseRecursively(_ traversalRoot: AbsolutePath) throws -> [AbsolutePath] {
guard exists(traversalRoot, followSymlink: true) else {
return []
}
@ -43,14 +43,14 @@ public extension FileSystem {
return result
}
func humanReadableFileSize(_ path: AbsolutePath) throws -> String {
public func humanReadableFileSize(_ path: AbsolutePath) throws -> String {
precondition(isFile(path))
// FIXME: should use `UnitInformationStorage`, but it's unavailable in open-source Foundation
return try String(format: "%.2f MB", Double(getFileInfo(path).size) / 1024 / 1024)
}
func resourcesDirectoryNames(relativeTo buildDirectory: AbsolutePath) throws -> [String] {
public func resourcesDirectoryNames(relativeTo buildDirectory: AbsolutePath) throws -> [String] {
try getDirectoryContents(buildDirectory).filter {
$0.hasSuffix(".resources")
}

View File

@ -15,16 +15,15 @@
import AsyncHTTPClient
import Foundation
public extension HTTPClient.Request {
static func get(url: URL) throws -> Self {
extension HTTPClient.Request {
public static func get(url: URL) throws -> Self {
try get(url: url.absoluteString)
}
static func get(url: String) throws -> Self {
public static func get(url: String) throws -> Self {
var request = try HTTPClient.Request(url: url)
request.headers.add(name: "User-Agent", value: "carton \(cartonVersion)")
if
url.starts(with: "https://api.github.com/"),
if url.starts(with: "https://api.github.com/"),
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"]
{
request.headers.add(name: "Authorization", value: "Bearer \(token)")

View File

@ -22,16 +22,15 @@ private let webpackRegex = try! RegEx(pattern: "at (.+) \\(webpack:///(.+?)\\)")
private let wasmRegex = try! RegEx(pattern: "at (.+) \\(<anonymous>:(.+?)\\)")
// swiftlint:enable force_try
public extension StringProtocol {
var chromeStackTrace: [StackTraceItem] {
extension StringProtocol {
public var chromeStackTrace: [StackTraceItem] {
split(separator: "\n").dropFirst().compactMap {
if let webpackMatch = webpackRegex.matchGroups(in: String($0)).first,
let symbol = webpackMatch.first,
let location = webpackMatch.last
{
return StackTraceItem(symbol: symbol, location: location, kind: .javaScript)
} else if
let wasmMatch = wasmRegex.matchGroups(in: String($0)).first,
} else if let wasmMatch = wasmRegex.matchGroups(in: String($0)).first,
let symbol = wasmMatch.first,
let location = wasmMatch.last
{

View File

@ -16,8 +16,8 @@ import Foundation
import Splash
import TSCBasic
private extension TokenType {
var color: String {
extension TokenType {
fileprivate var color: String {
// Reference on escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
switch self {
case .keyword: return "[35;1m" // magenta;bold
@ -120,15 +120,18 @@ public struct DiagnosticsParser: ProcessOutputParser {
if components.count > 3 {
lineIdx += 1
let file = line.replacingOccurrences(of: message, with: "")
guard file.split(separator: "/").last?
guard
file.split(separator: "/").last?
.replacingOccurrences(of: ":", with: "") == String(currFile)
else { continue }
fileMessages.append(
.init(
kind: CustomDiagnostic
.Kind(rawValue: String(components[2]
.trimmingCharacters(in: .whitespaces))) ??
.note,
kind:
CustomDiagnostic
.Kind(
rawValue: String(
components[2]
.trimmingCharacters(in: .whitespaces))) ?? .note,
file: file,
line: components[0],
char: components[1],

View File

@ -22,16 +22,15 @@ private let webpackRegex = try! RegEx(pattern: "(.+)@webpack:///(.+)")
private let wasmRegex = try! RegEx(pattern: "(.+)@http://127.0.0.1.+WebAssembly.instantiate:(.+)")
// swiftlint:enable force_try
public extension StringProtocol {
var firefoxStackTrace: [StackTraceItem] {
extension StringProtocol {
public var firefoxStackTrace: [StackTraceItem] {
split(separator: "\n").compactMap {
if let webpackMatch = webpackRegex.matchGroups(in: String($0)).first,
let symbol = webpackMatch.first,
let location = webpackMatch.last
{
return StackTraceItem(symbol: symbol, location: location, kind: .javaScript)
} else if
let wasmMatch = wasmRegex.matchGroups(in: String($0)).first,
} else if let wasmMatch = wasmRegex.matchGroups(in: String($0)).first,
let symbol = wasmMatch.first,
let location = wasmMatch.last
{

View File

@ -22,8 +22,8 @@ private let jsRegex = try! RegEx(pattern: "(.+?)(?:@(?:\\[(?:native|wasm) code\\
private let wasmRegex = try! RegEx(pattern: "<\\?>\\.wasm-function\\[(.+)\\]@\\[wasm code\\]")
// swiftlint:enable force_try
public extension StringProtocol {
var safariStackTrace: [StackTraceItem] {
extension StringProtocol {
public var safariStackTrace: [StackTraceItem] {
split(separator: "\n").compactMap {
if let wasmMatch = wasmRegex.matchGroups(in: String($0)).first,
let symbol = wasmMatch.first
@ -33,8 +33,7 @@ public extension StringProtocol {
location: nil,
kind: .webAssembly
)
} else if
let jsMatch = jsRegex.matchGroups(in: String($0)).first,
} else if let jsMatch = jsRegex.matchGroups(in: String($0)).first,
let symbol = jsMatch.first
{
let loc: String?

View File

@ -16,26 +16,28 @@ import Foundation
import Splash
import TSCBasic
private extension String.StringInterpolation {
mutating func appendInterpolation(_ regexLabel: TestsParser.Regex.Label) {
extension String.StringInterpolation {
fileprivate mutating func appendInterpolation(_ regexLabel: TestsParser.Regex.Label) {
appendInterpolation("<\(regexLabel.rawValue)>")
}
}
private extension StringProtocol {
func range(of regex: NSRegularExpression,
labelled label: TestsParser.Regex.Label) -> Range<String.Index>?
{
extension StringProtocol {
fileprivate func range(
of regex: NSRegularExpression,
labelled label: TestsParser.Regex.Label
) -> Range<String.Index>? {
range(of: regex, named: label.rawValue)
}
func match(of regex: NSRegularExpression, labelled label: TestsParser.Regex.Label) -> String
fileprivate func match(of regex: NSRegularExpression, labelled label: TestsParser.Regex.Label)
-> String
.SubSequence?
{
match(of: regex, named: label.rawValue)
}
func match(
fileprivate func match(
of regex: NSRegularExpression,
labelled labelA: TestsParser.Regex.Label,
_ labelB: TestsParser.Regex.Label
@ -76,19 +78,24 @@ public struct TestsParser: ProcessOutputParser {
}
static let suiteStarted = try! NSRegularExpression(
pattern: #"Test Suite '(?\#(.suite)[^']*)' started at (?\#(.timestamp)\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})"#
pattern:
#"Test Suite '(?\#(.suite)[^']*)' started at (?\#(.timestamp)\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})"#
)
static let suiteFinished = try! NSRegularExpression(
pattern: #"Test Suite '(?\#(.suite)[^']*)' (?\#(.status)(failed|passed)) at (?\#(.timestamp)\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})"#
pattern:
#"Test Suite '(?\#(.suite)[^']*)' (?\#(.status)(failed|passed)) at (?\#(.timestamp)\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})"#
)
static let suiteSummary = try! NSRegularExpression(
pattern: #"Executed (?\#(.testCount)\d+) (test|tests), with (?\#(.failCount)\d+) (failure|failures) \((?\#(.unexpectedCount)\d+) unexpected\) in (?\#(.duration)\d+\.\d+) \(\d+\.\d+\) seconds"#
pattern:
#"Executed (?\#(.testCount)\d+) (test|tests), with (?\#(.failCount)\d+) (failure|failures) \((?\#(.unexpectedCount)\d+) unexpected\) in (?\#(.duration)\d+\.\d+) \(\d+\.\d+\) seconds"#
)
static let caseFinished = try! NSRegularExpression(
pattern: #"Test Case '(?\#(.suite)[^']+)\.(?\#(.testCase)[^']+)' (?\#(.status)(failed|passed)) \((?\#(.duration)(\d+)\.(\d+)) seconds\)"#
pattern:
#"Test Case '(?\#(.suite)[^']+)\.(?\#(.testCase)[^']+)' (?\#(.status)(failed|passed)) \((?\#(.duration)(\d+)\.(\d+)) seconds\)"#
)
static let problem = try! NSRegularExpression(
pattern: #"(?\#(.path)(.+)(\/|)([^/]+)):(?\#(.line)\d+): (?\#(.status)\w+): (?\#(.suite)\w+)\.(?\#(.testCase)\w+) : "#
pattern:
#"(?\#(.path)(.+)(\/|)([^/]+)):(?\#(.line)\d+): (?\#(.status)\w+): (?\#(.suite)\w+)\.(?\#(.testCase)\w+) : "#
)
enum Assertion: String, CaseIterable {
@ -127,15 +134,18 @@ public struct TestsParser: ProcessOutputParser {
pattern: #"XCTAssertEqual failed: (?\#(.received).*) is not equal to (?\#(.expected).*) - "#
)
static let xctAssertGreaterThan = try! NSRegularExpression(
pattern: #"XCTAssertGreaterThan failed: (?\#(.received).*) is not greater than (?\#(.expected).*) - "#
pattern:
#"XCTAssertGreaterThan failed: (?\#(.received).*) is not greater than (?\#(.expected).*) - "#
)
static let xctAssertLessThan = try! NSRegularExpression(
pattern: #"XCTAssertLessThan failed: (?\#(.received).*) is not less than (?\#(.expected).*) - "#
pattern:
#"XCTAssertLessThan failed: (?\#(.received).*) is not less than (?\#(.expected).*) - "#
)
static func xctAssert(_ assertion: Assertion) -> NSRegularExpression {
try! NSRegularExpression(
pattern: #"\#(assertion.funcName) failed: \("(?\#(.received).*)"\) \#(assertion.innerMessage) \("(?\#(.expected).*)"\) - "#
pattern:
#"\#(assertion.funcName) failed: \("(?\#(.received).*)"\) \#(assertion.innerMessage) \("(?\#(.expected).*)"\) - "#
)
}
}
@ -168,11 +178,13 @@ public struct TestsParser: ProcessOutputParser {
let lines = output.split(separator: "\n")
var suites = [Suite]()
var unmappedProblems = [(
var unmappedProblems = [
(
suite: String.SubSequence,
testCase: String.SubSequence,
problem: DiagnosticsParser.CustomDiagnostic
)]()
)
]()
for line in lines {
if let suite = line.match(of: Regex.suiteStarted, labelled: .suite) {

View File

@ -61,9 +61,9 @@ extension ProcessError: CustomStringConvertible {
}
}
public extension TSCBasic.Process {
extension TSCBasic.Process {
// swiftlint:disable:next function_body_length
static func run(
public static func run(
_ arguments: [String],
environment: [String: String] = [:],
loadingMessage: String = "Running...",
@ -77,11 +77,12 @@ public extension TSCBasic.Process {
terminal.write(environment.map { "\($0)=\($1)" }.joined(separator: " ") + " ")
}
let processName = arguments[0].first == "/" ?
AbsolutePath(arguments[0]).basename : arguments[0]
let processName =
arguments[0].first == "/" ? try AbsolutePath(validating: arguments[0]).basename : arguments[0]
do {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<(), Swift.Error>) in
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<(), Swift.Error>) in
DispatchQueue.global().async {
var stdoutBuffer = ""
@ -105,8 +106,10 @@ public extension TSCBasic.Process {
arguments: arguments,
environment: ProcessEnv.vars.merging(environment) { _, new in new },
outputRedirection: .stream(stdout: stdout, stderr: stderr),
verbose: true,
startNewProcessGroup: true
startNewProcessGroup: true,
loggingHandler: {
terminal.write($0)
}
)
let result = Result<ProcessResult, Swift.Error> {

View File

@ -40,7 +40,8 @@ func demangle(_ mangledName: String) -> String {
if let demangledNamePtr = demangledNamePtr {
let demangledName = String(cString: demangledNamePtr)
free(demangledNamePtr)
return demangledName
return
demangledName
.replacingOccurrences(of: " Swift.", with: " ")
.replacingOccurrences(of: "(Swift.", with: "(")
.replacingOccurrences(of: "<Swift.", with: "<")

View File

@ -14,16 +14,15 @@
import TSCBasic
private extension String {
static var home = "\u{001B}[H"
static var clearScreen = "\u{001B}[2J\u{001B}[H\u{001B}[3J"
static var clear = "\u{001B}[J"
extension String {
fileprivate static var home = "\u{001B}[H"
fileprivate static var clearScreen = "\u{001B}[2J\u{001B}[H\u{001B}[3J"
fileprivate static var clear = "\u{001B}[J"
}
public extension InteractiveWriter {
func logLookup<T>(_ description: String, _ target: T, newline: Bool = false)
where T: CustomStringConvertible
{
extension InteractiveWriter {
public func logLookup<T>(_ description: String, _ target: T, newline: Bool = false)
where T: CustomStringConvertible {
write(description)
write("\(target)\n", inColor: .cyan, bold: true)
if newline {
@ -31,11 +30,11 @@ public extension InteractiveWriter {
}
}
func clearWindow() {
public func clearWindow() {
write(.clearScreen)
}
func homeAndClear() {
public func homeAndClear() {
write(.home)
write(.clear)
}

View File

@ -15,8 +15,8 @@
import Crypto
import TSCBasic
public extension ByteString {
var hexSHA256: String {
extension ByteString {
public var hexSHA256: String {
ByteString(SHA256.hash(data: contents)).hexadecimalRepresentation
}
}

View File

@ -18,9 +18,8 @@ public struct ExpectationError: Error, CustomStringConvertible {
public let description: String
}
/** Implements throwing equality assertions, as compared to standard assertions that trap
in debug mode.
*/
/// Implements throwing equality assertions, as compared to standard assertions that trap
/// in debug mode.
struct Equality<T: Equatable, C> {
let description: (_ x: T, _ y: T, _ context: C) -> String

View File

@ -13,10 +13,10 @@
// limitations under the License.
import AsyncHTTPClient
import Basics
import CartonHelpers
import Foundation
import TSCBasic
import TSCUtility
public enum EntrypointError: Error {
}
@ -33,19 +33,21 @@ public struct Entrypoint {
public func paths(
on fileSystem: FileSystem
// swiftlint:disable:next large_tuple
) -> (cartonDir: AbsolutePath, staticDir: AbsolutePath, filePath: AbsolutePath) {
let cartonDir = fileSystem.homeDirectory.appending(component: ".carton")
) throws -> (cartonDir: AbsolutePath, staticDir: AbsolutePath, filePath: AbsolutePath) {
let cartonDir = try fileSystem.homeDirectory.appending(component: ".carton")
let staticDir = cartonDir.appending(component: "static")
return (cartonDir, staticDir, staticDir.appending(component: fileName))
}
public func check(on fileSystem: FileSystem, _ terminal: InteractiveWriter) throws {
let (cartonDir, staticDir, filePath) = paths(on: fileSystem)
let (cartonDir, staticDir, filePath) = try paths(on: fileSystem)
// If hash check fails, download the `static.zip` archive and unpack it
if try !fileSystem.exists(filePath) || SHA256().hash(
if try !fileSystem.exists(filePath)
|| SHA256().hash(
fileSystem.readFileContents(filePath)
) != sha256 {
) != sha256
{
terminal.logLookup("Directory doesn't exist or contains outdated polyfills: ", staticDir)
let archiveFile = cartonDir.appending(component: "static.zip")
try fileSystem.removeFileTree(staticDir)
@ -58,7 +60,8 @@ public struct Entrypoint {
try fileSystem.createDirectory(staticDir)
try tsc_await {
ZipArchiver().extract(from: archiveFile, to: staticDir, completion: $0)
ZipArchiver(fileSystem: fileSystem).extract(
from: archiveFile, to: staticDir, completion: $0)
}
}
}

View File

@ -144,10 +144,10 @@ extension Templates {
.init(
url: "https://github.com/swiftwasm/JavaScriptKit",
version: .from(compatibleJSKitVersion.description)
),
)
],
targetDepencencies: [
.init(name: "JavaScriptKit", package: "JavaScriptKit"),
.init(name: "JavaScriptKit", package: "JavaScriptKit")
],
terminal
)
@ -165,7 +165,8 @@ extension Templates {
_ terminal: InteractiveWriter
) async throws {
try fileSystem.changeCurrentWorkingDirectory(to: project.path)
try await createPackage(type: .executable,
try await createPackage(
type: .executable,
fileSystem: fileSystem,
project: project,
terminal)
@ -177,10 +178,10 @@ extension Templates {
.init(
url: "https://github.com/TokamakUI/Tokamak",
version: .from("0.11.0")
),
)
],
targetDepencencies: [
.init(name: "TokamakShim", package: "Tokamak"),
.init(name: "TokamakShim", package: "Tokamak")
],
terminal
)

View File

@ -28,8 +28,8 @@ extension Application {
let manifest: Manifest
let product: ProductDescription?
let entrypoint: Entrypoint
let onWebSocketOpen: (WebSocket, DestinationEnvironment) async -> ()
let onWebSocketClose: (WebSocket) async -> ()
let onWebSocketOpen: (WebSocket, DestinationEnvironment) async -> Void
let onWebSocketClose: (WebSocket) async -> Void
}
func configure(_ configuration: Configuration) throws {
@ -52,7 +52,8 @@ extension Application {
}
return customIndexContent.map {
HTML(value: HTML.indexPage(
HTML(
value: HTML.indexPage(
customContent: $0,
entrypointName: configuration.entrypoint.fileName
))
@ -61,7 +62,8 @@ extension Application {
// Don't limit the size of frame to accept large test outputs
webSocket("watcher", maxFrameSize: .init(integerLiteral: Int(UInt32.max))) { request, ws in
let environment = request.headers["User-Agent"].compactMap(DestinationEnvironment.init).first
let environment =
request.headers["User-Agent"].compactMap(DestinationEnvironment.init).first
?? .other
Task { await configuration.onWebSocketOpen(ws, environment) }

View File

@ -29,16 +29,21 @@ extension HTML: ResponseEncodable {
public func encodeResponse(for request: Request) -> EventLoopFuture<Response> {
var headers = HTTPHeaders()
headers.add(name: .contentType, value: "text/html")
return request.eventLoop.makeSucceededFuture(.init(
return request.eventLoop.makeSucceededFuture(
.init(
status: .ok, headers: headers, body: .init(string: value)
))
}
public static func readCustomIndexPage(at path: String?, on fileSystem: FileSystem) throws -> String? {
public static func readCustomIndexPage(at path: String?, on fileSystem: FileSystem) throws
-> String?
{
if let customIndexPage = path {
let content = try localFileSystem.readFileContents(customIndexPage.isAbsolutePath ?
AbsolutePath(customIndexPage) :
AbsolutePath(localFileSystem.currentWorkingDirectory!, customIndexPage)).description
let content = try localFileSystem.readFileContents(
customIndexPage.isAbsolutePath
? AbsolutePath(validating: customIndexPage)
: AbsolutePath(localFileSystem.currentWorkingDirectory!, customIndexPage)
).description
guard content.contains("</head>") else {
throw HTMLError.customIndexPageWithoutHead

View File

@ -284,7 +284,7 @@ extension Server {
_ configuration: Configuration,
in environment: DestinationEnvironment,
terminal: InteractiveWriter
) -> (WebSocket, String) -> () {
) -> (WebSocket, String) -> Void {
{ [weak self] _, text in
guard let self = self else { return }
guard
@ -304,9 +304,11 @@ extension Server {
}
} else {
terminal.write("\nAn error occurred, here's the raw stack trace for it:\n", inColor: .red)
terminal.write(" Please create an issue or PR to the Carton repository\n" +
" with your browser name and this raw stack trace so\n" +
" we can add support for it: https://github.com/swiftwasm/carton\n", inColor: .gray)
terminal.write(
" Please create an issue or PR to the Carton repository\n"
+ " with your browser name and this raw stack trace so\n"
+ " we can add support for it: https://github.com/swiftwasm/carton\n", inColor: .gray
)
terminal.write(rawStackTrace + "\n")
}
@ -340,7 +342,6 @@ public func openInSystemBrowser(url: String) -> Bool {
let process = Process(
arguments: [openCommand, url],
outputRedirection: .none,
verbose: false,
startNewProcessGroup: true
)
do {

File diff suppressed because one or more lines are too long

View File

@ -55,7 +55,7 @@ public final class Builder {
String(format: "%.2f seconds", abs(buildStarted.timeIntervalSinceNow))
)
var transformers: [(inout InputByteStream, inout InMemoryOutputWriter) throws -> ()] = []
var transformers: [(inout InputByteStream, inout InMemoryOutputWriter) throws -> Void] = []
if flavor.environment == .node || flavor.environment == .defaultBrowser {
// If building for JS-host environments,
// - i64 params in imports are not supported without bigint-i64 feature
@ -71,7 +71,8 @@ public final class Builder {
transformers.append(transformer.transform)
}
// Strip unnecessary autolink sections, which is only used at link-time
transformers.append(CustomSectionStripper(stripIf: {
transformers.append(
CustomSectionStripper(stripIf: {
$0 == ".swift1_autolink_entries"
}).transform)
@ -109,7 +110,7 @@ public final class Builder {
return try await buildWithoutSanitizing(builderArguments: arguments)
case .stackOverflow:
let sanitizerFile =
fileSystem.homeDirectory.appending(components: ".carton", "static", "so_sanitizer.wasm")
try fileSystem.homeDirectory.appending(components: ".carton", "static", "so_sanitizer.wasm")
var modifiedArguments = arguments
modifiedArguments.append(contentsOf: [

View File

@ -22,8 +22,8 @@ public enum DestinationEnvironment {
case edge
}
public extension String {
func parsedStackTrace(in environment: DestinationEnvironment) -> [StackTraceItem]? {
extension String {
public func parsedStackTrace(in environment: DestinationEnvironment) -> [StackTraceItem]? {
switch environment {
case .safari: return safariStackTrace
case .firefox: return firefoxStackTrace

View File

@ -14,13 +14,15 @@
import Basics
import CartonHelpers
import PackageModel
import PackageLoading
import PackageModel
import TSCBasic
import Workspace
extension Manifest {
static func from(path: AbsolutePath, swiftc: AbsolutePath, fileSystem: FileSystem, terminal: InteractiveWriter) async throws -> Manifest {
static func from(
path: AbsolutePath, swiftc: AbsolutePath, fileSystem: FileSystem, terminal: InteractiveWriter
) async throws -> Manifest {
terminal.write("\nParsing package manifest: ", inColor: .yellow)
let destination = try Destination.hostDestination(swiftc.parentDirectory)
let toolchain = try UserToolchain(destination: destination)
@ -28,7 +30,8 @@ extension Manifest {
let observability = ObservabilitySystem { _, diagnostic in
terminal.write("\n\(diagnostic)")
}
let workspace = try Workspace(fileSystem: fileSystem, forRootPackage: path, customManifestLoader: loader)
let workspace = try Workspace(
fileSystem: fileSystem, forRootPackage: path, customManifestLoader: loader)
let manifest = try await workspace.loadRootManifest(
at: path,
observabilityScope: observability.topScope

View File

@ -119,7 +119,7 @@ public final class Toolchain {
_ fileSystem: FileSystem,
_ terminal: InteractiveWriter
) async throws {
let toolchainSystem = ToolchainSystem(fileSystem: fileSystem)
let toolchainSystem = try ToolchainSystem(fileSystem: fileSystem)
let (swiftPath, version) = try await toolchainSystem.inferSwiftPath(from: versionSpec, terminal)
self.swiftPath = swiftPath
self.version = version
@ -128,7 +128,8 @@ public final class Toolchain {
if let workingDirectory = fileSystem.currentWorkingDirectory {
let swiftc = swiftPath.parentDirectory.appending(component: "swiftc")
manifest = await Result {
try await Manifest.from(path: workingDirectory, swiftc: swiftc, fileSystem: fileSystem, terminal: terminal)
try await Manifest.from(
path: workingDirectory, swiftc: swiftc, fileSystem: fileSystem, terminal: terminal)
}
} else {
manifest = .failure(ToolchainError.noWorkingDirectory)
@ -144,7 +145,7 @@ public final class Toolchain {
let binPath = output.first
else { fatalError("failed to decode UTF8 output of the `swift build` invocation") }
return AbsolutePath(binPath)
return try AbsolutePath(validating: binPath)
}
private func inferDevProduct(hint: String?) throws -> ProductDescription? {
@ -157,7 +158,8 @@ public final class Toolchain {
candidateProducts = candidateProducts.filter { $0.name == productName }
guard candidateProducts.count == 1 else {
terminal.write("""
terminal.write(
"""
Failed to disambiguate the executable product, \
make sure `\(productName)` product is present in Package.swift
""", inColor: .red)
@ -226,9 +228,11 @@ public final class Toolchain {
private func emitJSKitWarningIfNeeded() throws {
let manifest = try manifest.get()
guard let jsKit = manifest.dependencies.first(where: {
guard
let jsKit = manifest.dependencies.first(where: {
$0.nameForTargetDependencyResolutionOnly == "JavaScriptKit"
}) else {
})
else {
return
}
@ -302,7 +306,9 @@ public final class Toolchain {
return .init(arguments: builderArguments, mainWasmPath: mainWasmPath, product: product)
}
public func getTestProduct(flavor: BuildFlavor) throws -> (name: String, artifactPath: AbsolutePath) {
public func getTestProduct(flavor: BuildFlavor) throws -> (
name: String, artifactPath: AbsolutePath
) {
let manifest = try manifest.get()
let binPath = try inferBinPath(isRelease: flavor.isRelease)
let testProductName = "\(manifest.displayName)PackageTests"
@ -375,7 +381,8 @@ public final class Toolchain {
}
}
builderArguments.append(contentsOf: flavor.swiftCompilerFlags.flatMap {
builderArguments.append(
contentsOf: flavor.swiftCompilerFlags.flatMap {
["-Xswiftc", $0]
})

View File

@ -20,8 +20,8 @@ import TSCUtility
private let expectedArchiveSize = 891_856_371
private extension FileDownloadDelegate.Progress {
var totalOrEstimatedBytes: Int {
extension FileDownloadDelegate.Progress {
fileprivate var totalOrEstimatedBytes: Int {
totalBytes ?? expectedArchiveSize
}
}

View File

@ -46,7 +46,7 @@ public class ToolchainSystem {
let cartonToolchainResolver: CartonToolchainResolver
let resolvers: [ToolchainResolver]
public init(fileSystem: FileSystem) {
public init(fileSystem: FileSystem) throws {
self.fileSystem = fileSystem
let userLibraryPath = NSSearchPathForDirectoriesInDomains(
@ -59,27 +59,30 @@ public class ToolchainSystem {
.localDomainMask,
true
).first
userXCToolchainResolver = userLibraryPath.flatMap {
XCToolchainResolver(libraryPath: AbsolutePath($0), fileSystem: fileSystem)
userXCToolchainResolver = try userLibraryPath.flatMap {
XCToolchainResolver(libraryPath: try AbsolutePath(validating: $0), fileSystem: fileSystem)
}
let rootXCToolchainResolver = rootLibraryPath.flatMap {
XCToolchainResolver(libraryPath: AbsolutePath($0), fileSystem: fileSystem)
let rootXCToolchainResolver = try rootLibraryPath.flatMap {
XCToolchainResolver(libraryPath: try AbsolutePath(validating: $0), fileSystem: fileSystem)
}
let xctoolchainResolvers: [ToolchainResolver] = [
userXCToolchainResolver, rootXCToolchainResolver,
].compactMap { $0 }
cartonToolchainResolver = CartonToolchainResolver(fileSystem: fileSystem)
resolvers = [
cartonToolchainResolver = try CartonToolchainResolver(fileSystem: fileSystem)
resolvers =
try [
cartonToolchainResolver,
SwiftEnvToolchainResolver(fileSystem: fileSystem),
] + xctoolchainResolvers
}
private var libraryPaths: [AbsolutePath] {
NSSearchPathForDirectoriesInDomains(
get throws {
try NSSearchPathForDirectoriesInDomains(
.libraryDirectory, [.localDomainMask], true
).map { AbsolutePath($0) }
).map { try AbsolutePath(validating: $0) }
}
}
public var swiftVersionPath: AbsolutePath {
@ -156,7 +159,8 @@ public class ToolchainSystem {
let release = try tsc_await {
client.execute(request: request).flatMapResult { response -> Result<Release, Error> in
guard (200..<300).contains(response.status.code), let body = response.body else {
return .failure(ToolchainError.invalidResponse(
return .failure(
ToolchainError.invalidResponse(
url: releaseURL,
status: response.status.code
))

View File

@ -47,8 +47,8 @@ final class SwiftEnvToolchainResolver: ToolchainResolver {
let versionsPath: AbsolutePath
let fileSystem: FileSystem
init(fileSystem: FileSystem) {
versionsPath = fileSystem.homeDirectory.appending(components: ".swiftenv", "versions")
init(fileSystem: FileSystem) throws {
versionsPath = try fileSystem.homeDirectory.appending(components: ".swiftenv", "versions")
self.fileSystem = fileSystem
}
@ -68,8 +68,8 @@ final class CartonToolchainResolver: ToolchainResolver {
let cartonSDKPath: AbsolutePath
let fileSystem: FileSystem
init(fileSystem: FileSystem) {
cartonSDKPath = fileSystem.homeDirectory.appending(components: ".carton", "sdk")
init(fileSystem: FileSystem) throws {
cartonSDKPath = try fileSystem.homeDirectory.appending(components: ".carton", "sdk")
self.fileSystem = fileSystem
}

View File

@ -52,9 +52,10 @@ public struct WebDriverClient {
}
"""#
public static func newSession(endpoint: URL, body: String = defaultSessionRequestBody,
httpClient: HTTPClient) async throws -> WebDriverClient
{
public static func newSession(
endpoint: URL, body: String = defaultSessionRequestBody,
httpClient: HTTPClient
) async throws -> WebDriverClient {
struct Response: Decodable {
let sessionId: String
}
@ -71,13 +72,15 @@ public struct WebDriverClient {
}
let decoder = JSONDecoder()
let response = try decoder.decode(ValueResponse<Response>.self, from: responseBody)
return WebDriverClient(client: httpClient,
return WebDriverClient(
client: httpClient,
driverEndpoint: endpoint,
sessionId: response.sessionId)
}
private func makeSessionURL(_ components: String...) -> String {
var url = driverEndpoint
var url =
driverEndpoint
.appendingPathComponent("session")
.appendingPathComponent(sessionId)
for component in components {

View File

@ -39,7 +39,7 @@ struct HashArchive: AsyncParsableCommand {
let terminal = InteractiveWriter.stdout
let cwd = localFileSystem.currentWorkingDirectory!
let staticPath = AbsolutePath(cwd, "static")
let dotFilesStaticPath = localFileSystem.homeDirectory.appending(
let dotFilesStaticPath = try localFileSystem.homeDirectory.appending(
components: ".carton",
"static"
)
@ -70,8 +70,11 @@ struct HashArchive: AsyncParsableCommand {
try localFileSystem.removeFileTree(dotFilesEntrypointPath)
try localFileSystem.copy(from: entrypointPath, to: dotFilesEntrypointPath)
return (entrypoint, try SHA256().hash(localFileSystem.readFileContents(entrypointPath))
.hexadecimalRepresentation.uppercased())
return (
entrypoint,
try SHA256().hash(localFileSystem.readFileContents(entrypointPath))
.hexadecimalRepresentation.uppercased()
)
}
try localFileSystem.writeFileContents(
@ -87,7 +90,8 @@ struct HashArchive: AsyncParsableCommand {
try await Process.run(["zip", "-j", "static.zip"] + archiveSources, terminal)
let staticArchiveContents = try localFileSystem.readFileContents(AbsolutePath(
let staticArchiveContents = try localFileSystem.readFileContents(
AbsolutePath(
localFileSystem.currentWorkingDirectory!,
RelativePath("static.zip")
))

View File

@ -15,10 +15,11 @@
// Created by Cavelle Benjamin on Dec/25/20.
//
@testable import CartonCLI
import TSCBasic
import XCTest
@testable import CartonCLI
final class BundleCommandTests: XCTestCase {
func testWithNoArguments() throws {
try withFixture("EchoExecutable") { packageDirectory in
@ -63,7 +64,7 @@ final class BundleCommandTests: XCTestCase {
return
}
let headers = try Process.checkNonZeroExit(arguments: [
"wasm-objdump", "--headers", bundleDirectory.appending(component: wasmBinary).pathString
"wasm-objdump", "--headers", bundleDirectory.appending(component: wasmBinary).pathString,
])
XCTAssert(headers.contains("\"name\""), "name section not found: \(headers)")
}
@ -77,7 +78,9 @@ final class BundleCommandTests: XCTestCase {
func getFileSizeOfWasmBinary(wasmOptimizations: WasmOptimizations) throws -> UInt64 {
let bundleDirectory = tmpDirPath.appending(component: "Bundle")
try Process.checkNonZeroExit(arguments: [cartonPath, "bundle", "--wasm-optimizations", wasmOptimizations.rawValue])
try Process.checkNonZeroExit(arguments: [
cartonPath, "bundle", "--wasm-optimizations", wasmOptimizations.rawValue,
])
guard let wasmFile = (bundleDirectory.ls().filter { $0.contains("wasm") }).first else {
XCTFail("No wasm binary found")

View File

@ -12,8 +12,8 @@
import ArgumentParser
import XCTest
public extension ExitCode {
static var quit = ExitCode(SIGQUIT)
extension ExitCode {
public static var quit = ExitCode(SIGQUIT)
}
public func stop(process id: Int32, exitCode: ExitCode = .success) {
@ -26,8 +26,8 @@ public protocol TestableParsableArguments: ParsableArguments {
var didValidateExpectation: XCTestExpectation { get }
}
public extension TestableParsableArguments {
mutating func validate() throws {
extension TestableParsableArguments {
public mutating func validate() throws {
didValidateExpectation.fulfill()
}
}
@ -37,14 +37,14 @@ public protocol TestableParsableCommand: ParsableCommand, TestableParsableArgume
var didRunExpectation: XCTestExpectation { get }
}
public extension TestableParsableCommand {
mutating func run() throws {
extension TestableParsableCommand {
public mutating func run() throws {
didRunExpectation.fulfill()
}
}
public extension XCTestExpectation {
convenience init(singleExpectation description: String) {
extension XCTestExpectation {
public convenience init(singleExpectation description: String) {
self.init(description: description)
expectedFulfillmentCount = 1
assertForOverFulfill = true
@ -103,7 +103,7 @@ public func AssertParse<A>(
_ arguments: [String],
file: StaticString = #file,
line: UInt = #line,
closure: (A) throws -> ()
closure: (A) throws -> Void
) where A: ParsableArguments {
do {
let parsed = try type.parse(arguments)
@ -120,7 +120,7 @@ public func AssertParseCommand<A: ParsableCommand>(
_ arguments: [String],
file: StaticString = #file,
line: UInt = #line,
closure: (A) throws -> ()
closure: (A) throws -> Void
) {
do {
let command = try rootCommand.parseAsRoot(arguments)
@ -186,15 +186,15 @@ public func AssertHelp<T: ParsableCommand, U: ParsableCommand>(
)
}
public extension XCTest {
var debugURL: URL {
extension XCTest {
public var debugURL: URL {
let bundleURL = Bundle(for: type(of: self)).bundleURL
return bundleURL.lastPathComponent.hasSuffix("xctest")
? bundleURL.deletingLastPathComponent()
: bundleURL
}
var cartonPath: String {
public var cartonPath: String {
debugURL.appendingPathComponent("carton").path
}
@ -205,7 +205,7 @@ public extension XCTest {
/// - parameter cwd: The current working directory for executing the command.
/// - parameter file: The file the assertion is coming from.
/// - parameter line: The line the assertion is coming from.
func executeCommand(
public func executeCommand(
command: String,
shouldPrintOutput: Bool = false,
cwd: URL? = nil, // To allow for testing of file-based output
@ -217,7 +217,8 @@ public extension XCTest {
let commandName = String(splitCommand.first!)
let commandURL = debugURL.appendingPathComponent(commandName)
guard (try? commandURL.checkResourceIsReachable()) ?? false else {
XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.",
XCTFail(
"No executable at '\(commandURL.standardizedFileURL.path)'.",
file: file, line: line)
return nil
}
@ -261,7 +262,7 @@ public extension XCTest {
/// - parameter debug: Debug the assertion by printing out the command string.
/// - parameter file: The file the assertion is coming from.
/// - parameter line: The line the assertion is coming from.
func AssertExecuteCommand(
public func AssertExecuteCommand(
command: String,
cwd: URL? = nil, // To allow for testing of file based output
expected: String? = nil,
@ -276,7 +277,8 @@ public extension XCTest {
let commandName = String(splitCommand.first!)
let commandURL = debugURL.appendingPathComponent(commandName)
guard (try? commandURL.checkResourceIsReachable()) ?? false else {
XCTFail("No executable at '\(commandURL.standardizedFileURL.path)'.",
XCTFail(
"No executable at '\(commandURL.standardizedFileURL.path)'.",
file: file, line: line)
return
}

View File

@ -16,9 +16,10 @@
//
import AsyncHTTPClient
@testable import CartonCLI
import XCTest
@testable import CartonCLI
final class DevCommandTests: XCTestCase {
private var client: HTTPClient?
@ -31,11 +32,13 @@ final class DevCommandTests: XCTestCase {
func testWithNoArguments() throws {
// FIXME: Don't assume a specific port is available since it can be used by others or tests
try withFixture("EchoExecutable") { packageDirectory in
guard let process = executeCommand(
guard
let process = executeCommand(
command: "carton dev --verbose",
shouldPrintOutput: true,
cwd: packageDirectory.url
) else {
)
else {
XCTFail("Could not create process")
return
}
@ -47,11 +50,13 @@ final class DevCommandTests: XCTestCase {
func testWithArguments() throws {
// FIXME: Don't assume a specific port is available since it can be used by others or tests
try withFixture("EchoExecutable") { packageDirectory in
guard let process = executeCommand(
guard
let process = executeCommand(
command: "carton dev --verbose --port 8081",
shouldPrintOutput: true,
cwd: packageDirectory.url
) else {
)
else {
XCTFail("Could not create process")
return
}
@ -90,7 +95,8 @@ final class DevCommandTests: XCTestCase {
read: .seconds(timeOut)
)
client = HTTPClient(eventLoopGroupProvider: .createNew,
client = HTTPClient(
eventLoopGroupProvider: .createNew,
configuration: HTTPClient.Configuration(timeout: timeout))
var response: HTTPClient.Response?

View File

@ -15,10 +15,11 @@
// Created by Cavelle Benjamin on Dec/20/20.
//
@testable import CartonCLI
import TSCBasic
import XCTest
@testable import CartonCLI
final class InitCommandTests: XCTestCase {
func testWithNoArguments() throws {
try withTemporaryDirectory { tmpDirPath in
@ -87,7 +88,9 @@ final class InitCommandTests: XCTestCase {
"Tests/\(package)Tests/\(package)Tests.swift does not exist"
)
let actualTemplateSource = try String(contentsOfFile: packageDirectory
let actualTemplateSource = try String(
contentsOfFile:
packageDirectory
.appending(components: "Sources", package, "App.swift").pathString)
XCTAssertEqual(expectedTemplateSource, actualTemplateSource, "Template Sources do not match")

View File

@ -12,10 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
@testable import CartonCLI
import TSCBasic
import XCTest
@testable import CartonCLI
final class IntegrationTests: XCTestCase {
func testTokamakBundle() throws {
try withTemporaryDirectory { tmpDirPath in

View File

@ -15,13 +15,14 @@
// Created by Cavelle Benjamin on Dec/25/20.
//
@testable import CartonCLI
import TSCBasic
import XCTest
@testable import CartonCLI
final class SDKCommandTests: XCTestCase {
func testInstall() throws {
AssertExecuteCommand(
try AssertExecuteCommand(
command: "carton sdk install",
cwd: packageDirectory.url,
expected: "SDK successfully installed!",
@ -30,7 +31,7 @@ final class SDKCommandTests: XCTestCase {
}
func testVersions() throws {
AssertExecuteCommand(
try AssertExecuteCommand(
command: "carton sdk versions",
cwd: packageDirectory.url,
expected: "wasm-",

View File

@ -18,8 +18,8 @@ extension Substring {
}
}
public extension String {
func trimmingLines() -> String {
extension String {
public func trimmingLines() -> String {
split(separator: "\n", omittingEmptySubsequences: false)
.map { $0.trimmed() }
.joined(separator: "\n")

View File

@ -66,7 +66,8 @@ final class TestCommandTests: XCTestCase {
cwd: packageDirectory.url
)
AssertExecuteCommand(
command: "carton test --environment node --prebuilt-test-bundle-path ./.build/wasm32-unknown-wasi/debug/NodeJSKitTestPackageTests.wasm",
command:
"carton test --environment node --prebuilt-test-bundle-path ./.build/wasm32-unknown-wasi/debug/NodeJSKitTestPackageTests.wasm",
cwd: packageDirectory.url
)
}
@ -98,7 +99,9 @@ final class TestCommandTests: XCTestCase {
}
try withFixture(fixture) { packageDirectory in
try ProcessEnv.chdir(packageDirectory)
let process = Process(arguments: [cartonPath, "test", "--environment", "defaultBrowser", "--headless"])
let process = Process(arguments: [
cartonPath, "test", "--environment", "defaultBrowser", "--headless",
])
try process.launch()
let result = try process.waitUntilExit()
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0))

View File

@ -21,29 +21,35 @@ import TSCTestSupport
/// Returns path to the built products directory.
public var productsDirectory: AbsolutePath {
get throws {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return AbsolutePath(bundle.bundleURL.deletingLastPathComponent().path)
return try AbsolutePath(validating: bundle.bundleURL.deletingLastPathComponent().path)
}
fatalError("couldn't find the products directory")
#else
return AbsolutePath(Bundle.main.bundleURL.path)
return try AbsolutePath(validating: Bundle.main.bundleURL.path)
#endif
}
}
public var testFixturesDirectory: AbsolutePath {
packageDirectory.appending(components: "Tests", "Fixtures")
get throws {
try packageDirectory.appending(components: "Tests", "Fixtures")
}
}
public var packageDirectory: AbsolutePath {
AbsolutePath(#filePath)
get throws {
try AbsolutePath(validating: #filePath)
.parentDirectory
.parentDirectory
.parentDirectory
}
}
func withFixture(_ name: String, _ body: (AbsolutePath) throws -> ()) throws {
let fixtureDir = testFixturesDirectory.appending(component: name)
func withFixture(_ name: String, _ body: (AbsolutePath) throws -> Void) throws {
let fixtureDir = try testFixturesDirectory.appending(component: name)
try withTemporaryDirectory(prefix: name) { tmpDirPath in
let dstDir = tmpDirPath.appending(component: name)
try systemQuietly("cp", "-R", "-H", fixtureDir.pathString, dstDir.pathString)
@ -76,8 +82,4 @@ extension AbsolutePath {
else { return [] }
return paths
}
static var home: AbsolutePath {
AbsolutePath(FileManager.default.homeDirectoryForCurrentUser.path)
}
}

View File

@ -13,13 +13,15 @@
// limitations under the License.
import CartonHelpers
@testable import CartonKit
import class Foundation.Bundle
@testable import SwiftToolchain
import TSCBasic
import TSCUtility
import XCTest
import class Foundation.Bundle
@testable import CartonKit
@testable import SwiftToolchain
final class CartonTests: XCTestCase {
/// Returns path to the built products directory.
var productsDirectory: Foundation.URL {
@ -117,25 +119,29 @@ final class CartonTests: XCTestCase {
func testDestinationEnvironment() {
XCTAssertEqual(
DestinationEnvironment(
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0"
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0"
),
.firefox
)
XCTAssertEqual(
DestinationEnvironment(
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
),
.edge
)
XCTAssertEqual(
DestinationEnvironment(
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
),
.chrome
)
XCTAssertEqual(
DestinationEnvironment(
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15"
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15"
),
.safari
)

View File

@ -15,9 +15,10 @@
// Created by Max Desiatov on 08/11/2020.
//
@testable import CartonHelpers
import XCTest
@testable import CartonHelpers
final class StackTraceTests: XCTestCase {}
extension StackTraceTests {
func testFirefoxStackTrace() {
@ -74,79 +75,108 @@ extension StackTraceTests {
symbol: "write",
location: "wasm-function[62062]:0x12af331",
kind: .webAssembly
), .init(
),
.init(
symbol: "swift_reportError",
location: "wasm-function[21654]:0x37c242",
kind: .webAssembly
), .init(
),
.init(
symbol: "_swift_stdlib_reportFatalErrorInFile",
location: "wasm-function[22950]:0x3e2996",
kind: .webAssembly
), .init(
symbol: "closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[3635]:0xd717d",
kind: .webAssembly
), .init(
symbol: "merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[3636]:0xd7374",
kind: .webAssembly
), .init(
symbol: "Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[2752]:0xa7917",
kind: .webAssembly
), .init(
),
.init(
symbol: "Swift.Array.subscript.getter : (Int) -> A",
location: "wasm-function[2982]:0xb34da",
kind: .webAssembly
), .init(
),
.init(
symbol: "TestApp.crash() -> ()",
location: "wasm-function[1372]:0x8012c",
kind: .webAssembly
), .init(
),
.init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> () in TestApp",
location: "wasm-function[1367]:0x7f4e7",
kind: .webAssembly
), .init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: "wasm-function[787]:0x5003b",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: "wasm-function[786]:0x4ff96",
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: "wasm-function[783]:0x4fe00",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: "wasm-function[782]:0x4fdc8",
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: "wasm-function[812]:0x52ddd",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: "wasm-function[802]:0x529bc",
kind: .webAssembly
), .init(
symbol: "JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
),
.init(
symbol:
"JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
location: "wasm-function[801]:0x525e8",
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function_impl",
location: "wasm-function[800]:0x52158",
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function",
location: "wasm-function[1388]:0x814d3",
kind: .webAssembly
), .init(
),
.init(
symbol: "callHostFunction",
location: "./node_modules/javascript-kit-swift/Runtime/lib/index.js?:110:21",
kind: .javaScript
), .init(
),
.init(
symbol: "swjs_create_function/func_ref<",
location: "./node_modules/javascript-kit-swift/Runtime/lib/index.js?:280:28",
kind: .javaScript
@ -193,91 +223,123 @@ extension StackTraceTests {
symbol: "forEach",
location: nil,
kind: .javaScript
), .init(
),
.init(
symbol: "wasm-stub",
location: nil,
kind: .javaScript
), .init(
),
.init(
symbol: "write",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "swift_reportError",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "_swift_stdlib_reportFatalErrorInFile",
location: nil,
kind: .webAssembly
), .init(
symbol: "closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: nil,
kind: .webAssembly
), .init(
symbol: "merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: nil,
kind: .webAssembly
), .init(
symbol: "Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "Swift.Array.subscript.getter : (Int) -> A",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "TestApp.crash() -> ()",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> () in TestApp",
location: nil,
kind: .webAssembly
), .init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: nil,
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: nil,
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: nil,
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: nil,
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: nil,
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: nil,
kind: .webAssembly
), .init(
symbol: "JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
),
.init(
symbol:
"JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function_impl",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function",
location: nil,
kind: .webAssembly
), .init(
),
.init(
symbol: "wasm-stub",
location: nil,
kind: .javaScript
), .init(
),
.init(
symbol: "swjs_call_host_function",
location: nil,
kind: .javaScript
), .init(
),
.init(
symbol: "callHostFunction",
location: nil,
kind: .javaScript
@ -345,79 +407,108 @@ extension StackTraceTests {
symbol: "write",
location: "wasm-function[62105]:0x12b19bc",
kind: .webAssembly
), .init(
),
.init(
symbol: "swift_reportError",
location: "wasm-function[21697]:0x37e8aa",
kind: .webAssembly
), .init(
),
.init(
symbol: "_swift_stdlib_reportFatalErrorInFile",
location: "wasm-function[22993]:0x3e4ffe",
kind: .webAssembly
), .init(
symbol: "closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"closure #1 (UnsafeBufferPointer<UInt8>) -> () in closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[3676]:0xd96fc",
kind: .webAssembly
), .init(
symbol: "merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"merged closure #1 (UnsafeBufferPointer<UInt8>) -> () in _assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[3677]:0xd98f3",
kind: .webAssembly
), .init(
symbol: "Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
),
.init(
symbol:
"Swift._assertionFailure(_: StaticString, _: StaticString, file: StaticString, line: UInt, flags: UInt32) -> Never",
location: "wasm-function[2793]:0xa9f38",
kind: .webAssembly
), .init(
),
.init(
symbol: "Swift.Array.subscript.getter : (Int) -> A",
location: "wasm-function[3023]:0xb5afb",
kind: .webAssembly
), .init(
),
.init(
symbol: "TestApp.crash() -> ()",
location: "wasm-function[1413]:0x8274d",
kind: .webAssembly
), .init(
),
.init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> () in TestApp",
location: "wasm-function[1408]:0x81b08",
kind: .webAssembly
), .init(
symbol: "closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: "wasm-function[816]:0x51881",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
),
.init(
symbol:
"partial apply forwarder for closure #1 (Array<JavaScriptKit.JSValue>) -> JavaScriptKit.JSValue in JavaScriptKit.JSClosure.init((Array<JavaScriptKit.JSValue>) -> ()) -> JavaScriptKit.JSClosure",
location: "wasm-function[815]:0x517dc",
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: "wasm-function[812]:0x51646",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue)",
location: "wasm-function[811]:0x5160e",
kind: .webAssembly
), .init(
symbol: "reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: "wasm-function[839]:0x54566",
kind: .webAssembly
), .init(
symbol: "partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
),
.init(
symbol:
"partial apply forwarder for reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Array<JavaScriptKit.JSValue>) -> (@out JavaScriptKit.JSValue) to @escaping @callee_guaranteed (@guaranteed Array<JavaScriptKit.JSValue>) -> (@owned JavaScriptKit.JSValue)",
location: "wasm-function[831]:0x54202",
kind: .webAssembly
), .init(
symbol: "JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
),
.init(
symbol:
"JavaScriptKit._call_host_function_impl(UInt32, UnsafePointer<__C.RawJSValue>, Int32, UInt32) -> ()",
location: "wasm-function[830]:0x53e2e",
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function_impl",
location: "wasm-function[829]:0x5399e",
kind: .webAssembly
), .init(
),
.init(
symbol: "_call_host_function",
location: "wasm-function[1429]:0x83af4",
kind: .webAssembly
), .init(
),
.init(
symbol: "callHostFunction",
location: "./node_modules/javascript-kit-swift/Runtime/lib/index.js?:110:21",
kind: .javaScript
), .init(
),
.init(
symbol: "HTMLButtonElement.eval",
location: "./node_modules/javascript-kit-swift/Runtime/lib/index.js?:295:28",
kind: .javaScript

View File

@ -6,7 +6,7 @@ import PackageDescription
let package = Package(
name: "NodeJSKitTest",
dependencies: [
.package(url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.15.0"),
.package(url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.15.0")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.

View File

@ -6,10 +6,10 @@ import PackageDescription
let package = Package(
name: "CartonTestApp",
products: [
.executable(name: "TestApp", targets: ["TestApp"]),
.executable(name: "TestApp", targets: ["TestApp"])
],
dependencies: [
.package(url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.15.0"),
.package(url: "https://github.com/swiftwasm/JavaScriptKit", from: "0.15.0")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test

View File

@ -44,7 +44,8 @@ let handler = JSClosure { _ in
buttonNode.onclick = .object(handler)
var div = document.createElement("div")
div.innerHTML = .string(#"""
div.innerHTML = .string(
#"""
<a href=\#(Bundle.module.path(forResource: "data", ofType: "json")!)>Link to a static resource</a>
<br/>
<a href=\#(Bundle.main
@ -56,7 +57,8 @@ var timerElement = document.createElement("p")
_ = document.body.appendChild(timerElement)
let timer = JSTimer(millisecondsDelay: 1000, isRepeating: true) {
let date = JSDate()
timerElement.innerHTML = .string("""
timerElement.innerHTML = .string(
"""
<p>Current date is \(date.toLocaleDateString())</p>
<p>Current time is \(date.toLocaleTimeString())</p>
<p>Current <code>Date().timeIntervalSince1970</code> is \(Date().timeIntervalSince1970)</p>