Skip to content

Commit

Permalink
When Output is redirected, do not output the status indicators
Browse files Browse the repository at this point in the history
  • Loading branch information
mivano committed Dec 22, 2023
1 parent 86fc585 commit 463c106
Show file tree
Hide file tree
Showing 9 changed files with 261 additions and 6 deletions.
4 changes: 3 additions & 1 deletion src/Commands/AccumulatedCost/AccumulatedCostCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,11 @@ public override async Task<int> ExecuteAsync(CommandContext context, Accumulated
AccumulatedCostDetails accumulatedCost = null;

Subscription subscription = null;
await AnsiConsole.Status()

await AnsiConsoleExt.Status()
.StartAsync("Fetching cost data...", async ctx =>
{

if (settings.GetScope.IsSubscriptionBased)
{
ctx.Status = "Fetching subscription details...";
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/CostByResource/CostByResourceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, CostByResou
// Fetch the costs from the Azure Cost Management API
IEnumerable<CostResourceItem> resources = new List<CostResourceItem>();

await AnsiConsole.Status()
await AnsiConsoleExt.Status()
.StartAsync("Fetching cost data for resources...", async ctx =>
{
resources = await _costRetriever.RetrieveCostForResources(
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/CostByTag/CostByTagCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, CostByTagSe
// Fetch the costs from the Azure Cost Management API
IEnumerable<CostResourceItem> resources = new List<CostResourceItem>();

await AnsiConsole.Status()
await AnsiConsoleExt.Status()
.StartAsync("Fetching cost data for resources...", async ctx =>
{
resources = await _costRetriever.RetrieveCostForResources(
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/DailyCost/DailyCost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, DailyCostSe

IEnumerable<CostDailyItem> dailyCost = new List<CostDailyItem>();

await AnsiConsole.Status()
await AnsiConsoleExt.Status()
.StartAsync("Fetching daily cost data...", async ctx =>
{
// Fetch the costs from the Azure Cost Management API
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/WhatIf/DevTestWhatIfCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, WhatIfSetti



await AnsiConsole.Status()
await AnsiConsoleExt.Status()
.StartAsync("Fetching cost data for resources...", async ctx =>
{
resources = await _costRetriever.RetrieveCostForResources(
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/WhatIf/RegionWhatIfCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public override async Task<int> ExecuteAsync(CommandContext context, WhatIfSetti
IEnumerable<UsageDetails> resources;
Dictionary<UsageDetails, List<PriceRecord>> pricesByRegion = new();

await AnsiConsole.Status()
await AnsiConsoleExt.Status()
.StartAsync("Fetching cost data for resources...", async ctx =>
{
resources = await _costRetriever.RetrieveUsageDetails(
Expand Down
15 changes: 15 additions & 0 deletions src/OutputFormatters/SpectreConsole/AnsiConsoleExt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using AzureCostCli.OutputFormatters.SpectreConsole;

namespace Spectre.Console;

public static partial class AnsiConsoleExt
{
/// <summary>
/// Creates a new <see cref="StatusExt"/> instance.
/// </summary>
/// <returns>A <see cref="StatusExt"/> instance.</returns>
public static StatusExt Status()
{
return new StatusExt(AnsiConsole.Console);
}
}
94 changes: 94 additions & 0 deletions src/OutputFormatters/SpectreConsole/StatusContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using Spectre.Console;

namespace AzureCostCli.OutputFormatters.SpectreConsole;
/*
Some of the SpectreConsole code is internal, so copied here for reuse.
The following license applies to this code:
MIT License
Copyright (c) 2020 Patrik Svensson, Phil Scott, Nils Andresen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class StatusContext
{
private readonly ProgressContext _context;
private readonly ProgressTask? _task;
private readonly SpinnerColumn _spinnerColumn;

/// <summary>
/// Gets or sets the current status.
/// </summary>
public string Status
{
get => _task?.Description;
set => SetStatus(value);
}

/// <summary>
/// Gets or sets the current spinner.
/// </summary>
public Spinner Spinner
{
get => _spinnerColumn.Spinner;
set => SetSpinner(value);
}

/// <summary>
/// Gets or sets the current spinner style.
/// </summary>
public Style? SpinnerStyle
{
get => _spinnerColumn.Style;
set => _spinnerColumn.Style = value;
}

internal StatusContext()
{

}

internal StatusContext(ProgressContext context, ProgressTask task, SpinnerColumn spinnerColumn)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_task = task ?? throw new ArgumentNullException(nameof(task));
_spinnerColumn = spinnerColumn ?? throw new ArgumentNullException(nameof(spinnerColumn));
}

/// <summary>
/// Refreshes the status.
/// </summary>
public void Refresh()
{
_context.Refresh();
}

private void SetStatus(string status)
{
if (status is null)
{
throw new ArgumentNullException(nameof(status));
}

if (_task is not null)
{
_task.Description = status;
}
}

private void SetSpinner(Spinner spinner)
{
if (spinner is null)
{
throw new ArgumentNullException(nameof(spinner));
}

_spinnerColumn.Spinner = spinner;
}
}
144 changes: 144 additions & 0 deletions src/OutputFormatters/SpectreConsole/StatusExt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
Some of the SpectreConsole code is internal, so copied here for reuse.
The following license applies to this code:
MIT License
Copyright (c) 2020 Patrik Svensson, Phil Scott, Nils Andresen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Spectre.Console;

namespace AzureCostCli.OutputFormatters.SpectreConsole;

public class StatusExt
{
private readonly IAnsiConsole _console;

/// <summary>
/// Gets or sets the spinner.
/// </summary>
public Spinner? Spinner { get; set; }

/// <summary>
/// Gets or sets the spinner style.
/// </summary>
public Style? SpinnerStyle { get; set; } = Color.Yellow;

/// <summary>
/// Gets or sets a value indicating whether or not status
/// should auto refresh. Defaults to <c>true</c>.
/// </summary>
public bool AutoRefresh { get; set; } = true;

/// <summary>
/// Initializes a new instance of the <see cref="Status"/> class.
/// </summary>
/// <param name="console">The console.</param>
public StatusExt(IAnsiConsole console)
{
_console = console ?? throw new ArgumentNullException(nameof(console));
}

/// <summary>
/// Starts a new status display.
/// </summary>
/// <param name="status">The status to display.</param>
/// <param name="action">The action to execute.</param>
public void Start(string status, Action<StatusContext> action)
{
var task = StartAsync(status, ctx =>
{
action(ctx);
return Task.CompletedTask;
});

task.GetAwaiter().GetResult();
}

/// <summary>
/// Starts a new status display.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="status">The status to display.</param>
/// <param name="func">The action to execute.</param>
/// <returns>The result.</returns>
public T Start<T>(string status, Func<StatusContext, T> func)
{
var task = StartAsync(status, ctx => Task.FromResult(func(ctx)));
return task.GetAwaiter().GetResult();
}

/// <summary>
/// Starts a new status display.
/// </summary>
/// <param name="status">The status to display.</param>
/// <param name="action">The action to execute.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StartAsync(string status, Func<StatusContext, Task> action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}

if (Console.IsOutputRedirected)
{
await action(new StatusContext()).ConfigureAwait(false);
return;
}

_ = await StartAsync<object?>(status, async statusContext =>
{
await action(statusContext).ConfigureAwait(false);
return default;
}).ConfigureAwait(false);
}

/// <summary>
/// Starts a new status display and returns a result.
/// </summary>
/// <typeparam name="T">The result type of task.</typeparam>
/// <param name="status">The status to display.</param>
/// <param name="func">The action to execute.</param>
/// <returns>A <see cref="Task{T}"/> representing the asynchronous operation.</returns>
public async Task<T> StartAsync<T>(string status, Func<StatusContext, Task<T>> func)
{
if (func is null)
{
throw new ArgumentNullException(nameof(func));
}

// Set the progress columns
var spinnerColumn = new SpinnerColumn(Spinner ?? Spinner.Known.Default)
{
Style = SpinnerStyle ?? Style.Plain,
};

var progress = new Progress(_console)
{
AutoClear = true,
AutoRefresh = AutoRefresh,
};

progress.Columns(new ProgressColumn[]
{
spinnerColumn,
new TaskDescriptionColumn(),
});



return await progress.StartAsync(async ctx =>
{
var statusContext = new StatusContext(ctx, ctx.AddTask(status), spinnerColumn);
return await func(statusContext).ConfigureAwait(false);
}).ConfigureAwait(false);
}
}

0 comments on commit 463c106

Please sign in to comment.