|
| 1 | +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// Adapted from package:pub lib/src/progress.dart to align progress updates |
| 6 | +// visually with pub. It would be better to let pub stream updates to dartdev |
| 7 | +// and have dartdev display progress in a consistent way for all kinds of |
| 8 | +// progress. |
| 9 | +// TODO(https://dartbug.com/61539): Standardize. |
| 10 | + |
| 11 | +import 'dart:async'; |
| 12 | +import 'dart:io'; |
| 13 | + |
| 14 | +/// Runs [callback] while displaying a live-updating progress indicator. |
| 15 | +/// |
| 16 | +/// The [message] is shown to the user, followed by "..." and a timer. |
| 17 | +/// The progress indicator is only animated if output is going to a terminal. |
| 18 | +/// When the [callback] completes, the progress indicator is stopped and the |
| 19 | +/// final time is shown. |
| 20 | +Future<T> progress<T>( |
| 21 | + String message, |
| 22 | + Future<T> Function() callback, |
| 23 | +) async { |
| 24 | + final progress = _Progress(message); |
| 25 | + return callback().whenComplete(progress._stop); |
| 26 | +} |
| 27 | + |
| 28 | +/// A live-updating progress indicator for long-running log entries. |
| 29 | +class _Progress { |
| 30 | + /// The timer used to write "..." during a progress log. |
| 31 | + late final Timer _timer; |
| 32 | + |
| 33 | + /// The [Stopwatch] used to track how long a progress log has been running. |
| 34 | + final _stopwatch = Stopwatch(); |
| 35 | + |
| 36 | + /// The progress message as it's being incrementally appended. |
| 37 | + /// |
| 38 | + /// When the progress is done, a single entry will be added to the log for it. |
| 39 | + final String _message; |
| 40 | + |
| 41 | + /// Gets the current progress time as a parenthesized, formatted string. |
| 42 | + String get _time => '(${_niceDuration(_stopwatch.elapsed)})'; |
| 43 | + |
| 44 | + /// The length of the most recently-printed [_time] string. |
| 45 | + var _timeLength = 0; |
| 46 | + |
| 47 | + /// Creates a new progress indicator. |
| 48 | + _Progress(this._message) { |
| 49 | + _stopwatch.start(); |
| 50 | + |
| 51 | + // The animation is only shown when it would be meaningful to a human. |
| 52 | + // That means we're writing a visible message to a TTY at normal log levels |
| 53 | + // with non-JSON output. |
| 54 | + if (!_terminalOutputForStdout) { |
| 55 | + // Not animating, so just log the start and wait until the task is |
| 56 | + // completed. |
| 57 | + stdout.write('$_message...'); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + _timer = Timer.periodic(const Duration(milliseconds: 100), (_) { |
| 62 | + _update(); |
| 63 | + }); |
| 64 | + |
| 65 | + stdout.write('$_message... '); |
| 66 | + } |
| 67 | + |
| 68 | + /// Stops the progress indicator. |
| 69 | + void _stop() { |
| 70 | + if (!_terminalOutputForStdout) { |
| 71 | + // Not animating, so just log the start and wait until the task is |
| 72 | + // completed. |
| 73 | + stdout.write('$_message...'); |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + _stopwatch.stop(); |
| 78 | + _timer.cancel(); |
| 79 | + // print one final update to show the user the final time. |
| 80 | + _update(); |
| 81 | + stdout.writeln(); |
| 82 | + } |
| 83 | + |
| 84 | + /// Refreshes the progress line. |
| 85 | + void _update() { |
| 86 | + // Show the time only once it gets noticeably long. |
| 87 | + if (_stopwatch.elapsed.inSeconds == 0) return; |
| 88 | + |
| 89 | + // Erase the last time that was printed. Erasing just the time using `\b` |
| 90 | + // rather than using `\r` to erase the entire line ensures that we don't |
| 91 | + // spam progress lines if they're wider than the terminal width. |
| 92 | + stdout.write('\b' * _timeLength); |
| 93 | + final time = _time; |
| 94 | + _timeLength = time.length; |
| 95 | + stdout.write(gray(time)); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +/// Returns `true` if [stdout] should be treated as a terminal. |
| 100 | +bool get _terminalOutputForStdout => stdout.hasTerminal; |
| 101 | + |
| 102 | +/// Returns a human-friendly representation of [duration]. |
| 103 | +String _niceDuration(Duration duration) { |
| 104 | + final hasMinutes = duration.inMinutes > 0; |
| 105 | + final result = hasMinutes ? '${duration.inMinutes}:' : ''; |
| 106 | + |
| 107 | + final s = duration.inSeconds % 60; |
| 108 | + final ms = duration.inMilliseconds % 1000; |
| 109 | + |
| 110 | + final msString = (ms ~/ 100).toString(); |
| 111 | + |
| 112 | + return "$result${hasMinutes ? _padLeft(s.toString(), 2, '0') : s}" |
| 113 | + '.${msString}s'; |
| 114 | +} |
| 115 | + |
| 116 | +/// Pads [source] to [length] by adding [char]s at the beginning. |
| 117 | +/// |
| 118 | +/// If [char] is `null`, it defaults to a space. |
| 119 | +String _padLeft(String source, int length, [String char = ' ']) { |
| 120 | + if (source.length >= length) return source; |
| 121 | + |
| 122 | + return char * (length - source.length) + source; |
| 123 | +} |
| 124 | + |
| 125 | +/// Wraps [text] in the ANSI escape codes to make it gray when on a platform |
| 126 | +/// that supports that. |
| 127 | +/// |
| 128 | +/// Use this for text that's less important than the text around it. |
| 129 | +String gray(String text) => '$_gray$text$_none'; |
| 130 | + |
| 131 | +final _none = _getAnsi('\u001b[0m'); |
| 132 | +final _gray = _getAnsi('\u001b[38;5;245m'); |
| 133 | + |
| 134 | +String _getAnsi(String ansiCode) => canUseAnsiCodes ? ansiCode : ''; |
| 135 | + |
| 136 | +/// Whether ansi codes such as color escapes are safe to use. |
| 137 | +/// |
| 138 | +/// On a terminal we can use ansi codes also on Windows. |
| 139 | +/// |
| 140 | +/// Tests should make sure to run the subprocess with or without an attached |
| 141 | +/// terminal to decide if colors will be provided. |
| 142 | +bool get canUseAnsiCodes { |
| 143 | + return (!Platform.environment.containsKey('NO_COLOR')) && |
| 144 | + _terminalOutputForStdout && |
| 145 | + stdout.supportsAnsiEscapes; |
| 146 | +} |
0 commit comments