Skip to content

Commit

Permalink
fix(mason_logger): only animate progress on terminals
Browse files Browse the repository at this point in the history
  • Loading branch information
felangel committed Oct 28, 2022
1 parent 713a853 commit 10d5b2c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/mason_logger.yaml
Expand Up @@ -36,6 +36,9 @@ jobs:
- name: Analyze
run: dart analyze --fatal-infos --fatal-warnings .

- name: Verify CI
run: dart example/test.dart

- name: Run Tests
run: |
dart pub global activate coverage 1.2.0
Expand Down
10 changes: 10 additions & 0 deletions packages/mason_logger/example/test.dart
@@ -0,0 +1,10 @@
import 'package:mason_logger/mason_logger.dart';

Future<void> main() async {
final logger = Logger();
final progress = logger.progress('Calculating');
await Future<void>.delayed(const Duration(seconds: 1));
progress.update('Almost done');
await Future<void>.delayed(const Duration(seconds: 1));
progress.complete('Done');
}
21 changes: 16 additions & 5 deletions packages/mason_logger/lib/src/progress.dart
Expand Up @@ -51,6 +51,17 @@ class Progress {
_stopwatch
..reset()
..start();

// The animation is only shown when it would be meaningful.
// Do not animate if the stdio type is not a terminal.
if (io.stdioType(_stdout) != io.StdioType.terminal) {
final frames = _options.animation.frames;
final char = frames.isEmpty ? '' : frames.first;
final prefix = char.isEmpty ? char : '${lightGreen.wrap(char)} ';
_write('$prefix$_message...');
return;
}

_timer = Timer.periodic(const Duration(milliseconds: 80), _onTick);
}

Expand All @@ -62,7 +73,7 @@ class Progress {

final Stopwatch _stopwatch;

late final Timer _timer;
Timer? _timer;

String _message;

Expand All @@ -74,12 +85,12 @@ class Progress {
_write(
'''$_clearLine${lightGreen.wrap('✓')} ${update ?? _message} $_time\n''',
);
_timer.cancel();
_timer?.cancel();
}

/// End the progress and mark it as failed.
void fail([String? update]) {
_timer.cancel();
_timer?.cancel();
_write('$_clearLine${red.wrap('✗')} ${update ?? _message} $_time\n');
_stopwatch.stop();
}
Expand All @@ -93,7 +104,7 @@ class Progress {

/// Cancel the progress and remove the written line.
void cancel() {
_timer.cancel();
_timer?.cancel();
_write(_clearLine);
_stopwatch.stop();
}
Expand All @@ -103,7 +114,7 @@ class Progress {
'\r'; // bring cursor to the start of the current line
}

void _onTick(Timer _) {
void _onTick(Timer? _) {
_index++;
final frames = _options.animation.frames;
final char = frames.isEmpty ? '' : frames[_index % frames.length];
Expand Down

0 comments on commit 10d5b2c

Please sign in to comment.