Skip to content

Commit cfd85a7

Browse files
committed
add failing examples code
1 parent d70998c commit cfd85a7

File tree

10 files changed

+334
-37
lines changed

10 files changed

+334
-37
lines changed

example/add/bin/add.dart

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import 'package:add/add.dart';
2+
3+
void main() {
4+
print(calculate(7, 7, times: 3));
5+
}

example/add/hook/build.dart

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,73 @@
11
import 'dart:io';
22

3-
import 'package:add/src/hook_helpers/hook_helpers.dart';
3+
import 'package:logging/logging.dart';
44
import 'package:native_assets_cli/native_assets_cli.dart';
55
import 'package:native_toolchain_cmake/native_toolchain_cmake.dart';
6+
import 'package:native_toolchain_cmake/src/native_toolchain/cmake.dart';
7+
import 'package:native_toolchain_cmake/src/utils/run_process.dart';
8+
9+
Logger createCapturingLogger(List<String> capturedMessages) => Logger.detached('')
10+
..level = Level.ALL
11+
..onRecord.listen((record) {
12+
print('${record.level.name}: ${record.time}: ${record.message}');
13+
capturedMessages.add(record.message);
14+
});
615

716
void main(List<String> args) async {
817
await build(args, (input, output) async {
9-
final sourceDir = Directory(await getPackagePath('add'));
10-
await runBuild(input, output, sourceDir.uri.resolve('src'));
18+
final sourceDir = Directory(await getPackagePath('add')).uri.resolve('src');
19+
final dstDir = Directory(await getPackagePath('add')).uri.resolve('build');
20+
assert(Directory(sourceDir.toFilePath()).existsSync());
21+
if (!Directory(dstDir.toFilePath()).existsSync()) {
22+
Directory(dstDir.toFilePath()).createSync(recursive: true);
23+
}
24+
// await runBuild(input, output, sourceDir.uri.resolve('src'));
25+
final messages = <String>[];
26+
final logger = createCapturingLogger(messages);
27+
final cm = (await cmake.defaultResolver?.resolve(logger: logger))?.first;
28+
assert(cm != null);
29+
// final result = await runProcess(
30+
// executable: cm!.uri,
31+
// arguments: [
32+
// "-S",
33+
// sourceDir.toFilePath(),
34+
// "-B",
35+
// dstDir.toFilePath(),
36+
// "-DCMAKE_INSTALL_PREFIX=install",
37+
// "-DCMAKE_BUILD_TYPE=Debug",
38+
// ],
39+
// logger: logger,
40+
// captureOutput: true,
41+
// throwOnUnexpectedExitCode: false,
42+
// );
43+
// assert(result.exitCode == 0);
44+
45+
// NOTE: stucks
46+
// Process.runSync(
47+
// cm!.uri.toFilePath(),
48+
// [
49+
// "-S",
50+
// sourceDir.toFilePath(),
51+
// "-B",
52+
// dstDir.toFilePath(),
53+
// "-DCMAKE_INSTALL_PREFIX=install",
54+
// ],
55+
// );
56+
57+
// NOTE: Also stucks
58+
final result = await runProcess(
59+
executable: cm!.uri,
60+
arguments: [
61+
"-S",
62+
sourceDir.toFilePath(),
63+
"-B",
64+
dstDir.toFilePath(),
65+
"-DCMAKE_INSTALL_PREFIX=install",
66+
],
67+
logger: logger,
68+
captureOutput: true,
69+
throwOnUnexpectedExitCode: false,
70+
);
71+
assert(result.exitCode == 0);
1172
});
1273
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
@OnPlatform({
2+
'mac-os': Timeout.factor(2),
3+
'windows': Timeout.factor(10),
4+
})
5+
import 'dart:ffi';
6+
import 'dart:io';
7+
8+
import 'package:native_toolchain_cmake/native_toolchain_cmake.dart';
9+
import 'package:add/src/hook_helpers/hook_helpers.dart';
10+
import 'package:test/test.dart';
11+
12+
import 'helpers.dart';
13+
14+
void main() {
15+
final targetOS = OS.current;
16+
final macOSConfig = targetOS == OS.macOS ? MacOSCodeConfig(targetVersion: 12) : null;
17+
18+
for (final buildMode in BuildMode.values) {
19+
// works fine
20+
test('CMakeBuilder-library-$buildMode', () async {
21+
final tempUri = await tempDirForTest();
22+
final tempUri2 = await tempDirForTest();
23+
24+
const name = 'add';
25+
26+
final buildInputBuilder = BuildInputBuilder()
27+
..setupShared(
28+
packageName: name,
29+
packageRoot: tempUri,
30+
outputFile: tempUri.resolve('output.json'),
31+
outputDirectory: tempUri,
32+
outputDirectoryShared: tempUri2,
33+
)
34+
..config.setupBuild(
35+
linkingEnabled: false,
36+
dryRun: false,
37+
)
38+
..config.setupShared(buildAssetTypes: [CodeAsset.type])
39+
..config.setupCode(
40+
targetOS: targetOS,
41+
macOS: macOSConfig,
42+
targetArchitecture: Architecture.current,
43+
// Ignored by executables.
44+
linkModePreference: LinkModePreference.dynamic,
45+
);
46+
47+
final buildInput = BuildInput(buildInputBuilder.json);
48+
final buildOutput = BuildOutputBuilder();
49+
50+
await runBuild(buildInput, buildOutput, Directory("src").absolute.uri);
51+
52+
final dylibUri = tempUri.resolve('install/lib/${OS.current.dylibFileName(name)}');
53+
expect(await File.fromUri(dylibUri).exists(), true);
54+
final dylib = openDynamicLibraryForTest(dylibUri.toFilePath());
55+
final add = dylib.lookupFunction<Int32 Function(Int32, Int32), int Function(int, int)>('math_add');
56+
expect(add(1, 2), 3);
57+
});
58+
}
59+
}

example/add/test/helpers.dart

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
import 'dart:async';
6+
import 'dart:ffi';
7+
import 'dart:io';
8+
9+
import 'package:logging/logging.dart';
10+
import 'package:test/test.dart';
11+
12+
export 'package:native_assets_cli/code_assets_builder.dart';
13+
14+
const keepTempKey = 'KEEP_TEMPORARY_DIRECTORIES';
15+
16+
Future<Uri> tempDirForTest({String? prefix, bool keepTemp = false}) async {
17+
final tempDir = await Directory.systemTemp.createTemp(prefix);
18+
// Deal with Windows temp folder aliases.
19+
final tempUri = Directory(await tempDir.resolveSymbolicLinks()).uri.normalizePath();
20+
if ((!Platform.environment.containsKey(keepTempKey) || Platform.environment[keepTempKey]!.isEmpty) &&
21+
!keepTemp) {
22+
addTearDown(() => tempDir.delete(recursive: true));
23+
}
24+
return tempUri;
25+
}
26+
27+
/// Logger that outputs the full trace when a test fails.
28+
Logger get logger => _logger ??= () {
29+
// A new logger is lazily created for each test so that the messages
30+
// captured by printOnFailure are scoped to the correct test.
31+
addTearDown(() => _logger = null);
32+
return _createTestLogger();
33+
}();
34+
35+
Logger? _logger;
36+
37+
Logger createCapturingLogger(List<String> capturedMessages) =>
38+
_createTestLogger(capturedMessages: capturedMessages);
39+
40+
Logger _createTestLogger({List<String>? capturedMessages}) => Logger.detached('')
41+
..level = Level.ALL
42+
..onRecord.listen((record) {
43+
printOnFailure('${record.level.name}: ${record.time}: ${record.message}');
44+
capturedMessages?.add(record.message);
45+
});
46+
47+
/// Test files are run in a variety of ways, find this package root in all.
48+
///
49+
/// Test files can be run from source from any working directory. The Dart SDK
50+
/// `tools/test.py` runs them from the root of the SDK for example.
51+
///
52+
/// Test files can be run from dill from the root of package. `package:test`
53+
/// does this.
54+
///
55+
/// https://github.com/dart-lang/test/issues/110
56+
Uri findPackageRoot(String packageName) {
57+
final script = Platform.script;
58+
final fileName = script.name;
59+
if (fileName.endsWith('_test.dart')) {
60+
// We're likely running from source.
61+
var directory = script.resolve('.');
62+
while (true) {
63+
final dirName = directory.name;
64+
if (dirName == packageName) {
65+
return directory;
66+
}
67+
final parent = directory.resolve('..');
68+
if (parent == directory) break;
69+
directory = parent;
70+
}
71+
} else if (fileName.endsWith('.dill')) {
72+
final cwd = Directory.current.uri;
73+
final dirName = cwd.name;
74+
if (dirName == packageName) {
75+
return cwd;
76+
}
77+
}
78+
throw StateError("Could not find package root for package '$packageName'. "
79+
'Tried finding the package root via Platform.script '
80+
"'${Platform.script.toFilePath()}' and Directory.current "
81+
"'${Directory.current.uri.toFilePath()}'.");
82+
}
83+
84+
Uri packageUri = findPackageRoot('native_toolchain_c');
85+
86+
extension on Uri {
87+
String get name => pathSegments.where((e) => e != '').last;
88+
}
89+
90+
/// Opens the [DynamicLibrary] at [path] and register a tear down hook to close
91+
/// it when the current test is done.
92+
DynamicLibrary openDynamicLibraryForTest(String path) {
93+
final library = DynamicLibrary.open(path);
94+
addTearDown(library.close);
95+
return library;
96+
}

lib/src/builder/builder.dart

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ class CMakeBuilder implements Builder {
4444
final BuildMode buildMode;
4545

4646
final List<String>? targets;
47-
final Generator? generator;
47+
final Generator generator;
48+
final String? toolset;
4849

4950
// ios.toolchain.cmake
5051
// https://github.com/leetal/ios-cmake?tab=readme-ov-file#exposed-variables
@@ -69,7 +70,8 @@ class CMakeBuilder implements Builder {
6970
this.linkModePreference,
7071
this.buildMode = BuildMode.release,
7172
this.targets,
72-
this.generator,
73+
this.generator = Generator.defaultGenerator,
74+
this.toolset,
7375
this.enableBitcode = false,
7476
this.enableArc = true,
7577
this.enableVisibility = true, // necessary to expose symbols

lib/src/builder/generator.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ class Generator {
1717
static const Generator vs2022 = Generator._('Visual Studio 17 2022');
1818

1919
static const Generator defaultGenerator = Generator._("default");
20+
21+
List<String> toArgs() => name == "default" ? [] : ["-G", name];
2022
}

0 commit comments

Comments
 (0)