diff --git a/engine/src/flutter/tools/engine_tool/BUILD.gn b/engine/src/flutter/tools/engine_tool/BUILD.gn index 398eb012e7..23cb8c0728 100644 --- a/engine/src/flutter/tools/engine_tool/BUILD.gn +++ b/engine/src/flutter/tools/engine_tool/BUILD.gn @@ -9,6 +9,7 @@ group("tests") { public_deps = [ ":build_command_test", ":build_plan_test", + ":cleanup_command_test", ":entry_point_test", ":fetch_command_test", ":flutter_tools_test", @@ -41,6 +42,10 @@ dart_test("build_command_test") { main_dart = "test/commands/build_command_test.dart" } +dart_test("cleanup_command_test") { + main_dart = "test/commands/cleanup_command_test.dart" +} + dart_test("build_plan_test") { main_dart = "test/commands/build_plan_test.dart" } diff --git a/engine/src/flutter/tools/engine_tool/README.md b/engine/src/flutter/tools/engine_tool/README.md index 74772ac103..f2ecd191b2 100644 --- a/engine/src/flutter/tools/engine_tool/README.md +++ b/engine/src/flutter/tools/engine_tool/README.md @@ -108,9 +108,9 @@ See [building a host engine](#building-a-host-engine) and > [!CAUTION] > Each build configuration (sometimes called a _variant_) produces a different > set of output files in `$ENGINE/src/out`, e.g. ``$ENGINE/src/out/host_debug`; -> these outputs can be multiple GBs, and add up quickly. Consider manually -> cleaning up a `src/out` directory and/or +1'ing the following feature -> request: . +> these outputs can be multiple GBs, and add up quickly. Consider using +> [`et cleanup`](#reclaiming-older-output-directories) to delete older output +> directories automatically. ## Common Tasks @@ -257,8 +257,7 @@ cd to/project/dir et run ``` -> [!NOTE] -> `et run` will rebuild (if necessary) host and target builds, which can take +> [!NOTE] > `et run` will rebuild (if necessary) host and target builds, which can take > a significant amount of time. ## Advanced Features @@ -353,6 +352,25 @@ If you need to build a configuration _not-specified_, consider the following: > [!TIP] > For more information on [build configurations, see the README](../../ci/builders/README.md). +### Reclaiming older output directories + +The `et cleanup` command removes older output directories that have not been +accessed, by default in the last 30 days, but customizable with the command-line +argument `--untouched-since`. + +Consider using `dry-run` to preview what _would_ be deleted: + +```sh +# Deletes all output directories older than 30 days. +et cleanup + +# Shows what output directories would be deleted by the above command. +et cleanup --dry-run + +# Deletes all output directories accessed last in 2023. +et cleanup --untouched-since=2024-01-01 +``` + ## Contributing We welcome contributions to improve `et` for our all developers. diff --git a/engine/src/flutter/tools/engine_tool/lib/src/commands/cleanup_command.dart b/engine/src/flutter/tools/engine_tool/lib/src/commands/cleanup_command.dart new file mode 100644 index 0000000000..894c2f1495 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/lib/src/commands/cleanup_command.dart @@ -0,0 +1,164 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +import '../logger.dart'; +import 'command.dart'; +import 'flags.dart'; + +/// The `cleanup` command for removing unnecessary on-disk artifacts. +final class CleanupCommand extends CommandBase { + /// Constructs the `cleanup` command. + CleanupCommand({ + required super.environment, + super.help = false, + super.usageLineLength, + }) { + argParser.addFlag( + dryRunFlag, + abbr: 'd', + help: 'Write changes to stdout without modifying the file system.', + negatable: false, + ); + + argParser.addOption( + 'untouched-since', + defaultsTo: () { + const thirtyDays = Duration(days: 30); + final dateTime = environment.now().subtract(thirtyDays); + return _toDateString(dateTime); + }(), + help: 'What date to consider artifacts old enough to safely remove.', + valueHelp: 'YYYY-MM-DD', + ); + } + + @override + String get name => 'cleanup'; + + @override + String get description => 'Removes stale or unnecessary on-disk artifacts.'; + + @override + List get aliases => const ['gc']; + + static final _dateString = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$'); + + @override + Future run() async { + final dryRun = argResults!.flag('dry-run'); + final since = () { + final yyyyMmDd = argResults!.option('untouched-since')!; + final dateMatch = _dateString.matchAsPrefix(yyyyMmDd); + if (dateMatch == null) { + throw FatalError('Invalid --untouched-since: $yyyyMmDd'); + } + return DateTime( + int.parse(dateMatch.group(1)!), + int.parse(dateMatch.group(2)!), + int.parse(dateMatch.group(3)!), + ); + }(); + + // Look at the directories in "out" for ones older than "since". + environment.logger.status('Checking ${environment.engine.outDir.path}...'); + final toDelete = [ + await for (final entity in environment.engine.outDir.list()) + if (entity is Directory && + _shouldDelete(entity, ifAccessedLaterThan: since)) + entity + ]..sort((a, b) => a.path.compareTo(b.path)); + + if (toDelete.isEmpty) { + environment.logger.status( + 'No directories were accessed later than ${_toDateString(since)}.', + ); + return 0; + } + + final totalSize = toDelete.fold(0, (p, n) => p + _getSizeRecursive(n)); + + if (dryRun) { + environment.logger.status( + 'The following directories were accessed later than ${_toDateString(since)}:', + ); + for (final e in toDelete) { + environment.logger.status(' ${p.basename(e.path)}'); + } + environment.logger.status( + 'Run without --dry-run to reclaim ' + '${_toReadableBytes(totalSize.toDouble())}.', + ); + return 0; + } + + final spinner = environment.logger.startSpinner(); + for (final e in toDelete) { + try { + await e.delete(recursive: true); + } on FileSystemException catch (_) { + environment.logger.warning('Failed to delete ${p.basename(e.path)}'); + } + } + spinner.finish(); + + environment.logger.status( + 'Deleted ${toDelete.length} output directories and reclaimed ' + '${_toReadableBytes(totalSize.toDouble())}.', + ); + + return 0; + } + + static bool _shouldDelete( + Directory entity, { + required DateTime ifAccessedLaterThan, + }) { + final accessed = entity.statSync().accessed; + return accessed.isBefore(ifAccessedLaterThan); + } +} + +int _getSizeRecursive(Directory dir) { + return dir.listSync().fold(0, (p, n) => p + n.statSync().size); +} + +String _toDateString(DateTime dateTime) { + final output = StringBuffer('${dateTime.year}-'); + output.write(dateTime.month.toString().padLeft(2, '0')); + output.write('-'); + output.write(dateTime.day.toString().padLeft(2, '0')); + return output.toString(); +} + +String _toReadableBytes(double bytes) { + var type = _FileSize.bytes; + if (bytes >= 1024) { + type = _FileSize.kilobytes; + bytes = bytes / 1024; + } + if (bytes >= 1024) { + type = _FileSize.megabytes; + bytes = bytes / 1024; + } + if (bytes >= 1024) { + type = _FileSize.gigabytes; + bytes = bytes / 1024; + } + return '${bytes.toStringAsFixed(2)}${type.suffix}'; +} + +enum _FileSize { + bytes('bytes'), + kilobytes('KB'), + megabytes('MB'), + gigabytes('GB'); + + const _FileSize(this.suffix); + final String suffix; +} diff --git a/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart b/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart index d1afdd874d..04fe0ba849 100644 --- a/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart +++ b/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart @@ -7,6 +7,7 @@ import 'package:engine_build_configs/engine_build_configs.dart'; import '../environment.dart'; import 'build_command.dart'; +import 'cleanup_command.dart'; import 'fetch_command.dart'; import 'flags.dart'; import 'format_command.dart'; @@ -34,6 +35,10 @@ final class ToolCommandRunner extends CommandRunner { usageLineLength: _usageLineLength, ) { final List> commands = >[ + CleanupCommand( + environment: environment, + usageLineLength: _usageLineLength, + ), FetchCommand( environment: environment, usageLineLength: _usageLineLength, diff --git a/engine/src/flutter/tools/engine_tool/lib/src/environment.dart b/engine/src/flutter/tools/engine_tool/lib/src/environment.dart index 94bedd1e14..0a1b13a5e3 100644 --- a/engine/src/flutter/tools/engine_tool/lib/src/environment.dart +++ b/engine/src/flutter/tools/engine_tool/lib/src/environment.dart @@ -26,6 +26,7 @@ final class Environment { required this.logger, required this.platform, required this.processRunner, + this.now = DateTime.now, this.verbose = false, }); @@ -47,6 +48,9 @@ final class Environment { /// Facility for commands to run subprocesses. final ProcessRunner processRunner; + /// Returns the current [Datetime]. + final DateTime Function() now; + /// Whether it appears that the current environment supports remote builds. /// /// This is a heuristic based on the presence of certain directories in the diff --git a/engine/src/flutter/tools/engine_tool/lib/src/logger.dart b/engine/src/flutter/tools/engine_tool/lib/src/logger.dart index 411d8d1902..d642769aa5 100644 --- a/engine/src/flutter/tools/engine_tool/lib/src/logger.dart +++ b/engine/src/flutter/tools/engine_tool/lib/src/logger.dart @@ -31,8 +31,7 @@ class Logger { /// Constructs a logger for use in the tool. Logger({ log.Level level = statusLevel, - }) - : _logger = log.Logger.detached('et'), + }) : _logger = log.Logger.detached('et'), _test = false { _logger.level = level; _logger.onRecord.listen(_handler); @@ -45,8 +44,7 @@ class Logger { Logger.test( void Function(log.LogRecord) onLog, { log.Level level = statusLevel, - }) - : _logger = log.Logger.detached('et'), + }) : _logger = log.Logger.detached('et'), _test = true { _logger.level = level; _logger.onRecord.listen(onLog); @@ -187,6 +185,7 @@ class Logger { } /// Starts printing a progress spinner. + @useResult Spinner startSpinner({ void Function()? onFinish, }) { diff --git a/engine/src/flutter/tools/engine_tool/test/commands/cleanup_command_test.dart b/engine/src/flutter/tools/engine_tool/test/commands/cleanup_command_test.dart new file mode 100644 index 0000000000..5408b6f133 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/test/commands/cleanup_command_test.dart @@ -0,0 +1,153 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io'; + +import 'package:engine_tool/src/commands/command_runner.dart'; +import 'package:engine_tool/src/logger.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import '../src/matchers.dart'; +import '../src/utils.dart'; + +void main() { + test('prints instead of deleting when --dry-run', () async { + final fakeNow = DateTime.now().add(const Duration(days: 100)); + final testEnv = TestEnvironment.withTestEngine(now: () => fakeNow); + addTearDown(testEnv.cleanup); + + final targetDir = Directory(p.join( + testEnv.environment.engine.outDir.path, + 'host_old', + )); + await targetDir.create(recursive: true); + + final runner = ToolCommandRunner( + environment: testEnv.environment, + configs: {}, + ); + + final result = await runner.run(['cleanup', '--dry-run']); + expect(result, 0); + + expect( + targetDir.existsSync(), + true, + reason: '--dry-run should not delete directories', + ); + + expect( + testEnv.testLogs, + containsAllInOrder([ + logRecord( + contains('Checking ${testEnv.environment.engine.outDir.path}'), + ), + logRecord( + contains('The following directories were accessed later than'), + ), + logRecord( + contains('host_old'), + ), + ]), + ); + }); + + test('uses 30 days if --untouched-since is omitted', () async { + final fakeNow = DateTime.now().add(const Duration(days: 32)); + final testEnv = TestEnvironment.withTestEngine(now: () => fakeNow); + addTearDown(testEnv.cleanup); + + final targetDir = Directory(p.join( + testEnv.environment.engine.outDir.path, + 'host_old', + )); + await targetDir.create(recursive: true); + + final runner = ToolCommandRunner( + environment: testEnv.environment, + configs: {}, + ); + + final result = await runner.run(['cleanup']); + expect(result, 0); + + expect( + targetDir.existsSync(), + false, + reason: 'Should be > 30 days since accessed', + ); + + expect( + testEnv.testLogs, + containsAllInOrder([ + logRecord( + contains('Checking ${testEnv.environment.engine.outDir.path}'), + ), + logRecord( + contains('Deleted 1 output directories'), + ), + ]), + ); + }); + + test('parses the provided YYYY-MM-DD', () async { + final fakeNow = DateTime.now(); + final testEnv = TestEnvironment.withTestEngine(now: () => fakeNow); + addTearDown(testEnv.cleanup); + + final targetDir = Directory(p.join( + testEnv.environment.engine.outDir.path, + 'host_old', + )); + await targetDir.create(recursive: true); + + final runner = ToolCommandRunner( + environment: testEnv.environment, + configs: {}, + ); + + final result = await runner.run([ + 'cleanup', + '--untouched-since=${fakeNow.year + 1}-01-01', + ]); + expect(result, 0); + + expect( + targetDir.existsSync(), + false, + reason: 'Due to --untouched-since being a year in the future', + ); + + expect( + testEnv.testLogs, + containsAllInOrder([ + logRecord( + contains('Checking ${testEnv.environment.engine.outDir.path}'), + ), + logRecord( + contains('Deleted 1 output directories'), + ), + ]), + ); + }); + + test('refuses an invalid YYYY-MM-DD date', () async { + final testEnv = TestEnvironment.withTestEngine(); + addTearDown(testEnv.cleanup); + + final runner = ToolCommandRunner( + environment: testEnv.environment, + configs: {}, + ); + + expect( + runner.run([ + 'cleanup', + '--untouched-since=02-14-2024', + ]), + throwsA(isA()), + ); + }); +} diff --git a/engine/src/flutter/tools/engine_tool/test/src/utils.dart b/engine/src/flutter/tools/engine_tool/test/src/utils.dart index 4ab0c4dd4e..55f33bf797 100644 --- a/engine/src/flutter/tools/engine_tool/test/src/utils.dart +++ b/engine/src/flutter/tools/engine_tool/test/src/utils.dart @@ -61,6 +61,7 @@ class TestEnvironment { Logger? logger, ffi.Abi abi = ffi.Abi.macosArm64, bool verbose = false, + DateTime Function() now = DateTime.now, this.cannedProcesses = const [], }) { testLogs = []; @@ -100,6 +101,7 @@ class TestEnvironment { })), logger: logger, verbose: verbose, + now: now, ); } @@ -108,6 +110,7 @@ class TestEnvironment { ffi.Abi abi = ffi.Abi.linuxX64, List cannedProcesses = const [], bool verbose = false, + DateTime Function() now = DateTime.now, }) { final io.Directory rootDir = io.Directory.systemTemp.createTempSync('et'); final TestEngine engine = TestEngine.createTemp(rootDir: rootDir); @@ -135,6 +138,7 @@ class TestEnvironment { abi: abi, cannedProcesses: cannedProcesses + [cannedGn], verbose: verbose, + now: now, ); return testEnvironment; }