Code Monkey home page Code Monkey logo

shellprogressbar's Introduction

ShellProgressBar

visualize (concurrent) progress in your console application

This is a great little library to visualize long running command line tasks.

.NET Core ready!

It also supports spawning child progress bars which allows you to visualize dependencies and concurrency rather nicely.

Tested on OSX

example osx

and Windows

example win cmd

(Powershell works too, see example further down)

Install

Get it on nuget: http://www.nuget.org/packages/ShellProgressBar/

Usage

Usage is really straightforward

const int totalTicks = 10;
var options = new ProgressBarOptions
{
    ProgressCharacter = '─',
    ProgressBarOnBottom = true
};
using (var pbar = new ProgressBar(totalTicks, "Initial message", options))
{
    pbar.Tick(); //will advance pbar to 1 out of 10.
    //we can also advance and update the progressbar text
    pbar.Tick("Step 2 of 10"); 
}

Reporting progression

There are two ways to report progression. You can use the Tick() function as described above. Alternatively you can report progression through an IProgress<T> instance that you obtain by calling AsProgress<T>() on the progress bar object.

For a simple case where the progress type is a float value between 0.0 and 1.0 that represents the completion percentage, use progressBar.AsProgress<float>():

using ProgressBar progressBar = new ProgressBar(10000, "My Progress Message");
IProgress progress = progressBar.AsProgress<float>();
progress.Report(0.25); // Advances the progress bar to 25%

See IntegrationWithIProgressExample.cs and IntegrationWithIProgressPercentageExample.cs in the src/ShellProgressBar.Example/Examples directory for full examples.

Options

Progress bar position

const int totalTicks = 10;
var options = new ProgressBarOptions
{
	ProgressCharacter = '─',
	ProgressBarOnBottom = true
};
using (var pbar = new ProgressBar(totalTicks, "progress bar is on the bottom now", options))
{
	TickToCompletion(pbar, totalTicks, sleep: 500);
}

By default the progress bar is at the top and the message at the bottom. This can be flipped around if so desired.

bar_on_bottom

Styling changes

const int totalTicks = 10;
var options = new ProgressBarOptions
{
	ForegroundColor = ConsoleColor.Yellow,
	ForegroundColorDone = ConsoleColor.DarkGreen,
	BackgroundColor = ConsoleColor.DarkGray,
	BackgroundCharacter = '\u2593'
};
using (var pbar = new ProgressBar(totalTicks, "showing off styling", options))
{
	TickToCompletion(pbar, totalTicks, sleep: 500);
}

Many aspects can be styled including foreground color, background (inactive portion) and changing the color on completion.

styling

No real time update

By default a timer will draw the screen every 500ms. You can configure the progressbar to only be drawn when .Tick() is called.

const int totalTicks = 5;
var options = new ProgressBarOptions
{
	DisplayTimeInRealTime = false
};
using (var pbar = new ProgressBar(totalTicks, "only draw progress on tick", options))
{
	TickToCompletion(pbar, totalTicks, sleep:1750);
}

If you look at the time passed you will see it skips 02:00

update_on_tick

Descendant progressbars

A progressbar can spawn child progress bars and each child can spawn its own progressbars. Each child can have its own styling options.

This is great to visualize concurrent running tasks.

const int totalTicks = 10;
var options = new ProgressBarOptions
{
	ForegroundColor = ConsoleColor.Yellow,
	BackgroundColor = ConsoleColor.DarkYellow,
	ProgressCharacter = '─'
};
var childOptions = new ProgressBarOptions
{
	ForegroundColor = ConsoleColor.Green,
	BackgroundColor = ConsoleColor.DarkGreen,
	ProgressCharacter = '─'
};
using (var pbar = new ProgressBar(totalTicks, "main progressbar", options))
{
	TickToCompletion(pbar, totalTicks, sleep: 10, childAction: () =>
	{
		using (var child = pbar.Spawn(totalTicks, "child actions", childOptions))
		{
			TickToCompletion(child, totalTicks, sleep: 100);
		}
	});
}

children

By default children will collapse when done, making room for new/concurrent progressbars.

You can keep them around by specifying CollapseWhenFinished = false

var childOptions = new ProgressBarOptions
{
	ForegroundColor = ConsoleColor.Green,
	BackgroundColor = ConsoleColor.DarkGreen,
	ProgressCharacter = '─',
	CollapseWhenFinished = false
};

children_no_collapse

FixedDurationBar

ProgressBar is great for visualizing tasks with an unknown runtime. If you have a task that you know takes a fixed amount of time there is also a FixedDurationBar subclass. FixedDurationBar will Tick() automatically but other then that all the options and usage are the same. Except it relies on the real time update feature so disabling that will throw.

FixedDurationBar exposes an IsCompleted and CompletedHandle

Credits

The initial implementation was inspired by this article. http://www.bytechaser.com/en/articles/ckcwh8nsyt/display-progress-bar-in-console-application-in-c.aspx

And obviously anyone who sends a PR to this repository 👍

shellprogressbar's People

Contributors

0xced avatar bozhidar-a avatar diegosps avatar dlech avatar drehtisch avatar erickmcarvalho avatar gakera avatar gfs avatar hakakou avatar jonilviv avatar jstallm avatar kjaleshire avatar klemmchr avatar mandreko avatar mburtscher avatar mpdreamz avatar peter-shinydocs avatar sckelemen avatar teastears avatar thoemmi avatar toyz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

shellprogressbar's Issues

Timer broken in new Windows Terminal

In the new Windows Terminal.
When you start a new timer at the bottom of the terminal like this:
image

Each .Tick() breaks the progress bar up in multiple lines like this:
image

Repro steps

  1. Open a new "Windows terminal"
  2. Make sure you are at the bottom of the terminal
  3. Start a new progressbar

Expected
I dont want the progressbar to be broken in several lines.

Actual
The progressbar is broken up in several lines for each tick()

OBS
I get the same behavioure in a terminal in VS Code

Suggestion: Windows Taskbar progress

I think it would be cool if this library optionally displayed the progress in Windows Taskbar.

This can be done through TaskbarManager from Windows API Code Pack, or by p/invoking WinAPI directly. Console window handle can be obtained from

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetConsoleWindow();

Unfortunately I do not have time to do a proper implementation/pull request at the moment, so just an idea.

Readme drift

Hi there. Just grabbed your progress bar and I'm digging it. I noticed that you have a 4 argument constructor in the README showing a quick way to get up and running, but you have actually removed this overload and switched to the options style. Just wondering if you could add this to the readme for quick and easy up and running. Thanks and very much appreciate the progress bar.

Overflow on CJK or Full width character contained message

Hello! I love shellprogressbar.
duration column overflows on full-width characters such as CJK or Emoji contained message.
The program has no problem , but it looks like weired.
I think that Emoji will be used frequently in the future.

  • Expected
    expected
  • Actual
    actual

Child progress bars not working in powershell

Child progress bars do not render correctly in powershell or in the VS Code terminal. All the children write over the root progressbar instead of being stacked on top of each other.

I seems to only display correctly in the Windows command shell.

My options are set to : ```
ProgressBarOptions(
ForegroundColor = ConsoleColor.Yellow,
ForegroundColorDone = Nullable<>(ConsoleColor.DarkGreen),
BackgroundColor = Nullable<
>(ConsoleColor.DarkGray),
BackgroundCharacter = Nullable<_>('\u2593'),
ProgressBarOnBottom = true,
CollapseWhenFinished = false)

Crashes immediately in VS code

Pretty sure this is caused by the differing environment that VS code offers but the following code works in visual studio as a core 2.2 console app just fine. But opening it up in VS Code it crashes immediately on the using ProgressBar line.

           const int totalTicks = 10;
            var options = new ProgressBarOptions
            {
                ForegroundColor = ConsoleColor.Yellow,
                BackgroundColor = ConsoleColor.DarkYellow,
                ProgressCharacter = '─'
            };

            using (var pbar = new ProgressBar(totalTicks, "main progressbar", options))
            {
                for(var index = 0; index < 100; index++)
                {
                    pbar.Tick(index, "Test");
                    System.Threading.Thread.Sleep(500);
                }
            }

The exception message is:

Exception has occurred: CLR/System.IO.IOException
An unhandled exception of type 'System.IO.IOException' occurred in System.Console.dll: 'The handle is invalid'
at System.ConsolePal.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.get_CursorTop()
at ShellProgressBar.ProgressBar..ctor(Int32 maxTicks, String message, ProgressBarOptions options)
at DataTableTest.Program.Main(String[] args) in C:\Users\ekramer\Documents\VS Code Projects\DataTableTest\Program.cs:line 24

At this point theirs probably nothing that can be done until VS code matures a bit more but I figured I'd let you guys know so that people using VS code won't be surprised when this happens. Like I said it works just fine in Visual Studio.

Progress Bars take up more than one line

I've been trying to diagnose this, but haven't yet figured it out. When I use the progress bars, it seems like every tick of the timer results in a new level of the progress bar.

Imgur

Run progressbar as background Thread.Task

Hi, how it's possible to run progress bar inside of separated thread? I don't want to code this synchronously, because when i have task longer than 1 sec, then time is not updated until next Tick() is called.

Here is my wrapper class, that run Tick in while loop and it will update every 1/4 sec. Even when this task runs and Tick is called progress bar not updating. What do i do wrong? Thx.

using ShellProgressBar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace App.Infrastructure.Helpers
{
    class ProgressBarHelper
    {
        public virtual int ItemsCount { get; set; } = 0;
        public virtual int CurrentItem { get; set; } = 0;
        public virtual string Message { get; set; } = "";

        public ProgressBarHelper(int itemsCount)
        {
            ItemsCount = itemsCount;

            var options = new ProgressBarOptions
            {
                ProgressCharacter = '\u2588',
                ProgressBarOnBottom = true,
                ForegroundColor = ConsoleColor.White,
                ForegroundColorDone = ConsoleColor.White,
                BackgroundColor = ConsoleColor.DarkGray,
                BackgroundCharacter = '\u2593',
                DisplayTimeInRealTime = false
            };


            using (var pbar = new ProgressBar(ItemsCount, Message, options))
            {
                Task.Run(() =>
                {
                    while (CurrentItem < ItemsCount)
                    {
                        pbar.Tick(CurrentItem, Message);
                        Thread.Sleep(250);
                    }
                });
            }
        }

        public void Stop()
        {
            CurrentItem = ItemsCount;
        }

        public void Next(string message = null)
        {
            if(message != null)
            {
                Message = message;
            }
            CurrentItem++;
        }

        public void SetCurrent(int currentItem, string message = null)
        {
            if(message != null)
            {
                Message = message;
            }
            CurrentItem = currentItem;
        }
    }
}

System.ArgumentOutOfRangeException

Description: ProgressBar does not display in this console. All progress messages appear in a separate line. An exception (ArgumentOutOfRangeException) is raised just after I try disposing the progress bar. The progressBar.Percentage is 100.

Problem Console: Visual Studio 2019 Developer Command Prompt v16.4.3
Works On: PowerShell 5.1.17763.771, Visual Studio 2019 Debug Console, and on the usual Windows command prompt.

Exception Trace
System.ArgumentOutOfRangeException: The value must be greater than or equal to zero and less than the console's buffer size in that dimension. (Parameter 'top') Actual value was 300. at System.ConsolePal.SetCursorPosition(Int32 left, Int32 top) at System.Console.SetCursorPosition(Int32 left, Int32 top) at ShellProgressBar.ProgressBar.UpdateProgress() at ShellProgressBar.ProgressBar.Dispose()

PS: Thank you all for the great job.

High Tick Count performance Issues

When using a high amount for max ticks (i.e. 10k), the ticking itself requires a lot of cpu. The following code requires 40+ seconds on my machine even though its not really doing anything:

var progressBarOptions = new ProgressBarOptions()
{
    ProgressCharacter = '_'
};

using (var pbar = new ProgressBar(10000, "Test", progressBarOptions))
{
    for (var i = 0; i < pbar.MaxTicks; i++)
    {
        pbar.Tick();
    }
}

I didnt do any profiling but I assume its because of the redraw that occurs everytime ProgressBar.Tick() is called.

Since the realtime rendering uses a timer to update the rendering, i think it should be easily possible to implement. Maybe via an additional progress bar option or parameter to the progressbar constructor/tick function to disable redraw on tick - this would either require public access to the DisplayProgress method or it would force the use of the realtime update option.

Not working on Mac os

I am having this issue

Jonathans-MacBook-Pro:osx.10.11-x64 jonatthu$ ./Generatthor

Unhandled Exception: System.NotSupportedException: Task bar progress only works on Windows
at ShellProgressBar.ProgressBarOptions.set_EnableTaskBarProgress(Boolean value)
at Generatthor.Program.Bootstrap() in /Users/jonatthu/Documents/Jonatthu/Generatthor/Generatthor/Program.cs:line 43
at Generatthor.Program.Main(String[] args) in /Users/jonatthu/Documents/Jonatthu/Generatthor/Generatthor/Program.cs:line 100
Abort trap: 6
Jonathans-MacBook

Version

Crashes in Ubuntu 16.04

  1. Compiled under Windows:
    using (var pg = new ProgressBar(100, "Lalala")) {
    for (int i = 0; i < 10; i++) {
    Thread.Sleep(500); //pg.Tick(); <-commented
    } }
    `
    dotnet --version
    2.1.104

  1. Published for Ubuntu 16.04 under Windows:
    dotnet publish -c release -r ubuntu.16.04-x64

  1. Copied to Ubuntu 16.04

  1. Exception thrown by application running in Ubuntu 16.04:

Unhandled Exception: System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at ShellProgressBar.StringExtensions.Excerpt(String phrase, Int32 length)
at ShellProgressBar.ProgressBar.ProgressBarBottomHalf(Double percentage, DateTime startDate, Nullable`1 endDate, String message, Indentation[] indentation, Boolean progressBarOnBottom)
at ShellProgressBar.ProgressBar.DisplayProgress()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()

How to set progress bar length?

Hi. Great work!
Is it possible to add nullable property like progress bar length into ProgressBarOptions and use it instead of Console.WindowWidth if it set?
When console window 's widh is changed, progress bar looks not very well.

How to use `Progress<T>` and not the Ticks?

Currently to show the progress have to know upfront the maxTicks and simply increment the ticks. Is there a chance to use ProgressBar with Progress<T>?

In principle I'm looking for the capability to use

var progress = new Progress<double>(val => pbar.Percentage = val);

but this property exposes only getter and I can't find any other element that could do such a thing.

Child progress not displayed

I have some code essentially the same as below:

ProgressBarOptions options = new ProgressBarOptions
{
	ForegroundColor = ConsoleColor.Yellow,
	BackgroundColor = ConsoleColor.DarkYellow,
	ProgressCharacter = '─'
};
ProgressBarOptions childOptions = new ProgressBarOptions
{
	ForegroundColor =ConsoleColor.Green,
	BackgroundColor = ConsoleColor.DarkGreen,
	ProgressCharacter = '─',
	CollapseWhenFinished = false
};

int numChildren = 2;

using (var pbar = new ProgressBar(numChildren, "Total Progress", options))
{
	// Some prep code
	List<myObject> ReturnedResults1 = GetResults();
	using (var child = pbar.Spawn(ReturnedResults1.Count, "Child task 1", childOptions))
	{
		foreach(var result in ReturnedResults1)
		{
			// process result
			child.Tick();
		}
	}
	
	pbar.Tick();
	
	// Some more prep code
	List<myObject> ReturnedResults2 = GetResults2();
	
	using (var child = pbar.Spawn(ReturnedResults2.Count, "Child task 2", childOptions))
	{
		foreach(var result in ReturnedResults2)
		{
			// process result2
			child.Tick();
		}
	}
	pbar.Tick();
}
Console.WriteLine("Done.");

The "Total progress" displays and increments correctly as the code runs, but the two child progress bars are not displayed at all.

Once all the code is complete (it does all run to completion) there are about 6 blank lines after the total progress bar before the "Done" text.

Displaying outside console messages

Is there a way to send messages to the progress bar for it to display permanently? I am thinking of something like how gradle works.

Currently, the issue I am dealing with is that NLog is sending messages to the console and the cursor reset makes everything look janky. I have disabled console logging but would love a solution that could both display a progress bar and display permanent messages.

[FEATURE] Displaying ETA ?

I think that an option to display the estimate of ending time could be useful in many situations.
It could be implemented with a stopwatch measuring the time between each ProgressBar.Update
call to get the average time of a cycle (which is then multiplied according to what we want to show). This allows for multiple time display modes: elapsed/estimated total or estimated remaining time or anything else.

Change colour during progress

Is there anyway to change the colour after progressbar is initiated? Would be cool to shift colours based on status of the task.

Indeterminate Progress Bar Support

An important feature of progress bars is that they have an indeterminate mode, for situations when we want to convey to the user that we're still working, but we have no idea what the progress of the action is.

Is this something that could be added?

allow option to disable rendering for code that's ran by unit testers.

right now with in my unit tests getting invalid handle error;

"System.IO.IOException: The handle is invalid.
   at System.ConsolePal.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
   at System.Console.get_CursorTop()
   at ShellProgressBar.ProgressBar..ctor(Int32 maxTicks, String message, ProgressBarOptions options)

Bug in ProgressBarBase.Tick()

Hello!

Thanks for the great work on this project. Nice little library, very useful.

I discovered a bug in ProgressBarBase.Tick() in the latest version of the library that is published to NuGet (4.0.0). When you call Tick() with a newTickCount that is equal to the current tick count, the method doesn't simply leave the tick count unchanged -- it increments the tick count by one.

This caused some very strange behavior in my application, where a parent progress bar percentage occasionally appeared to be rolling back for a split second. This was occurring because the increment in progress for the child task was large enough to increase the tick for the child progress bar, but not for the parent progress bar. This resulted in a call to Tick() for the parent progress bar with a newTickCount equal to the current tick count, which caused the tick count to unexpectedly increment by one. If another small progress update occurred shortly thereafter, it would update the tick count to the original value -- causing it to appear to roll back by one tick.

Joe

Sample

Update the sample in Github, because the latest source code does not have a constructor with four parameters.

ProgressBar.WriteLine doesn't show recent messages

I will use a built-in test case as an example. I expect the built-in test case to work out of box.

Steps to reproduce:

clone this project and checkout c28355f

apply this patch

--- src/ShellProgressBar.Example/Examples/PersistMessageExample.cs: c28355ff	2021-02-06 11:26:24.000000000 +0800
+++ src/ShellProgressBar.Example/Examples/PersistMessageExample.cs: 	2021-02-06 11:22:24.000000000 +0800
@@ -46,12 +46,12 @@
 		private static void LongRunningTask(FixedDurationBar bar)
 		{
 			for (var i = 0; i < 1_000_000; i++)
 			{
 				bar.Message = $"{i} events";
 				if (bar.IsCompleted) break;
-				if (i % 500 == 0) bar.WriteLine($"Report {i} to console above the progressbar");
+				if (i % 5 == 0) bar.WriteLine($"Report {i} to console above the progressbar");
 				Thread.Sleep(1);
 			}
 		}
 	}
 }

Expected:

I expect to see
Report 15 to console above the progressbar
up to
Report 1000 to console above the progressbar
,etc. while the progrss bar is running.

Actual

Latest messages don't show. See the screenshot.
progress

WriteLine not work with .net Framework

I'm using with .Net framework .Nothing appears except the first line. I changed some of code parts , but console still not showing like the .net core example
image

Crashes in git bash

Maybe its expected since it´s not written any support, but it could be good to know that it doesnt work in git bash on windows, it fails:
Unhandled Exception: System.IO.IOException: The handle is invalid.

Splendid lib otherwise :-)

Does not play well with logging

I've got a console app that I'm looking to have a displayed progress (two layers deep) but also have log output to the console.

Unfortunately the logger (Serilog in my case) and ShellProgressBar don't play well with each other and are constantly overwriting each other which leaves the console an incomprehensible mess. Is there any way to prevent this or do I need to research how to make a custom Serilog console sink? Like maybe somehow force it to stick to certain lines or percentage of the screen or something?

thanks,
E

Using child progress bars causes main bar to jump up on console

Apologies for the unusual title.

I have a list of ~160 sub-lists, I set a main bar to track the process of iteration over the master list, and then a child bar to track progression through each sub-list.

Every time my app iterates over a sub-list, a child bar is added, however the main bar is pushed up a line and thus erases anything on said line. This is obviously less than ideal, and could be just my lack of knowledge regarding the settings of your application.

Other than that, it runs amazing!

Running time can't exceed 24 hours

The running time will reset to 0 when the total running time exceeds 24 hours. I left a program runs for straight two days, I checked the progress by the end of the first day, and it shows 21:04:30. Later when I check the time again on the third day morning, it only shows 9 hours something.

So I am assuming that the timer resets.

Multiple bars broke view in parallel

I'm trying display some information about tests in parallel, but look like component have some issue
image
image
var testResultsChannel = Channel.CreateUnbounded<(bool passed, string status, string error)>(); var optionsPass = new ProgressBarOptions { DenseProgressBar = true, ForegroundColor = ConsoleColor.Blue, ForegroundColorDone = ConsoleColor.DarkGreen, BackgroundColor = ConsoleColor.DarkGray, BackgroundCharacter = '\u2593', CollapseWhenFinished = false }; var optionsErr = new ProgressBarOptions { DenseProgressBar = true, ForegroundColor = ConsoleColor.Red, ForegroundColorDone = ConsoleColor.DarkRed, BackgroundColor = ConsoleColor.DarkGray, BackgroundCharacter = '\u2593', CollapseWhenFinished = false }; using (var pbar = new ProgressBar(UserCount, "Progress", optionsPass)) { ChildProgressBar pass = null; var status = new Dictionary<string, ChildProgressBar>(); while (true) { var tcResult = await testResultsChannel.Reader.ReadAsync().ConfigureAwait(false); if (tcResult.passed) { if (pass == null) { pass = pbar.Spawn(UserCount, "PASS", optionsPass); } pass.Tick(); pbar.Tick(); } else if (!string.IsNullOrEmpty(tcResult.error)) { if (!status.ContainsKey(tcResult.error)) { status.Add(tcResult.error, pbar.Spawn(UserCount, tcResult.error, optionsErr)); } status[tcResult.error].Tick(); pbar.Tick(); } else if (!string.IsNullOrEmpty(tcResult.status)) { if (!status.ContainsKey(tcResult.status)) { status.Add(tcResult.status, pbar.Spawn(UserCount, tcResult.status, optionsPass)); } status[tcResult.status].Tick(); } } }

Mono compatibility on a Mac

I made some changes so that this would work using Mono in a terminal on a Mac, are you interested in seeing them?

Only keep 10 child spawns

Hello,

I have a task that spawns 165 tasks (sequentially) and I would like to keep the history of tasks finished, but when spawning more than what the window can handle, sometimes the new child shows, sometimes it doesn't (but the program is still working and ticking).

Is there a way to limit the number of children to like 10? And only collapse old ones when the limit was reached?

Thank you!

how to test a project for useing ShellProgressBar?

I create a project using CommandLineUtils
and I use ShellProgressBar for my command ,when I use dotnet tool command,the ShellProgressBar works well.
But there are some bugs in my project,I want to fix them by UnitTest
then,I test my command like this

[Fact]
public void DownloadFileFromFtp()
{
  var content=new CommandLineApplication<DownloadFtp>();
    var services = new ServiceCollection()
        .AddLogging()
        .AddSingleton(Program.Configuration)
        .AddSingleton(Program.Configuration.Get<APPConfig>())
        .BuildServiceProvider();

    content.Conventions
        .UseDefaultConventions()
        .UseConstructorInjection(services);
    
    content.Parse();

    var result = content.Execute(@"--path=/CUSTDB/1901-0048.rar", "--taskid=1907-7777");//run the command

    result.Should().Be(0);
}

and then I will get System.IO.IOException: 句柄无效 error
the Stack Trace like this

Stack Trace: 
    ConsolePal.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
    Console.get_CursorTop()
    ProgressBar.ctor(Int32 maxTicks, String message, ProgressBarOptions options)
    DownloadFtp.SaveFileFromFtp(CommandLineApplication app, String remoteFilePath, String taskId) line 134

if I debug the UnitTest ,it will not get the error.

I think,the reason is UnitTest do not run in a shell
so,how can I solve this problem?
or,what is the right way to UnitTest ShellProgressBar?

[Suggestion] Add a way to continue displaying text under the progressbar

Sometimes I'd like to be more verbose about what the program does, doing something like

50.0% parsing done		      						00:10:07
===============================================---------------------------------------------
Parsing file 'hello world.txt'...
Done in 1.07s
Parsing file 'adasfadaad.txt'...
Done in 8.28s
Parsing file 'bank account passwords.txt'...
Done in 0.72s

Is there any changce it could be implemented? Even if not through Console.WriteLine("msg"), then at least via something like pbar.Write("msg")

Support to Int64 values of newTickCount and maxTicks

I need to proccess billions of records and show progress, so a sugest change parameters newTickCount, and maxTicks to Int64 intead of Int:

public void Tick(int newTickCount, TimeSpan estimatedDuration, string message = null);
public void Tick(int newTickCount, string message = null);
protected ProgressBarBase(int maxTicks, string message, ProgressBarOptions options);

net4x as a target framework

Hi,

Did you consider setting net4x framework as target framework? I know that netstandard is working well on everything, but when using "old csproj type" adding netstandard nuget results in additional dlls in binary directory. Binaries that are not really nessesary when targeting only .net 4.7 (for example).

It's not really a big issue, but it's kinda annoying. And i can't use new csproj for now (company legacy policy...)

Only two levels displayed if ProgressBarOnBottom = true

Example code:

                var progressBarOptions = new ProgressBarOptions
                {
                    CollapseWhenFinished = true,
                    ProgressBarOnBottom = true,
                    DisplayTimeInRealTime = true,
                    ForegroundColor = ConsoleColor.White
                };

                using (var l1Bar =
                    new ProgressBar(10, "Level 1", progressBarOptions))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        using (var l2Bar =
                            l1Bar.Spawn(10, $"Level 2 [{i}]", progressBarOptions))
                        {
                            for (int j = 0; j < 10; j++)
                            {
                                using (var l3Bar =
                                    l2Bar.Spawn(10, $"Level 3 [{j}]", progressBarOptions))
                                {
                                    for (int k = 0; k < 10; k++)
                                    {
                                        Thread.Sleep(200);
                                        l3Bar.Tick();
                                    }
                                }
                                l2Bar.Tick($"Level 2 [{i}]");
                            }
                        }
                        l1Bar.Tick();
                    }
                }

When ProgressBarOnBottom is set to true only two bars appear. When the option is commented out, all three will appear.

Feature request: Set progress by percentage

I would like to set the progress by percentage.

Something like this:

// Set progress to 10.7%
ProgressBar.SetPercentage(10.7);
// or
ProgressBar.SetPercentage(10.7m);

Currently using hardcoded 1000 ticks and:

ProgressBar.Tick((int)(progress / 0.1m));

Also would be nice to support a single digits after the comma separator, so it will display "10.7%" instead of "10.70%". Also because it's faster to read, and not as

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.