From 463c1063fe399f740f9f90bec944217e2dc02836 Mon Sep 17 00:00:00 2001 From: Michiel van Oudheusden Date: Fri, 22 Dec 2023 17:15:27 +0100 Subject: [PATCH] When Output is redirected, do not output the status indicators --- .../AccumulatedCost/AccumulatedCostCommand.cs | 4 +- .../CostByResource/CostByResourceCommand.cs | 2 +- src/Commands/CostByTag/CostByTagCommand.cs | 2 +- src/Commands/DailyCost/DailyCost.cs | 2 +- src/Commands/WhatIf/DevTestWhatIfCommand.cs | 2 +- src/Commands/WhatIf/RegionWhatIfCommand.cs | 2 +- .../SpectreConsole/AnsiConsoleExt.cs | 15 ++ .../SpectreConsole/StatusContext.cs | 94 ++++++++++++ .../SpectreConsole/StatusExt.cs | 144 ++++++++++++++++++ 9 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 src/OutputFormatters/SpectreConsole/AnsiConsoleExt.cs create mode 100644 src/OutputFormatters/SpectreConsole/StatusContext.cs create mode 100644 src/OutputFormatters/SpectreConsole/StatusExt.cs diff --git a/src/Commands/AccumulatedCost/AccumulatedCostCommand.cs b/src/Commands/AccumulatedCost/AccumulatedCostCommand.cs index 5445fe1..f3a80d8 100644 --- a/src/Commands/AccumulatedCost/AccumulatedCostCommand.cs +++ b/src/Commands/AccumulatedCost/AccumulatedCostCommand.cs @@ -84,9 +84,11 @@ public override async Task 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..."; diff --git a/src/Commands/CostByResource/CostByResourceCommand.cs b/src/Commands/CostByResource/CostByResourceCommand.cs index 8bc8de3..3c764a8 100644 --- a/src/Commands/CostByResource/CostByResourceCommand.cs +++ b/src/Commands/CostByResource/CostByResourceCommand.cs @@ -88,7 +88,7 @@ public override async Task ExecuteAsync(CommandContext context, CostByResou // Fetch the costs from the Azure Cost Management API IEnumerable resources = new List(); - await AnsiConsole.Status() + await AnsiConsoleExt.Status() .StartAsync("Fetching cost data for resources...", async ctx => { resources = await _costRetriever.RetrieveCostForResources( diff --git a/src/Commands/CostByTag/CostByTagCommand.cs b/src/Commands/CostByTag/CostByTagCommand.cs index ef1eb66..76d1c33 100644 --- a/src/Commands/CostByTag/CostByTagCommand.cs +++ b/src/Commands/CostByTag/CostByTagCommand.cs @@ -87,7 +87,7 @@ public override async Task ExecuteAsync(CommandContext context, CostByTagSe // Fetch the costs from the Azure Cost Management API IEnumerable resources = new List(); - await AnsiConsole.Status() + await AnsiConsoleExt.Status() .StartAsync("Fetching cost data for resources...", async ctx => { resources = await _costRetriever.RetrieveCostForResources( diff --git a/src/Commands/DailyCost/DailyCost.cs b/src/Commands/DailyCost/DailyCost.cs index 92b1e95..a0707ff 100644 --- a/src/Commands/DailyCost/DailyCost.cs +++ b/src/Commands/DailyCost/DailyCost.cs @@ -86,7 +86,7 @@ public override async Task ExecuteAsync(CommandContext context, DailyCostSe IEnumerable dailyCost = new List(); - await AnsiConsole.Status() + await AnsiConsoleExt.Status() .StartAsync("Fetching daily cost data...", async ctx => { // Fetch the costs from the Azure Cost Management API diff --git a/src/Commands/WhatIf/DevTestWhatIfCommand.cs b/src/Commands/WhatIf/DevTestWhatIfCommand.cs index 8c164d6..af7f372 100644 --- a/src/Commands/WhatIf/DevTestWhatIfCommand.cs +++ b/src/Commands/WhatIf/DevTestWhatIfCommand.cs @@ -67,7 +67,7 @@ public override async Task ExecuteAsync(CommandContext context, WhatIfSetti - await AnsiConsole.Status() + await AnsiConsoleExt.Status() .StartAsync("Fetching cost data for resources...", async ctx => { resources = await _costRetriever.RetrieveCostForResources( diff --git a/src/Commands/WhatIf/RegionWhatIfCommand.cs b/src/Commands/WhatIf/RegionWhatIfCommand.cs index 2d20b7f..79233b9 100644 --- a/src/Commands/WhatIf/RegionWhatIfCommand.cs +++ b/src/Commands/WhatIf/RegionWhatIfCommand.cs @@ -63,7 +63,7 @@ public override async Task ExecuteAsync(CommandContext context, WhatIfSetti IEnumerable resources; Dictionary> pricesByRegion = new(); - await AnsiConsole.Status() + await AnsiConsoleExt.Status() .StartAsync("Fetching cost data for resources...", async ctx => { resources = await _costRetriever.RetrieveUsageDetails( diff --git a/src/OutputFormatters/SpectreConsole/AnsiConsoleExt.cs b/src/OutputFormatters/SpectreConsole/AnsiConsoleExt.cs new file mode 100644 index 0000000..d3b69a3 --- /dev/null +++ b/src/OutputFormatters/SpectreConsole/AnsiConsoleExt.cs @@ -0,0 +1,15 @@ +using AzureCostCli.OutputFormatters.SpectreConsole; + +namespace Spectre.Console; + +public static partial class AnsiConsoleExt +{ + /// + /// Creates a new instance. + /// + /// A instance. + public static StatusExt Status() + { + return new StatusExt(AnsiConsole.Console); + } +} \ No newline at end of file diff --git a/src/OutputFormatters/SpectreConsole/StatusContext.cs b/src/OutputFormatters/SpectreConsole/StatusContext.cs new file mode 100644 index 0000000..0e81551 --- /dev/null +++ b/src/OutputFormatters/SpectreConsole/StatusContext.cs @@ -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; + + /// + /// Gets or sets the current status. + /// + public string Status + { + get => _task?.Description; + set => SetStatus(value); + } + + /// + /// Gets or sets the current spinner. + /// + public Spinner Spinner + { + get => _spinnerColumn.Spinner; + set => SetSpinner(value); + } + + /// + /// Gets or sets the current spinner style. + /// + 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)); + } + + /// + /// Refreshes the status. + /// + 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; + } +} \ No newline at end of file diff --git a/src/OutputFormatters/SpectreConsole/StatusExt.cs b/src/OutputFormatters/SpectreConsole/StatusExt.cs new file mode 100644 index 0000000..b2b13a3 --- /dev/null +++ b/src/OutputFormatters/SpectreConsole/StatusExt.cs @@ -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; + + /// + /// Gets or sets the spinner. + /// + public Spinner? Spinner { get; set; } + + /// + /// Gets or sets the spinner style. + /// + public Style? SpinnerStyle { get; set; } = Color.Yellow; + + /// + /// Gets or sets a value indicating whether or not status + /// should auto refresh. Defaults to true. + /// + public bool AutoRefresh { get; set; } = true; + + /// + /// Initializes a new instance of the class. + /// + /// The console. + public StatusExt(IAnsiConsole console) + { + _console = console ?? throw new ArgumentNullException(nameof(console)); + } + + /// + /// Starts a new status display. + /// + /// The status to display. + /// The action to execute. + public void Start(string status, Action action) + { + var task = StartAsync(status, ctx => + { + action(ctx); + return Task.CompletedTask; + }); + + task.GetAwaiter().GetResult(); + } + + /// + /// Starts a new status display. + /// + /// The result type. + /// The status to display. + /// The action to execute. + /// The result. + public T Start(string status, Func func) + { + var task = StartAsync(status, ctx => Task.FromResult(func(ctx))); + return task.GetAwaiter().GetResult(); + } + + /// + /// Starts a new status display. + /// + /// The status to display. + /// The action to execute. + /// A representing the asynchronous operation. + public async Task StartAsync(string status, Func action) + { + if (action is null) + { + throw new ArgumentNullException(nameof(action)); + } + + if (Console.IsOutputRedirected) + { + await action(new StatusContext()).ConfigureAwait(false); + return; + } + + _ = await StartAsync(status, async statusContext => + { + await action(statusContext).ConfigureAwait(false); + return default; + }).ConfigureAwait(false); + } + + /// + /// Starts a new status display and returns a result. + /// + /// The result type of task. + /// The status to display. + /// The action to execute. + /// A representing the asynchronous operation. + public async Task StartAsync(string status, Func> 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); + } + }