wp-cli / php-cli-tools

A collection of tools to help with PHP command line utilities
MIT License
673 stars 118 forks source link

Wrong expected total time in progress bar when make_progress_bar used multiple times #144

Closed ctzkane closed 11 months ago

ctzkane commented 3 years ago

Using make_progress_bar multiple times in a WP_CLI command displays wrong expected total time after the first use.

Repro:

Consider the following cli command

class TestMultipleProgressBars {
    private function run($message) {
        $progress = \WP_CLI\Utils\make_progress_bar($message, 10);
        $i = 10;
        while ($i-- >= 0) {
            sleep(1);
            $progress->tick();
        }
        $progress->finish();
        $progress->reset();
        unset($progress);
    }
    public function multiple_progress_bars() {
        $this->run('1st pass');
        $this->run('2nd pass');
        $this->run('3rd pass');
    }
}
WP_CLI::add_command('test', 'TestMultipleProgressBars');

running this results in the following STDOUT output

$ wp test multiple_progress_bars
1st pass  100% [====================================] 0:10 / 0:10
2nd pass  100% [====================================] 0:10 / 0:21
3rd pass  100% [====================================] 0:10 / 0:32

The expected result should read 0:10 as the expected time for the 2nd and 3rd pass. The numbers shown during the execution are also wrong, calculating a much higher time when each subsequent pass starts.

This is due to the usage of static function variables in php-cli-tools lib/cli/Notify.php

    public function speed() {       
              static $tick, $iteration = 0, $speed = 0;

The fix would be to convert those as member variables of the class, or somehow reset them when the Reset method is called.

danielbachhuber commented 11 months ago

Thanks for the @ctzkane! This definitely looks like a bug, and I agree with your assessment on the cause.

Feel free to submit a pull request, if you'd like. Here is some guidance on our pull request best practices.