Skip to content
Open
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
38 changes: 28 additions & 10 deletions cli/Sources/Noora/Components/ProgressBarStep.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,23 @@ import Foundation
import Logging
import Rainbow

public struct ProgressBarUpdate: Sendable, Equatable {
public let progress: Double
public let detail: String?

public init(progress: Double, detail: String? = nil) {
self.progress = progress
self.detail = detail
}
}

struct ProgressBarStep<V> {
// MARK: - Attributes

let message: String
let successMessage: String?
let errorMessage: String?
let task: (@escaping (Double) -> Void) async throws -> V
let task: (@escaping (ProgressBarUpdate) -> Void) async throws -> V
let theme: Theme
let terminal: Terminaling
let renderer: Rendering
Expand All @@ -24,7 +34,7 @@ struct ProgressBarStep<V> {
message: String,
successMessage: String?,
errorMessage: String?,
task: @escaping (@escaping (Double) -> Void) async throws -> V,
task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V,
theme: Theme,
terminal: Terminaling,
renderer: Rendering,
Expand Down Expand Up @@ -61,15 +71,17 @@ struct ProgressBarStep<V> {

var spinnerIcon: String?
var lastProgress = 0.0
var lastDetail: String?

spinner.spin { icon in
spinnerIcon = icon
render(progress: lastProgress, icon: spinnerIcon ?? "ℹ︎")
render(progress: lastProgress, icon: spinnerIcon ?? "ℹ︎", detail: lastDetail)
}

do {
let result = try await task { progress in
lastProgress = progress
let result = try await task { update in
lastProgress = update.progress
lastDetail = update.detail
}
renderer.render(
.progressCompletionMessage(
Expand Down Expand Up @@ -101,11 +113,11 @@ struct ProgressBarStep<V> {
let start = DispatchTime.now()

do {
render(progress: 0, icon: "ℹ︎")
render(progress: 0, icon: "ℹ︎", detail: nil)

// The updated progress is ignored in non-interactive environments
let result = try await task { progress in
render(progress: progress, icon: "ℹ︎")
let result = try await task { update in
render(progress: update.progress, icon: "ℹ︎", detail: update.detail)
}

let message: String = .progressCompletionMessage(
Expand All @@ -132,7 +144,7 @@ struct ProgressBarStep<V> {
return "[\(String(format: "%.1f", elapsedTime))s]".hexIfColoredTerminal(theme.muted, terminal)
}

private func render(progress: Double, icon: String) {
private func render(progress: Double, icon: String, detail: String?) {
let width = 30
let completed: Int
if progress == 0.0 {
Expand All @@ -143,8 +155,14 @@ struct ProgressBarStep<V> {
let completedBar = String(repeating: "█", count: completed)
let incompleteBar = String(repeating: "▒", count: width - completed)
let bar = completedBar + incompleteBar
let detailSuffix: String
if let detail, !detail.isEmpty {
detailSuffix = " (\(detail))"
} else {
detailSuffix = ""
}
let output =
"\(icon.hexIfColoredTerminal(theme.primary, terminal)) \(message) \(bar.hexIfColoredTerminal(theme.primary, terminal)) \(Int(floor(progress * 100)))%"
"\(icon.hexIfColoredTerminal(theme.primary, terminal)) \(message) \(bar.hexIfColoredTerminal(theme.primary, terminal)) \(Int(floor(progress * 100)))%\(detailSuffix)"
if terminal.isInteractive {
renderer.render(
output,
Expand Down
65 changes: 64 additions & 1 deletion cli/Sources/Noora/Noora.swift
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,23 @@ public protocol Noorable: Sendable {
task: @escaping (@escaping (Double) -> Void) async throws -> V
) async throws -> V

/// Shows a progress bar step with optional detail text.
/// - Parameters:
/// - message: The message that represents "what's being done"
/// - successMessage: The message that the step gets updated to when the action completes.
/// - errorMessage: The message that the step gets updated to when the action errors.
/// - renderer: A rendering interface that holds the UI state.
/// - task: The asynchronous task to run. The caller can use the argument that the function takes to update the progress.
/// The value should be between 0 and 1. The detail text is appended after the percentage when present.
/// message.
func progressBarStep<V>(
message: String,
successMessage: String?,
errorMessage: String?,
renderer: Rendering,
Comment on lines +314 to +316
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These three can have default arguments. Which would remove the need for two overloads

task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this conflict with the other overloads in practical use?

) async throws -> V

/// Displays a static table
/// - Parameters:
/// - headers: Column headers
Expand Down Expand Up @@ -766,6 +783,25 @@ public final class Noora: Noorable {
errorMessage: String?,
renderer: Rendering,
task: @escaping (@escaping (Double) -> Void) async throws -> V
) async throws -> V {
try await progressBarStep(
message: message,
successMessage: successMessage,
errorMessage: errorMessage,
renderer: renderer
) { update in
try await task { progress in
update(ProgressBarUpdate(progress: progress))
}
}
}

public func progressBarStep<V>(
message: String,
successMessage: String?,
errorMessage: String?,
renderer: Rendering,
task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V
) async throws -> V {
try await ProgressBarStep(
message: message,
Expand Down Expand Up @@ -1303,7 +1339,6 @@ extension Noorable {
message: message,
successMessage: nil,
errorMessage: nil,
renderer: Renderer(),
task: task
)
}
Expand All @@ -1323,6 +1358,34 @@ extension Noorable {
)
}

public func progressBarStep<V>(
message: String,
task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V
) async throws -> V {
try await progressBarStep(
message: message,
successMessage: nil,
errorMessage: nil,
renderer: Renderer(),
task: task
)
}

public func progressBarStep<V>(
message: String,
successMessage: String?,
errorMessage: String?,
task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V
) async throws -> V {
try await progressBarStep(
message: message,
successMessage: successMessage,
errorMessage: errorMessage,
renderer: Renderer(),
task: task
)
}

Comment on lines +1361 to +1388
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These 2 can be removed if you use default arguments

public func table(
headers: [String],
rows: [[String]],
Expand Down
16 changes: 16 additions & 0 deletions cli/Sources/Noora/NooraMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,22 @@
)
}

public func progressBarStep<V>(
message: String,
successMessage: String?,
errorMessage: String?,
renderer: Rendering,
task: @escaping (@escaping (ProgressBarUpdate) -> Void) async throws -> V
) async throws -> V {
try await noora.progressBarStep(
message: message,
successMessage: successMessage,
errorMessage: errorMessage,
renderer: renderer,
task: task
)
}

public func format(_ terminalText: TerminalText) -> String {
noora.format(terminalText)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ struct ProgressBarStepCommand: AsyncParsableCommand {
) { progress in
let totalSteps = 100
let stepInterval: UInt64 = 4_000_000_000 / UInt64(totalSteps) // 4 seconds divided by steps
let totalSize = 2.33

for step in 0 ... totalSteps {
let progressValue = Double(step) / Double(totalSteps)
progress(progressValue)
let downloaded = totalSize * progressValue
let detail = String(format: "%.2f GB/%.2f GB", downloaded, totalSize)
progress(ProgressBarUpdate(progress: progressValue, detail: detail))

if step < totalSteps {
try await Task.sleep(nanoseconds: stepInterval)
Expand Down
46 changes: 37 additions & 9 deletions cli/Tests/NooraTests/Components/ProgressBarStepTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ struct ProgressBarStepTests {
successMessage: "Project graph loaded",
errorMessage: "Failed to load the project graph",
task: { updateProgress in
updateProgress(0.1)
updateProgress(0.5)
updateProgress(0.9)
updateProgress(ProgressBarUpdate(progress: 0.1))
updateProgress(ProgressBarUpdate(progress: 0.5))
updateProgress(ProgressBarUpdate(progress: 0.9))
},
theme: Theme.test(),
terminal: MockTerminal(isInteractive: false),
Expand Down Expand Up @@ -87,9 +87,9 @@ struct ProgressBarStepTests {
successMessage: nil,
errorMessage: nil,
task: { updateProgress in
updateProgress(0.1)
updateProgress(0.5)
updateProgress(0.9)
updateProgress(ProgressBarUpdate(progress: 0.1))
updateProgress(ProgressBarUpdate(progress: 0.5))
updateProgress(ProgressBarUpdate(progress: 0.9))
},
theme: Theme.test(),
terminal: MockTerminal(isInteractive: false),
Expand All @@ -114,6 +114,34 @@ struct ProgressBarStepTests {
)
}

@Test func renders_detail_text_when_provided_in_non_interactive_terminal() async throws {
// Given
let standardOutput = MockStandardPipeline()
let standardError = MockStandardPipeline()
let standardPipelines = StandardPipelines(output: standardOutput, error: standardError)

let subject = ProgressBarStep(
message: "Downloading artifacts",
successMessage: nil,
errorMessage: nil,
task: { updateProgress in
updateProgress(ProgressBarUpdate(progress: 0.33, detail: "123 MB/2.33 GB"))
},
theme: Theme.test(),
terminal: MockTerminal(isInteractive: false),
renderer: renderer,
standardPipelines: standardPipelines,
spinner: spinner,
logger: nil
)

// When
try await subject.run()

// Then
#expect(standardOutput.writtenContent.value.range(of: "33% (123 MB/2.33 GB)") != nil)
}

@Test func renders_the_right_output_when_failure_and_non_interactive_terminal() async throws {
// Given
let standardOutput = MockStandardPipeline()
Expand Down Expand Up @@ -159,11 +187,11 @@ struct ProgressBarStepTests {
successMessage: "Project graph loaded",
errorMessage: "Failed to load the project graph",
task: { updateProgress in
updateProgress(0.1)
updateProgress(ProgressBarUpdate(progress: 0.1))
spinner.lastBlock?("⠋")
updateProgress(0.5)
updateProgress(ProgressBarUpdate(progress: 0.5))
spinner.lastBlock?("⠋")
updateProgress(0.9)
updateProgress(ProgressBarUpdate(progress: 0.9))
spinner.lastBlock?("⠋")
},
theme: Theme.test(),
Expand Down
6 changes: 4 additions & 2 deletions docs/content/components/step/progress-bar.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@ This component represents a long-running step in the execution of a command show
### Example

```swift
try await Noora().progressStep(
try await Noora().progressBarStep(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean progressStep is a deprecated API? Are we going to maintain both? If so, I find it a bit confusing as a consumer of the API.

message: "Processing the graph",
successMessage: "Project graph processed",
errorMessage: "Failed to process the project graph"
) { updateProgress in
for step in steps {
try await runStep()
// Use updateProgress to update the progress. The value should be between 0 and 1.
updateProgress(step / steps)
let progress = Double(step) / Double(steps)
let detail = "\(step) / \(steps) nodes"
updateProgress(ProgressBarUpdate(progress: progress, detail: detail))
}
}
```
Expand Down
Loading