Skip to content

Commit e438632

Browse files
authored
Turn on line wrapping in usage and status messages, adds ANSI color to doctor and analysis messages. (flutter#22656)
This turns on text wrapping for usage messages and status messages. When on a terminal, wraps to the width of the terminal. When writing to a non-terminal, wrap lines at a default column width (currently defined to be 100 chars). If --no-wrap is specified, then no wrapping occurs. If --wrap-column is specified, wraps to that column (if --wrap is on). Adds ANSI color to the doctor and analysis output on terminals. This is in this PR with the wrapping, since wrapping needs to know how to count visible characters in the presence of ANSI sequences. (This is just one more step towards re-implementing all of Curses for Flutter. :-)) Will not print ANSI sequences when sent to a non-terminal, or of --no-color is specified. Fixes ANSI color and bold sequences so that they can be combined (bold, colored text), and a small bug in indentation calculation for wrapping. Since wrapping is now turned on, also removed many redundant '\n's in the code.
1 parent cdf1cec commit e438632

36 files changed

Lines changed: 1118 additions & 216 deletions

‎dev/bots/analyze-sample-code.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ linter:
223223
print('Found $sampleCodeSections sample code sections.');
224224
final Process process = await Process.start(
225225
_flutter,
226-
<String>['analyze', '--no-preamble', '--no-congratulate', mainDart.parent.path],
226+
<String>['--no-wrap', 'analyze', '--no-preamble', '--no-congratulate', mainDart.parent.path],
227227
workingDirectory: tempDir.path,
228228
);
229229
final List<String> errors = <String>[];

‎packages/flutter_tools/lib/src/android/android_studio_validator.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ class NoAndroidStudioValidator extends DoctorValidator {
8080
'Android Studio not found; download from https://developer.android.com/studio/index.html\n'
8181
'(or visit https://flutter.io/setup/#android-setup for detailed instructions).'));
8282

83-
return ValidationResult(ValidationType.missing, messages,
83+
return ValidationResult(ValidationType.notAvailable, messages,
8484
statusInfo: 'not installed');
8585
}
8686
}

‎packages/flutter_tools/lib/src/base/logger.dart‎

Lines changed: 57 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
// found in the LICENSE file.
44

55
import 'dart:async';
6-
import 'dart:convert' show LineSplitter;
76

87
import 'package:meta/meta.dart';
98

@@ -28,26 +27,57 @@ abstract class Logger {
2827

2928
bool get hasTerminal => stdio.hasTerminal;
3029

31-
/// Display an error level message to the user. Commands should use this if they
30+
/// Display an error [message] to the user. Commands should use this if they
3231
/// fail in some way.
32+
///
33+
/// The [message] argument is printed to the stderr in red by default.
34+
/// The [stackTrace] argument is the stack trace that will be printed if
35+
/// supplied.
36+
/// The [emphasis] argument will cause the output message be printed in bold text.
37+
/// The [color] argument will print the message in the supplied color instead
38+
/// of the default of red. Colors will not be printed if the output terminal
39+
/// doesn't support them.
40+
/// The [indent] argument specifies the number of spaces to indent the overall
41+
/// message. If wrapping is enabled in [outputPreferences], then the wrapped
42+
/// lines will be indented as well.
43+
/// If [hangingIndent] is specified, then any wrapped lines will be indented
44+
/// by this much more than the first line, if wrapping is enabled in
45+
/// [outputPreferences].
3346
void printError(
3447
String message, {
3548
StackTrace stackTrace,
3649
bool emphasis,
3750
TerminalColor color,
51+
int indent,
52+
int hangingIndent,
3853
});
3954

4055
/// Display normal output of the command. This should be used for things like
4156
/// progress messages, success messages, or just normal command output.
4257
///
43-
/// If [newline] is null, then it defaults to "true". If [emphasis] is null,
44-
/// then it defaults to "false".
58+
/// The [message] argument is printed to the stderr in red by default.
59+
/// The [stackTrace] argument is the stack trace that will be printed if
60+
/// supplied.
61+
/// If the [emphasis] argument is true, it will cause the output message be
62+
/// printed in bold text. Defaults to false.
63+
/// The [color] argument will print the message in the supplied color instead
64+
/// of the default of red. Colors will not be printed if the output terminal
65+
/// doesn't support them.
66+
/// If [newline] is true, then a newline will be added after printing the
67+
/// status. Defaults to true.
68+
/// The [indent] argument specifies the number of spaces to indent the overall
69+
/// message. If wrapping is enabled in [outputPreferences], then the wrapped
70+
/// lines will be indented as well.
71+
/// If [hangingIndent] is specified, then any wrapped lines will be indented
72+
/// by this much more than the first line, if wrapping is enabled in
73+
/// [outputPreferences].
4574
void printStatus(
4675
String message, {
4776
bool emphasis,
4877
TerminalColor color,
4978
bool newline,
5079
int indent,
80+
int hangingIndent,
5181
});
5282

5383
/// Use this for verbose tracing output. Users can turn this output on in order
@@ -82,8 +112,11 @@ class StdoutLogger extends Logger {
82112
StackTrace stackTrace,
83113
bool emphasis,
84114
TerminalColor color,
115+
int indent,
116+
int hangingIndent,
85117
}) {
86118
message ??= '';
119+
message = wrapText(message, indent: indent, hangingIndent: hangingIndent);
87120
_status?.cancel();
88121
_status = null;
89122
if (emphasis == true)
@@ -102,19 +135,16 @@ class StdoutLogger extends Logger {
102135
TerminalColor color,
103136
bool newline,
104137
int indent,
138+
int hangingIndent,
105139
}) {
106140
message ??= '';
141+
message = wrapText(message, indent: indent, hangingIndent: hangingIndent);
107142
_status?.cancel();
108143
_status = null;
109144
if (emphasis == true)
110145
message = terminal.bolden(message);
111146
if (color != null)
112147
message = terminal.color(message, color);
113-
if (indent != null && indent > 0) {
114-
message = LineSplitter.split(message)
115-
.map<String>((String line) => ' ' * indent + line)
116-
.join('\n');
117-
}
118148
if (newline != false)
119149
message = '$message\n';
120150
writeToStdOut(message);
@@ -203,8 +233,13 @@ class BufferLogger extends Logger {
203233
StackTrace stackTrace,
204234
bool emphasis,
205235
TerminalColor color,
236+
int indent,
237+
int hangingIndent,
206238
}) {
207-
_error.writeln(terminal.color(message, color ?? TerminalColor.red));
239+
_error.writeln(terminal.color(
240+
wrapText(message, indent: indent, hangingIndent: hangingIndent),
241+
color ?? TerminalColor.red,
242+
));
208243
}
209244

210245
@override
@@ -214,11 +249,12 @@ class BufferLogger extends Logger {
214249
TerminalColor color,
215250
bool newline,
216251
int indent,
252+
int hangingIndent,
217253
}) {
218254
if (newline != false)
219-
_status.writeln(message);
255+
_status.writeln(wrapText(message, indent: indent, hangingIndent: hangingIndent));
220256
else
221-
_status.write(message);
257+
_status.write(wrapText(message, indent: indent, hangingIndent: hangingIndent));
222258
}
223259

224260
@override
@@ -262,8 +298,14 @@ class VerboseLogger extends Logger {
262298
StackTrace stackTrace,
263299
bool emphasis,
264300
TerminalColor color,
301+
int indent,
302+
int hangingIndent,
265303
}) {
266-
_emit(_LogType.error, message, stackTrace);
304+
_emit(
305+
_LogType.error,
306+
wrapText(message, indent: indent, hangingIndent: hangingIndent),
307+
stackTrace,
308+
);
267309
}
268310

269311
@override
@@ -273,8 +315,9 @@ class VerboseLogger extends Logger {
273315
TerminalColor color,
274316
bool newline,
275317
int indent,
318+
int hangingIndent,
276319
}) {
277-
_emit(_LogType.status, message);
320+
_emit(_LogType.status, wrapText(message, indent: indent, hangingIndent: hangingIndent));
278321
}
279322

280323
@override

‎packages/flutter_tools/lib/src/base/terminal.dart‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import '../globals.dart';
1111
import 'context.dart';
1212
import 'io.dart' as io;
1313
import 'platform.dart';
14+
import 'utils.dart';
1415

1516
final AnsiTerminal _kAnsiTerminal = AnsiTerminal();
1617

@@ -30,6 +31,45 @@ enum TerminalColor {
3031
grey,
3132
}
3233

34+
final OutputPreferences _kOutputPreferences = OutputPreferences();
35+
36+
OutputPreferences get outputPreferences => (context == null || context[OutputPreferences] == null)
37+
? _kOutputPreferences
38+
: context[OutputPreferences];
39+
40+
/// A class that contains the context settings for command text output to the
41+
/// console.
42+
class OutputPreferences {
43+
OutputPreferences({
44+
bool wrapText,
45+
int wrapColumn,
46+
bool showColor,
47+
}) : wrapText = wrapText ?? true,
48+
wrapColumn = wrapColumn ?? const io.Stdio().terminalColumns ?? kDefaultTerminalColumns,
49+
showColor = showColor ?? platform.stdoutSupportsAnsi ?? false;
50+
51+
/// If [wrapText] is true, then output text sent to the context's [Logger]
52+
/// instance (e.g. from the [printError] or [printStatus] functions) will be
53+
/// wrapped to be no longer than the [wrapColumn] specifies. Defaults to true.
54+
final bool wrapText;
55+
56+
/// The column at which any output sent to the context's [Logger] instance
57+
/// (e.g. from the [printError] or [printStatus] functions) will be wrapped.
58+
/// Ignored if [wrapText] is false. Defaults to the width of the output
59+
/// terminal, or to [kDefaultTerminalColumns] if not writing to a terminal.
60+
final int wrapColumn;
61+
62+
/// Whether or not to output ANSI color codes when writing to the output
63+
/// terminal. Defaults to whatever [platform.stdoutSupportsAnsi] says if
64+
/// writing to a terminal, and false otherwise.
65+
final bool showColor;
66+
67+
@override
68+
String toString() {
69+
return '$runtimeType[wrapText: $wrapText, wrapColumn: $wrapColumn, showColor: $showColor]';
70+
}
71+
}
72+
3373
class AnsiTerminal {
3474
static const String bold = '\u001B[1m';
3575
static const String reset = '\u001B[0m';
@@ -62,8 +102,16 @@ class AnsiTerminal {
62102
if (!supportsColor || message.isEmpty)
63103
return message;
64104
final StringBuffer buffer = StringBuffer();
65-
for (String line in message.split('\n'))
105+
for (String line in message.split('\n')) {
106+
// If there were resets in the string before, then keep them, but
107+
// restart the bold right after. This prevents embedded resets from
108+
// stopping the boldness.
109+
line = line.replaceAll(reset, '$reset$bold');
110+
// Remove all codes at the end of the string, since we're just going
111+
// to reset them, and they would either be redundant, or have no effect.
112+
line = line.replaceAll(RegExp('(\u001b\[[0-9;]+m)+\$'), '');
66113
buffer.writeln('$bold$line$reset');
114+
}
67115
final String result = buffer.toString();
68116
// avoid introducing a new newline to the emboldened text
69117
return (!message.endsWith('\n') && result.endsWith('\n'))
@@ -76,8 +124,17 @@ class AnsiTerminal {
76124
if (!supportsColor || color == null || message.isEmpty)
77125
return message;
78126
final StringBuffer buffer = StringBuffer();
79-
for (String line in message.split('\n'))
80-
buffer.writeln('${_colorMap[color]}$line$reset');
127+
final String colorCodes = _colorMap[color];
128+
for (String line in message.split('\n')) {
129+
// If there were resets in the string before, then keep them, but
130+
// restart the color right after. This prevents embedded resets from
131+
// stopping the colors.
132+
line = line.replaceAll(reset, '$reset$colorCodes');
133+
// Remove any extra codes at the end of the string, since we're just going
134+
// to reset them.
135+
line = line.replaceAll(RegExp('(\u001b\[[0-9;]*m)+\$'), '');
136+
buffer.writeln('$colorCodes$line$reset');
137+
}
81138
final String result = buffer.toString();
82139
// avoid introducing a new newline to the colored text
83140
return (!message.endsWith('\n') && result.endsWith('\n'))

0 commit comments

Comments
 (0)