Skip to content
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

no use file-descriptor for output #10

Merged
merged 1 commit into from
Oct 22, 2022
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
16 changes: 15 additions & 1 deletion .swiftpm/xcode/xcshareddata/xcschemes/grain.xcscheme
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "GrainDescriptor"
BuildableName = "GrainDescriptor"
BlueprintName = "GrainDescriptor"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
Expand Down Expand Up @@ -78,7 +92,7 @@
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "./Sources/Fixture.swift ./fixtures/openapi.swift --verbose "
argument = "./Sources/Fixture.swift ./fixtures/openapi.swift --output /Users/muukii/Desktop"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
Expand Down
7 changes: 4 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,19 @@ let package = Package(
.target(
name: "GrainDescriptor",
dependencies: [
"Alamofire"
"Alamofire",
.product(name: "SwiftToolsSupport-auto", package: "swift-tools-support-core"),
],
swiftSettings: [
.unsafeFlags(["-enable-library-evolution"])
// .unsafeFlags(["-enable-library-evolution"])
]
),
.executableTarget(
name: "Grain",
dependencies: [
"GrainDescriptor",
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "SwiftToolsSupport", package: "swift-tools-support-core"),
.product(name: "SwiftToolsSupport-auto", package: "swift-tools-support-core"),
]
),
.testTarget(
Expand Down
2 changes: 1 addition & 1 deletion Sources/Fixture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ serialize {
response
}
GrainMember("context") {
context.filePath
context.filePath.pathString
}
}

Expand Down
92 changes: 15 additions & 77 deletions Sources/Grain/CLI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,6 @@ struct CLI: AsyncParsableCommand {

struct Render: AsyncParsableCommand {

struct RenderResult {
let outputData: Data
let headerData: Data

func header() -> GrainDescriptor.Header {
.decode(headerData)
}

func outputString() -> String {
String(data: outputData, encoding: .utf8)!
}

}

struct DomainError: Swift.Error, LocalizedError, Equatable {

var errorDescription: String?
Expand All @@ -66,50 +52,24 @@ struct CLI: AsyncParsableCommand {
AbsolutePath($0, relativeTo: localFileSystem.currentWorkingDirectory!)
}

let results = try await withThrowingTaskGroup(of: (AbsolutePath, RenderResult).self) { group in
await withThrowingTaskGroup(of: Void.self) { group in

for path in validatedPaths {
group.addTask {
let result = try await self.render(path)
return (path, result)

let context = GrainDescriptor.Context(
filePath: path,
outputDir: outputDirectory.map { AbsolutePath($0, relativeTo: localFileSystem.currentWorkingDirectory!) }
)

try await self.render(path, context: context)
}
}

return try await group.reduce(into: [(AbsolutePath, RenderResult)]()) { partialResult, result in
partialResult.append(result)
}

}

if let outputDirectory {

let outputDirectoryAbsolute = AbsolutePath(outputDirectory, relativeTo: localFileSystem.currentWorkingDirectory!)

for result in results {

let path = result.0
let r = result.1
let c = r.header()

let fileName = [path.basenameWithoutExt, c.outputConfiguration.fileExtension].compactMap { $0 }.joined(separator: ".")

let writePath = outputDirectoryAbsolute.appending(component: fileName)

try r.outputData.write(to: URL.init(fileURLWithPath: writePath.pathString), options: [.atomic])

Log.info("✅ \(writePath.pathString)")

}

} else {
for result in results {
print(result.1.outputString())
}
}

}
}

private func render(_ targetFilePath: AbsolutePath) async throws -> RenderResult {
private func render(_ targetFilePath: AbsolutePath, context: GrainDescriptor.Context) async throws {

guard localFileSystem.exists(targetFilePath) else {
throw CLIError.fileNotFound
Expand Down Expand Up @@ -197,7 +157,7 @@ runtimeFrameworksPath: \(runtimeFrameworksPath)
]
cmd += ["-swift-version", "5"]

return try await withTemporaryDirectory { workingPath -> RenderResult in
return try await withTemporaryDirectory { workingPath in

let compiledFile = workingPath.appending(component: "compiled")

Expand Down Expand Up @@ -226,26 +186,10 @@ runtimeFrameworksPath: \(runtimeFrameworksPath)

// make an output
do {

let outputFile = workingPath.appending(component: "output")
let outputHeaderFile = workingPath.appending(component: "output_header")

guard let outputFileDesc = fopen(outputFile.pathString, "w") else {
throw DomainError.couldNotCreateOutputFile
}

guard let outputHeaderFileDesc = fopen(outputHeaderFile.pathString, "w") else {
throw DomainError.couldNotCreateOutputFile
}


var cmd: [String] = []

cmd += [compiledFile.pathString]

cmd += ["-fileno-output", "\(fileno(outputFileDesc))"]
cmd += ["-fileno-header", "\(fileno(outputHeaderFileDesc))"]

let context = GrainDescriptor.Context(filePath: targetFilePath.pathString)

cmd += ["-context", context.json()]

Expand All @@ -255,9 +199,6 @@ runtimeFrameworksPath: \(runtimeFrameworksPath)
loggingHandler: { log in }
)

fclose(outputFileDesc)
fclose(outputHeaderFileDesc)

// Return now if there was an error.
if result.exitStatus != .terminated(code: 0) {

Expand All @@ -266,12 +207,9 @@ runtimeFrameworksPath: \(runtimeFrameworksPath)

throw DomainError.failureInMakingOutput
}

let output: Data = try localFileSystem.readFileContents(outputFile)
let outputHeader: Data = try localFileSystem.readFileContents(outputHeaderFile)

return .init(outputData: output, headerData: outputHeader)


Log.info(try result.utf8Output())

}

}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Grain/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ enum Log {
static func info(
file: StaticString = #file,
line: UInt = #line,
_ object: @autoclosure () -> Any
_ object: Any
) {
print(object())
print(object)
}

static func error(
Expand Down
Loading