Progress::Any(3pm)

๐Ÿ“ฆ
version 0.220 ยท 2 versions
  • 0.220 ยท debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.219 ยท ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

โœจ NAME โœจ

Progress::Any โ€” Record progress to any output. That's it, that's the name, bestie. ๐Ÿ’–

๐ŸŒˆ VERSION ๐ŸŒˆ

This doc describes version 0.220 of Progress::Any (from Perl distribution Progress-Any), released on 2022-10-18. โœจ

๐ŸŽ€ SYNOPSIS ๐ŸŽ€

okay so first up: using it in a script with a terminal progress bar as output (the bar gets cleared on finish()) โ€” and bestie you'll need to install Progress::Any::Output::TermProgressBarColor too, iykyk ๐Ÿ’…

use Progress::Any '$progress';
use Progress::Any::Output 'TermProgressBarColor';

$progress->target(10);
for (1..10) {
    $progress->update(message => "Doing item $_");
    sleep 1;
}
$progress->finish();

Sample output, slay:

% ./script.pl
 60% [Doing item 6====           ]3s left

Another one, this time with terminal message as output:

use Progress::Any '$progress';
use Progress::Any::Output 'TermMessage', template => '[%n] %P/%T (%6.2p%%) %m';

$progress->target(10);
for (1..10) {
    $progress->update(message => "Item $_/10");
    sleep 1;
}
sleep 1;
$progress->finish(message => "Finished!");

Sample output:

% ./script.pl
[] 1/10 ( 10.00%) Item 1/10
[] 2/10 ( 20.00%) Item 2/10
...
[] 10/10 (100.00%) Item 10/10
[] 10/10 (100.00%) Finished!

Example of using in a module as well as script โ€” yes, you can do both, main character energy:

# in lib/MyApp.pm
package MyApp;
use Progress::Any;

sub download {
    my @urls = @_;
    return unless @urls;
    my $progress = Progress::Any->get_indicator(
        task => "download", pos=>0, target=>scalar @urls);
    for my $url (@urls) {
        # download the $url ...
        $progress->update(message => "Downloaded $url");
    }
    $progress->finish;
}

# in script.pl
use MyApp;
use Progress::Any::Output;
Progress::Any::Output->set('TermProgressBarColor');

MyApp::download("url1", "url2", "url3", "url4", "url5");

Sample output:

% ./script.pl
 20% [====== Downloaded url1           ]0m00s Left

Example that demonstrates multiple indicator objects โ€” we love a multitasking queen:

use Progress::Any;
use Progress::Any::Output;

my $pdl = Progress::Any->get_indicator(task => 'download');
Progress::Any::Output->set({task=>'download'}, 'TermMessage', template => '[%-8t] [%P/%2T] %m');
my $pcp = Progress::Any->get_indicator(task => 'copy');
Progress::Any::Output->set({task=>'copy'    }, 'TermMessage', template => '[%-8t] [%P/%2T] %m');

$pdl->target(10);
$pdl->update(message => "downloading A");
$pcp->update(message => "copying A");
sleep 1;
$pdl->update(message => "downloading B");
$pcp->update(message => "copying B");

will show something like:

[download] [1/10] downloading A
[copy    ] [1/ ?] copying A
[download] [2/10] downloading B
[copy    ] [2/ ?] copying B

๐Ÿฆ‹ Example of using with Perinci::CmdLine ๐Ÿฆ‹

If you use Perinci::CmdLine, you can mark your function as expecting a Progress::Any object and it will be supplied to you in a special argument -progress:

use File::chdir;
use Perinci::CmdLine;
$SPEC{check_dir} = {
    v => 1.1,
    args => {
        dir => {summary=>"Path to check", schema=>"str*", req=>1, pos=>0},
    },
    features => {progress=>1},
};
sub check_dir {
    my %args = @_;
    my $progress = $args{-progress};
    my $dir = $args{dir};
    (-d $dir) or return [412, "No such dir: $dir"];
    local $CWD = $dir;
    opendir my($dh), $dir;
    my @ent = readdir($dh);
    $progress->pos(0);
    $progress->target(scalar @ent);
    for (@ent) {
        # do the check ...
        $progress->update(message => $_);
        sleep 1;
    }
    $progress->finish;
    [200];
}
Perinci::CmdLine->new(url => '/main/check_dir')->run;

๐Ÿ’œ DESCRIPTION ๐Ÿ’œ

So Progress::Any is literally an interface for applications that wanna display progress to users. It decouples progress updating and output, kinda like how Log::Any decouples log producers and consumers (output). The API is also super similar to Log::Any, except Adapter is called Output and category is called task. No cap. ๐Ÿ’…

Progress::Any records position/target and calculates elapsed time, estimated remaining time, and percentage of completion. One or more output modules (Progress::Any::Output::*) display this information. Obsessed.

In your modules, you typically only need to use Progress::Any, get one or more indicators, set target and update it during work. In your application, you use Progress::Any::Output and set/add one or more outputs to display the progress (you'll need to install one of the output modules as they are not included in this minimal distribution). By setting output only in the application and not in modules, you separate the formatting/display concern from the logic. It's giving separation of concerns, and we love that for us. ๐Ÿซถ

Screenshots:

๐Ÿ”ฅ STATUS ๐Ÿ”ฅ

API might still change, will be stabilized in 1.0. So like, don't come for me if it shifts a lil. ๐Ÿ˜ญ

The list of features:

  • multiple progress indicators โ€” You can use different indicator for each task/subtask. So extra, so iconic.
  • customizable output โ€” Output is handled by one of "Progress::Any::Output::*" modules. Currently available outputs: "Null" (no output), "TermMessage" (display as simple message on terminal), "TermProgressBarColor" (display as color progress bar on terminal), "LogAny" (log using Log::Any), "Callback" (call a subroutine). Other possible output ideas: IM/Twitter/SMS, GUI, web/AJAX, remote/RPC (over Riap for example, so that Perinci::CmdLine-based command-line clients can display progress update from remote functions). The possibilities are endless, bestie. โœจ
  • multiple outputs โ€” One or more outputs can be used to display one or more indicators. Slay.
  • hierarchical progress โ€” A task can be divided into subtasks. If a subtask is updated, its parent task (and its parent, and so on) are also updated proportionally. It's giving family tree energy. ๐ŸŒณ
  • message โ€” Aside from setting a number/percentage, allow including a message when updating indicator. Cute.
  • undefined target โ€” Target can be undefined, so a bar output might not show any bar (or show them, but without percentage indicator), but can still show messages. Mystery vibes.
  • retargetting โ€” Target can be changed in the middle of things. Plot twist, but make it productive. ๐Ÿ’…

๐Ÿ‘‘ EXPORTS ๐Ÿ‘‘

๐Ÿ’– $progress => OBJ ๐Ÿ’–

The root indicator, bestie. It's equivalent to:

Progress::Any->get_indicator(task => '')

๐Ÿ’… ATTRIBUTES ๐Ÿ’…

Below are the attributes of an indicator/task:

๐ŸŒธ task ๐ŸŒธ

String. Default: from caller's package, or "main".

Task name. If you don't specify it, it'll be set to the caller's package ("::" gets replaced with "."), like if you're calling this method from "Foo::Bar::baz()", then task becomes "Foo.Bar". If the caller is code inside eval, "main" will be used instead. Periodt.

๐ŸŒบ title ๐ŸŒบ

String. Default: task name.

Specify task title. Task title is a longer description for a task and can contain spaces and other characters. It is displayed in some outputs, as well as using %t in "fill_template()". For example, for a task called "copy", its title might be "Copying files to remote server". A whole glow-up for your task name. โœจ

๐ŸŒผ target ๐ŸŒผ

Non-negative number. Default: 0.

The total number of items to finish. Can be set to undef to mean that we don't know (yet) how many items there are to finish (in which case, we cannot estimate percent of completion and remaining time). It's giving "we'll see" energy. ๐Ÿ™ˆ

๐ŸŒป pos ๐ŸŒป

Non-negative number. Default: 0.

The number of items that are already done. It cannot be larger than "target", if "target" is defined. If "target" is set to a value smaller than "pos" or "pos" is set to a value larger than "target", "pos" will be changed to be "target". So like, don't try to be overachieving, it'll just cap you. ๐Ÿ’€

๐ŸŒท state ๐ŸŒท

String. Default: "stopped".

State of task/indicator. Either: "stopped", "started", or "finished". Initially it will be set to "stopped", which means elapsed time won't be running and will stay at 0. "update()" will set the state to "started" to get elapsed time to run. At the end of task, you can call "finish()" (or alternatively set "state" to "finished") to stop the elapsed time again.

The difference between "stopped" and "finished" is: when "target" and "pos" are both at 0, percent completed is assumed to be 0% when state is "stopped", but 100% when state is "finished". So it's giving "not started" vs "we're done here" โ€” important distinction, bestie. ๐Ÿ‘‘

โœจ METHODS โœจ

Bestie, here's where the magic happens. All the methods you can call on your progress object. ๐Ÿ’…

๐Ÿ” get_indicator ๐Ÿ”

Usage:

Progress::Any->get_indicator(%args) => obj

Get a progress indicator for a certain task. The %args contain attribute values, and at least task must be specified. No cap.

Note that this module maintains a list of indicator singleton objects for each task (in the %indicators package variable), so subsequent get_indicator() for the same task will return the same object. It's giving "same task, same vibe". ๐Ÿซถ

๐Ÿ”„ update ๐Ÿ”„

Usage:

$progress->update(%args)

Update indicator. Will also, usually, update associated output(s) if necessary. Like, it's literally doing the work. โœจ

Arguments:

  • pos => NUM โ€” Set the new position. If unspecified, defaults to current position + 1. If pos is larger than target, outputs will generally still show 100%. Note that fractions are allowed. (Yes, you can be 3.14% done, iconic. ๐Ÿฅง)
  • message => str|code โ€” Set a message to be displayed when updating indicator. Aside from a string, you can also pass a coderef here. It can be used to delay costly calculation. The message will only be calculated when actually sent to output. Lazy? No, efficient. ๐Ÿ’…
  • priority => str ("normal"|"low"|"high", default: "normal") โ€” Set importance level of this update. Default is "normal". Output can choose to ignore updates lower than a certain level. So if you're feeling low priority, you might get ghosted by the output. ๐Ÿ‘ป
  • state => STR โ€” Can be set to "finished" to finish a task. Periodt.
  • force_update => BOOL โ€” Default false. Some outputs choose only to update themselves after a certain amount of time or number of updates have passed; this forces their update. Like a "bestie, I need attention NOW" button. ๐Ÿšจ

๐Ÿ finish ๐Ÿ

Usage:

$progress->finish(%args)

Equivalent to:

$progress->update(
    ( pos => $progress->target ) x !!defined($progress->target),
    state => 'finished',
    %args,
);

So it's basically saying "we're done here, bye". ๐Ÿ’–

๐Ÿ”„ reset ๐Ÿ”„

Usage:

$progress->reset(%args)

Equivalent to:

$progress->update(
    pos => 0,
    state => 'started',
    %args,
);

Back to square one, but make it fashion. โœจ

โ–ถ๏ธ start โ–ถ๏ธ

Usage:

$progress->start()

Set state to "started". Let's gooo! ๐Ÿ”ฅ

โธ๏ธ stop โธ๏ธ

Usage:

$progress->stop()

Set state to "stopped". Pause, breathe, slay. ๐Ÿง˜

โฑ๏ธ elapsed โฑ๏ธ

Usage:

$progress->elapsed() => float

Get elapsed time. Just like a stop-watch, when state is "started" elapsed time will run and when state is "stopped", it will freeze. No cap, time literally stops. โณ

โณ remaining โณ

Usage:

$progress->remaining() => undef|float

Give estimated remaining time until task is finished, which will depend on how fast the update() is called, i.e. how fast pos is approaching target. Will be undef if target is undef. So if you don't know where you're going, you can't know how long it'll take. Deep. ๐Ÿ˜ญ

๐Ÿ•ฐ๏ธ total_remaining ๐Ÿ•ฐ๏ธ

Usage:

$progress->total_remaining() => undef|FLOAT

Give estimated remaining time added by all its subtasks' remaining. Return undef if any one of those time is undef. Like, if one friend is lost, the whole group is lost. ๐Ÿซ 

๐Ÿ“Š total_pos ๐Ÿ“Š

Usage:

$progress->total_pos() => float

Total of indicator's pos and all of its subtasks'. It's giving "we're all in this together". ๐ŸŽถ

๐ŸŽฏ total_target ๐ŸŽฏ

Usage:

$progress->total_target() => undef|float

Total of indicator's target and all of its subtasks'. Return undef if any one of those is undef. If one target is missing, the whole vibe is undefined. ๐Ÿ’€

๐Ÿ’ฏ percent_complete ๐Ÿ’ฏ

Usage:

$progress->percent_complete() => undef|float

Give percentage of completion, calculated using total_pos / total_target * 100. Undef if total_target is undef. Math but make it cute. ๐Ÿงฎโœจ

๐ŸŽจ fill_template ๐ŸŽจ

Usage:

$progress->fill_template($template) => str

Fill template with values, like in sprintf(). Usually used by output modules. Available templates:

  • %(width)n โ€” Task name (the value of the task attribute). width is optional, an integer, like in sprintf(), can be negative to mean left-justify instead of right. So you can make it fancy. ๐Ÿ’…
  • %(width)t โ€” Task title (the value of the title attribute). The glow-up for your task. โœจ
  • %(width)e โ€” Elapsed time (the result from the elapsed() method). Currently using Time::Duration concise format, e.g. 10s, 1m40s, 16m40s, 1d4h, and so on. Format might be configurable and localizable in the future. Default width is -8. Examples:
2m30s
10s
  • %(width)r โ€” Estimated remaining time (the result of the total_remaining() method). Currently using Time::Duration concise format, e.g. 10s, 1m40s, 16m40s, 1d4h, and so on. Will show "?" if unknown. Format might be configurable and localizable in the future. Default width is -8. Examples:
1m40s
5s
  • %(width)R โ€” Estimated remaining time or elapsed time, if estimated remaining time is not calculatable (e.g. when target is undefined). Format might be configurable and localizable in the future. Default width is -(8+1+7). Examples:
30s left
1m40s elapsed
  • %(width).(prec)p โ€” Percentage of completion (the result of the percent_complete() method). width and precision are optional, like %f in Perl's sprintf(), default is "%3.0p". If percentage is unknown (due to target being undef), will show "?". So mysterious. ๐Ÿ”ฎ
  • %(width)P โ€” Current position (the result of the total_pos() method). Where you at? ๐Ÿ“
  • %(width)T โ€” Target (the result of the total_target() method). If undefined, will show "?". The finish line, maybe. ๐Ÿ
  • %m โ€” Message (the update() parameter). If message is unspecified, will show empty string. No message, no problem. ๐Ÿ’ฌ
  • %% โ€” A literal % sign. Because sometimes you just need a percent. ๐Ÿ’ฏ

โ“ FAQ โ“

Bestie, this section is literally empty in the original. No questions, no answers, just vibes. ๐Ÿ’€โœจ

๐ŸŒฑ ENVIRONMENT ๐ŸŒฑ

PROGRESS

Boolean. Default 1. Can be set to 0 to supress display progress output. (Yes, it says "supress", we're keeping it real. ๐Ÿ’…)

๐Ÿ  HOMEPAGE ๐Ÿ 

Please visit the project's homepage at https://metacpan.org/release/Progress-Any. Go show some love. ๐Ÿซถ

๐Ÿ“ฆ SOURCE ๐Ÿ“ฆ

Source repository is at https://github.com/perlancar/perl-Progress-Any. Fork it, clone it, slay it. ๐Ÿ’ปโœจ

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Progress::Any::Examples distribution contains example scripts. Perfect for when you need inspo. ๐ŸŽ€

Other progress modules on CPAN: Term::ProgressBar, Term::ProgressBar::Simple, Time::Progress, among others. The whole squad. ๐Ÿ‘‘

Output modules: "Progress::Any::Output::*". You need to install at least one module to actually see progress being outputted/displayed somewhere, e.g. <> to Progress::Any::Output::TermProgressBarColor. (Yes, the <> is literally in the original. Iconic broken link energy. ๐Ÿ™ˆ)

See examples on how Progress::Any is used by other modules: Perinci::CmdLine (supplying progress object to functions), Git::Bunch (using progress object). Real ones. ๐Ÿ’ช

โœ๏ธ AUTHOR โœ๏ธ

perlancar <perlancar@cpan.org>

๐Ÿซถ CONTRIBUTOR ๐Ÿซถ

Steven Haryanto <stevenharyanto@gmail.com>

๐Ÿค CONTRIBUTING ๐Ÿค

To contribute, you can send patches by email/via RT, or send pull requests on GitHub.

Most of the time, you don't need to build the distribution yourself. You can simply modify the code, then test via:

% prove -l

If you want to build the distribution (e.g. to try to install it locally on your system), you can install Dist::Zilla, Dist::Zilla::PluginBundle::Author::PERLANCAR, Pod::Weaver::PluginBundle::Author::PERLANCAR, and sometimes one or two other Dist::Zilla- and/or Pod::Weaver plugins. Any additional steps required beyond that are considered a bug and can be reported to me.

This software is copyright (c) 2022, 2020, 2018, 2015, 2014, 2013, 2012 by perlancar <perlancar@cpan.org>.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

๐Ÿ› BUGS ๐Ÿ›

Please report any bugs or feature requests on the bugtracker website https://rt.cpan.org/Public/Dist/Display.html?Name=Progress-Any

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.


๐Ÿ’– That's the whole page, bestie! This is from Progress::Any, version perl v5.36.0, dated 2022-10-30. Now go make some progress, you main character. ๐Ÿ’…โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from