Add and document et cleanup. (flutter/engine#56327)
Closes https://github.com/flutter/flutter/issues/157945. ```sh % et cleanup --dry-run Checking /Users/matanl/Developer/engine/src/out... The following directories were accessed later than 2024-10-02: android_debug android_debug_arm64 android_debug_unopt android_debug_unopt_arm64_ide host_debug_unopt_arm64_ide ios_debug ios_debug_sim_unopt_arm64 ios_debug_unopt ios_debug_unopt_arm64 license_script_output wasm_release web_tests Run without --dry-run to reclaim 2.79gb. ``` ```sh flutter % et cleanup Checking /Users/matanl/Developer/engine/src/out... Deleted 12 output directories and reclaimed 2.79gb. ```
This commit is contained in:
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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: <https://github.com/flutter/flutter/issues/157945>.
|
||||
> 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.
|
||||
|
||||
@@ -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<String> get aliases => const ['gc'];
|
||||
|
||||
static final _dateString = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$');
|
||||
|
||||
@override
|
||||
Future<int> 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;
|
||||
}
|
||||
@@ -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<int> {
|
||||
usageLineLength: _usageLineLength,
|
||||
) {
|
||||
final List<Command<int>> commands = <Command<int>>[
|
||||
CleanupCommand(
|
||||
environment: environment,
|
||||
usageLineLength: _usageLineLength,
|
||||
),
|
||||
FetchCommand(
|
||||
environment: environment,
|
||||
usageLineLength: _usageLineLength,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}) {
|
||||
|
||||
@@ -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<FatalError>()),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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 <CannedProcess>[],
|
||||
}) {
|
||||
testLogs = <LogRecord>[];
|
||||
@@ -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<CannedProcess> cannedProcesses = const <CannedProcess>[],
|
||||
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 + <CannedProcess>[cannedGn],
|
||||
verbose: verbose,
|
||||
now: now,
|
||||
);
|
||||
return testEnvironment;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user