Skip to content

Commit

Permalink
Remove or replace unnecessary usages of late (#4512)
Browse files Browse the repository at this point in the history
  • Loading branch information
parlough authored Feb 6, 2025
1 parent 4a2cbf3 commit a652ee4
Show file tree
Hide file tree
Showing 12 changed files with 97 additions and 99 deletions.
4 changes: 2 additions & 2 deletions lib/src/command/add.dart
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ Specify multiple sdk packages with descriptors.''');
resolutionPubspec = await _addPackageToPubspec(resolutionPubspec, update);
}

late SolveResult solveResult;
final SolveResult solveResult;

try {
/// Use [SolveType.UPGRADE] to solve for the highest version of [package]
Expand Down Expand Up @@ -520,7 +520,7 @@ Specify multiple sdk packages with descriptors.''');
}

/// The package to be added.
late final PackageRef ref;
final PackageRef ref;
final path = argResults.path;
if (argResults.hasGitOptions) {
final gitUrl = argResults.gitUrl;
Expand Down
44 changes: 23 additions & 21 deletions lib/src/entrypoint.dart
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ See $workspacesDocUrl for more information.''',
'"pub" version, please run "$topLevelProgram pub get".');
}

late String packageConfigRaw;
final String packageConfigRaw;
try {
packageConfigRaw = readTextFile(packageConfigPath);
} on FileException {
Expand All @@ -249,7 +249,7 @@ See $workspacesDocUrl for more information.''',
'please run "$topLevelProgram pub get".',
);
}
late PackageConfig result;
final PackageConfig result;
try {
result = PackageConfig.fromJson(
json.decode(packageConfigRaw) as Object?,
Expand Down Expand Up @@ -297,7 +297,7 @@ See $workspacesDocUrl for more information.''',

/// The path to the entrypoint's ".dart_tool/package_config.json" file
/// relative to the current working directory .
late String packageConfigPath = p.relative(
late final String packageConfigPath = p.relative(
p.normalize(p.join(workspaceRoot.dir, '.dart_tool', 'package_config.json')),
);

Expand Down Expand Up @@ -434,19 +434,21 @@ See $workspacesDocUrl for more information.''',
VersionConstraint? entrypointSdkConstraint,
}) async {
final entries = <PackageConfigEntry>[];
late final relativeFromPath = p.join(workspaceRoot.dir, '.dart_tool');
for (final name in ordered(lockFile.packages.keys)) {
final id = lockFile.packages[name]!;
final rootPath = cache.getDirectory(id, relativeFrom: relativeFromPath);
final pubspec = await cache.describe(id);
entries.add(
PackageConfigEntry(
name: name,
rootUri: p.toUri(rootPath),
packageUri: p.toUri('lib/'),
languageVersion: pubspec.languageVersion,
),
);
if (lockFile.packages.isNotEmpty) {
final relativeFromPath = p.join(workspaceRoot.dir, '.dart_tool');
for (final name in ordered(lockFile.packages.keys)) {
final id = lockFile.packages[name]!;
final rootPath = cache.getDirectory(id, relativeFrom: relativeFromPath);
final pubspec = await cache.describe(id);
entries.add(
PackageConfigEntry(
name: name,
rootUri: p.toUri(rootPath),
packageUri: p.toUri('lib/'),
languageVersion: pubspec.languageVersion,
),
);
}
}

if (!isCachedGlobal) {
Expand Down Expand Up @@ -1016,8 +1018,8 @@ To update `$lockFilePath` run `$topLevelProgram pub get`$suffix without
rootDir = parent;
break;
}
final potentialPubspacPath = p.join(parent, 'pubspec.yaml');
if (tryStatFile(potentialPubspacPath) == null) {
final potentialPubspecPath = p.join(parent, 'pubspec.yaml');
if (tryStatFile(potentialPubspecPath) == null) {
// No package at [parent] continue to next dir.
continue;
}
Expand All @@ -1029,8 +1031,8 @@ To update `$lockFilePath` run `$topLevelProgram pub get`$suffix without
final workspaceRefText = tryReadTextFile(potentialWorkspaceRefPath);
if (workspaceRefText == null) {
log.fine(
'`$potentialPubspacPath` exists without corresponding '
'`$potentialPubspacPath` or `$potentialWorkspaceRefPath`.',
'`$potentialPubspecPath` exists without corresponding '
'`$potentialPubspecPath` or `$potentialWorkspaceRefPath`.',
);
return null;
} else {
Expand Down Expand Up @@ -1093,7 +1095,7 @@ To update `$lockFilePath` run `$topLevelProgram pub get`$suffix without
return null;
}
final lockFilePath = p.normalize(p.join(rootDir, 'pubspec.lock'));
late final packageConfig = _loadPackageConfig(packageConfigPath);
final packageConfig = _loadPackageConfig(packageConfigPath);
if (p.isWithin(cache.rootDir, packageConfigPath)) {
// We always consider a global package (inside the cache) up-to-date.
return (packageConfig, rootDir);
Expand Down
10 changes: 5 additions & 5 deletions lib/src/error_group.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@ class ErrorGroup {
///
/// We need to be able to access it internally as an [_ErrorGroupFuture] so
/// we can check if it has listeners and signal errors on it.
late _ErrorGroupFuture _done;
late final _ErrorGroupFuture<void> _done;

/// Returns a [Future] that completes successfully when all members of `this`
/// are complete, or with an error if any member receives an error.
///
/// This [Future] is effectively in the group in that an error on it won't be
/// passed to the top-level error handler unless no members of the group have
/// listeners attached.
Future get done => _done;
Future<void> get done => _done;

/// Creates a new group with no members.
ErrorGroup() {
Expand Down Expand Up @@ -257,17 +257,17 @@ class _ErrorGroupStream<T> extends Stream<T> {
var _isDone = false;

/// The underlying [StreamController] for `this`.
late final StreamController<T> _controller;
final StreamController<T> _controller;

/// The controller's [Stream].
///
/// May be different than `_controller.stream` if the wrapped stream is a
/// broadcasting stream.
late Stream<T> _stream;
late final Stream<T> _stream;

/// The [StreamSubscription] that connects the wrapped [Stream] to
/// [_controller].
late StreamSubscription<T> _subscription;
late final StreamSubscription<T> _subscription;

/// Whether `this` has any listeners.
bool get _hasListeners => _controller.hasListener;
Expand Down
11 changes: 5 additions & 6 deletions lib/src/executable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -351,8 +351,8 @@ Future<DartExecutableWithPackageConfig> getExecutableForCommand(
CommandResolutionIssue.fileNotFound,
);
}
late final String command;
String package;
final String command;
final String package;
if (descriptor.contains(':')) {
final parts = descriptor.split(':');
if (parts.length > 2) {
Expand All @@ -361,12 +361,11 @@ Future<DartExecutableWithPackageConfig> getExecutableForCommand(
CommandResolutionIssue.parseError,
);
}
package = parts[0];
if (package.isEmpty) package = rootPackageName;
final packageName = parts[0];
package = packageName.isNotEmpty ? packageName : rootPackageName;
command = parts[1];
} else {
package = descriptor;
if (package.isEmpty) package = rootPackageName;
package = descriptor.isNotEmpty ? descriptor : rootPackageName;
command = package;
}

Expand Down
6 changes: 3 additions & 3 deletions lib/src/global_packages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ To recompile executables, first run `$topLevelProgram pub global deactivate $nam

/// Shows the user the currently active package with [name], if any.
LockFile? _describeActive(String name, SystemCache cache) {
late final LockFile lockFile;
final LockFile lockFile;
try {
lockFile = LockFile.load(_getLockFilePath(name), cache.sources);
} on IOException {
Expand Down Expand Up @@ -380,7 +380,7 @@ To recompile executables, first run `$topLevelProgram pub global deactivate $nam
/// Returns an [Entrypoint] loaded with the active package if found.
Future<Entrypoint> find(String name) async {
final lockFilePath = _getLockFilePath(name);
late final LockFile lockFile;
final LockFile lockFile;
try {
lockFile = LockFile.load(lockFilePath, cache.sources);
} on IOException {
Expand Down Expand Up @@ -861,7 +861,7 @@ Try reactivating the package.
final pubInvocation =
runningFromTest ? Platform.script.toFilePath() : 'pub';

late String binstub;
final String binstub;
// We need an absolute path since relative ones won't be relative to the
// right directory when the user runs this.
snapshot = p.absolute(snapshot);
Expand Down
56 changes: 29 additions & 27 deletions lib/src/io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -950,26 +950,11 @@ class PubProcess {
/// The underlying `dart:io` [Process].
final Process _process;

/// The mutable field for [stdin].
late EventSink<List<int>> _stdin;

/// The mutable field for [stdinClosed].
late Future _stdinClosed;

/// The mutable field for [stdout].
late ByteStream _stdout;

/// The mutable field for [stderr].
late ByteStream _stderr;

/// The mutable field for [exitCode].
late Future<int> _exitCode;

/// The sink used for passing data to the process's standard input stream.
///
/// Errors on this stream are surfaced through [stdinClosed], [stdout],
/// [stderr], and [exitCode], which are all members of an [ErrorGroup].
EventSink<List<int>> get stdin => _stdin;
final EventSink<List<int>> stdin;

// TODO(nweiz): write some more sophisticated Future machinery so that this
// doesn't surface errors from the other streams/futures, but still passes its
Expand All @@ -981,44 +966,61 @@ class PubProcess {
/// This is in an [ErrorGroup] with [stdout], [stderr], and [exitCode], so any
/// error in process will be passed to it, but won't reach the top-level error
/// handler unless nothing has handled it.
Future get stdinClosed => _stdinClosed;
final Future stdinClosed;

/// The process's standard output stream.
///
/// This is in an [ErrorGroup] with [stdinClosed], [stderr], and [exitCode],
/// so any error in process will be passed to it, but won't reach the
/// top-level error handler unless nothing has handled it.
ByteStream get stdout => _stdout;
final ByteStream stdout;

/// The process's standard error stream.
///
/// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [exitCode],
/// so any error in process will be passed to it, but won't reach the
/// top-level error handler unless nothing has handled it.
ByteStream get stderr => _stderr;
final ByteStream stderr;

/// A [Future] that will complete to the process's exit code once the process
/// has finished running.
///
/// This is in an [ErrorGroup] with [stdinClosed], [stdout], and [stderr], so
/// any error in process will be passed to it, but won't reach the top-level
/// error handler unless nothing has handled it.
Future<int> get exitCode => _exitCode;
final Future<int> exitCode;

PubProcess._(
this._process, {
required this.stdin,
required this.stdinClosed,
required this.stdout,
required this.stderr,
required this.exitCode,
});

/// Creates a new [PubProcess] wrapping [process].
PubProcess(Process process) : _process = process {
factory PubProcess(Process process) {
final errorGroup = ErrorGroup();

final (consumerSink, done) = _consumerToSink(process.stdin);
_stdin = consumerSink;
_stdinClosed = errorGroup.registerFuture(done);
final stdinClosed = errorGroup.registerFuture(done);

_stdout = ByteStream(errorGroup.registerStream(process.stdout));
_stderr = ByteStream(errorGroup.registerStream(process.stderr));
final stdout = ByteStream(errorGroup.registerStream(process.stdout));
final stderr = ByteStream(errorGroup.registerStream(process.stderr));

final exitCodeCompleter = Completer<int>();
_exitCode = errorGroup.registerFuture(exitCodeCompleter.future);
_process.exitCode.then(exitCodeCompleter.complete);
final exitCode = errorGroup.registerFuture(exitCodeCompleter.future);
process.exitCode.then(exitCodeCompleter.complete);

return PubProcess._(
process,
stdin: consumerSink,
stdinClosed: stdinClosed,
stdout: stdout,
stderr: stderr,
exitCode: exitCode,
);
}

/// Sends [signal] to the underlying process.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/lock_file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class LockFile {

/// The intersections of all SDK constraints for all locked packages, indexed
/// by SDK identifier.
Map<String, SdkConstraint> sdkConstraints;
final Map<String, SdkConstraint> sdkConstraints;

/// Dependency names that appeared in the root package's `dependencies`
/// section.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/package.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Package {
///
/// If [dir] is just a parent directory like ../.. it gets replaced with
/// the absolute dir.
late String presentationDir =
late final String presentationDir =
p.isWithin(dir, '.') ? p.normalize(p.absolute(dir)) : dir;

/// The name of the package.
Expand Down
2 changes: 1 addition & 1 deletion lib/src/pubspec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ environment:
Uri? overridesLocation,
required Description containingDescription,
}) {
late final YamlMap pubspecMap;
final YamlMap pubspecMap;
YamlMap? overridesFileMap;
try {
pubspecMap = _ensureMap(loadYamlNode(contents, sourceUrl: location));
Expand Down
6 changes: 3 additions & 3 deletions lib/src/source/hosted.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,7 @@ class HostedSource extends CachedSource {
return (await Future.wait(
listDir(rootDir).map((serverDir) async {
final directory = p.basename(serverDir);
late final String url;
final String url;
try {
url = _directoryToUrl(directory);
} on FormatException {
Expand Down Expand Up @@ -1493,13 +1493,13 @@ class HostedSource extends CachedSource {
versions.firstWhereOrNull((i) => i.version == id.version);
final packageName = id.name;
final version = id.version;
late final Uint8List contentHash;
if (versionInfo == null) {
throw PackageNotFoundException(
'Package $packageName has no version $version',
);
}

late final Uint8List contentHash;
final archiveUrl = versionInfo.archiveUrl;
log.io('Get package from $archiveUrl.');
log.fine('Downloading ${log.bold(id.name)} ${id.version}...');
Expand Down Expand Up @@ -1626,7 +1626,7 @@ See $contentHashesDocumentationUrl.
) async {
// Extract to a temp-folder and do atomic rename to preserve the integrity
// of the cache.
late final Uint8List contentHash;
final Uint8List contentHash;

final tempDir = cache.createTempDir();
final PackageId id;
Expand Down
7 changes: 3 additions & 4 deletions lib/src/system_cache.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,9 @@ Consider setting the `PUB_CACHE` variable manually.
})();

/// The available sources.
late final _sources = Map<String, Source>.fromIterable(
[hosted, git, path, sdk],
key: (source) => (source as Source).name,
);
late final _sources = {
for (final source in [hosted, git, path, sdk]) source.name: source,
};

Source sources(String? name) {
return name == null
Expand Down
Loading

0 comments on commit a652ee4

Please sign in to comment.