Skip to content

Commit 1aa4fef

Browse files
authored
[flutter_tools] Add CleanService and flutter clean support for tool extensions (flutter#194577)
Adds `CleanEnvironment` in `package:flutter_tools_core`, `CleanService` in `package:flutter_tools_extension`, `LinuxCleanService` in `package:flutter_tools_extension_linux_prototype`, and `ExtensionCleanManager` in `flutter_tools` so `flutter clean` invokes active tool extension clean handlers before removing `.dart_tool/`. Part of flutter#190755 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 82e2490 commit 1aa4fef

20 files changed

Lines changed: 899 additions & 6 deletions

File tree

‎packages/flutter_tools/lib/executable.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ List<FlutterCommand> generateCommands({
279279
),
280280
ChannelCommand(verboseHelp: verboseHelp, toolContext: toolDependencies.toolContext),
281281
CleanCommand(
282+
extensionCleanManager: toolDependencies.extensionCleanManager,
282283
verbose: verbose,
283284
toolContext: toolDependencies.toolContext,
284285
xcode: toolDependencies.appleContext.xcode,

‎packages/flutter_tools/lib/src/commands/clean.dart‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import '../base/logger.dart';
1212
import '../base/terminal.dart';
1313
import '../build_info.dart';
1414
import '../context/tool_context.dart';
15+
import '../experimental/extension_clean_manager.dart';
1516
import '../ios/xcodeproj.dart';
1617
import '../macos/xcode.dart';
1718
import '../project.dart';
@@ -22,6 +23,7 @@ class CleanCommand extends FlutterCommand {
2223
required ToolContext super.toolContext,
2324
required this._xcode,
2425
required this._xcodeProjectInterpreter,
26+
this._extensionCleanManager,
2527
this._verbose = false,
2628
}) : _toolContext = toolContext {
2729
requiresPubspecYaml();
@@ -52,6 +54,7 @@ class CleanCommand extends FlutterCommand {
5254
);
5355
}
5456

57+
final ExtensionCleanManager? _extensionCleanManager;
5558
final ToolContext _toolContext;
5659
final Xcode _xcode;
5760
final XcodeProjectInterpreter _xcodeProjectInterpreter;
@@ -108,6 +111,8 @@ class CleanCommand extends FlutterCommand {
108111
final Directory buildDir = flutterProject.directory.childDirectory(
109112
getBuildDirectory(config, fs),
110113
);
114+
await _extensionCleanManager?.cleanProject(flutterProject, buildDirectory: buildDir);
115+
111116
await deleteFile(buildDir, flutterProject);
112117

113118
await deleteFile(flutterProject.dartTool, flutterProject);

‎packages/flutter_tools/lib/src/context/tool_dependencies.dart‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import '../device.dart';
3737
import '../doctor.dart';
3838
import '../emulator.dart';
3939
import '../experimental/extension_build_manager.dart';
40+
import '../experimental/extension_clean_manager.dart';
4041
import '../experimental/extension_discovery.dart';
4142
import '../experimental/extension_manager.dart';
4243
import '../features.dart';
@@ -99,6 +100,7 @@ class ToolDependencies {
99100
required this.featureFlags,
100101
required this.toolContext,
101102
this.extensionBuildManager,
103+
this.extensionCleanManager,
102104
this.extensionManager,
103105
});
104106

@@ -132,6 +134,9 @@ class ToolDependencies {
132134
/// Manager for querying custom build targets and executing builds via tool extensions.
133135
final ExtensionBuildManager? extensionBuildManager;
134136

137+
/// Manager for delegating project-specific clean operations to tool extensions.
138+
final ExtensionCleanManager? extensionCleanManager;
139+
135140
/// Manager for discovering and communicating with active tool extensions.
136141
final ExtensionManager? extensionManager;
137142

@@ -616,6 +621,12 @@ class ToolDependencies {
616621
logger: finalLogger,
617622
);
618623

624+
final extensionCleanManager = ExtensionCleanManager(
625+
extensionManager: extensionManager,
626+
featureFlags: finalFeatureFlags,
627+
logger: finalLogger,
628+
);
629+
619630
final DeviceManager finalDeviceManager =
620631
deviceManager ??
621632
FlutterDeviceManager(
@@ -652,6 +663,7 @@ class ToolDependencies {
652663
doctor: finalDoctor,
653664
emulatorManager: finalEmulatorManager,
654665
extensionBuildManager: extensionBuildManager,
666+
extensionCleanManager: extensionCleanManager,
655667
extensionManager: extensionManager,
656668
featureFlags: finalFeatureFlags,
657669
toolContext: finalToolContext,
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:async';
6+
7+
import 'package:flutter_tools_core/flutter_tools_core.dart';
8+
import 'package:flutter_tools_extension/flutter_tools_extension.dart';
9+
10+
import '../base/file_system.dart';
11+
import '../base/logger.dart';
12+
import '../features.dart';
13+
import '../project.dart';
14+
import 'extension_discovery.dart';
15+
import 'extension_manager.dart';
16+
17+
/// Manages delegating project-specific `flutter clean` operations to tool extensions.
18+
class ExtensionCleanManager {
19+
ExtensionCleanManager({
20+
required this._extensionManager,
21+
required this._featureFlags,
22+
required this._logger,
23+
});
24+
25+
final ExtensionManager _extensionManager;
26+
final FeatureFlags _featureFlags;
27+
final Logger _logger;
28+
29+
/// Invokes [CleanService.clean] on all active tool extensions for [project].
30+
Future<void> cleanProject(FlutterProject project, {required Directory buildDirectory}) async {
31+
if (!_featureFlags.isToolExtensionsEnabled) {
32+
return;
33+
}
34+
35+
try {
36+
await _extensionManager.ensureInitialized();
37+
} on Object catch (e) {
38+
_logger.printWarning('Failed to initialize extension manager for clean: $e');
39+
return;
40+
}
41+
42+
final cleanExtensions = <ExtensionConnection>[
43+
for (final connection in _extensionManager.connections)
44+
if (connection.capabilities.services.contains(CleanService.serviceNamespace)) connection,
45+
];
46+
47+
if (cleanExtensions.isEmpty) {
48+
return;
49+
}
50+
51+
final environment = CleanEnvironment(
52+
buildDir: buildDirectory.absolute.uri,
53+
projectRoot: project.directory.absolute.uri,
54+
);
55+
56+
final Status status = _logger.startProgress('Cleaning extension build artifacts...');
57+
try {
58+
await Future.wait(
59+
cleanExtensions.map((ExtensionConnection connection) async {
60+
try {
61+
await connection.sendRequest(
62+
CleanService.cleanMethod,
63+
params: <String, Object?>{CleanService.environmentParam: environment.toMap()},
64+
// TODO(bkonyi): Support heartbeat / liveness monitoring for long-running RPCs,
65+
// https://github.com/flutter/flutter/issues/193955.
66+
timeout: null,
67+
);
68+
} on Object catch (e) {
69+
_logger.printError(
70+
'Failed to clean extension artifacts for "${connection.extensionName}": $e',
71+
);
72+
}
73+
}),
74+
);
75+
} finally {
76+
status.stop();
77+
}
78+
}
79+
}

‎packages/flutter_tools/lib/src/experimental/extension_discovery.dart‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,23 @@ class ExtensionConnection {
2020
required Isolate this._isolate,
2121
required this._peer,
2222
required this.capabilities,
23+
required this.extensionName,
2324
required this._logger,
2425
});
2526

27+
/// Fallback extension name used when an extension does not report one in its capabilities.
28+
static const defaultExtensionName = 'unknown_extension';
29+
2630
Isolate? _isolate;
2731
final json_rpc.Peer _peer;
2832
final Logger _logger;
2933

3034
/// The capabilities and supported service namespaces of the extension.
3135
final ToolExtensionCapabilities capabilities;
3236

37+
/// The resolved package or extension name of the connected extension.
38+
final String extensionName;
39+
3340
bool _isDisposed = false;
3441

3542
/// Sends an RPC request to the extension isolate.
@@ -117,6 +124,7 @@ class ExtensionConnection {
117124
isolate: isolate,
118125
peer: peer,
119126
capabilities: capabilities,
127+
extensionName: capabilities.extensionName ?? defaultExtensionName,
120128
logger: logger,
121129
);
122130
} on TimeoutException {

‎packages/flutter_tools/packages/flutter_tools_core/lib/flutter_tools_core.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
library flutter_tools_core;
1010

1111
export 'src/build.dart';
12+
export 'src/clean.dart';
1213
export 'src/config.dart';
1314
export 'src/device.dart';
1415
export 'src/diagnostics.dart';
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:meta/meta.dart';
6+
7+
// TODO(bkonyi): Include ExtensionFlutterProject on CleanEnvironment once
8+
// https://github.com/flutter/flutter/pull/193749 lands so extensions can
9+
// inspect project metadata (such as isModule or isPlugin) during clean.
10+
11+
/// Environment context provided to tool extensions during `flutter clean`.
12+
///
13+
/// The host `flutter_tools` constructs a [CleanEnvironment] with the absolute
14+
/// directory URIs for the project root and build output directory and sends it
15+
/// to active extensions implementing `CleanService`.
16+
@immutable
17+
class CleanEnvironment {
18+
const CleanEnvironment({required this.buildDir, required this.projectRoot});
19+
20+
/// Deserializes a [CleanEnvironment] from a JSON-serializable map.
21+
///
22+
/// Throws a [FormatException] if required fields are missing or are not
23+
/// valid trailing-slash-terminated absolute `file:` directory URIs.
24+
factory CleanEnvironment.fromJson(Map<String, Object?> json) {
25+
if (json case {
26+
projectRootKey: final String projectRootStr,
27+
buildDirKey: final String buildDirStr,
28+
}) {
29+
final Uri? projectRootUri = _parseDirectoryUri(projectRootStr);
30+
final Uri? buildDirUri = _parseDirectoryUri(buildDirStr);
31+
if (projectRootUri != null && buildDirUri != null) {
32+
return CleanEnvironment(buildDir: buildDirUri, projectRoot: projectRootUri);
33+
}
34+
}
35+
throw FormatException('Invalid CleanEnvironment JSON: $json');
36+
}
37+
38+
static Uri? _parseDirectoryUri(String rawUri) {
39+
final Uri? uri = Uri.tryParse(rawUri);
40+
if (uri != null && uri.isScheme('file') && uri.hasAbsolutePath && uri.path.endsWith('/')) {
41+
return uri;
42+
}
43+
return null;
44+
}
45+
46+
/// Map key for [buildDir].
47+
static const String buildDirKey = 'buildDir';
48+
49+
/// Map key for [projectRoot].
50+
static const String projectRootKey = 'projectRoot';
51+
52+
/// The absolute build directory URI of the Flutter project being cleaned
53+
/// (e.g., `file:///path/to/my_app/build/`), trailing-slash terminated and
54+
/// honoring any custom `flutter config --build-dir` setting.
55+
final Uri buildDir;
56+
57+
/// The absolute root directory URI of the Flutter project being cleaned
58+
/// (e.g., `file:///path/to/my_app/`), trailing-slash terminated.
59+
final Uri projectRoot;
60+
61+
/// Serializes the clean environment to a JSON-serializable map.
62+
Map<String, Object?> toMap() => <String, Object?>{
63+
projectRootKey: projectRoot.toString(),
64+
buildDirKey: buildDir.toString(),
65+
};
66+
67+
@override
68+
bool operator ==(Object other) {
69+
return identical(this, other) ||
70+
(other is CleanEnvironment &&
71+
other.projectRoot == projectRoot &&
72+
other.buildDir == buildDir);
73+
}
74+
75+
@override
76+
int get hashCode => Object.hash(projectRoot, buildDir);
77+
78+
@override
79+
String toString() => 'CleanEnvironment(projectRoot: $projectRoot, buildDir: $buildDir)';
80+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter_tools_core/flutter_tools_core.dart';
6+
import 'package:test/test.dart';
7+
8+
void main() {
9+
group('CleanEnvironment', () {
10+
test('serializes and deserializes correctly', () {
11+
final env = CleanEnvironment(
12+
buildDir: Uri.directory('/path/to/project/build'),
13+
projectRoot: Uri.directory('/path/to/project'),
14+
);
15+
16+
final Map<String, Object?> json = env.toMap();
17+
expect(json, <String, Object?>{
18+
'projectRoot': 'file:///path/to/project/',
19+
'buildDir': 'file:///path/to/project/build/',
20+
});
21+
22+
final deserialized = CleanEnvironment.fromJson(json);
23+
expect(deserialized, equals(env));
24+
expect(deserialized.hashCode, equals(env.hashCode));
25+
expect(
26+
deserialized.toString(),
27+
'CleanEnvironment(projectRoot: file:///path/to/project/, '
28+
'buildDir: file:///path/to/project/build/)',
29+
);
30+
});
31+
32+
test('equality respects all fields', () {
33+
final a = CleanEnvironment(
34+
buildDir: Uri.directory('/path/to/project/build'),
35+
projectRoot: Uri.directory('/path/to/project'),
36+
);
37+
final b = CleanEnvironment(
38+
buildDir: Uri.directory('/path/to/project/build'),
39+
projectRoot: Uri.directory('/path/to/project'),
40+
);
41+
final c = CleanEnvironment(
42+
buildDir: Uri.directory('/path/to/other/build'),
43+
projectRoot: Uri.directory('/path/to/project'),
44+
);
45+
final d = CleanEnvironment(
46+
buildDir: Uri.directory('/path/to/project/build'),
47+
projectRoot: Uri.directory('/path/to/other'),
48+
);
49+
50+
expect(a, equals(b));
51+
expect(a, isNot(equals(c)));
52+
expect(a, isNot(equals(d)));
53+
});
54+
55+
test('throws FormatException on missing or relative paths', () {
56+
expect(() => CleanEnvironment.fromJson(const <String, Object?>{}), throwsFormatException);
57+
expect(
58+
() =>
59+
CleanEnvironment.fromJson(const <String, Object?>{'projectRoot': 'file:///only/root'}),
60+
throwsFormatException,
61+
);
62+
expect(
63+
() => CleanEnvironment.fromJson(const <String, Object?>{
64+
'projectRoot': 'relative/path',
65+
'buildDir': 'file:///path/to/project/build/',
66+
}),
67+
throwsFormatException,
68+
);
69+
expect(
70+
() => CleanEnvironment.fromJson(const <String, Object?>{
71+
'projectRoot': 'file:///path/to/project/',
72+
'buildDir': 'relative/build',
73+
}),
74+
throwsFormatException,
75+
);
76+
expect(
77+
() => CleanEnvironment.fromJson(const <String, Object?>{
78+
'projectRoot': 'file:///path/to/project/',
79+
'buildDir': 'file:///path/to/project/build',
80+
}),
81+
throwsFormatException,
82+
);
83+
expect(
84+
() => CleanEnvironment.fromJson(const <String, Object?>{
85+
'projectRoot': 'file:///path/to/project',
86+
'buildDir': 'file:///path/to/project/build/',
87+
}),
88+
throwsFormatException,
89+
);
90+
expect(
91+
() => CleanEnvironment.fromJson(const <String, Object?>{
92+
'projectRoot': 'http://example.com/dir/',
93+
'buildDir': 'file:///path/to/project/build/',
94+
}),
95+
throwsFormatException,
96+
);
97+
expect(
98+
() => CleanEnvironment.fromJson(const <String, Object?>{
99+
'projectRoot': 'file:///path/to/project/',
100+
'buildDir': 'http://example.com/dir/',
101+
}),
102+
throwsFormatException,
103+
);
104+
});
105+
});
106+
}

0 commit comments

Comments
 (0)