Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate code excerpter packages to null safety #146

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Further cleanup, simplifications, and formatting
  • Loading branch information
parlough committed Jan 10, 2022
commit 2b4bce0ac6d71b02b9af87b92566d3f979632cda
2 changes: 1 addition & 1 deletion packages/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ linter:
- avoid_catching_errors
parlough marked this conversation as resolved.
Show resolved Hide resolved
- avoid_dynamic_calls
- avoid_empty_else
#- avoid_function_literals_in_foreach_calls
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_private_typedef_functions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import 'package:logging/logging.dart';
import 'src/code_excerpt_updater.dart';
import 'src/logger.dart';

const _commandName = 'code_excerpt_updater';
parlough marked this conversation as resolved.
Show resolved Hide resolved
final _validExt = RegExp(r'\.(dart|jade|md)$');
final _dotPathRe = RegExp(r'(^|/)\..*($|/)');
const String _commandName = 'code_excerpt_updater';
final RegExp _dotPathRe = RegExp(r'(^|/)\..*($|/)');
final RegExp _validExt = RegExp(r'\.(dart|jade|md)$');

/// Processes `.dart` and `.md` files, recursively traverses directories
/// using [Updater]. See this command's help for CLI argument details.
Expand Down
6 changes: 3 additions & 3 deletions packages/code_excerpt_updater/lib/src/args.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ class ArgProcessor {
return info;
}

RegExp supportedArgs = RegExp(
final RegExp supportedArgs = RegExp(
r'^(class|diff-with|diff-u|from|indent-by|path-base|plaster|region|replace|'
r'remove|retain|skip|take|title|to)$',
);
RegExp argRegExp = RegExp(r'^([-\w]+)\s*(=\s*"(.*?)"\s*|\b)\s*');
final RegExp argRegExp = RegExp(r'^([-\w]+)\s*(=\s*"(.*?)"\s*|\b)\s*');

void _extractAndNormalizeNamedArgs(InstrInfo info, String? argsAsString) {
if (argsAsString == null) return;
Expand Down Expand Up @@ -98,7 +98,7 @@ class ArgProcessor {
_isNullOr(args['take'], _isInt);
}

final isNumericRegExp = RegExp(r'^[-+]?\d+$');
final RegExp isNumericRegExp = RegExp(r'^[-+]?\d+$');

bool _isInt(String value) => isNumericRegExp.hasMatch(value);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ import 'instr_info.dart';
import 'issue_reporter.dart';
import 'logger.dart';

final _stringListEquality = const ListEquality<String>().equals;

/// A simple line-based updater for markdown code-blocks. It processes given
/// files line-by-line, looking for matches to [procInstrRE] contained within
/// markdown code blocks.
Expand Down Expand Up @@ -55,7 +53,8 @@ class Updater {
int _origNumLines = 0;
List<String> _lines = [];

int _numSrcDirectives = 0, _numUpdatedFrag = 0;
int _numSrcDirectives = 0;
int _numUpdatedFrag = 0;

/// [err] defaults to [stderr].
Updater(
Expand Down Expand Up @@ -256,7 +255,8 @@ class Updater {
RegExp(r'({){|(})}'), (m) => '${m[1] ?? m[2]}!${m[1] ?? m[2]}')
: _line;
}).toList(growable: false);
if (!_stringListEquality(currentCodeBlock, prefixedCodeExcerpt)) {
if (!const ListEquality<String>()
.equals(currentCodeBlock, prefixedCodeExcerpt)) {
_numUpdatedFrag++;
}
final result = <String>[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,8 @@ CodeTransformer toCodeTransformer(String arg) {
final matcher = patternArgToMatcher(arg, 'to');
return (String code) {
final lines = code.split(eol);
final i = _indexWhere(lines, matcher); // lines.indexWhere(matcher)
final i = lines.indexWhere(matcher);
if (i < 0) return code;
return lines.take(i + 1).join(eol);
};
}

/// Patch: 1.24.3 doesn't have Iterable.indexWhere(). Drop this once we drop 1.x
int _indexWhere(List<String> list, bool Function(String s) test) {
for (var i = 0; i < list.length; i++) {
if (test(list[i])) return i;
}
return -1;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'core.dart';
import 'replace.dart';

const defaultPlaster = '···';
const String defaultPlaster = '···';

class PlasterCodeTransformer {
final bool excerptsYaml;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import '../util.dart';
import 'core.dart';

class ReplaceCodeTransformer {
ReplaceCodeTransformer(this._reporter);

final IssueReporter _reporter;

final _matchDollarNumRE = RegExp(r'(\$+)(&|\d*)');
final _endRE = RegExp(r'^g;?\s*$');
final RegExp _matchDollarNumRE = RegExp(r'(\$+)(&|\d*)');
final RegExp _endRE = RegExp(r'^g;?\s*$');

ReplaceCodeTransformer(this._reporter);

CodeTransformer? codeTransformer(String? replaceExp) {
void _reportErr([String extraInfo = '']) {
Expand Down
6 changes: 3 additions & 3 deletions packages/code_excerpt_updater/lib/src/constants.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// App-wide constants

const backslash = '\\';
const eol = '\n';
const zeroChar = '\u{0}';
const String backslash = '\\';
const String eol = '\n';
const String zeroChar = '\u{0}';

typedef Predicate<T> = bool Function(T);
6 changes: 3 additions & 3 deletions packages/code_excerpt_updater/lib/src/diff/diff.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class Diff {
bool _parsed = false;

final List<String?> fileInfo = [null, null];
List<Hunk> hunks = [];
final List<Hunk> hunks = [];

Diff(this._rawText);

Expand All @@ -34,7 +34,7 @@ class Diff {
for (var i = 0; i < hunks.length; i++) {
final hunk = hunks[i];
if (hunk.dropLinesAfter(to)) {
hunks = hunks.take(i + 1).toList();
hunks.length = i + 1;
return true;
}
}
Expand Down Expand Up @@ -68,7 +68,7 @@ class Diff {
fileInfo[1] = lines[1];

var i = 2;
hunks = [];
hunks.clear();
while (i < lines.length) {
if (!lines[i].startsWith('@@')) throw _invalidHunk(i);
final start = i++;
Expand Down
3 changes: 2 additions & 1 deletion packages/code_excerpt_updater/lib/src/diff/hunk.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const eol = '\n';
class Hunk {
static final Hunk empty = Hunk('');

final headRegExp = RegExp(r'@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@(.*)');
static final RegExp headRegExp =
RegExp(r'@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@(.*)');

String _rawText;

Expand Down
15 changes: 7 additions & 8 deletions packages/code_excerpt_updater/lib/src/differ.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ typedef ErrorReporter = void Function(String msg);
typedef ExcerptFetcher = Iterable<String>? Function(String path, String region);

class Differ {
Differ(this._excerptFetcher, this._log, this._reportError);

final docregionRe = RegExp(r'#(end)?doc(plaster|region)\b');
final RegExp docregionRe = RegExp(r'#(end)?doc(plaster|region)\b');
final ExcerptFetcher _excerptFetcher;
final ErrorReporter _reportError;
final Logger _log;

Directory? _tmpDir;
late final Directory _tmpDir = Directory.systemTemp;

Differ(this._excerptFetcher, this._log, this._reportError);

Iterable<String>? getDiff(String relativeSrcPath1, String region,
Map<String, String?> args, String pathPrefix) {
Expand Down Expand Up @@ -129,7 +129,7 @@ class Differ {
File _writeTmp(String filePath, String content) {
final ext = p.extension(filePath);
final tmpFilePath =
p.join(getTmpDir().path, 'differ_src_${filePath.hashCode}$ext');
p.join(tempDirectory.path, 'differ_src_${filePath.hashCode}$ext');
final tmpFile = File(tmpFilePath);
tmpFile.writeAsStringSync(content);
return tmpFile;
Expand All @@ -141,7 +141,7 @@ class Differ {
// return i;
// }

final _diffFileIdRegEx = RegExp(r'^(---|\+\+\+) ([^\t]+)\t(.*)$');
final RegExp _diffFileIdRegEx = RegExp(r'^(---|\+\+\+) ([^\t]+)\t(.*)$');

String _adjustDiffFileIdLine(String relativePath, String diffFileIdLine) {
final line = diffFileIdLine;
Expand All @@ -153,6 +153,5 @@ class Differ {
return '${match[1]} $relativePath';
}

Directory getTmpDir() =>
_tmpDir ??= Directory.systemTemp; // .createTempSync();
Directory get tempDirectory => _tmpDir;
}
4 changes: 2 additions & 2 deletions packages/code_excerpt_updater/lib/src/excerpt_getter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import 'issue_reporter.dart';
import 'logger.dart';
import 'util.dart';

const _defaultYamlExcerptLeftBorderChar = ''; // I.e., no char by default
const _yamlExcerptLeftBorderCharKey = '#border';
const String _defaultYamlExcerptLeftBorderChar = ''; // I.e., no char by default
const String _yamlExcerptLeftBorderCharKey = '#border';

class ExcerptGetter {
ExcerptGetter(
Expand Down
3 changes: 2 additions & 1 deletion packages/code_excerpt_updater/lib/src/issue_reporter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ class IssueReporter {
final IssueContext _ctx;
final Stdout _stderr;

int numWarnings = 0, numErrors = 0;
int numWarnings = 0;
int numErrors = 0;

IssueReporter(this._ctx, [Stdout? err]) : _stderr = err ?? stderr;

Expand Down
12 changes: 5 additions & 7 deletions packages/code_excerpt_updater/lib/src/util.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import 'dart:math';

import 'constants.dart';

// ignore_for_file: type_annotate_public_apis

/// String to int conversion
int? toInt(String? s, {int radix = 10, int? errorValue}) {
if (s == null) {
Expand All @@ -18,8 +16,8 @@ int? toInt(String? s, {int radix = 10, int? errorValue}) {

//-----------------------------------------------------------------------------

final _blankLineRegEx = RegExp(r'^\s*$');
final _leadingWhitespaceRegEx = RegExp(r'^[ \t]*');
final RegExp _blankLineRegEx = RegExp(r'^\s*$');
final RegExp _leadingWhitespaceRegEx = RegExp(r'^[ \t]*');

Iterable<String> trimMinLeadingSpace(Iterable<String> lines) {
final nonBlankLines = lines.where((s) => !_blankLineRegEx.hasMatch(s));
Expand All @@ -43,10 +41,10 @@ Iterable<String> trimMinLeadingSpace(Iterable<String> lines) {
//-----------------------------------------------------------------------------
// TODO: consider writing the following conversions as a string transformer.

final escapedSlashRE = RegExp(r'\\/');
final RegExp escapedSlashRE = RegExp(r'\\/');

final _slashHexCharRE = RegExp(r'\\x(..)');
final _slashLetterRE = RegExp(r'\\([\\nt])');
final RegExp _slashHexCharRE = RegExp(r'\\x(..)');
final RegExp _slashLetterRE = RegExp(r'\\([\\nt])');

/// Encode special characters: '\t', `\n`, and `\xHH` where `HH` are hex digits.
String encodeSlashChar(String s) => s
Expand Down
4 changes: 2 additions & 2 deletions packages/code_excerpter/lib/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import 'package:build/build.dart';
import 'src/excerpter.dart';
import 'src/util/line.dart';

const excerptLineLeftBorderChar = '|';
const String excerptLineLeftBorderChar = '|';

class CodeExcerptBuilder implements Builder {
final outputExtension = '.excerpt.yaml';
static const outputExtension = '.excerpt.yaml';

final BuilderOptions? options;

Expand Down
4 changes: 2 additions & 2 deletions packages/code_excerpter/lib/src/directive.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
/// - CSS and Java-like languages: `*/`
/// - HTML: `-->`
///
final _directiveRegEx = RegExp(
final RegExp _directiveRegEx = RegExp(
r'^(\s*)(\S.*?)?#((?:end)?docregion)\b\s*(.*?)(?:\s*(?:-->|\*\/))?\s*$');

final _argSeparator = RegExp(r'\s*,\s*');
final RegExp _argSeparator = RegExp(r'\s*,\s*');

/// Represents a code-excerpter directive (both the model and lexical elements)
class Directive {
Expand Down
4 changes: 3 additions & 1 deletion packages/code_excerpter/lib/src/excerpter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ class Excerpter {

if (directive == null) {
// Add line to open regions
_openExcerpts.forEach((name) => excerpts[name]?.add(_line));
for (final name in _openExcerpts) {
excerpts[name]?.add(_line);
}
return;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/code_excerpter/lib/src/util/line.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'dart:math' show min;

const eol = '\n';
const String eol = '\n';

final blankLine = RegExp(r'^\s*$');
final _leadingWhitespace = RegExp(r'^[ \t]*');
final RegExp blankLine = RegExp(r'^\s*$');
final RegExp _leadingWhitespace = RegExp(r'^[ \t]*');

/// WARNING: this method potentially mutates its argument.
void dropTrailingBlankLines(List<String> lines) {
Expand Down
6 changes: 5 additions & 1 deletion packages/code_excerpter/lib/src/util/logging.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ final Logger log = () {
if (logger == null) {
logger = Logger('package:code_excerpter');
Logger.root.level = initLevel;
Logger.root.onRecord.listen((r) => logListeners.forEach((h) => h(r)));
Logger.root.onRecord.listen((r) {
for (final h in logListeners) {
h(r);
}
});
}

return logger;
Expand Down
4 changes: 2 additions & 2 deletions packages/code_excerpter/test/excerpter_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ void main() {
});

group('region not closed:', () {
['', '\n'].forEach((eol) {
for (final eol in const ['', '\n']) {
group('empty region:', () {
test('default region', () {
final excerpter = Excerpter(uri, '#docregion$eol');
Expand All @@ -140,7 +140,7 @@ void main() {
{defaultRegionKey: expectedLines, 'b': expectedLines});
_expectNoLogs();
});
});
}
});

group('problems:', problemCases);
Expand Down