ProgressBar.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Cursor;
  12. use Symfony\Component\Console\Exception\LogicException;
  13. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  14. use Symfony\Component\Console\Output\ConsoleSectionOutput;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Terminal;
  17. /**
  18. * The ProgressBar provides helpers to display progress output.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. * @author Chris Jones <leeked@gmail.com>
  22. */
  23. final class ProgressBar
  24. {
  25. public const FORMAT_VERBOSE = 'verbose';
  26. public const FORMAT_VERY_VERBOSE = 'very_verbose';
  27. public const FORMAT_DEBUG = 'debug';
  28. public const FORMAT_NORMAL = 'normal';
  29. private const FORMAT_VERBOSE_NOMAX = 'verbose_nomax';
  30. private const FORMAT_VERY_VERBOSE_NOMAX = 'very_verbose_nomax';
  31. private const FORMAT_DEBUG_NOMAX = 'debug_nomax';
  32. private const FORMAT_NORMAL_NOMAX = 'normal_nomax';
  33. private int $barWidth = 28;
  34. private string $barChar;
  35. private string $emptyBarChar = '-';
  36. private string $progressChar = '>';
  37. private ?string $format = null;
  38. private ?string $internalFormat = null;
  39. private ?int $redrawFreq = 1;
  40. private int $writeCount = 0;
  41. private float $lastWriteTime = 0;
  42. private float $minSecondsBetweenRedraws = 0;
  43. private float $maxSecondsBetweenRedraws = 1;
  44. private OutputInterface $output;
  45. private int $step = 0;
  46. private int $startingStep = 0;
  47. private ?int $max = null;
  48. private int $startTime;
  49. private int $stepWidth;
  50. private float $percent = 0.0;
  51. private array $messages = [];
  52. private bool $overwrite = true;
  53. private Terminal $terminal;
  54. private ?string $previousMessage = null;
  55. private Cursor $cursor;
  56. private array $placeholders = [];
  57. private static array $formatters;
  58. private static array $formats;
  59. /**
  60. * @param int $max Maximum steps (0 if unknown)
  61. */
  62. public function __construct(OutputInterface $output, int $max = 0, float $minSecondsBetweenRedraws = 1 / 25)
  63. {
  64. if ($output instanceof ConsoleOutputInterface) {
  65. $output = $output->getErrorOutput();
  66. }
  67. $this->output = $output;
  68. $this->setMaxSteps($max);
  69. $this->terminal = new Terminal();
  70. if (0 < $minSecondsBetweenRedraws) {
  71. $this->redrawFreq = null;
  72. $this->minSecondsBetweenRedraws = $minSecondsBetweenRedraws;
  73. }
  74. if (!$this->output->isDecorated()) {
  75. // disable overwrite when output does not support ANSI codes.
  76. $this->overwrite = false;
  77. // set a reasonable redraw frequency so output isn't flooded
  78. $this->redrawFreq = null;
  79. }
  80. $this->startTime = time();
  81. $this->cursor = new Cursor($output);
  82. }
  83. /**
  84. * Sets a placeholder formatter for a given name, globally for all instances of ProgressBar.
  85. *
  86. * This method also allow you to override an existing placeholder.
  87. *
  88. * @param string $name The placeholder name (including the delimiter char like %)
  89. * @param callable(ProgressBar):string $callable A PHP callable
  90. */
  91. public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void
  92. {
  93. self::$formatters ??= self::initPlaceholderFormatters();
  94. self::$formatters[$name] = $callable;
  95. }
  96. /**
  97. * Gets the placeholder formatter for a given name.
  98. *
  99. * @param string $name The placeholder name (including the delimiter char like %)
  100. */
  101. public static function getPlaceholderFormatterDefinition(string $name): ?callable
  102. {
  103. self::$formatters ??= self::initPlaceholderFormatters();
  104. return self::$formatters[$name] ?? null;
  105. }
  106. /**
  107. * Sets a placeholder formatter for a given name, for this instance only.
  108. *
  109. * @param callable(ProgressBar):string $callable A PHP callable
  110. */
  111. public function setPlaceholderFormatter(string $name, callable $callable): void
  112. {
  113. $this->placeholders[$name] = $callable;
  114. }
  115. /**
  116. * Gets the placeholder formatter for a given name.
  117. *
  118. * @param string $name The placeholder name (including the delimiter char like %)
  119. */
  120. public function getPlaceholderFormatter(string $name): ?callable
  121. {
  122. return $this->placeholders[$name] ?? $this::getPlaceholderFormatterDefinition($name);
  123. }
  124. /**
  125. * Sets a format for a given name.
  126. *
  127. * This method also allow you to override an existing format.
  128. *
  129. * @param string $name The format name
  130. * @param string $format A format string
  131. */
  132. public static function setFormatDefinition(string $name, string $format): void
  133. {
  134. self::$formats ??= self::initFormats();
  135. self::$formats[$name] = $format;
  136. }
  137. /**
  138. * Gets the format for a given name.
  139. *
  140. * @param string $name The format name
  141. */
  142. public static function getFormatDefinition(string $name): ?string
  143. {
  144. self::$formats ??= self::initFormats();
  145. return self::$formats[$name] ?? null;
  146. }
  147. /**
  148. * Associates a text with a named placeholder.
  149. *
  150. * The text is displayed when the progress bar is rendered but only
  151. * when the corresponding placeholder is part of the custom format line
  152. * (by wrapping the name with %).
  153. *
  154. * @param string $message The text to associate with the placeholder
  155. * @param string $name The name of the placeholder
  156. */
  157. public function setMessage(string $message, string $name = 'message'): void
  158. {
  159. $this->messages[$name] = $message;
  160. }
  161. public function getMessage(string $name = 'message'): ?string
  162. {
  163. return $this->messages[$name] ?? null;
  164. }
  165. public function getStartTime(): int
  166. {
  167. return $this->startTime;
  168. }
  169. public function getMaxSteps(): int
  170. {
  171. return $this->max ?? 0;
  172. }
  173. public function getProgress(): int
  174. {
  175. return $this->step;
  176. }
  177. private function getStepWidth(): int
  178. {
  179. return $this->stepWidth;
  180. }
  181. public function getProgressPercent(): float
  182. {
  183. return $this->percent;
  184. }
  185. public function getBarOffset(): float
  186. {
  187. return floor(null !== $this->max ? $this->percent * $this->barWidth : (null === $this->redrawFreq ? (int) (min(5, $this->barWidth / 15) * $this->writeCount) : $this->step) % $this->barWidth);
  188. }
  189. public function getEstimated(): float
  190. {
  191. if (0 === $this->step || $this->step === $this->startingStep) {
  192. return 0;
  193. }
  194. return round((time() - $this->startTime) / ($this->step - $this->startingStep) * $this->max);
  195. }
  196. public function getRemaining(): float
  197. {
  198. if (0 === $this->step || $this->step === $this->startingStep) {
  199. return 0;
  200. }
  201. return round((time() - $this->startTime) / ($this->step - $this->startingStep) * ($this->max - $this->step));
  202. }
  203. public function setBarWidth(int $size): void
  204. {
  205. $this->barWidth = max(1, $size);
  206. }
  207. public function getBarWidth(): int
  208. {
  209. return $this->barWidth;
  210. }
  211. public function setBarCharacter(string $char): void
  212. {
  213. $this->barChar = $char;
  214. }
  215. public function getBarCharacter(): string
  216. {
  217. return $this->barChar ?? (null !== $this->max ? '=' : $this->emptyBarChar);
  218. }
  219. public function setEmptyBarCharacter(string $char): void
  220. {
  221. $this->emptyBarChar = $char;
  222. }
  223. public function getEmptyBarCharacter(): string
  224. {
  225. return $this->emptyBarChar;
  226. }
  227. public function setProgressCharacter(string $char): void
  228. {
  229. $this->progressChar = $char;
  230. }
  231. public function getProgressCharacter(): string
  232. {
  233. return $this->progressChar;
  234. }
  235. public function setFormat(string $format): void
  236. {
  237. $this->format = null;
  238. $this->internalFormat = $format;
  239. }
  240. /**
  241. * Sets the redraw frequency.
  242. *
  243. * @param int|null $freq The frequency in steps
  244. */
  245. public function setRedrawFrequency(?int $freq): void
  246. {
  247. $this->redrawFreq = null !== $freq ? max(1, $freq) : null;
  248. }
  249. public function minSecondsBetweenRedraws(float $seconds): void
  250. {
  251. $this->minSecondsBetweenRedraws = $seconds;
  252. }
  253. public function maxSecondsBetweenRedraws(float $seconds): void
  254. {
  255. $this->maxSecondsBetweenRedraws = $seconds;
  256. }
  257. /**
  258. * Returns an iterator that will automatically update the progress bar when iterated.
  259. *
  260. * @template TKey
  261. * @template TValue
  262. *
  263. * @param iterable<TKey, TValue> $iterable
  264. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
  265. *
  266. * @return iterable<TKey, TValue>
  267. */
  268. public function iterate(iterable $iterable, ?int $max = null): iterable
  269. {
  270. if (0 === $max) {
  271. $max = null;
  272. }
  273. $max ??= is_countable($iterable) ? \count($iterable) : null;
  274. if (0 === $max) {
  275. $this->max = 0;
  276. $this->stepWidth = 2;
  277. $this->finish();
  278. return;
  279. }
  280. $this->start($max);
  281. foreach ($iterable as $key => $value) {
  282. yield $key => $value;
  283. $this->advance();
  284. }
  285. $this->finish();
  286. }
  287. /**
  288. * Starts the progress output.
  289. *
  290. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
  291. * @param int $startAt The starting point of the bar (useful e.g. when resuming a previously started bar)
  292. */
  293. public function start(?int $max = null, int $startAt = 0): void
  294. {
  295. $this->startTime = time();
  296. $this->step = $startAt;
  297. $this->startingStep = $startAt;
  298. $startAt > 0 ? $this->setProgress($startAt) : $this->percent = 0.0;
  299. if (null !== $max) {
  300. $this->setMaxSteps($max);
  301. }
  302. $this->display();
  303. }
  304. /**
  305. * Advances the progress output X steps.
  306. *
  307. * @param int $step Number of steps to advance
  308. */
  309. public function advance(int $step = 1): void
  310. {
  311. $this->setProgress($this->step + $step);
  312. }
  313. /**
  314. * Sets whether to overwrite the progressbar, false for new line.
  315. */
  316. public function setOverwrite(bool $overwrite): void
  317. {
  318. $this->overwrite = $overwrite;
  319. }
  320. public function setProgress(int $step): void
  321. {
  322. if ($this->max && $step > $this->max) {
  323. $this->max = $step;
  324. } elseif ($step < 0) {
  325. $step = 0;
  326. }
  327. $redrawFreq = $this->redrawFreq ?? (($this->max ?? 10) / 10);
  328. $prevPeriod = $redrawFreq ? (int) ($this->step / $redrawFreq) : 0;
  329. $currPeriod = $redrawFreq ? (int) ($step / $redrawFreq) : 0;
  330. $this->step = $step;
  331. $this->percent = match ($this->max) {
  332. null => 0,
  333. 0 => 1,
  334. default => (float) $this->step / $this->max,
  335. };
  336. $timeInterval = microtime(true) - $this->lastWriteTime;
  337. // Draw regardless of other limits
  338. if ($this->max === $step) {
  339. $this->display();
  340. return;
  341. }
  342. // Throttling
  343. if ($timeInterval < $this->minSecondsBetweenRedraws) {
  344. return;
  345. }
  346. // Draw each step period, but not too late
  347. if ($prevPeriod !== $currPeriod || $timeInterval >= $this->maxSecondsBetweenRedraws) {
  348. $this->display();
  349. }
  350. }
  351. public function setMaxSteps(?int $max): void
  352. {
  353. if (0 === $max) {
  354. $max = null;
  355. }
  356. $this->format = null;
  357. if (null === $max) {
  358. $this->max = null;
  359. $this->stepWidth = 4;
  360. } else {
  361. $this->max = max(0, $max);
  362. $this->stepWidth = Helper::width((string) $this->max);
  363. }
  364. }
  365. /**
  366. * Finishes the progress output.
  367. */
  368. public function finish(): void
  369. {
  370. if (null === $this->max) {
  371. $this->max = $this->step;
  372. }
  373. if (($this->step === $this->max || null === $this->max) && !$this->overwrite) {
  374. // prevent double 100% output
  375. return;
  376. }
  377. $this->setProgress($this->max ?? $this->step);
  378. }
  379. /**
  380. * Outputs the current progress string.
  381. */
  382. public function display(): void
  383. {
  384. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  385. return;
  386. }
  387. if (null === $this->format) {
  388. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  389. }
  390. $this->overwrite($this->buildLine());
  391. }
  392. /**
  393. * Removes the progress bar from the current line.
  394. *
  395. * This is useful if you wish to write some output
  396. * while a progress bar is running.
  397. * Call display() to show the progress bar again.
  398. */
  399. public function clear(): void
  400. {
  401. if (!$this->overwrite) {
  402. return;
  403. }
  404. if (null === $this->format) {
  405. $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
  406. }
  407. $this->overwrite('');
  408. }
  409. private function setRealFormat(string $format): void
  410. {
  411. // try to use the _nomax variant if available
  412. if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
  413. $this->format = self::getFormatDefinition($format.'_nomax');
  414. } elseif (null !== self::getFormatDefinition($format)) {
  415. $this->format = self::getFormatDefinition($format);
  416. } else {
  417. $this->format = $format;
  418. }
  419. }
  420. /**
  421. * Overwrites a previous message to the output.
  422. */
  423. private function overwrite(string $message): void
  424. {
  425. if ($this->previousMessage === $message) {
  426. return;
  427. }
  428. $originalMessage = $message;
  429. if ($this->overwrite) {
  430. if (null !== $this->previousMessage) {
  431. if ($this->output instanceof ConsoleSectionOutput) {
  432. $messageLines = explode("\n", $this->previousMessage);
  433. $lineCount = \count($messageLines);
  434. $lastLineWithoutDecoration = Helper::removeDecoration($this->output->getFormatter(), end($messageLines) ?? '');
  435. // When the last previous line is empty (without formatting) it is already cleared by the section output, so we don't need to clear it again
  436. if ('' === $lastLineWithoutDecoration) {
  437. --$lineCount;
  438. }
  439. foreach ($messageLines as $messageLine) {
  440. $messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine));
  441. if ($messageLineLength > $this->terminal->getWidth()) {
  442. $lineCount += floor($messageLineLength / $this->terminal->getWidth());
  443. }
  444. }
  445. $this->output->clear($lineCount);
  446. } else {
  447. $lineCount = substr_count($this->previousMessage, "\n");
  448. for ($i = 0; $i < $lineCount; ++$i) {
  449. $this->cursor->moveToColumn(1);
  450. $this->cursor->clearLine();
  451. $this->cursor->moveUp();
  452. }
  453. $this->cursor->moveToColumn(1);
  454. $this->cursor->clearLine();
  455. }
  456. }
  457. } elseif ($this->step > 0) {
  458. $message = \PHP_EOL.$message;
  459. }
  460. $this->previousMessage = $originalMessage;
  461. $this->lastWriteTime = microtime(true);
  462. $this->output->write($message);
  463. ++$this->writeCount;
  464. }
  465. private function determineBestFormat(): string
  466. {
  467. return match ($this->output->getVerbosity()) {
  468. // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
  469. OutputInterface::VERBOSITY_VERBOSE => $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX,
  470. OutputInterface::VERBOSITY_VERY_VERBOSE => $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX,
  471. OutputInterface::VERBOSITY_DEBUG => $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX,
  472. default => $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX,
  473. };
  474. }
  475. private static function initPlaceholderFormatters(): array
  476. {
  477. return [
  478. 'bar' => function (self $bar, OutputInterface $output) {
  479. $completeBars = $bar->getBarOffset();
  480. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  481. if ($completeBars < $bar->getBarWidth()) {
  482. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::length(Helper::removeDecoration($output->getFormatter(), $bar->getProgressCharacter()));
  483. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  484. }
  485. return $display;
  486. },
  487. 'elapsed' => fn (self $bar) => Helper::formatTime(time() - $bar->getStartTime(), 2),
  488. 'remaining' => function (self $bar) {
  489. if (null === $bar->getMaxSteps()) {
  490. throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  491. }
  492. return Helper::formatTime($bar->getRemaining(), 2);
  493. },
  494. 'estimated' => function (self $bar) {
  495. if (null === $bar->getMaxSteps()) {
  496. throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  497. }
  498. return Helper::formatTime($bar->getEstimated(), 2);
  499. },
  500. 'memory' => fn (self $bar) => Helper::formatMemory(memory_get_usage(true)),
  501. 'current' => fn (self $bar) => str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', \STR_PAD_LEFT),
  502. 'max' => fn (self $bar) => $bar->getMaxSteps(),
  503. 'percent' => fn (self $bar) => floor($bar->getProgressPercent() * 100),
  504. ];
  505. }
  506. private static function initFormats(): array
  507. {
  508. return [
  509. self::FORMAT_NORMAL => ' %current%/%max% [%bar%] %percent:3s%%',
  510. self::FORMAT_NORMAL_NOMAX => ' %current% [%bar%]',
  511. self::FORMAT_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  512. self::FORMAT_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%',
  513. self::FORMAT_VERY_VERBOSE => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  514. self::FORMAT_VERY_VERBOSE_NOMAX => ' %current% [%bar%] %elapsed:6s%',
  515. self::FORMAT_DEBUG => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  516. self::FORMAT_DEBUG_NOMAX => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  517. ];
  518. }
  519. private function buildLine(): string
  520. {
  521. \assert(null !== $this->format);
  522. $regex = '{%([a-z\-_]+)(?:\:([^%]+))?%}i';
  523. $callback = function ($matches) {
  524. if ($formatter = $this->getPlaceholderFormatter($matches[1])) {
  525. $text = $formatter($this, $this->output);
  526. } elseif (isset($this->messages[$matches[1]])) {
  527. $text = $this->messages[$matches[1]];
  528. } else {
  529. return $matches[0];
  530. }
  531. if (isset($matches[2])) {
  532. $text = \sprintf('%'.$matches[2], $text);
  533. }
  534. return $text;
  535. };
  536. $line = preg_replace_callback($regex, $callback, $this->format);
  537. // gets string length for each sub line with multiline format
  538. $linesLength = array_map(fn ($subLine) => Helper::width(Helper::removeDecoration($this->output->getFormatter(), rtrim($subLine, "\r"))), explode("\n", $line));
  539. $linesWidth = max($linesLength);
  540. $terminalWidth = $this->terminal->getWidth();
  541. if ($linesWidth <= $terminalWidth) {
  542. return $line;
  543. }
  544. $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
  545. return preg_replace_callback($regex, $callback, $this->format);
  546. }
  547. }