Skip to content

Commit faee016

Browse files
Stop writing static files in ~/.carton/static
Instead, write them under plugin work directory
1 parent 9082e65 commit faee016

File tree

9 files changed

+52
-133
lines changed

9 files changed

+52
-133
lines changed

Plugins/CartonTest/Plugin.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ struct CartonTestPlugin: CommandPlugin {
103103
"test",
104104
"--prebuilt-test-bundle-path", testProductArtifactPath,
105105
"--environment", options.environment.rawValue,
106+
"--plugin-work-directory", context.pluginWorkDirectory.string
106107
]
107108
+ resourcesPaths.flatMap {
108109
["--resources", $0.string]

Sources/CartonCLI/Commands/Bundle.swift

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,6 @@ import CartonKit
1818
import Foundation
1919
import WasmTransformer
2020

21-
private let dependency = Entrypoint(
22-
fileName: "bundle.js",
23-
sha256: bundleEntrypointSHA256
24-
)
25-
2621
enum WasmOptimizations: String, CaseIterable, ExpressibleByArgument {
2722
case size, none
2823
}
@@ -78,8 +73,6 @@ struct Bundle: AsyncParsableCommand {
7873
func run() async throws {
7974
let terminal = InteractiveWriter.stderr
8075

81-
try dependency.check(on: localFileSystem, terminal)
82-
8376
var mainWasmPath = try AbsolutePath(
8477
validating: mainWasmPath, relativeTo: localFileSystem.currentWorkingDirectory!)
8578
let buildDirectory = mainWasmPath.parentDirectory
@@ -175,9 +168,8 @@ struct Bundle: AsyncParsableCommand {
175168
try localFileSystem.move(from: wasmOutputFilePath, to: mainModulePath)
176169

177170
// Copy the bundle entrypoint, point to the binary, and give it a cachebuster name.
178-
let (_, _, entrypointPath) = try dependency.paths(on: localFileSystem)
179-
let entrypoint = try ByteString(
180-
encodingAsUTF8: localFileSystem.readFileContents(entrypointPath)
171+
let entrypoint = ByteString(
172+
encodingAsUTF8: StaticResource.bundle
181173
.description
182174
.replacingOccurrences(
183175
of: "REPLACE_THIS_WITH_THE_MAIN_WEBASSEMBLY_MODULE",

Sources/CartonCLI/Commands/Dev.swift

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import CartonKit
1818
import Foundation
1919

2020
struct Dev: AsyncParsableCommand {
21-
static let entrypoint = Entrypoint(fileName: "dev.js", sha256: devEntrypointSHA256)
21+
static let entrypoint = Entrypoint(fileName: "dev.js", content: StaticResource.dev)
2222

2323
@Option(help: "Specify name of an executable product in development.")
2424
var product: String?
@@ -93,8 +93,6 @@ struct Dev: AsyncParsableCommand {
9393
func run() async throws {
9494
let terminal = InteractiveWriter.stdout
9595

96-
try Self.entrypoint.check(on: localFileSystem, terminal)
97-
9896
let paths = try watchPaths.map {
9997
try AbsolutePath(validating: $0, relativeTo: localFileSystem.currentWorkingDirectory!)
10098
}

Sources/CartonCLI/Commands/Test.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ struct Test: AsyncParsableCommand {
8686
)
8787
var resources: [String] = []
8888

89+
@Option(name: .long, help: ArgumentHelp(
90+
"Internal: Path to writable directory", visibility: .private
91+
))
92+
var pluginWorkDirectory: String = "./"
93+
8994
func validate() throws {
9095
if headless && environment != .browser {
9196
throw TestError(
@@ -96,8 +101,9 @@ struct Test: AsyncParsableCommand {
96101
func run() async throws {
97102
let terminal = InteractiveWriter.stdout
98103
let bundlePath: AbsolutePath
104+
let cwd = localFileSystem.currentWorkingDirectory!
99105
bundlePath = try AbsolutePath(
100-
validating: prebuiltTestBundlePath, relativeTo: localFileSystem.currentWorkingDirectory!)
106+
validating: prebuiltTestBundlePath, relativeTo: cwd)
101107
guard localFileSystem.exists(bundlePath, followSymlink: true) else {
102108
terminal.write(
103109
"No prebuilt binary found at \(bundlePath)\n",
@@ -125,6 +131,7 @@ struct Test: AsyncParsableCommand {
125131
).run()
126132
case .node:
127133
try await NodeTestRunner(
134+
pluginWorkDirectory: AbsolutePath(validating: pluginWorkDirectory, relativeTo: cwd),
128135
testFilePath: bundlePath,
129136
listTestCases: list,
130137
testCases: testCases,

Sources/CartonCLI/Commands/TestRunners/BrowserTestRunner.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import WebDriverClient
2424
#endif
2525

2626
private enum Constants {
27-
static let entrypoint = Entrypoint(fileName: "test.js", sha256: testEntrypointSHA256)
27+
static let entrypoint = Entrypoint(fileName: "test.js", content: StaticResource.test)
2828
}
2929

3030
enum BrowserTestRunnerError: Error, CustomStringConvertible {
@@ -152,7 +152,6 @@ struct BrowserTestRunner: TestRunner {
152152
}
153153

154154
func run() async throws {
155-
try Constants.entrypoint.check(on: localFileSystem, terminal)
156155
let server = try await Server(
157156
.init(
158157
builder: nil,

Sources/CartonCLI/Commands/TestRunners/NodeTestRunner.swift

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,12 @@ import CartonKit
1717
import Foundation
1818

1919
private enum Constants {
20-
static let entrypoint = Entrypoint(fileName: "testNode.js", sha256: testNodeEntrypointSHA256)
20+
static let entrypoint = Entrypoint(fileName: "testNode.js", content: StaticResource.testNode)
2121
}
2222

2323
/// Test runner for Node.js.
2424
struct NodeTestRunner: TestRunner {
25+
let pluginWorkDirectory: AbsolutePath
2526
let testFilePath: AbsolutePath
2627
let listTestCases: Bool
2728
let testCases: [String]
@@ -30,12 +31,13 @@ struct NodeTestRunner: TestRunner {
3031
func run() async throws {
3132
terminal.write("\nRunning the test bundle with Node.js:\n", inColor: .yellow)
3233

33-
try Constants.entrypoint.check(on: localFileSystem, terminal)
34-
let (_, _, entrypointPath) = try Constants.entrypoint.paths(on: localFileSystem)
34+
let entrypointPath = try Constants.entrypoint.write(
35+
at: pluginWorkDirectory, fileSystem: localFileSystem
36+
)
3537

3638
// Allow Node.js to resolve modules from resource directories by making them relative to the entrypoint path.
3739
let buildDirectory = testFilePath.parentDirectory
38-
let staticDirectory = entrypointPath.parentDirectory
40+
let staticDirectory = pluginWorkDirectory
3941

4042
// Clean up existing symlinks before creating new ones.
4143
for existingSymlink in try localFileSystem.resourcesDirectoryNames(relativeTo: staticDirectory)

Sources/CartonKit/Model/Entrypoint.swift

Lines changed: 7 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -15,62 +15,18 @@
1515
import CartonHelpers
1616
import Foundation
1717

18-
private struct StringError: Equatable, Codable, CustomStringConvertible, Error {
19-
let description: String
20-
init(_ description: String) {
21-
self.description = description
22-
}
23-
}
24-
25-
extension StringError: CustomNSError {
26-
var errorUserInfo: [String: Any] {
27-
return [NSLocalizedDescriptionKey: self.description]
28-
}
29-
}
30-
3118
public struct Entrypoint {
3219
let fileName: String
33-
let sha256: ByteString
20+
let content: ByteString
3421

35-
public init(fileName: String, sha256: ByteString) {
22+
public init(fileName: String, content: Data) {
3623
self.fileName = fileName
37-
self.sha256 = sha256
24+
self.content = ByteString(content)
3825
}
3926

40-
public func paths(
41-
on fileSystem: FileSystem
42-
// swiftlint:disable:next large_tuple
43-
) throws -> (cartonDir: AbsolutePath, staticDir: AbsolutePath, filePath: AbsolutePath) {
44-
let cartonDir = try fileSystem.homeDirectory.appending(component: ".carton")
45-
let staticDir = cartonDir.appending(component: "static")
46-
return (cartonDir, staticDir, staticDir.appending(component: fileName))
47-
}
48-
49-
public func check(on fileSystem: FileSystem, _ terminal: InteractiveWriter) throws {
50-
let (cartonDir, staticDir, filePath) = try paths(on: fileSystem)
51-
52-
// If hash check fails, download the `static.zip` archive and unpack it
53-
if try !fileSystem.exists(filePath, followSymlink: true)
54-
|| SHA256().hash(
55-
fileSystem.readFileContents(filePath)
56-
) != sha256
57-
{
58-
terminal.logLookup("Directory doesn't exist or contains outdated polyfills: ", staticDir)
59-
let archiveFile = cartonDir.appending(component: "static.zip")
60-
try fileSystem.removeFileTree(staticDir)
61-
try fileSystem.removeFileTree(archiveFile)
62-
63-
let staticArchiveBytes = Data(base64Encoded: staticArchiveContents)!
64-
try fileSystem.createDirectory(cartonDir, recursive: true)
65-
try fileSystem.writeFileContents(archiveFile, bytes: ByteString(staticArchiveBytes))
66-
terminal.logLookup("Unpacking the archive: ", archiveFile)
67-
68-
try fileSystem.createDirectory(staticDir, recursive: false)
69-
let result = try Process.popen(
70-
args: "unzip", archiveFile.pathString, "-d", staticDir.pathString)
71-
guard result.exitStatus == .terminated(code: 0) else {
72-
throw try StringError(result.utf8stderrOutput())
73-
}
74-
}
27+
public func write(at directory: AbsolutePath, fileSystem: FileSystem) throws -> AbsolutePath {
28+
let path = directory.appending(component: fileName)
29+
try fileSystem.writeFileContents(path, bytes: content)
30+
return path
7531
}
7632
}

Sources/CartonKit/Server/StaticArchive.swift

Lines changed: 7 additions & 21 deletions
Large diffs are not rendered by default.

Sources/carton-release/HashArchive.swift

Lines changed: 19 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,14 @@ struct HashArchive: AsyncParsableCommand {
3939
let terminal = InteractiveWriter.stdout
4040
let cwd = localFileSystem.currentWorkingDirectory!
4141
let staticPath = try AbsolutePath(validating: "static", relativeTo: cwd)
42-
let dotFilesStaticPath = try localFileSystem.homeDirectory.appending(
43-
components: ".carton",
44-
"static"
45-
)
4642

47-
try localFileSystem.createDirectory(dotFilesStaticPath, recursive: true)
48-
var hashes: [(String, String)] = []
43+
var fileContent = """
44+
import Foundation
45+
46+
public enum StaticResource {
47+
48+
"""
49+
4950
for entrypoint in ["dev", "bundle", "test", "testNode"] {
5051
let tsFilename = "\(entrypoint).ts"
5152
let filename = "\(entrypoint).js"
@@ -70,52 +71,29 @@ struct HashArchive: AsyncParsableCommand {
7071
}
7172
try Foundation.Process.run(npx.asURL, arguments: arguments).waitUntilExit()
7273
let entrypointPath = try AbsolutePath(validating: filename, relativeTo: staticPath)
73-
let dotFilesEntrypointPath = dotFilesStaticPath.appending(component: filename)
74-
try localFileSystem.removeFileTree(dotFilesEntrypointPath)
75-
try localFileSystem.copy(from: entrypointPath, to: dotFilesEntrypointPath)
76-
77-
hashes.append(
78-
(
79-
entrypoint,
80-
try SHA256().hash(localFileSystem.readFileContents(entrypointPath))
81-
.hexadecimalRepresentation.uppercased()
82-
))
83-
}
84-
85-
let archiveSources = try localFileSystem.getDirectoryContents(staticPath)
86-
.map { try AbsolutePath(validating: $0, relativeTo: staticPath) }
87-
.map(\.pathString)
8874

89-
try await Process.run(["zip", "-j", "static.zip"] + archiveSources, terminal)
90-
91-
let staticArchiveContents = try localFileSystem.readFileContents(
92-
AbsolutePath(
93-
validating: "static.zip",
94-
relativeTo: localFileSystem.currentWorkingDirectory!
95-
))
96-
97-
// Base64 is not an efficient way, but too long byte array literal breaks type-checker
98-
let hashesFileContent = """
99-
import CartonHelpers
75+
// Base64 is not an efficient way, but too long byte array literal breaks type-checker
76+
let base64Content = try localFileSystem.readFileContents(entrypointPath).withData {
77+
$0.base64EncodedString()
78+
}
79+
fileContent += """
80+
public static let \(entrypoint): Data = Data(base64Encoded: \"\(base64Content)\")!
10081
101-
\(hashes.map {
10282
"""
103-
public let \($0)EntrypointSHA256 = ByteString([
104-
\(arrayString(from: $1))
105-
])
106-
"""
107-
}.joined(separator: "\n\n"))
83+
}
10884

109-
public let staticArchiveContents = "\(staticArchiveContents.withData { $0.base64EncodedString() })"
110-
"""
85+
fileContent += """
86+
87+
}
88+
"""
11189

11290
try localFileSystem.writeFileContents(
11391
AbsolutePath(
11492
cwd,
11593
RelativePath(validating: "Sources").appending(
11694
components: "CartonKit", "Server", "StaticArchive.swift")
11795
),
118-
bytes: ByteString(encodingAsUTF8: hashesFileContent)
96+
bytes: ByteString(encodingAsUTF8: fileContent)
11997
)
12098
}
12199
}

0 commit comments

Comments
 (0)