utils.dart 16.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:math' as math;
Devon Carew's avatar
Devon Carew committed
7

8
import 'package:file/file.dart';
9
import 'package:intl/intl.dart';
10
import 'package:path/path.dart' as path; // flutter_ignore: package_path_import
Devon Carew's avatar
Devon Carew committed
11

12
import '../convert.dart';
13

14 15 16
/// A path jointer for URL paths.
final path.Context urlContext = path.url;

17 18 19 20 21 22 23 24 25 26 27 28
/// Convert `foo_bar` to `fooBar`.
String camelCase(String str) {
  int index = str.indexOf('_');
  while (index != -1 && index < str.length - 2) {
    str = str.substring(0, index) +
      str.substring(index + 1, index + 2).toUpperCase() +
      str.substring(index + 2);
    index = str.indexOf('_');
  }
  return str;
}

29
final RegExp _upperRegex = RegExp(r'[A-Z]');
30 31

/// Convert `fooBar` to `foo_bar`.
32
String snakeCase(String str, [ String sep = '_' ]) {
33
  return str.replaceAllMapped(_upperRegex,
34
      (Match m) => '${m.start == 0 ? '' : sep}${m[0]!.toLowerCase()}');
35 36
}

37 38 39 40 41
/// Converts `fooBar` to `FooBar`.
///
/// This uses [toBeginningOfSentenceCase](https://pub.dev/documentation/intl/latest/intl/toBeginningOfSentenceCase.html),
/// with the input and return value of non-nullable.
String sentenceCase(String str, [String? locale]) {
42
  if (str.isEmpty) {
43
    return str;
44
  }
45 46 47 48 49 50
  return toBeginningOfSentenceCase(str, locale)!;
}

/// Converts `foo_bar` to `Foo Bar`.
String snakeCaseToTitleCase(String snakeCaseString) {
  return snakeCaseString.split('_').map(camelCase).map(sentenceCase).join(' ');
51 52
}

53
/// Return the plural of the given word (`cat(s)`).
54
String pluralize(String word, int count) => count == 1 ? word : '${word}s';
55

56 57
/// Return the name of an enum item.
String getEnumName(dynamic enumItem) {
58 59
  final String name = '$enumItem';
  final int index = name.indexOf('.');
60 61 62
  return index == -1 ? name : name.substring(index + 1);
}

63
String toPrettyJson(Object jsonable) {
64 65
  final String value = const JsonEncoder.withIndent('  ').convert(jsonable);
  return '$value\n';
66 67
}

68 69
final NumberFormat kSecondsFormat = NumberFormat('0.0');
final NumberFormat kMillisecondsFormat = NumberFormat.decimalPattern();
70 71

String getElapsedAsSeconds(Duration duration) {
72
  final double seconds = duration.inMilliseconds / Duration.millisecondsPerSecond;
73 74 75 76 77 78
  return '${kSecondsFormat.format(seconds)}s';
}

String getElapsedAsMilliseconds(Duration duration) {
  return '${kMillisecondsFormat.format(duration.inMilliseconds)}ms';
}
79

80 81 82
/// Return a String - with units - for the size in MB of the given number of bytes.
String getSizeAsMB(int bytesLength) {
  return '${(bytesLength / (1024 * 1024)).toStringAsFixed(1)}MB';
83 84
}

85 86 87 88
/// A class to maintain a list of items, fire events when items are added or
/// removed, and calculate a diff of changes when a new list of items is
/// available.
class ItemListNotifier<T> {
89
  ItemListNotifier(): _items = <T>{};
90

91
  ItemListNotifier.from(List<T> items) : _items = Set<T>.of(items);
92 93 94

  Set<T> _items;

95 96
  final StreamController<T> _addedController = StreamController<T>.broadcast();
  final StreamController<T> _removedController = StreamController<T>.broadcast();
97 98 99 100 101 102 103

  Stream<T> get onAdded => _addedController.stream;
  Stream<T> get onRemoved => _removedController.stream;

  List<T> get items => _items.toList();

  void updateWithNewList(List<T> updatedList) {
104
    final Set<T> updatedSet = Set<T>.of(updatedList);
105

106 107
    final Set<T> addedItems = updatedSet.difference(_items);
    final Set<T> removedItems = _items.difference(updatedSet);
108 109 110

    _items = updatedSet;

111 112
    addedItems.forEach(_addedController.add);
    removedItems.forEach(_removedController.add);
113 114
  }

115 116 117 118 119 120
  void removeItem(T item) {
    if (_items.remove(item)) {
      _removedController.add(item);
    }
  }

121 122 123 124 125 126
  /// Close the streams.
  void dispose() {
    _addedController.close();
    _removedController.close();
  }
}
127 128

class SettingsFile {
129 130
  SettingsFile();

131 132 133
  SettingsFile.parse(String contents) {
    for (String line in contents.split('\n')) {
      line = line.trim();
134
      if (line.startsWith('#') || line.isEmpty) {
135
        continue;
136
      }
137
      final int index = line.indexOf('=');
138
      if (index != -1) {
139
        values[line.substring(0, index)] = line.substring(index + 1);
140
      }
141 142 143 144
    }
  }

  factory SettingsFile.parseFromFile(File file) {
145
    return SettingsFile.parse(file.readAsStringSync());
146 147 148 149 150
  }

  final Map<String, String> values = <String, String>{};

  void writeContents(File file) {
151
    file.parent.createSync(recursive: true);
152
    file.writeAsStringSync(values.keys.map<String>((String key) {
153 154 155 156
      return '$key=${values[key]}';
    }).join('\n'));
  }
}
157

158 159
/// Given a data structure which is a Map of String to dynamic values, return
/// the same structure (`Map<String, dynamic>`) with the correct runtime types.
160 161
Map<String, dynamic>? castStringKeyedMap(dynamic untyped) {
  final Map<dynamic, dynamic>? map = untyped as Map<dynamic, dynamic>?;
162
  return map?.cast<String, dynamic>();
163 164
}

165 166 167 168 169 170
/// Smallest column that will be used for text wrapping. If the requested column
/// width is smaller than this, then this is what will be used.
const int kMinColumnWidth = 10;

/// Wraps a block of text into lines no longer than [columnWidth].
///
171 172 173 174
/// Tries to split at whitespace, but if that's not good enough to keep it under
/// the limit, then it splits in the middle of a word. If [columnWidth] (minus
/// any indent) is smaller than [kMinColumnWidth], the text is wrapped at that
/// [kMinColumnWidth] instead.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
///
/// Preserves indentation (leading whitespace) for each line (delimited by '\n')
/// in the input, and will indent wrapped lines that same amount, adding
/// [indent] spaces in addition to any existing indent.
///
/// If [hangingIndent] is supplied, then that many additional spaces will be
/// added to each line, except for the first line. The [hangingIndent] is added
/// to the specified [indent], if any. This is useful for wrapping
/// text with a heading prefix (e.g. "Usage: "):
///
/// ```dart
/// String prefix = "Usage: ";
/// print(prefix + wrapText(invocation, indent: 2, hangingIndent: prefix.length, columnWidth: 40));
/// ```
///
/// yields:
/// ```
///   Usage: app main_command <subcommand>
///          [arguments]
/// ```
///
/// If [outputPreferences.wrapText] is false, then the text will be returned
197 198
/// unchanged. If [shouldWrap] is specified, then it overrides the
/// [outputPreferences.wrapText] setting.
199
///
200 201 202
/// If the amount of indentation (from the text, [indent], and [hangingIndent])
/// is such that less than [kMinColumnWidth] characters can fit in the
/// [columnWidth], then the indent is truncated to allow the text to fit.
203
String wrapText(String text, {
204 205 206 207
  required int columnWidth,
  required bool shouldWrap,
  int? hangingIndent,
  int? indent,
208
}) {
209
  assert(columnWidth >= 0);
210 211 212 213 214 215 216
  if (text == null || text.isEmpty) {
    return '';
  }
  indent ??= 0;
  hangingIndent ??= 0;
  final List<String> splitText = text.split('\n');
  final List<String> result = <String>[];
217
  for (final String line in splitText) {
218 219 220 221 222 223 224 225 226
    String trimmedText = line.trimLeft();
    final String leadingWhitespace = line.substring(0, line.length - trimmedText.length);
    List<String> notIndented;
    if (hangingIndent != 0) {
      // When we have a hanging indent, we want to wrap the first line at one
      // width, and the rest at another (offset by hangingIndent), so we wrap
      // them twice and recombine.
      final List<String> firstLineWrap = _wrapTextAsLines(
        trimmedText,
227
        columnWidth: columnWidth - leadingWhitespace.length - indent,
228
        shouldWrap: shouldWrap,
229 230 231
      );
      notIndented = <String>[firstLineWrap.removeAt(0)];
      trimmedText = trimmedText.substring(notIndented[0].length).trimLeft();
232
      if (trimmedText.isNotEmpty) {
233 234
        notIndented.addAll(_wrapTextAsLines(
          trimmedText,
235
          columnWidth: columnWidth - leadingWhitespace.length - indent - hangingIndent,
236
          shouldWrap: shouldWrap,
237 238 239 240 241
        ));
      }
    } else {
      notIndented = _wrapTextAsLines(
        trimmedText,
242
        columnWidth: columnWidth - leadingWhitespace.length - indent,
243
        shouldWrap: shouldWrap,
244 245
      );
    }
246
    String? hangingIndentString;
247
    final String indentString = ' ' * indent;
248
    result.addAll(notIndented.map<String>(
249 250 251 252 253
      (String line) {
        // Don't return any lines with just whitespace on them.
        if (line.isEmpty) {
          return '';
        }
254 255 256 257 258
        String truncatedIndent = '$indentString${hangingIndentString ?? ''}$leadingWhitespace';
        if (truncatedIndent.length > columnWidth - kMinColumnWidth) {
          truncatedIndent = truncatedIndent.substring(0, math.max(columnWidth - kMinColumnWidth, 0));
        }
        final String result = '$truncatedIndent$line';
259
        hangingIndentString ??= ' ' * hangingIndent!;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        return result;
      },
    ));
  }
  return result.join('\n');
}

// Used to represent a run of ANSI control sequences next to a visible
// character.
class _AnsiRun {
  _AnsiRun(this.original, this.character);

  String original;
  String character;
}

/// Wraps a block of text into lines no longer than [columnWidth], starting at the
/// [start] column, and returning the result as a list of strings.
///
/// Tries to split at whitespace, but if that's not good enough to keep it
/// under the limit, then splits in the middle of a word. Preserves embedded
/// newlines, but not indentation (it trims whitespace from each line).
///
/// If [columnWidth] is not specified, then the column width will be the width of the
/// terminal window by default. If the stdout is not a terminal window, then the
/// default will be [outputPreferences.wrapColumn].
///
287 288 289
/// The [columnWidth] is clamped to [kMinColumnWidth] at minimum (so passing negative
/// widths is fine, for instance).
///
290
/// If [outputPreferences.wrapText] is false, then the text will be returned
291 292
/// simply split at the newlines, but not wrapped. If [shouldWrap] is specified,
/// then it overrides the [outputPreferences.wrapText] setting.
293 294
List<String> _wrapTextAsLines(String text, {
  int start = 0,
295 296
  required int columnWidth,
  required bool shouldWrap,
297
}) {
298 299 300 301 302 303 304 305 306 307 308
  if (text == null || text.isEmpty) {
    return <String>[''];
  }
  assert(start >= 0);

  // Splits a string so that the resulting list has the same number of elements
  // as there are visible characters in the string, but elements may include one
  // or more adjacent ANSI sequences. Joining the list elements again will
  // reconstitute the original string. This is useful for manipulating "visible"
  // characters in the presence of ANSI control codes.
  List<_AnsiRun> splitWithCodes(String input) {
309
    final RegExp characterOrCode = RegExp('(\u001b\\[[0-9;]*m|.)', multiLine: true);
310 311
    List<_AnsiRun> result = <_AnsiRun>[];
    final StringBuffer current = StringBuffer();
312
    for (final Match match in characterOrCode.allMatches(input)) {
313
      current.write(match[0]);
314
      if (match[0]!.length < 4) {
315
        // This is a regular character, write it out.
316
        result.add(_AnsiRun(current.toString(), match[0]!));
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
        current.clear();
      }
    }
    // If there's something accumulated, then it must be an ANSI sequence, so
    // add it to the end of the last entry so that we don't lose it.
    if (current.isNotEmpty) {
      if (result.isNotEmpty) {
        result.last.original += current.toString();
      } else {
        // If there is nothing in the string besides control codes, then just
        // return them as the only entry.
        result = <_AnsiRun>[_AnsiRun(current.toString(), '')];
      }
    }
    return result;
  }

334
  String joinRun(List<_AnsiRun> list, int start, [ int? end ]) {
335 336 337 338
    return list.sublist(start, end).map<String>((_AnsiRun run) => run.original).join().trim();
  }

  final List<String> result = <String>[];
339
  final int effectiveLength = math.max(columnWidth - start, kMinColumnWidth);
340
  for (final String line in text.split('\n')) {
341 342
    // If the line is short enough, even with ANSI codes, then we can just add
    // add it and move on.
343
    if (line.length <= effectiveLength || !shouldWrap) {
344 345 346 347 348 349 350 351 352 353
      result.add(line);
      continue;
    }
    final List<_AnsiRun> splitLine = splitWithCodes(line);
    if (splitLine.length <= effectiveLength) {
      result.add(line);
      continue;
    }

    int currentLineStart = 0;
354
    int? lastWhitespace;
355 356
    // Find the start of the current line.
    for (int index = 0; index < splitLine.length; ++index) {
357
      if (splitLine[index].character.isNotEmpty && _isWhitespace(splitLine[index])) {
358 359 360 361 362 363 364 365 366 367 368 369 370
        lastWhitespace = index;
      }

      if (index - currentLineStart >= effectiveLength) {
        // Back up to the last whitespace, unless there wasn't any, in which
        // case we just split where we are.
        if (lastWhitespace != null) {
          index = lastWhitespace;
        }

        result.add(joinRun(splitLine, currentLineStart, index));

        // Skip any intervening whitespace.
371
        while (index < splitLine.length && _isWhitespace(splitLine[index])) {
372 373 374 375 376 377 378 379 380 381 382
          index++;
        }

        currentLineStart = index;
        lastWhitespace = null;
      }
    }
    result.add(joinRun(splitLine, currentLineStart));
  }
  return result;
}
383 384 385 386 387

/// Returns true if the code unit at [index] in [text] is a whitespace
/// character.
///
/// Based on: https://en.wikipedia.org/wiki/Whitespace_character#Unicode
388
bool _isWhitespace(_AnsiRun run) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402
  final int rune = run.character.isNotEmpty ? run.character.codeUnitAt(0) : 0x0;
  return rune >= 0x0009 && rune <= 0x000D ||
      rune == 0x0020 ||
      rune == 0x0085 ||
      rune == 0x1680 ||
      rune == 0x180E ||
      rune >= 0x2000 && rune <= 0x200A ||
      rune == 0x2028 ||
      rune == 0x2029 ||
      rune == 0x202F ||
      rune == 0x205F ||
      rune == 0x3000 ||
      rune == 0xFEFF;
}
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

final RegExp _interpolationRegex = RegExp(r'\$\{([^}]*)\}');

/// Given a string that possibly contains string interpolation sequences
/// (so for example, something like `ping -n 1 ${host}`), replace all those
/// interpolation sequences with the matching value given in [replacementValues].
///
/// If the value could not be found inside [replacementValues], an empty
/// string will be substituted instead.
///
/// However, if the dollar sign inside the string is preceded with a backslash,
/// the sequences won't be substituted at all.
///
/// Example:
/// ```dart
/// final interpolated = _interpolateString(r'ping -n 1 ${host}', {'host': 'raspberrypi'});
/// print(interpolated);  // will print 'ping -n 1 raspberrypi'
///
/// final interpolated2 = _interpolateString(r'ping -n 1 ${_host}', {'host': 'raspberrypi'});
/// print(interpolated2); // will print 'ping -n 1 '
/// ```
String interpolateString(String toInterpolate, Map<String, String> replacementValues) {
  return toInterpolate.replaceAllMapped(_interpolationRegex, (Match match) {
    /// The name of the variable to be inserted into the string.
    /// Example: If the source string is 'ping -n 1 ${host}',
    ///   `name` would be 'host'
    final String name = match.group(1)!;
    return replacementValues.containsKey(name) ? replacementValues[name]! : '';
  });
}

/// Given a list of strings possibly containing string interpolation sequences
/// (so for example, something like `['ping', '-n', '1', '${host}']`), replace
/// all those interpolation sequences with the matching value given in [replacementValues].
///
/// If the value could not be found inside [replacementValues], an empty
/// string will be substituted instead.
///
/// However, if the dollar sign inside the string is preceded with a backslash,
/// the sequences won't be substituted at all.
///
/// Example:
/// ```dart
/// final interpolated = _interpolateString(['ping', '-n', '1', r'${host}'], {'host': 'raspberrypi'});
/// print(interpolated);  // will print '[ping, -n, 1, raspberrypi]'
///
/// final interpolated2 = _interpolateString(['ping', '-n', '1', r'${_host}'], {'host': 'raspberrypi'});
/// print(interpolated2); // will print '[ping, -n, 1, ]'
/// ```
List<String> interpolateStringList(List<String> toInterpolate, Map<String, String> replacementValues) {
  return toInterpolate.map((String s) => interpolateString(s, replacementValues)).toList();
}
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

/// Returns the first line-based match for [regExp] in [file].
///
/// Assumes UTF8 encoding.
Match? firstMatchInFile(File file, RegExp regExp) {
  if (!file.existsSync()) {
    return null;
  }
  for (final String line in file.readAsLinesSync()) {
    final Match? match = regExp.firstMatch(line);
    if (match != null) {
      return match;
    }
  }
  return null;
}