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 8 : void created(String message) { 18 24 : 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 2 : void wrap( 30 : String? text, { 31 : required void Function(String?) print, 32 : int? length, 33 : }) { 34 : final maxLength = switch (length) { 35 8 : == null when stdout.hasTerminal => stdout.terminalColumns, 36 2 : == null when !stdout.hasTerminal => fallbackStdoutTerminalColumns, 37 : _ => length! 38 : }; 39 : 40 6 : for (final sentence in text?.split('/n') ?? <String>[]) { 41 2 : final words = sentence.split(' '); 42 : 43 2 : final currentLine = StringBuffer(); 44 4 : for (final word in words) { 45 : // Replace all ANSI sequences so we can get the true character length. 46 : final charLength = word 47 4 : .replaceAll(RegExp('\x1B(?:[@-Z\\-_]|[[0-?]*[ -/]*[@-~])'), '') 48 2 : .length; 49 : 50 6 : if (currentLine.length + charLength > maxLength) { 51 4 : print(currentLine.toString()); 52 2 : currentLine.clear(); 53 : } 54 4 : currentLine.write('$word '); 55 : } 56 : 57 4 : print(currentLine.toString()); 58 : } 59 : } 60 : }