Line data Source code
1 : import 'dart:io'; 2 : import 'package:mason_logger/mason_logger.dart'; 3 : import 'package:meta/meta.dart'; 4 : import 'package:universal_io/io.dart'; 5 : 6 : /// The fallback number of columns of the terminal. 7 : /// 8 : /// Used when the terminal number of columns (width) cannot be determined. For 9 : /// example, when running in Azure DevOps, see relevant issue: 10 : /// https://github.com/VeryGoodOpenSource/very_good_cli/issues/866 . 11 : @visibleForTesting 12 : const fallbackStdoutTerminalColumns = 80; 13 : 14 : /// Extension on the Logger class for custom styled logging. 15 : extension LoggerX on Logger { 16 : /// Log a message in the "created" style of the CLI. 17 1 : void created(String message) { 18 3 : info(lightCyan.wrap(styleBold.wrap(message))); 19 : } 20 : 21 : /// Wrap the [text] to fit perfectly within the width of the terminal when 22 : /// [print]ed. 23 : /// 24 : /// The text will wrap around the terminal width, and will not break words. If 25 : /// the terminal width cannot be determined, the text will wrap around the 26 : /// [fallbackStdoutTerminalColumns]. 27 : /// 28 : /// To completely overwrite the width you can use [length]. 29 1 : void wrap( 30 : String? text, { 31 : required void Function(String?) print, 32 : int? length, 33 : }) { 34 : late final int maxLength; 35 : if (length != null) { 36 : maxLength = length; 37 2 : } else if (stdout.hasTerminal) { 38 2 : maxLength = stdout.terminalColumns; 39 : } else { 40 : maxLength = fallbackStdoutTerminalColumns; 41 : } 42 : 43 3 : for (final sentence in text?.split('/n') ?? <String>[]) { 44 1 : final words = sentence.split(' '); 45 : 46 1 : final currentLine = StringBuffer(); 47 2 : for (final word in words) { 48 : // Replace all ANSI sequences so we can get the true character length. 49 : final charLength = word 50 2 : .replaceAll(RegExp('\x1B(?:[@-Z\\-_]|[[0-?]*[ -/]*[@-~])'), '') 51 1 : .length; 52 : 53 3 : if (currentLine.length + charLength > maxLength) { 54 2 : print(currentLine.toString()); 55 1 : currentLine.clear(); 56 : } 57 2 : currentLine.write('$word '); 58 : } 59 : 60 2 : print(currentLine.toString()); 61 : } 62 : } 63 : }