Created
January 12, 2021 03:44
-
-
Save patriksvensson/a9ccca4074af5f369f2ea6be7f2f164a to your computer and use it in GitHub Desktop.
A progress column for Spectre.Console that shows download progress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// A column showing download progress. | |
/// </summary> | |
public sealed class DownloadedColumn : ProgressColumn | |
{ | |
private static readonly string[] _suffixes = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; | |
private static readonly int _base = 1024; | |
/// <summary> | |
/// Gets or sets the <see cref="CultureInfo"/> to use. | |
/// </summary> | |
public CultureInfo? Culture { get; set; } | |
/// <inheritdoc/> | |
public override IRenderable Render(RenderContext context, ProgressTask task, TimeSpan deltaTime) | |
{ | |
var (unit, suffix, precision) = GetUnitAndSuffix(task.MaxValue); | |
var completed = Format(task.Value / unit, precision); | |
var totalString = Format(task.MaxValue / unit, precision); | |
return new Text($"{completed}/{totalString} {suffix}"); | |
} | |
private string Format(double value, int precision) | |
{ | |
return precision == 0 | |
? ((int)value).ToString(Culture ?? CultureInfo.CurrentCulture) | |
: value.ToString("0.#", Culture ?? CultureInfo.CurrentCulture); | |
} | |
private (double Unit, string Suffix, int Precision) GetUnitAndSuffix(double size) | |
{ | |
var unit = 0D; | |
var suffix = string.Empty; | |
var precision = 0; | |
for (var index = 0; index < _suffixes.Length; index++) | |
{ | |
unit = Math.Pow(_base, index); | |
if (size < (unit * _base)) | |
{ | |
suffix = _suffixes[index]; | |
precision = index == 0 ? 0 : 1; | |
break; | |
} | |
} | |
if (string.IsNullOrWhiteSpace(suffix)) | |
{ | |
suffix = _suffixes[0]; | |
precision = 0; | |
} | |
return (unit, suffix, precision); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment