-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathhelpers.dart
More file actions
283 lines (253 loc) · 8.8 KB
/
helpers.dart
File metadata and controls
283 lines (253 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. 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:logging/logging.dart';
import 'package:native_assets_builder/src/utils/run_process.dart'
as run_process;
import 'package:native_assets_cli/native_assets_cli.dart';
import 'package:native_assets_cli/native_assets_cli_internal.dart' as internal;
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';
extension UriExtension on Uri {
String get name => pathSegments.where((e) => e != '').last;
Uri get parent => File(toFilePath()).parent.uri;
FileSystemEntity get fileSystemEntity {
if (path.endsWith(Platform.pathSeparator) || path.endsWith('/')) {
return Directory.fromUri(this);
}
return File.fromUri(this);
}
}
const keepTempKey = 'KEEP_TEMPORARY_DIRECTORIES';
Future<void> inTempDir(
Future<void> Function(Uri tempUri) fun, {
String? prefix,
bool keepTemp = false,
}) async {
final tempDir = await Directory.systemTemp.createTemp(prefix);
// Deal with Windows temp folder aliases.
final tempUri =
Directory(await tempDir.resolveSymbolicLinks()).uri.normalizePath();
try {
await fun(tempUri);
} finally {
if ((!Platform.environment.containsKey(keepTempKey) ||
Platform.environment[keepTempKey]!.isEmpty) &&
!keepTemp) {
try {
await tempDir.delete(recursive: true);
} on FileSystemException {
// On Windows, the temp dir might still be locked even though all
// process invocations have finished.
if (!Platform.isWindows) rethrow;
}
}
}
}
/// Runs a [Process].
///
/// If [logger] is provided, stream stdout and stderr to it.
///
/// If [captureOutput], captures stdout and stderr.
Future<run_process.RunProcessResult> runProcess({
required Uri executable,
List<String> arguments = const [],
Uri? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
required Logger? logger,
bool captureOutput = true,
int expectedExitCode = 0,
bool throwOnUnexpectedExitCode = false,
}) =>
run_process.runProcess(
executable: executable,
arguments: arguments,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
logger: logger,
captureOutput: captureOutput,
expectedExitCode: expectedExitCode,
throwOnUnexpectedExitCode: throwOnUnexpectedExitCode,
);
/// Test files are run in a variety of ways, find this package root in all.
///
/// Test files can be run from source from any working directory. The Dart SDK
/// `tools/test.py` runs them from the root of the SDK for example.
///
/// Test files can be run from dill from the root of package. `package:test`
/// does this.
///
/// https://github.com/dart-lang/test/issues/110
Uri findPackageRoot(String packageName) {
final script = Platform.script;
final fileName = script.name;
if (fileName.endsWith('_test.dart')) {
// We're likely running from source.
var directory = script.resolve('.');
while (true) {
final dirName = directory.name;
if (dirName == packageName) {
return directory;
}
final parent = directory.resolve('..');
if (parent == directory) break;
directory = parent;
}
} else if (fileName.endsWith('.dill')) {
final cwd = Directory.current.uri;
final dirName = cwd.name;
if (dirName == packageName) {
return cwd;
}
}
throw StateError("Could not find package root for package '$packageName'. "
'Tried finding the package root via Platform.script '
"'${Platform.script.toFilePath()}' and Directory.current "
"'${Directory.current.uri.toFilePath()}'.");
}
final pkgNativeAssetsBuilderUri = findPackageRoot('native_assets_builder');
final testDataUri = pkgNativeAssetsBuilderUri.resolve('test_data/');
String unparseKey(String key) =>
'DART_HOOK_TESTING_${key.replaceAll('.', '__').toUpperCase()}';
/// Archiver provided by the environment.
///
/// Provided on Dart CI.
final Uri? _ar = Platform
.environment[unparseKey(internal.CCompilerConfigImpl.arConfigKeyFull)]
?.asFileUri();
/// Compiler provided by the environment.
///
/// Provided on Dart CI.
final Uri? _cc = Platform
.environment[unparseKey(internal.CCompilerConfigImpl.ccConfigKeyFull)]
?.asFileUri();
/// Linker provided by the environment.
///
/// Provided on Dart CI.
final Uri? _ld = Platform
.environment[unparseKey(internal.CCompilerConfigImpl.ldConfigKeyFull)]
?.asFileUri();
/// Path to script that sets environment variables for [_cc], [_ld], and [_ar].
///
/// Provided on Dart CI.
final Uri? _envScript = Platform.environment[
unparseKey(internal.CCompilerConfigImpl.envScriptConfigKeyFull)]
?.asFileUri();
/// Arguments for [_envScript] provided by environment.
///
/// Provided on Dart CI.
final List<String>? _envScriptArgs = Platform.environment[
unparseKey(internal.CCompilerConfigImpl.envScriptArgsConfigKeyFull)]
?.split(' ');
/// Configuration for the native toolchain.
///
/// Provided on Dart CI.
final cCompiler = internal.CCompilerConfigImpl(
compiler: _cc,
archiver: _ar,
linker: _ld,
envScript: _envScript,
envScriptArgs: _envScriptArgs,
);
extension on String {
Uri asFileUri() => Uri.file(this);
}
extension AssetIterable on Iterable<Asset> {
Future<bool> allExist() async {
final allResults = await Future.wait(map((e) => e.exists()));
final missing = allResults.contains(false);
return !missing;
}
}
extension on Asset {
Future<bool> exists() async {
final path_ = file;
return switch (path_) {
null => true,
_ => await path_.fileSystemEntity.exists(),
};
}
}
Future<void> copyTestProjects({
Uri? sourceUri,
required Uri targetUri,
}) async {
sourceUri ??= testDataUri;
final manifestUri = sourceUri.resolve('manifest.yaml');
final manifestFile = File.fromUri(manifestUri);
final manifestString = await manifestFile.readAsString();
final manifestYaml = loadYamlDocument(manifestString);
final manifest = [
for (final path in manifestYaml.contents as List<Object?>)
Uri(path: path as String)
];
final filesToCopy = manifest
.where((e) => !(e.pathSegments.last.startsWith('pubspec') &&
e.pathSegments.last.endsWith('.yaml')))
.toList();
final filesToModify = manifest
.where((e) =>
e.pathSegments.last.startsWith('pubspec') &&
e.pathSegments.last.endsWith('.yaml'))
.toList();
for (final pathToCopy in filesToCopy) {
final sourceFile = File.fromUri(sourceUri.resolveUri(pathToCopy));
final targetFileUri = targetUri.resolveUri(pathToCopy);
final targetDirUri = targetFileUri.parent;
final targetDir = Directory.fromUri(targetDirUri);
if (!(await targetDir.exists())) {
await targetDir.create(recursive: true);
}
// Copying files on MacOS and Windows preserves the source timestamps.
// The builder will use the cached build if the timestamps are equal.
// So just write the file instead.
final targetFile = File.fromUri(targetFileUri);
await targetFile.writeAsBytes(await sourceFile.readAsBytes());
}
for (final pathToModify in filesToModify) {
final sourceFile = File.fromUri(sourceUri.resolveUri(pathToModify));
final targetFileUri = targetUri.resolveUri(pathToModify);
final sourceString = await sourceFile.readAsString();
final modifiedString = sourceString.replaceAll(
'path: ../../',
'path: ${pkgNativeAssetsBuilderUri.toFilePath().unescape()}',
);
await File.fromUri(targetFileUri)
.writeAsString(modifiedString, flush: true);
}
}
extension UnescapePath on String {
/// Remove double encoding of slashes on windows, for string comparison with
/// Unix-style encoded strings.
String unescape() => replaceAll('\\', '/');
}
/// Logger that outputs the full trace when a test fails.
Logger get logger => _logger ??= () {
// A new logger is lazily created for each test so that the messages
// captured by printOnFailure are scoped to the correct test.
addTearDown(() => _logger = null);
return _createTestLogger();
}();
Logger? _logger;
Logger createCapturingLogger(
List<String> capturedMessages, {
Level level = Level.ALL,
}) =>
_createTestLogger(capturedMessages: capturedMessages, level: level);
Logger _createTestLogger({
List<String>? capturedMessages,
Level level = Level.ALL,
}) =>
Logger.detached('')
..level = level
..onRecord.listen((record) {
printOnFailure(
'${record.level.name}: ${record.time}: ${record.message}',
);
capturedMessages?.add(record.message);
});
final dartExecutable = File(Platform.resolvedExecutable).uri;