Skip to content

Commit

Permalink
Parallelize using withThrowingTaskGroup and waitForAll (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzalonunez authored Mar 27, 2023
1 parent 506d51f commit 65452e1
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions Sources/docc-gpt/DoccGPTRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ struct DoccGPTRunner {

// MARK: Private

/// The base URL for the OpenAI API.
private let baseURL = URL(string: "https://api.openai.com/v1/completions")!
/// The URL for the OpenAI API.
private let apiURL = URL(string: "https://api.openai.com/v1/completions")!

/// The `FileManager` used to access the filesystem.
private let fileManager = FileManager.default
Expand Down Expand Up @@ -88,7 +88,7 @@ struct DoccGPTRunner {
stream: false,
stop: "```")

var request = URLRequest(url: baseURL)
var request = URLRequest(url: apiURL)
request.httpBody = try jsonEncoder.encode(parameters)
request.httpMethod = "POST"
request.allHTTPHeaderFields = [
Expand Down Expand Up @@ -129,16 +129,22 @@ struct DoccGPTRunner {
- Throws: `DoccGPTRunnerError` if an error occurs.
*/
private func documentFiles(in directoryURL: URL) async throws {
guard let enumerator = fileManager.enumerator(atPath: directoryURL.path) else {
throw DoccGPTRunnerError.failedToCreateEnumerator
}
try await withThrowingTaskGroup(of: Void.self) { group in
guard let enumerator = fileManager.enumerator(atPath: directoryURL.path) else {
throw DoccGPTRunnerError.failedToCreateEnumerator
}

while let file = enumerator.nextObject() as? String {
guard file.hasSuffix(".swift") && !ignoredFiles.contains(file) else {
continue
while let file = enumerator.nextObject() as? String {
guard file.hasSuffix(".swift") && !ignoredFiles.contains(file) else {
continue
}
group.addTask {
let fileURL = directoryURL.appendingPathComponent(file)
try await documentFile(fileURL: fileURL)
}
}
let fileURL = directoryURL.appendingPathComponent(file)
try await documentFile(fileURL: fileURL)

try await group.waitForAll()
}
}
}

0 comments on commit 65452e1

Please sign in to comment.