From 26465f29f61f64ea1326332fa5697ca3dabf9dee Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jul 2026 02:58:58 -0700 Subject: [PATCH 1/5] test: add sync workflow and dart tool script --- .claude-plugin/marketplace.json | 21 +++ .claude-plugin/plugin.json | 18 +++ .github/workflows/sync_skills.yaml | 73 +++++++++++ .mcp.json | 11 ++ tool/sync_skills.dart | 201 +++++++++++++++++++++++++++++ 5 files changed, 324 insertions(+) create mode 100644 .claude-plugin/marketplace.json create mode 100644 .claude-plugin/plugin.json create mode 100644 .github/workflows/sync_skills.yaml create mode 100644 .mcp.json create mode 100644 tool/sync_skills.dart diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..6d9bac9 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,21 @@ +{ + "name": "dart-flutter", + "owner": { + "name": "Dart and Flutter Team", + "email": "stores@flutter.io" + }, + "description": "Official Claude Marketplace for Dart and Flutter plugins", + "plugins": [ + { + "name": "dart-flutter", + "description": "The official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase", + "category": "development", + "tags": [ + "dart", + "flutter", + "mobile" + ], + "source": "./" + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..7208a04 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "dart-flutter", + "displayName": "Dart and Flutter", + "version": "1.0.0", + "description": "Official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase", + "author": { + "name": "Dart and Flutter", + "url": "https://flutter.dev" + }, + "homepage": "https://github.com/flutter/skills", + "repository": "https://github.com/flutter/skills", + "license": "BSD-3-Clause", + "keywords": [ + "flutter", + "dart", + "mobile" + ] +} diff --git a/.github/workflows/sync_skills.yaml b/.github/workflows/sync_skills.yaml new file mode 100644 index 0000000..1b3cd65 --- /dev/null +++ b/.github/workflows/sync_skills.yaml @@ -0,0 +1,73 @@ +name: Sync Skills Directory via Git Hash (Dart) + +on: + schedule: + # Runs every Monday at 06:00 UTC (Monday morning) + - cron: '0 6 * * 1' + workflow_dispatch: + # Allows you to manually trigger the sync anytime from the Actions tab + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Checkout Flutter Skills (Destination) + uses: actions/checkout@v4 + with: + token: ${{ secrets.SYNC_PAT }} + path: dest_repo + + - name: Checkout Dart Skills (Source) + uses: actions/checkout@v4 + with: + repository: dart-lang/skills + fetch-depth: 50 + path: src_repo + + - name: Setup Dart Environment + uses: dart-lang/setup-dart@v1 + with: + sdk: stable + + - name: Execute Dart Sync Engine + id: sync_engine + # Continue on error so we can check if it exited early via code 10 + continue-on-error: true + run: | + cd dest_repo + # Run our compiled-on-the-fly Dart script + dart run tool/sync_skills.dart ../src_repo skills + EXIT_CODE=$? + + if [ $EXIT_CODE -eq 0 ]; then + echo "changes_detected=true" >> $GITHUB_OUTPUT + elif [ $EXIT_CODE -eq 10 ]; then + echo "changes_detected=false" >> $GITHUB_OUTPUT + echo "✅ Dart script signaled NO changes were found. Stopping workflow." + else + echo "❌ Dart script failed with error code $EXIT_CODE" + exit $EXIT_CODE + fi + + - name: Create Pull Request + if: steps.sync_engine.outputs.changes_detected == 'true' + uses: peter-evans/create-pull-request@v6 + with: + token: ${{ secrets.SYNC_PAT }} + path: dest_repo + branch: automation/sync-dart-skills + title: "🤖 chore: sync skills directory from dart-lang/skills" + commit-message: "chore: auto-sync skills directory from dart-lang/skills" + body: | + ### 🤖 Automated Skills Sync & Version Bump (Dart Powered) + This is an automated pull request to sync the contents of the `skills/` directory from [dart-lang/skills](https://github.com/dart-lang/skills). + + This run used a state-tracked Git hash (`.dart_skills_githash`) computed directly by our custom **Dart synchronization utility** (`tool/sync_skills.dart`). + + ### 🛠️ Changes Performed: + * **Preserved:** All native `flutter/*` skills in the repository remain unchanged. + * **Synced:** All new, modified, or deleted files inside `dart-lang/skills` have been carried over. + * **Bumped:** Automatically incremented the plugin version field in `.claude-plugin/plugin.json` to keep integrations updated. + labels: | + automated-pr + sync diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000..c6487d7 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "dart-mcp-server": { + "command": "dart", + "args": [ + "mcp-server" + ], + "env": {} + } + } +} diff --git a/tool/sync_skills.dart b/tool/sync_skills.dart new file mode 100644 index 0000000..dc2ff4f --- /dev/null +++ b/tool/sync_skills.dart @@ -0,0 +1,201 @@ +import 'dart:convert'; +import 'dart:io'; + +void main(List args) async { + String srcDir = '../src_repo'; + String destDir = 'skills'; + + if (args.length >= 2) { + srcDir = args[0]; + destDir = args[1]; + } else if (args.isNotEmpty) { + srcDir = args[0]; + } + + print('📌 Source Directory: $srcDir'); + print('📌 Destination Directory: $destDir'); + + final hashFile = + Platform.environment['SKILLS_HASH_FILE_PATH'] ?? + 'tool/.dart_skills_githash'; + const pluginFile = '.claude-plugin/plugin.json'; + + // 1. Get the latest commit hash from the source repository + final currentHashResult = await Process.run('git', [ + 'rev-parse', + 'HEAD', + ], workingDirectory: srcDir); + + if (currentHashResult.exitCode != 0) { + print('❌ Error getting current Git hash from source.'); + exit(1); + } + + final currentHash = (currentHashResult.stdout as String).trim(); + print('📌 Current Dart Repo Git Hash: $currentHash'); + + // Create destination directory if it doesn\'t exist + await Directory(destDir).create(recursive: true); + + // 2. Check if a previously synced hash exists + final hashFileObj = File(hashFile); + String? prevHash; + + if (await hashFileObj.exists()) { + prevHash = (await hashFileObj.readAsString()).trim(); + print('📌 Previously Synced Git Hash: $prevHash'); + + if (prevHash == currentHash) { + print('✅ No changes detected in the source repository (hashes match).'); + print('🚀 Exiting early to save workflow execution time.'); + // Exit code 10 signals to the workflow that no changes were made (and it should not make a PR) + exit(10); + } + } + + bool changesDetected = false; + + // 3. Sync changes using Git Diff + if (prevHash != null) { + // Check if the previous hash is still an ancestor (valid in history) + final isAncestorResult = await Process.run('git', [ + 'merge-base', + '--is-ancestor', + prevHash, + currentHash, + ], workingDirectory: srcDir); + + if (isAncestorResult.exitCode == 0) { + print( + '🔄 Fetching incremental diff between $prevHash and $currentHash...', + ); + + // Find files added, modified, or deleted inside skills/ + final diffResult = await Process.run('git', [ + 'diff', + '--name-status', + prevHash, + currentHash, + '--', + 'skills/', + ], workingDirectory: srcDir); + + final lines = (diffResult.stdout as String).trim().split('\n'); + for (final line in lines) { + if (line.isEmpty) continue; + + // git diff --name-status returns values like: "M\tskills/some-skill/file.md" + final parts = line.split(RegExp(r'\s+')); + if (parts.length < 2) continue; + + final status = parts[0]; + final srcPath = parts[1]; + + // Strip the "skills/" prefix to copy/delete relatively + final relPath = srcPath.replaceFirst('skills/', ''); + final finalDestPath = '$destDir/$relPath'; + + if (status == 'D') { + print('🗑️ Deleting removed Dart file/folder: $relPath'); + final fileToDelete = File(finalDestPath); + if (await fileToDelete.exists()) { + await fileToDelete.delete(recursive: true); + } else { + final dirToDelete = Directory(finalDestPath); + if (await dirToDelete.exists()) { + await dirToDelete.delete(recursive: true); + } + } + changesDetected = true; + } else { + print('📂 Copying added/modified Dart file: $relPath'); + final sourceFile = File('$srcDir/$srcPath'); + + if (await sourceFile.exists()) { + await File(finalDestPath).create(recursive: true); + await sourceFile.copy(finalDestPath); + changesDetected = true; + } + } + } + } else { + print( + '⚠️ Previous hash was not found in history. Performing fallback full sync.', + ); + changesDetected = await _fullSync(srcDir, destDir); + } + } else { + print( + '🆕 No previous hash tracked. Performing a clean sync of current Dart skills.', + ); + changesDetected = await _fullSync(srcDir, destDir); + } + + // 4. Update `.claude-plugin/plugin.json` version if changes were detected + if (changesDetected) { + final pluginFileObj = File(pluginFile); + if (await pluginFileObj.exists()) { + print('📈 Bumping patch version in $pluginFile...'); + try { + final content = await pluginFileObj.readAsString(); + final Map data = jsonDecode(content); + + final versionStr = data['version'] as String? ?? '1.0.0'; + final versionParts = versionStr.split('.'); + if (versionParts.length == 3) { + final patch = int.parse(versionParts[2]) + 1; + versionParts[2] = patch.toString(); + data['version'] = versionParts.join('.'); + + // Re-write back to json format with clean indentation and trailing newline + final encoder = const JsonEncoder.withIndent(' '); + await pluginFileObj.writeAsString('${encoder.convert(data)}\n'); + print('✅ Version bumped successfully to: ${data['version']}'); + } + } catch (e) { + print('⚠️ Failed parsing or writing plugin version: $e'); + } + } else { + print('⚠️ Warning: $pluginFile not found! Version was not bumped.'); + } + } + + // 5. Save the new hash to the tracker + await hashFileObj.writeAsString('$currentHash\n'); + print('✅ Saved commit hash $currentHash to tracker.'); + exit(0); +} + +// Fallback Helper to perform complete directory replication +Future _fullSync(String srcDir, String destDir) async { + final sourceSkillsDir = Directory('$srcDir/skills'); + if (!await sourceSkillsDir.exists()) { + print('❌ Error: Source skills/ folder not found.'); + return false; + } + + // Clean/delete existing sync-managed folders in destDir (skip native flutter-* folders) + final destSkillsDir = Directory(destDir); + if (await destSkillsDir.exists()) { + await for (final entity in destSkillsDir.list()) { + if (entity is Directory) { + final dirName = entity.path.split(RegExp(r'[/\\]')).last; + if (!dirName.startsWith('flutter-')) { + print('🗑️ Cleaning sync-managed folder: $dirName'); + await entity.delete(recursive: true); + } + } + } + } + + await for (final entity in sourceSkillsDir.list(recursive: true)) { + if (entity is File) { + final relPath = entity.path.replaceFirst('$srcDir/skills/', ''); + final destPath = '$destDir/$relPath'; + + await File(destPath).create(recursive: true); + await entity.copy(destPath); + } + } + return true; +} From 988cb49eed5b55f82dcb8c81527eed007f9313cf Mon Sep 17 00:00:00 2001 From: keertip <2192312+keertip@users.noreply.github.com> Date: Mon, 13 Jul 2026 10:19:41 +0000 Subject: [PATCH 2/5] chore: auto-sync skills directory from dart-lang/skills --- .claude-plugin/plugin.json | 2 +- skills/dart-add-unit-test/SKILL.md | 122 ++++ skills/dart-build-cli-app/SKILL.md | 185 ++++++ skills/dart-collect-coverage/SKILL.md | 141 +++++ skills/dart-fix-runtime-errors/SKILL.md | 166 ++++++ skills/dart-generate-test-mocks/SKILL.md | 155 +++++ .../dart-migrate-to-checks-package/SKILL.md | 528 ++++++++++++++++++ .../dart-resolve-package-conflicts/SKILL.md | 116 ++++ skills/dart-run-static-analysis/SKILL.md | 104 ++++ skills/dart-setup-ffi-assets/SKILL.md | 419 ++++++++++++++ skills/dart-use-ffigen/SKILL.md | 218 ++++++++ skills/dart-use-pattern-matching/SKILL.md | 146 +++++ skills/dart-use-primary-constructors/SKILL.md | 262 +++++++++ tool/.dart_skills_githash | 1 + 14 files changed, 2564 insertions(+), 1 deletion(-) create mode 100644 skills/dart-add-unit-test/SKILL.md create mode 100644 skills/dart-build-cli-app/SKILL.md create mode 100644 skills/dart-collect-coverage/SKILL.md create mode 100644 skills/dart-fix-runtime-errors/SKILL.md create mode 100644 skills/dart-generate-test-mocks/SKILL.md create mode 100644 skills/dart-migrate-to-checks-package/SKILL.md create mode 100644 skills/dart-resolve-package-conflicts/SKILL.md create mode 100644 skills/dart-run-static-analysis/SKILL.md create mode 100644 skills/dart-setup-ffi-assets/SKILL.md create mode 100644 skills/dart-use-ffigen/SKILL.md create mode 100644 skills/dart-use-pattern-matching/SKILL.md create mode 100644 skills/dart-use-primary-constructors/SKILL.md create mode 100644 tool/.dart_skills_githash diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7208a04..38866c2 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dart-flutter", "displayName": "Dart and Flutter", - "version": "1.0.0", + "version": "1.0.1", "description": "Official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase", "author": { "name": "Dart and Flutter", diff --git a/skills/dart-add-unit-test/SKILL.md b/skills/dart-add-unit-test/SKILL.md new file mode 100644 index 0000000..dc27083 --- /dev/null +++ b/skills/dart-add-unit-test/SKILL.md @@ -0,0 +1,122 @@ +--- +name: dart-add-unit-test +description: Write and organize unit tests for functions, methods, and classes using `package:test`. Use when creating new logic or fixing bugs to ensure code remains correct and regression-free. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:07:58 GMT +--- +# Testing Dart and Flutter Applications + +## Contents +- [Structuring Test Files](#structuring-test-files) +- [Writing Tests](#writing-tests) +- [Executing Tests](#executing-tests) +- [Test Implementation Workflow](#test-implementation-workflow) +- [Examples](#examples) + +## Structuring Test Files +Organize test files to mirror the `lib` directory structure to maintain predictability. + +* Place all test code within the `test` directory at the root of the package. +* Append `_test.dart` to the end of all test file names (e.g., `lib/src/utils.dart` should be tested in `test/src/utils_test.dart`). +* If writing integration tests, place them in an `integration_test` directory at the root of the package. + +## Writing Tests +Utilize `package:test` as the standard testing library for Dart applications. + +* Import `package:test/test.dart` (or `package:flutter_test/flutter_test.dart` for Flutter). +* Group related tests using the `group()` function to provide shared context. +* Define individual test cases using the `test()` function. +* Validate outcomes using the `expect()` function alongside matchers (e.g., `equals()`, `isTrue`, `throwsA()`). +* Write asynchronous tests using standard `async`/`await` syntax. The test runner automatically waits for the `Future` to complete. +* Manage test setup and teardown using `setUp()` and `tearDown()` callbacks. +* If testing code that relies on dependency injection, use `package:mockito` alongside `package:test` to generate mock objects, configure fixed scenarios, and verify interactions. + +## Executing Tests +Select the appropriate test runner based on the project type and test location. + +* If working on a pure Dart project, execute tests using the `dart test` command. +* If working on a Flutter project, execute tests using the `flutter test` command. +* If running integration tests, explicitly specify the directory path, as the default runner ignores it: `dart test integration_test` or `flutter test integration_test`. + +## Test Implementation Workflow + +Follow this sequential workflow when implementing new test suites. Copy the checklist to track your progress. + +### Task Progress +- [ ] 1. Create the test file in the `test/` directory, ensuring the `_test.dart` suffix. +- [ ] 2. Import `package:test/test.dart` and the target library. +- [ ] 3. Define a `main()` function. +- [ ] 4. Initialize shared resources or mocks using `setUp()`. +- [ ] 5. Write `test()` cases grouped by functionality using `group()`. +- [ ] 6. Execute the test suite using the appropriate CLI command. +- [ ] 7. **Feedback Loop**: Run test -> Review stack trace for failures -> Fix implementation or assertions -> Re-run until passing. + +## Examples + +### Standard Unit Test Suite +Demonstrates grouping, setup, synchronous, and asynchronous testing. + +```dart +import 'package:test/test.dart'; +import 'package:my_package/calculator.dart'; + +void main() { + group('Calculator', () { + late Calculator calc; + + setUp(() { + calc = Calculator(); + }); + + test('adds two numbers correctly', () { + expect(calc.add(2, 3), equals(5)); + }); + + test('handles asynchronous operations', () async { + final result = await calc.fetchRemoteValue(); + expect(result, isNotNull); + expect(result, greaterThan(0)); + }); + }); +} +``` + +### Mocking with Mockito +Demonstrates configuring a mock object for dependency injection testing. + +```dart +import 'package:test/test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:mockito/annotations.dart'; +import 'package:my_package/api_client.dart'; +import 'package:my_package/data_service.dart'; + +// Generate the mock using build_runner: dart run build_runner build +@GenerateNiceMocks([MockSpec()]) +import 'data_service_test.mocks.dart'; + +void main() { + group('DataService', () { + late MockApiClient mockApiClient; + late DataService dataService; + + setUp(() { + mockApiClient = MockApiClient(); + dataService = DataService(apiClient: mockApiClient); + }); + + test('returns parsed data on successful API call', () async { + // Configure the mock + when(mockApiClient.get('/data')).thenAnswer((_) async => '{"id": 1}'); + + // Execute the system under test + final result = await dataService.fetchData(); + + // Verify outcomes and interactions + expect(result.id, equals(1)); + verify(mockApiClient.get('/data')).called(1); + }); + }); +} +``` diff --git a/skills/dart-build-cli-app/SKILL.md b/skills/dart-build-cli-app/SKILL.md new file mode 100644 index 0000000..239a892 --- /dev/null +++ b/skills/dart-build-cli-app/SKILL.md @@ -0,0 +1,185 @@ +--- +name: dart-build-cli-app +description: Entrypoint structure, exit codes, cross-platform scripts. Use when building command line utilities, scripts, or applications. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 04 May 2026 17:41:00 GMT +--- +# Building Dart CLI Applications + +## Contents +- [Project Setup & Architecture](#project-setup--architecture) +- [Argument Parsing & Command Routing](#argument-parsing--command-routing) +- [Execution & Error Handling](#execution--error-handling) +- [Testing CLI Applications](#testing-cli-applications) +- [Compilation & Distribution](#compilation--distribution) +- [Workflows](#workflows) +- [Examples](#examples) + +## Project Setup & Architecture + +Initialize new CLI projects using the official Dart template to ensure standard directory structures. + +* Run `dart create -t cli ` to scaffold a console application with basic argument parsing. +* Place executable entry points (files containing `main()`) exclusively in the `bin/` directory. +* Place internal implementation logic in `lib/src/` and expose public APIs via `lib/.dart`. +* Enforce formatting in CI environments by running `dart format . --set-exit-if-changed`. This returns exit code 1 if formatting violations exist. + +## Argument Parsing & Command Routing + +Import the `args` package to manage command-line arguments, flags, and subcommands. + +* If building a simple script: Use `ArgParser` directly to define flags (`addFlag`) and options (`addOption`). +* If building a complex, multi-command CLI (like `git`): Implement `CommandRunner` and extend `Command` for each subcommand. +* Define global arguments on the `CommandRunner.argParser` and command-specific arguments on the individual `Command.argParser`. +* Catch `UsageException` to gracefully handle invalid arguments and display the automatically generated help text. +* **Validate Help Text Accuracy**: Ensure the help text provides all necessary information to run the tool. If the help text references a compiled executable name, and the user needs to add it to their PATH to run it that way, provide clear instructions on how to do so in the help text or description. + +## Execution & Error Handling + +Leverage the `io` and `stack_trace` packages to build robust, production-ready CLI tools. + +* Use the `io` package's `ExitCode` enum to return standard POSIX exit codes (e.g., `ExitCode.success.code`, `ExitCode.usage.code`). +* Use `sharedStdIn` from the `io` package if multiple asynchronous listeners need sequential access to standard input. +* Wrap the application execution in `Chain.capture()` from the `stack_trace` package to track asynchronous stack chains. +* Format output stack traces using `Trace.terse` or `Chain.terse` to strip noisy core library frames and present readable errors to the user. +* **Do not swallow exceptions** in lower-level logic or storage classes unless recovery is possible. Let them bubble up or rethrow them so higher-level commands know operations failed. +* **Fail fast and with non-zero exit codes**: Ensure operation failures result in descriptive error messages to `stderr` and appropriate non-zero exit codes (e.g., using `exit(1)` or triggering a 64 exit code after a caught `UsageException`). + +## Testing CLI Applications + +> [!IMPORTANT] +> **All new commands and significant features must be covered by automated tests.** Manual verification is not sufficient for testing logic. However, manual verification of help text and user experience (UX) is still required to ensure the interface is intuitive and correct. + +Use `test_process` and `test_descriptor` to write high-fidelity integration tests for your CLI. + +* Define expected filesystem states using `test_descriptor` (`d.dir`, `d.file`). +* Create the mock filesystem before execution using `await d.Descriptor.create()`. +* Spawn the CLI process using `TestProcess.start('dart', ['run', 'bin/cli.dart', ...args])`. +* Validate standard output and error streams using `StreamQueue` matchers (e.g., `emitsThrough`, `emits`). +* Assert the final exit code using `await process.shouldExit(0)`. +* Validate resulting filesystem mutations using `await d.Descriptor.validate()`. + +## Compilation & Distribution + +Select the appropriate compilation target based on your distribution requirements. + +* **If testing locally during development:** Use `dart run bin/cli.dart`. This uses the JIT compiler for rapid iteration. +* **If bundling code assets and dynamic libraries:** Use `dart build cli`. This runs build hooks and outputs to `build/cli/_/bundle/`. +* **If distributing a standalone native executable:** Use `dart compile exe bin/cli.dart -o `. This bundles the Dart runtime and machine code into a single file. +* **If distributing multiple apps with strict disk space limits:** Use `dart compile aot-snapshot bin/cli.dart`. Run the resulting `.aot` file using `dartaotruntime`. + +
+Cross-Compilation Targets (Linux Only) + +Dart supports cross-compiling to Linux from macOS, Windows, or Linux hosts. +Use the `--target-os` and `--target-arch` flags with `dart compile exe` or `dart compile aot-snapshot`. + +* `--target-os=linux` (Only Linux is currently supported as a cross-compilation target) +* `--target-arch=arm64` (64-bit ARM) +* `--target-arch=x64` (x86-64) +* `--target-arch=arm` (32-bit ARM) +* `--target-arch=riscv64` (64-bit RISC-V) + +Example: `dart compile exe --target-os=linux --target-arch=arm64 bin/cli.dart` +
+ +## Workflows + +### Task Progress: Implement a New CLI Command +- [ ] Create a new class extending `Command` in `lib/src/commands/`. +- [ ] Define the `name` and `description` properties. +- [ ] Register command-specific flags in the constructor using `argParser.addFlag()` or `argParser.addOption()`. +- [ ] Implement the `run()` method with the core logic. +- [ ] Register the new command in the `CommandRunner` instance in `bin/cli.dart` using `addCommand()`. +- [ ] Create tests for the new command in the `test/` directory using `test_process` or standard tests. +- [ ] Run validator -> Execute `dart run bin/cli.dart help ` to verify help text generation. +- [ ] Verify final UX: Compile the application using `dart compile exe` and run the resulting executable to verify the target user experience (e.g., `./bin/cli `). + +### Task Progress: Compile and Release Native Executable +- [ ] Run validator -> Execute `dart format . --set-exit-if-changed` to ensure code formatting. +- [ ] Run validator -> Execute `dart analyze` to ensure no static analysis errors. +- [ ] Run validator -> Execute `dart test` to pass all integration tests. +- [ ] Compile for host OS: `dart compile exe bin/cli.dart -o build/cli-host` +- [ ] Compile for Linux (if host is macOS/Windows): `dart compile exe --target-os=linux --target-arch=x64 bin/cli.dart -o build/cli-linux-x64` + +## Examples + +### Example: CommandRunner Implementation + +```dart +import 'dart:io'; +import 'package:args/command_runner.dart'; +import 'package:stack_trace/stack_trace.dart'; + +class CommitCommand extends Command { + @override + final String name = 'commit'; + @override + final String description = 'Record changes to the repository.'; + + CommitCommand() { + argParser.addFlag('all', abbr: 'a', help: 'Commit all changed files.'); + } + + @override + Future run() async { + final commitAll = argResults?['all'] as bool? ?? false; + print('Committing... (All: $commitAll)'); + } +} + +void main(List args) { + Chain.capture(() async { + final runner = CommandRunner('dgit', 'Distributed version control.') + ..addCommand(CommitCommand()); + + await runner.run(args); + }, onError: (error, chain) { + if (error is UsageException) { + stderr.writeln(error.message); + stderr.writeln(error.usage); + exit(64); // ExitCode.usage.code + } else { + stderr.writeln('Fatal error: $error'); + stderr.writeln(chain.terse); + exit(1); + } + }); +} +``` + +### Example: Integration Testing with Subprocesses + +```dart +import 'package:test/test.dart'; +import 'package:test_process/test_process.dart'; +import 'package:test_descriptor/test_descriptor.dart' as d; + +void main() { + test('CLI formats output correctly and modifies filesystem', () async { + // 1. Setup mock filesystem + await d.dir('project', [ + d.file('config.json', '{"key": "value"}') + ]).create(); + + // 2. Spawn the CLI process + final process = await TestProcess.start( + 'dart', + ['run', 'bin/cli.dart', 'process', '--path', '${d.sandbox}/project'] + ); + + // 3. Validate stdout stream + await expectLater(process.stdout, emitsThrough('Processing complete.')); + + // 4. Validate exit code + await process.shouldExit(0); + + // 5. Validate filesystem mutations + await d.dir('project', [ + d.file('config.json', '{"key": "value"}'), + d.file('output.log', 'Success') + ]).validate(); + }); +} +``` diff --git a/skills/dart-collect-coverage/SKILL.md b/skills/dart-collect-coverage/SKILL.md new file mode 100644 index 0000000..60dad77 --- /dev/null +++ b/skills/dart-collect-coverage/SKILL.md @@ -0,0 +1,141 @@ +--- +name: dart-collect-coverage +description: Collect coverage using the coverage packge and create an LCOV report +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:14:32 GMT +--- +# Implementing Dart and Flutter Test Coverage + +## Contents +- [Testing Fundamentals](#testing-fundamentals) +- [Coverage Directives](#coverage-directives) +- [Workflow: Configuring and Generating Coverage Reports](#workflow-configuring-and-generating-coverage-reports) +- [Workflow: Advanced Manual Coverage Collection](#workflow-advanced-manual-coverage-collection) +- [Examples](#examples) + +## Testing Fundamentals + +Structure your test suites using the standard Dart testing paradigms. Use `package:test` for Dart projects and `flutter_test` for Flutter projects. + +- **Unit Tests:** Verify individual functions, methods, or classes. +- **Component/Widget Tests:** Verify component behavior, layout, and interaction using mock objects (`package:mockito`). +- **Integration Tests:** Verify entire app flows on simulated or real devices. + +## Coverage Directives + +Exclude specific lines, blocks, or entire files from coverage metrics using inline comments. Pass the `--check-ignore` flag during formatting to enforce these directives. + +- Ignore a single line: `// coverage:ignore-line` +- Ignore a block of code: `// coverage:ignore-start` and `// coverage:ignore-end` +- Ignore an entire file: `// coverage:ignore-file` + +## Workflow: Configuring and Generating Coverage Reports + +Follow this sequential workflow to add the coverage package, execute tests, and generate an LCOV report. + +**Task Progress Checklist:** +- [ ] 1. Add `coverage` as a `dev_dependency`. +- [ ] 2. Execute the automated coverage script. +- [ ] 3. Validate the LCOV output. + +### 1. Add Dependencies +Add the `coverage` package as a `dev_dependency` to your project. Do not add it to standard dependencies. + +If working in a standard Dart project: +```bash +dart pub add dev:coverage +``` + +If working in a Flutter project: +```bash +flutter pub add dev:coverage +``` + +### 2. Collect Coverage and Generate LCOV +Use the bundled `test_with_coverage` script. This script automatically runs all tests, collects the JSON coverage data from the Dart VM, and formats it into an LCOV report. + +```bash +dart run coverage:test_with_coverage +``` +*Note: If working within a Dart workspace (monorepo), specify the test directories explicitly (e.g., `dart run coverage:test_with_coverage -- pkgs/foo/test pkgs/bar/test`).* + +### 3. Feedback Loop: Validate Output +**Run validator -> review errors -> fix:** +1. Verify that the `coverage/` directory was created in the project root. +2. Ensure `coverage/coverage.json` (raw data) and `coverage/lcov.info` (formatted report) exist. +3. If coverage is missing for specific files, ensure they are imported and executed by your test files, or add `// coverage:ignore-file` if they are intentionally excluded. + +## Workflow: Advanced Manual Coverage Collection + +If you require granular control over the VM service, isolate pausing, or need branch/function-level coverage, use the manual collection workflow. + +**Task Progress Checklist:** +- [ ] 1. Run tests with VM service enabled. +- [ ] 2. Collect raw JSON coverage. +- [ ] 3. Format JSON to LCOV. + +### 1. Run Tests with VM Service +Execute tests while pausing isolates on exit and exposing the VM service on a specific port (e.g., 8181). + +```bash +dart run --pause-isolates-on-exit --disable-service-auth-codes --enable-vm-service=8181 test & +``` + +### 2. Collect Raw Coverage +Extract the coverage data from the running VM service and output it to a JSON file. + +```bash +dart run coverage:collect_coverage --wait-paused --uri=http://127.0.0.1:8181/ -o coverage/coverage.json --resume-isolates +``` +*Optional: Append `--function-coverage` and `--branch-coverage` to gather deeper metrics (requires Dart VM 2.17.0+).* + +### 3. Format to LCOV +Convert the raw JSON data into the standard LCOV format. + +```bash +dart run coverage:format_coverage --packages=.dart_tool/package_config.json --lcov -i coverage/coverage.json -o coverage/lcov.info --check-ignore +``` + +## Examples + +### Example: `pubspec.yaml` Configuration +Ensure your `pubspec.yaml` reflects the `coverage` package strictly under `dev_dependencies`. + +```yaml +name: my_dart_app +environment: + sdk: ^3.0.0 + +dependencies: + path: ^1.8.0 + +dev_dependencies: + test: ^1.24.0 + coverage: ^1.15.0 +``` + +### Example: Applying Ignore Directives +Use ignore directives to prevent generated code or untestable edge cases from lowering coverage scores. + +```dart +// coverage:ignore-file +import 'package:meta/meta.dart'; + +class SystemConfig { + final String env; + + SystemConfig(this.env); + + // coverage:ignore-start + void legacyInit() { + print('Deprecated initialization'); + } + // coverage:ignore-end + + bool isProduction() { + if (env == 'prod') return true; + return false; // coverage:ignore-line + } +} +``` diff --git a/skills/dart-fix-runtime-errors/SKILL.md b/skills/dart-fix-runtime-errors/SKILL.md new file mode 100644 index 0000000..1a7db85 --- /dev/null +++ b/skills/dart-fix-runtime-errors/SKILL.md @@ -0,0 +1,166 @@ +--- +name: dart-fix-runtime-errors +description: Uses get_runtime_errors and lsp to fetch an active stack trace, locate the failing line, apply a fix, and verify resolution via hot_reload. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:13:22 GMT +--- +# Resolving Dart Static Analysis Errors + +## Contents +- [Core Concepts & Guidelines](#core-concepts--guidelines) + - [Type System & Soundness](#type-system--soundness) + - [Null Safety](#null-safety) + - [Error Handling](#error-handling) +- [Workflows](#workflows) + - [Workflow: Static Analysis Resolution](#workflow-static-analysis-resolution) +- [Examples](#examples) + +## Core Concepts & Guidelines + +### Type System & Soundness +Enforce Dart's sound type system to prevent runtime invalid states. + +* **Method Overrides:** Maintain sound return types (covariant) and parameter types (contravariant). Never tighten a parameter type in a subclass unless explicitly marked with the `covariant` keyword. +* **Generics & Collections:** Add explicit type annotations to generic classes (e.g., `List`, `Map`). Never assign a `List` to a typed list (e.g., `List`). +* **Downcasting:** Avoid implicit downcasts from `dynamic`. Use explicit casts (e.g., `as List`) when necessary, but ensure the underlying runtime type matches to prevent `TypeError` exceptions. +* **Strict Casts:** Enable `strict-casts: true` in `analysis_options.yaml` under `analyzer: language:` to force explicit casting and catch implicit downcast errors at compile time. + +### Null Safety +Eliminate static errors related to null safety by correctly managing variable initialization and nullability. + +* **Modifiers:** Apply `?` for nullable types, `!` for null assertions, and `required` for named parameters that cannot be null. +* **Late Initialization:** Use the `late` keyword for non-nullable variables guaranteed to be initialized before use. Apply this specifically to top-level or instance variables where Dart's control flow analysis cannot definitively prove initialization. +* **Wildcards:** Use the `_` wildcard variable (Dart 3.7+) for non-binding local variables or parameters to avoid unused variable warnings. + +### Error Handling +Distinguish between recoverable exceptions and unrecoverable errors. + +* **Catching:** Catch `Exception` subtypes for recoverable failures. +* **Errors:** Never explicitly catch `Error` or its subtypes (e.g., `TypeError`, `ArgumentError`). Errors indicate programming bugs that must be fixed, not caught. Enforce this by enabling the `avoid_catching_errors` linter rule. +* **Rethrowing:** Use `rethrow` inside a `catch` block to propagate an exception while preserving its original stack trace. + +## Workflows + +### Workflow: Static Analysis Resolution + +Use this sequential workflow to identify, fix, and verify static analysis errors in a Dart project. Copy the checklist to track your progress. + +**Task Progress:** +- [ ] 1. Run static analyzer. +- [ ] 2. Apply automated fixes. +- [ ] 3. Resolve remaining errors manually. +- [ ] 4. Verify fixes (Feedback Loop). + +**1. Run static analyzer** +Execute the Dart analyzer to identify all static errors in the target directory or file. +```bash +dart analyze . --fatal-infos +``` + +**2. Apply automated fixes** +Use the `dart fix` tool to automatically resolve standard linting and analysis issues. +```bash +# Preview changes +dart fix --dry-run +# Apply changes +dart fix --apply +``` + +**3. Resolve remaining errors manually** +Review the remaining analyzer output and apply conditional logic based on the error type: + +* **If the error is a Null Safety issue (e.g., "Property cannot be accessed on a nullable receiver"):** + * Verify if the variable can logically be null. + * If yes, use optional chaining (`?.`) or provide a fallback (`??`). + * If no, and initialization is guaranteed elsewhere, mark the declaration with `late`. +* **If the error is a Type Mismatch (e.g., "The argument type 'List' can't be assigned..."):** + * Trace the variable's initialization. + * Add explicit generic type annotations to the instantiation (e.g., `[]` instead of `[]`). +* **If the error is an Invalid Override (e.g., "The parameter type doesn't match the overridden method"):** + * Widen the parameter type to match the superclass, OR + * Add the `covariant` keyword to the parameter if tightening the type is intentionally required by the domain logic. + +**4. Verify fixes (Feedback Loop)** +Run the validator. Review errors. Fix. +```bash +dart analyze . +dart test +``` +* **If `dart analyze` reports errors:** Return to Step 3. +* **If `dart test` fails with a `TypeError`:** You have introduced an invalid explicit cast (`as T`) or accessed an uninitialized `late` variable. Locate the runtime failure and correct the type hierarchy or initialization order. + +## Examples + +### Example: Fixing Dynamic List Assignments +**Input (Fails Static Analysis):** +```dart +void printInts(List a) => print(a); + +void main() { + final list = []; // Inferred as List + list.add(1); + list.add(2); + printInts(list); // Error: List can't be assigned to List +} +``` + +**Output (Passes Static Analysis):** +```dart +void printInts(List a) => print(a); + +void main() { + final list = []; // Explicitly typed + list.add(1); + list.add(2); + printInts(list); +} +``` + +### Example: Fixing Method Overrides (Contravariance) +**Input (Fails Static Analysis):** +```dart +class Animal { + void chase(Animal a) {} +} + +class Cat extends Animal { + @override + void chase(Mouse a) {} // Error: Tightening parameter type +} +``` + +**Output (Passes Static Analysis):** +```dart +class Animal { + void chase(Animal a) {} +} + +class Cat extends Animal { + @override + void chase(covariant Mouse a) {} // Explicitly marked covariant +} +``` + +### Example: Fixing Null Safety with `late` +**Input (Fails Static Analysis):** +```dart +class Thermometer { + String temperature; // Error: Non-nullable instance field must be initialized + + void read() { + temperature = '20C'; + } +} +``` + +**Output (Passes Static Analysis):** +```dart +class Thermometer { + late String temperature; // Defers initialization check to runtime + + void read() { + temperature = '20C'; + } +} +``` diff --git a/skills/dart-generate-test-mocks/SKILL.md b/skills/dart-generate-test-mocks/SKILL.md new file mode 100644 index 0000000..fcd6d8b --- /dev/null +++ b/skills/dart-generate-test-mocks/SKILL.md @@ -0,0 +1,155 @@ +--- +name: dart-generate-test-mocks +description: Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`. Use when unit testing classes that depend on complex external services like APIs or databases. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:13:58 GMT +--- +# Testing and Mocking Dart Applications + +## Contents +- [Structuring Code for Testability](#structuring-code-for-testability) +- [Managing Dependencies](#managing-dependencies) +- [Generating Mocks](#generating-mocks) +- [Implementing Unit Tests](#implementing-unit-tests) +- [Workflow: Creating and Running Mocked Tests](#workflow-creating-and-running-mocked-tests) +- [Examples](#examples) + +## Structuring Code for Testability +Design Dart classes to support dependency injection. Isolate complex external dependencies (like API clients or databases) so they can be replaced with mock objects during testing. + +- Inject external services (e.g., `http.Client`) through class constructors. +- Represent URLs strictly as `Uri` objects using `Uri.parse(string)`. +- Utilize Dart's object-oriented features (classes, mixins) to define clear interfaces for external interactions. + +## Managing Dependencies +Configure the `pubspec.yaml` file with the necessary testing and code generation packages. + +- Add runtime dependencies (e.g., `package:http`) using `dart pub add http`. +- Add testing dependencies using `dart pub add dev:test dev:mockito dev:build_runner`. +- Import HTTP libraries with a prefix to avoid namespace collisions: `import 'package:http/http.dart' as http;`. + +## Generating Mocks +Use `package:mockito` and `build_runner` to automatically generate mock classes for fixed scenarios and behavior verification. + +- Always use the `@GenerateNiceMocks` annotation (preferable to `@GenerateMocks` to avoid missing stub exceptions). +- Place the annotation in the test file, passing a list of `MockSpec()` objects. +- Import the generated file using the `.mocks.dart` extension. +- Execute `build_runner` to generate the mock files: `dart run build_runner build`. + +## Implementing Unit Tests +Isolate the system under test using the generated mock objects. Use `package:test` to structure the test suite. + +- **Stubbing:** Configure mock behavior before interacting with the system under test. + - Use `when(mock.method()).thenReturn(value)` for synchronous methods. + - **CRITICAL:** Always use `thenAnswer((_) async => value)` for methods returning a `Future` or `Stream`. Never use `thenReturn` for asynchronous returns. +- **Verification:** Assert that the system under test interacted with the mock object correctly. + - Use `verify(mock.method()).called(1)` to check exact invocation counts. + - Use argument matchers like `any`, `anyNamed`, or `captureAny` for flexible verification. + +## Workflow: Creating and Running Mocked Tests + +Use the following checklist to implement and verify mocked unit tests. + +### Task Progress +- [ ] 1. Identify the external dependency to mock (e.g., `http.Client`). +- [ ] 2. Inject the dependency into the target class constructor. +- [ ] 3. Create a test file (e.g., `target_test.dart`) and add `@GenerateNiceMocks([MockSpec()])`. +- [ ] 4. Add the `part` or `import` directive for the generated `.mocks.dart` file. +- [ ] 5. Run `dart run build_runner build` to generate the mock classes. +- [ ] 6. Write the test cases using `group()` and `test()`. +- [ ] 7. Stub required behaviors using `when()`. +- [ ] 8. Execute the target method. +- [ ] 9. Verify interactions using `verify()` and assert outcomes using `expect()`. +- [ ] 10. Run the test suite using `dart test`. + +### Feedback Loop: Test Failures +If tests fail or `build_runner` encounters errors: +1. **Run validator:** Execute `dart test` or `dart run build_runner build`. +2. **Review errors:** Check for missing stubs, mismatched argument matchers, or syntax errors in the generated files. +3. **Fix:** + - If a mock method throws an unexpected null error, ensure you used `@GenerateNiceMocks`. + - If an async stub throws an `ArgumentError`, change `thenReturn` to `thenAnswer`. + - If `build_runner` fails, ensure the `.mocks.dart` import matches the file name exactly. +4. Repeat until all tests pass. + +## Examples + +### High-Fidelity Mocking and Testing Example + +**1. System Under Test (`lib/api_service.dart`)** +```dart +import 'dart:convert'; +import 'package:http/http.dart' as http; + +class ApiService { + final http.Client client; + + ApiService(this.client); + + Future fetchData(String urlString) async { + final uri = Uri.parse(urlString); + final response = await client.get(uri); + + if (response.statusCode == 200) { + return jsonDecode(response.body)['data']; + } else { + throw Exception('Failed to load data'); + } + } +} +``` + +**2. Test Implementation (`test/api_service_test.dart`)** +```dart +import 'package:test/test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:http/http.dart' as http; +import 'package:my_app/api_service.dart'; + +// Generate the mock class for http.Client +@GenerateNiceMocks([MockSpec()]) +import 'api_service_test.mocks.dart'; + +void main() { + group('ApiService', () { + late ApiService apiService; + late MockClient mockHttpClient; + + setUp(() { + mockHttpClient = MockClient(); + apiService = ApiService(mockHttpClient); + }); + + test('returns data if the http call completes successfully', () async { + // Arrange: Stub the async HTTP GET request using thenAnswer + when(mockHttpClient.get(any)).thenAnswer( + (_) async => http.Response('{"data": "Success"}', 200), + ); + + // Act + final result = await apiService.fetchData('https://api.example.com/data'); + + // Assert + expect(result, 'Success'); + + // Verify the mock was called with the correct Uri + verify(mockHttpClient.get(Uri.parse('https://api.example.com/data'))).called(1); + }); + + test('throws an exception if the http call completes with an error', () { + // Arrange + when(mockHttpClient.get(any)).thenAnswer( + (_) async => http.Response('Not Found', 404), + ); + + // Act & Assert + expect( + apiService.fetchData('https://api.example.com/data'), + throwsException, + ); + }); + }); +} +``` diff --git a/skills/dart-migrate-to-checks-package/SKILL.md b/skills/dart-migrate-to-checks-package/SKILL.md new file mode 100644 index 0000000..3daf894 --- /dev/null +++ b/skills/dart-migrate-to-checks-package/SKILL.md @@ -0,0 +1,528 @@ +--- +name: dart-migrate-to-checks-package +description: |- + Replace the usage of `expect` and similar functions from `package:matcher` + to `package:checks` equivalents. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Tue, 09 Jun 2026 19:30:00 GMT +--- +# Migrating Dart Tests to Package Checks + +Use this skill when you need to migrate a Dart test suite from the legacy +`package:matcher` (which is exported by default from `package:test/test.dart`) +to the modern, type-safe, and literate `package:checks` assertion library. + +## Contents +- [When to Use This Skill](#when-to-use-this-skill) +- [How to Use This Skill (The Workflow)](#how-to-use-this-skill-the-workflow) +- [Key Syntax Differences and Pitfalls](#key-syntax-differences-and-pitfalls) +- [Matcher-to-Checks Mapping Table](#matcher-to-checks-mapping-table) +- [Matchers with No Direct Replacements](#matchers-with-no-direct-replacements) +- [Strategies for Discovery](#strategies-for-discovery) +- [Examples](#examples) + +--- + +## When to Use This Skill +- When asked to "migrate tests to checks", "use package:checks", or + "modernize test assertions". +- When updating legacy test suites where static type safety, better + autocomplete in IDEs, and highly detailed failure diagnostics are desired. + +--- + +## How to Use This Skill (The Workflow) + +Follow this structured workflow to safely and systematically migrate a test suite: + +### 1. Dependency Setup +- Add `package:checks` as a `dev_dependency` in `pubspec.yaml`: + ```bash + dart pub add dev:checks + ``` +- Remove `package:matcher` if it is explicitly listed under `dev_dependencies` + (it is typically transitively included by `package:test`, which is fine). + +### 2. Identify and Plan Target Files +- Use the grep patterns in [Strategies for Discovery](#strategies-for-discovery) + to locate all test files containing legacy `expect` or `expectLater` calls. +- Decide whether to migrate files fully or incrementally. + +### 3. Migrating a File (Incremental or Full) +For any target test file: +1. **Update Imports**: + - Replace the generic `import 'package:test/test.dart';` with: + ```dart + import 'package:test/scaffolding.dart'; + import 'package:checks/checks.dart'; + ``` + - **For Incremental Migration**: If you only want to migrate some test cases + in the file, or want to migrate one step at a time, add: + ```dart + import 'package:test/expect.dart'; // Temporarily allows legacy expect() + ``` +2. **Translate Assertions**: Rewrite legacy `expect` and `expectLater` calls + to `check` syntax following the [Key Syntax Differences and + Pitfalls](#key-syntax-differences-and-pitfalls) and the + [Matcher-to-Checks Mapping Table](#matcher-to-checks-mapping-table). +3. **Verify via Compiler**: If migrating fully, remove the `import + 'package:test/expect.dart';` line. Any remaining un-migrated `expect` + calls will immediately surface as compiler errors, making them easy to + find and fix. + +### 4. Verification and Feedback Loops +- **Static Analysis**: Run static analysis on the target package: + ```bash + dart analyze + ``` + Pay close attention to generic type parameters on `.isA()` and + ensure asynchronous expectations are properly awaited (check for + `unawaited_futures` warnings). +- **Run Tests**: Execute the tests to verify both behavior and correct + assertion runtime logic: + ```bash + dart test + ``` + If a test fails, review the extremely detailed failure output of + `package:checks` to diagnose if the test is genuinely failing or if the + expectation was translated incorrectly. + +--- + +## Key Syntax Differences and Pitfalls + +> [!IMPORTANT] +> A line-for-line translation can sometimes introduce subtle bugs or false +> passes. Always review these key differences carefully: + +### 1. Collection Equality Pitfall (`equals` vs `deepEquals`) +- **Legacy Matcher**: `expect(actual, expected)` or `expect(actual, + equals(expected))` performed a **deep equality check** if the arguments + were collections (Lists, Maps, Sets). +- **Package Checks**: `.equals(expected)` corresponds strictly to + `operator ==`. Since Dart collections do not override `operator ==` for + element-wise comparison, using `.equals` on a collection will check for + *identity* and almost certainly fail at runtime. +- **Remediation**: You **must** replace collection equality assertions with + `.deepEquals(expected)`. + ```dart + // BEFORE (Matcher) + expect(myList, [1, 2, 3]); + + // AFTER (Checks) + check(myList).deepEquals([1, 2, 3]); + ``` + +### 2. The `reason` Parameter is now `because` +- **Legacy Matcher**: The explanation was passed as a trailing named + argument `reason` to `expect`: + ```dart + expect(actual, expectation, reason: 'Explanation'); + ``` +- **Package Checks**: The explanation is passed as the named argument + `because` to the `check` function *before* the actual subject: + ```dart + check(because: 'Explanation', actual).expectation(); + ``` + +### 3. Regular Expression Matching (`matches` vs `matchesPattern`) +- **Legacy Matcher**: The `matches(pattern)` matcher automatically converted + a `String` argument into a `RegExp` (e.g., `matches(r'\d')` matched `'1'`). +- **Package Checks**: `.matchesPattern(pattern)` treats a `String` argument + as a literal string pattern. +- **Remediation**: To match using a regular expression, you must explicitly + pass a `RegExp` object: + ```dart + // BEFORE (Matcher) + expect(someString, matches(r'\d+')); + + // AFTER (Checks) + check(someString).matchesPattern(RegExp(r'\d+')); + ``` + +### 4. Property Extraction (`TypeMatcher.having` vs `.has`) +- **Legacy Matcher**: Chained field/property expectations used + `TypeMatcher.having(feature, description, matcher)`: + ```dart + expect(actual, isA().having((p) => p.name, 'name', startsWith('A'))); + ``` +- **Package Checks**: The `.has(feature, description)` extension is + available on all `Subject`s, takes one fewer argument, and returns a new + `Subject` representing that property. You chain expectations directly off + it: + ```dart + check(actual).isA().has((p) => p.name, 'name').startsWith('A'); + ``` + +### 5. Synchronous vs. Asynchronous `throws` +- **Legacy Matcher**: In `package:matcher`, `throwsA` behaved similarly for both + synchronous closures and asynchronous futures when wrapped in `expect` or + `expectLater`. +- **Package Checks**: The `.throws()` expectation behaves differently and + has different return types depending on whether the subject is synchronous or + asynchronous: + - **Synchronous** (`Subject`): `.throws()` returns a + `Subject` synchronously. This **does not** accept a callback argument! + You chain or cascade expectations directly off the returned `Subject`: + ```dart + // YES (Synchronous chaining) + check(() => triggerSyncError()).throws() + ..has((e) => e.message, 'message').equals('invalid input'); + + // NO (Passing a callback to sync throws will cause a compiler error!) + check(() => triggerSync").throws((it) => ...); // ERROR! + ``` + - **Asynchronous** (`Subject>`): `.throws()` returns + `Future`. Because you cannot chain directly off a `Future`, this + **requires** an inspection callback: + ```dart + // YES (Asynchronous callback) + await check(triggerAsyncError()).throws((it) => it + ..has((e) => e.message, 'message').equals('invalid input')); + ``` + - **Crucial Pitfall**: Trying to chain expectations directly after an awaited + asynchronous `.throws()` (e.g., + `await check(future).throws().equals(...)`) will fail to compile + because it returns `Future`. + +### 6. RegExp / Pattern Equality +- **Legacy Matcher**: In `package:matcher`, `expect(myPattern,` + `equals(RegExp('Hello')))` worked because the matcher comparison rules + handled RegExp instances. +- **Package Checks**: `.equals()` uses strict Dart `==` equality. Since separate + `RegExp` instances do not satisfy `==`, using `.equals()` will fail at runtime. +- **Remediation**: Use `.isA()` type refinement along with cascades to + assert on the properties of the `RegExp` object explicitly: + ```dart + check(myPattern).isA() + ..has((r) => r.pattern, 'pattern').equals('Hello') + ..has((r) => r.isMultiLine, 'isMultiLine').isTrue(); + ``` + +### 7. Strict Nullable Boolean Safety (`bool?` fields) +- **Legacy Matcher**: Statically, `isTrue` and `isFalse` performed loose + dynamic checks at runtime, which silently accepted nullable booleans (`bool?`). +- **Package Checks**: `.isTrue()` and `.isFalse()` are defined strictly on + `Subject` (non-nullable). They are **not** available on `Subject`. +- **Remediation**: For fields declared as `bool?`, you must either refine the + subject (e.g., `.isNotNull().isTrue()`) or simply use `.equals(true)` and + `.equals(false)` which are generic and work on all types: + ```dart + // If options.flagOutdated is a bool? + check(options.flagOutdated).equals(true); + check(options.flagOutdated).equals(false); + ``` + +### 8. Map Key Containment (`containsKey` vs `contains`) +- **Legacy Matcher**: In `package:matcher`, `contains(key)` was used to assert + that a `Map` contained a specific key. +- **Package Checks**: Calling `.contains(...)` on a `Subject` is not + defined and will fail compilation. +- **Remediation**: Use the map-specific `.containsKey(key)` matcher instead: + ```dart + // BEFORE (Matcher) + expect(myMap, contains('my_key')); + + // AFTER (Checks) + check(myMap).containsKey('my_key'); + ``` + +### 9. Explicit Generic Parameters for Extension Types +- **Legacy Matcher**: `expect(extensionTypeConst, 3)` compiled because of loose + dynamic equality. +- **Package Checks**: If `QrEciValue` is an extension type representation of `int` + (e.g., `extension type const QrEciValue(int value) implements int`), calling + `.equals(3)` on a `Subject` fails because `3` (an `int`) is not + assignable to `QrEciValue`. Casting with `as int` will trigger an + "Unnecessary cast" static analysis warning because `QrEciValue` statically + implements `int`. +- **Remediation**: Explicitly specify the generic type parameter on the `check` + function to force checks to treat it as the primitive type: + ```dart + // YES (Type-safe and warning-free) + check(QrEciValue.iso8859_1).equals(3); + ``` + +### 10. Dynamic Map / JSON Lookup Casting +- **Legacy Matcher**: Loose dynamic typing allowed comparing nested json lookups + statically typed as `dynamic` directly against lists or maps. +- **Package Checks**: Strict type safety rejects the implicit assignment of + `dynamic` to `Iterable` in `.deepEquals(...)`. +- **Remediation**: Statically cast the dynamic lookup result to a `List` or `Map`: + ```dart + // YES (Explicit cast to List) + check(myIterable).deepEquals(json['data']['items'] as List); + ``` + +--- + +## Matcher-to-Checks Mapping Table + +Use this table as a quick reference for direct matcher replacements: + +| Legacy Matcher | Package Checks Equivalent | Notes | +| :--- | :--- | :--- | +| `expect(actual, expected)` | `check(actual).equals(expected)` | Use `.deepEquals` for collections! | +| `expect(actual, equals(expected))` | `check(actual).equals(expected)` | Use `.deepEquals` for collections! | +| `isA()` | `check(actual).isA()` | Chaining is supported directly | +| `same(expected)` | `check(actual).identicalTo(expected)` | Verifies identity | +| `anyElement(matcher)` | `check(iterable).any(conditionCallback)` | E.g. `check(list).any((e) => e.equals(1))` | +| `everyElement(matcher)` | `check(iterable).every(conditionCallback)` | E.g. `check(list).every((e) => e.isGreaterThan(0))` | +| `hasLength(expected)` | `check(actual).length.equals(expected)` | Works on String, Map, Iterable, etc. | +| `isNot(matcher)` | `check(actual).not(conditionCallback)` | E.g. `check(val).not((it) => it.equals(5))` | +| `contains(element)` | `check(actual).contains(element)` | Works on String, Iterable (use `containsKey` for Map!) | +| `contains(key)` (on a Map) | `check(map).containsKey(key)` | Map key containment | +| `startsWith(prefix)` | `check(string).startsWith(prefix)` | String only | +| `endsWith(suffix)` | `check(string).endsWith(suffix)` | String only | +| `isEmpty` | `check(actual).isEmpty()` | Works on String, Map, Iterable | +| `isNotEmpty` | `check(actual).isNotEmpty()` | Works on String, Map, Iterable | +| `isNull` | `check(actual).isNull()` | | +| `isNotNull` | `check(actual).isNotNull()` | | +| `isTrue` / `true` | `check(actual).isTrue()` | Works on non-nullable `bool` only | +| `isFalse` / `false` | `check(actual).isFalse()` | Works on non-nullable `bool` only | +| `completion(matcher)` | `await check(future).completes(conditionCallback)` | Must be awaited! | +| `throwsA(matcher)` | `await check(future).throws()` | Must be awaited! | +| `emits(value)` | `await check(streamQueue).emits(conditionCallback)` | Must be awaited! | +| `emitsThrough(value)` | `await check(streamQueue).emitsThrough(conditionCallback)` | Must be awaited! | +| `stringContainsInOrder(list)` | `check(string).containsInOrder(list)` | String only | +| `pairwiseCompare(...)` | `check(actual).pairwiseMatches(...)` | | + +--- + +## Matchers with No Direct Replacements + +Some legacy matchers do not have a one-to-one equivalent in `package:checks` +due to API cleanup. Use these standard workarounds: + +### 1. Specific Error Matchers +- **Legacy**: `throwsArgumentError`, `throwsStateError`, + `throwsUnsupportedError`, etc. +- **Checks**: Use `.throws()` with the specific error type: + ```dart + await check(triggerError()).throws(); + ``` + +### 2. The `anything` Matcher +- **Legacy**: `expect(actual, anything)` +- **Checks**: Pass an empty condition callback `(_) {}` when a condition is + syntactically required: + ```dart + await check(someFuture).completes((_) {}); + ``` + +### 3. Specific Numeric Toggles +- **Legacy**: `isPositive`, `isNegative`, `isZero`, `isNonPositive`, + `isNonNegative`, `isNonZero` +- **Checks**: Use explicit comparative expectations: + - `isPositive` $\rightarrow$ `isGreaterThan(0)` + - `isNegative` $\rightarrow$ `isLessThan(0)` + - `isZero` $\rightarrow$ `equals(0)` + - `isNonNegative` $\rightarrow$ `isGreaterOrEqual(0)` + +### 4. Numeric Ranges +- **Legacy**: `inClosedOpenRange(min, max)`, `inInclusiveRange(min, max)`, + etc. +- **Checks**: Chain the boundaries using the cascade operator (`..`): + ```dart + check(actualValue) + ..isGreaterOrEqual(min) + ..isLessThan(max); + ``` + +--- + +## Writing Custom Expectations (Replacing Custom Matchers) + +When migrating from a legacy codebase, you may encounter custom `Matcher` +subclasses. In `package:checks`, custom assertions are implemented as +`extension` methods on `Subject`. + +To write custom expectations, you must import the checks context API: +```dart +import 'package:checks/context.dart'; +``` + +### 1. Simple Custom Expectations (using `expect`) +Use `context.expect` to check a property and return a `Rejection` on failure: +```dart +extension CustomPersonChecks on Subject { + void isAdult() { + context.expect( + () => ['is an adult (age >= 18)'], + (actual) { + if (actual.age >= 18) return null; // Pass + return Rejection( + which: ['is only ${actual.age} years old'], + ); + }, + ); + } +} +``` + +### 2. Nested Property Extraction (using `nest` or `has`) +To extract a property and allow further chained checks, use `nest` or the +simpler `has` helper: +- **Using `has` (Recommended for simple, non-failing field access)**: + ```dart + extension CustomPersonChecks on Subject { + Subject
get address => has((p) => p.address, 'address'); + } + ``` +- **Using `nest` (For property extraction that can fail or reject)**: + ```dart + extension CustomPersonChecks on Subject { + Subject get ssn => context.nest( + 'has a valid SSN', + (actual) { + final ssnValue = actual.ssn; + if (ssnValue == null) { + return Extracted.rejection(which: ['has no SSN']); + } + return Extracted.value(ssnValue); + }, + ); + } + ``` + +### 3. Asynchronous Custom Expectations +If the expectation is asynchronous (e.g. checking a Future or Stream), use +`context.expectAsync` or `context.nestAsync` and return the resulting `Future`: +```dart +extension CustomFutureChecks on Subject> { + Future completesNormally() { + return context.expectAsync( + () => ['completes without throwing'], + (actual) async { + try { + await actual; + return null; // Pass + } catch (e) { + return Rejection(which: ['threw $e']); + } + }, + ); + } +} +``` + +--- + +## Strategies for Discovery + +Execute these commands in the terminal to identify legacy matchers and files +requiring migration: + +```bash +# 1. Find all test files containing legacy expect() or expectLater() +grep -rn "expect(" test/ +grep -rn "expectLater(" test/ + +# 2. Find potential collection equality pitfalls (literal lists or maps) +grep -rn "expect(.*, \[" test/ +grep -rn "expect(.*, {" test/ + +# 3. Find matches() calls (need conversion to RegExp + matchesPattern) +grep -rn "matches(" test/ + +# 4. Find legacy TypeMatcher.having() calls (which need conversion to .has()) +grep -rn "having(" test/ +``` + +--- + +## Examples + +### Basic Assertions +**Before (Matcher):** +```dart +expect(someValue, isNotNull); +expect(result, isTrue, reason: 'should be successful'); +expect(myString, startsWith('hello')); +``` + +**After (Checks):** +```dart +check(someValue).isNotNull(); +check(because: 'should be successful', result).isTrue(); +check(myString).startsWith('hello'); +``` + +### Collection and Deep Equality +**Before (Matcher):** +```dart +expect(items, [1, 2, 3]); +expect(configMap, equals({'port': 8080})); +``` + +**After (Checks):** +```dart +check(items).deepEquals([1, 2, 3]); +check(configMap).deepEquals({'port': 8080}); +``` + +### Chaining and Cascades +**Before (Matcher):** +```dart +expect(someString, allOf([ + startsWith('a'), + contains('b'), + endsWith('c'), +])); +``` + +**After (Checks):** +```dart +check(someString) + ..startsWith('a') + ..contains('b') + ..endsWith('c'); +``` + +### Complex Property Matching (has) +**Before (Matcher):** +```dart +expect(response, isA() + .having((r) => r.statusCode, 'statusCode', 200) + .having((r) => r.body, 'body', contains('success'))); +``` + +**After (Checks):** +```dart +check(response).isA() + ..has((r) => r.statusCode, 'statusCode').equals(200) + ..has((r) => r.body, 'body').contains('success'); +``` + +### Asynchronous Futures +**Before (Matcher):** +```dart +expect(fetchData(), completes); +expect(fetchData(), completion(equals('data'))); +expect(failingCall(), throwsA(isA())); +``` + +**After (Checks):** +```dart +await check(fetchData()).completes(); +await check(fetchData()).completes((it) => it.equals('data')); +await check(failingCall()).throws(); +``` + +### Asynchronous Streams +**Before (Matcher):** +```dart +var queue = StreamQueue(Stream.fromIterable([1, 2, 3])); +await expectLater(queue, emitsInOrder([1, 2, 3])); +``` + +**After (Checks):** +```dart +var queue = StreamQueue(Stream.fromIterable([1, 2, 3])); +await check(queue).inOrder([ + (s) => s.emits((e) => e.equals(1)), + (s) => s.emits((e) => e.equals(2)), + (s) => s.emits((e) => e.equals(3)), +]); +``` diff --git a/skills/dart-resolve-package-conflicts/SKILL.md b/skills/dart-resolve-package-conflicts/SKILL.md new file mode 100644 index 0000000..9a7ffdc --- /dev/null +++ b/skills/dart-resolve-package-conflicts/SKILL.md @@ -0,0 +1,116 @@ +--- +name: dart-resolve-package-conflicts +description: Workflow for fixing package version conflicts. Use this when `pub get` fails due to incompatible package versions. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:11:14 GMT +--- +# Managing Dart Dependencies + +## Contents +- [Core Concepts](#core-concepts) +- [Version Constraints](#version-constraints) +- [Workflow: Auditing Dependencies](#workflow-auditing-dependencies) +- [Workflow: Upgrading Dependencies](#workflow-upgrading-dependencies) +- [Workflow: Resolving Version Conflicts](#workflow-resolving-version-conflicts) +- [Examples](#examples) + +## Core Concepts + +Dart enforces a strict single-version rule for dependencies: a project and all its transitive dependencies must resolve to a single, shared version of any given package. This prevents runtime type mismatches but introduces the risk of "version lock." + +To mitigate version lock, Dart relies on version constraints rather than pinned versions in the `pubspec.yaml`. The `pubspec.lock` file maintains the exact resolved versions for reproducible builds. + +Understand the output columns of `dart pub outdated`: +* **Current:** The version currently recorded in `pubspec.lock`. +* **Upgradable:** The latest version allowed by the constraints in `pubspec.yaml`. `dart pub upgrade` resolves to this. +* **Resolvable:** The absolute latest version that can be resolved when factoring in all other dependencies in the project. +* **Latest:** The latest published version of the package (excluding prereleases). + +## Version Constraints + +* **Use Caret Syntax:** Always use caret syntax (e.g., `^1.2.3`) for dependencies in `pubspec.yaml`. This allows `pub` to select newer, non-breaking versions (up to, but not including, the next major version) during resolution. +* **Tighten Dev Dependencies:** Set the lower bound of `dev_dependencies` to the exact version currently used. This reduces resolution complexity and prevents older, incompatible dev tools from being selected. +* **Enforce Lockfiles in CI:** Use `dart pub get --enforce-lockfile` in CI/CD pipelines to ensure the exact versions tested locally are used in production. + +## Workflow: Auditing Dependencies + +Run this workflow periodically to identify stale packages that may impact stability or performance. + +**Task Progress:** +- [ ] Run `dart pub outdated`. +- [ ] Review the **Upgradable** column to identify packages that can be updated without modifying `pubspec.yaml`. +- [ ] Review the **Resolvable** column to identify packages that require constraint modifications in `pubspec.yaml` to update. +- [ ] Identify any packages marked as retracted or discontinued. + +## Workflow: Upgrading Dependencies + +Use conditional logic based on the audit results to upgrade dependencies. + +**Task Progress:** +- [ ] **If updating to "Upgradable" versions:** + - [ ] Run `dart pub upgrade`. + - [ ] Run `dart pub upgrade --tighten` to automatically update the lower bounds in `pubspec.yaml` to match the newly resolved versions. +- [ ] **If updating to "Resolvable" versions (Major updates):** + - [ ] Manually edit `pubspec.yaml` to bump the version constraint to match the "Resolvable" column (e.g., change `^0.11.0` to `^0.12.1`). + - [ ] Run `dart pub upgrade` to resolve the new constraints and update `pubspec.lock`. +- [ ] **Feedback Loop:** + - [ ] Run `dart analyze` -> review errors -> fix breaking API changes. + - [ ] Run `dart test` -> review failures -> fix regressions. + +## Workflow: Resolving Version Conflicts + +When `pub` cannot find a set of concrete versions that satisfy all constraints, or when dealing with a retracted package version, manipulate the lockfile surgically. + +**NEVER** delete the entire `pubspec.lock` file and run `dart pub get`. This causes uncontrolled upgrades across the entire dependency graph. + +**Task Progress:** +- [ ] Open `pubspec.lock`. +- [ ] Locate the specific YAML block for the conflicting or retracted package. +- [ ] Delete ONLY that package's entry from the lockfile. +- [ ] Run `dart pub get` to fetch the newest compatible, non-retracted version for that specific package. +- [ ] **Feedback Loop:** + - [ ] Run `dart pub deps` -> verify the dependency graph resolves correctly. + - [ ] If resolution fails, identify the transitive dependency causing the lock, update its constraint in `pubspec.yaml`, and retry. + +## Examples + +### Tightening Constraints +When `dart pub outdated` shows a package is resolvable to a higher minor/patch version, use the `--tighten` flag to update the `pubspec.yaml` automatically. + +**Input (`pubspec.yaml`):** +```yaml +dependencies: + http: ^0.13.0 +``` + +**Command:** +```bash +dart pub upgrade --tighten http +``` + +**Output (`pubspec.yaml`):** +```yaml +dependencies: + http: ^0.13.5 +``` + +### Surgical Lockfile Removal +If `package_a` is retracted or locked in a conflict, remove only its block from `pubspec.lock`. + +**Before (`pubspec.lock`):** +```yaml +packages: + package_a: + dependency: "direct main" + description: + name: package_a + url: "https://pub.dev" + source: hosted + version: "1.0.0" # Retracted version + package_b: + dependency: "direct main" + # ... +``` + +**Action:** Delete the `package_a` block entirely. Leave `package_b` untouched. Run `dart pub get`. diff --git a/skills/dart-run-static-analysis/SKILL.md b/skills/dart-run-static-analysis/SKILL.md new file mode 100644 index 0000000..27ca654 --- /dev/null +++ b/skills/dart-run-static-analysis/SKILL.md @@ -0,0 +1,104 @@ +--- +name: dart-run-static-analysis +description: Execute `dart analyze` to identify warnings and errors, and use `dart fix --apply` to automatically resolve mechanical lint issues. Use during development to ensure code quality and before committing changes. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:09:34 GMT +--- +# Analyzing and Fixing Dart Code + +## Contents +- [Analysis Configuration](#analysis-configuration) +- [Diagnostic Suppression](#diagnostic-suppression) +- [Workflow: Executing Static Analysis](#workflow-executing-static-analysis) +- [Workflow: Applying Automated Fixes](#workflow-applying-automated-fixes) +- [Examples](#examples) + +## Analysis Configuration + +Configure the Dart analyzer using the `analysis_options.yaml` file located at the package root. + +- **Base Configuration:** Always include a standard rule set (e.g., `package:lints/recommended.yaml` or `package:flutter_lints/flutter.yaml`) using the `include:` directive. +- **Strict Type Checks:** Enable strict type checks under the `analyzer: language:` node to prevent implicit downcasts and dynamic inferences. Set `strict-casts: true`, `strict-inference: true`, and `strict-raw-types: true`. +- **Linter Rules:** Explicitly enable or disable specific rules under the `linter: rules:` node. Use a key-value map (`rule_name: true/false`) when overriding included rules, or a list (`- rule_name`) when defining a fresh set. Do not mix list and map syntax in the same `rules` block. +- **Formatter Configuration:** Configure `dart format` behavior under the `formatter:` node. Set `page_width` (default 80) and `trailing_commas` (`automate` or `preserve`). +- **Analyzer Plugins:** Enable custom diagnostics by adding plugins under the `analyzer: plugins:` node. Ensure the plugin package is added as a `dev_dependency` in `pubspec.yaml`. + +## Diagnostic Suppression + +When a diagnostic (lint or warning) yields a false positive or applies to generated code, suppress it explicitly. + +- **File-level Exclusion:** Use the `analyzer: exclude:` node in `analysis_options.yaml` to exclude entire files or directories (e.g., `**/*.g.dart`) using glob patterns. +- **File-level Suppression:** Add `// ignore_for_file: ` at the top of a Dart file to suppress specific diagnostics for the entire file. Use `// ignore_for_file: type=lint` to suppress all linter rules. +- **Line-level Suppression:** Add `// ignore: ` on the line directly above the offending code, or appended to the end of the offending line. +- **Pubspec Suppression:** Add `# ignore: ` above the offending line in `pubspec.yaml` files (e.g., `# ignore: sort_pub_dependencies`). +- **Plugin Diagnostics:** Prefix the diagnostic code with the plugin name when suppressing plugin-specific issues (e.g., `// ignore: some_plugin/some_code`). + +## Workflow: Executing Static Analysis + +Use this workflow to identify type-related bugs, style violations, and potential runtime errors. + +**Task Progress:** +- [ ] 1. Verify `analysis_options.yaml` exists at the project root. +- [ ] 2. Run the analyzer using the `analyze_files` MCP tool (if available) or the CLI command `dart analyze `. +- [ ] 3. Review the diagnostic output. +- [ ] 4. If info-level issues must be treated as failures, append the `--fatal-infos` flag. +- [ ] 5. Resolve reported errors manually or proceed to the Automated Fixes workflow. + +## Workflow: Applying Automated Fixes + +Use this workflow to resolve outdated API usages, apply quick fixes, and migrate code (e.g., Dart 3 migrations). + +**Task Progress:** +- [ ] 1. Execute a dry run to preview proposed changes using the `dart_fix` MCP tool or CLI command `dart fix --dry-run`. +- [ ] 2. Review the proposed fixes to ensure they align with the intended architecture. +- [ ] 3. If additional fixes are required, verify that the corresponding linter rules are enabled in `analysis_options.yaml`. +- [ ] 4. Apply the fixes using the `dart_fix` MCP tool or CLI command `dart fix --apply`. +- [ ] 5. Format the modified code using the `dart_format` MCP tool or CLI command `dart format .`. +- [ ] 6. Run the static analysis workflow to verify all diagnostics are resolved. + +## Examples + +### Comprehensive `analysis_options.yaml` + +```yaml +include: package:flutter_lints/recommended.yaml + +analyzer: + exclude: + - "**/*.g.dart" + - "lib/generated/**" + language: + strict-casts: true + strict-inference: true + strict-raw-types: true + errors: + todo: ignore + invalid_assignment: warning + missing_return: error + +linter: + rules: + avoid_shadowing_type_parameters: false + await_only_futures: true + use_super_parameters: true + +formatter: + page_width: 100 + trailing_commas: preserve +``` + +### Inline Diagnostic Suppression + +```dart +// Suppress for the entire file +// ignore_for_file: unused_local_variable, dead_code + +void processData() { + // Suppress for a specific line + // ignore: invalid_assignment + int x = ''; + + const y = 10; // ignore: constant_identifier_names +} +``` diff --git a/skills/dart-setup-ffi-assets/SKILL.md b/skills/dart-setup-ffi-assets/SKILL.md new file mode 100644 index 0000000..9f92eab --- /dev/null +++ b/skills/dart-setup-ffi-assets/SKILL.md @@ -0,0 +1,419 @@ +--- +name: dart-setup-ffi-assets +description: "Guides agents in compiling and packaging C/C++ source code into dynamic or static libraries (Code Assets) using Dart's Native Assets hook system (via hook/build.dart and hook/link.dart utilizing package:hooks and package:native_toolchain_c). Use when a user asks to: 'setup native assets', 'compile C/C++ source code', 'bundle dynamic libraries', 'build native C code', 'link native assets', 'implement build.dart or link.dart hooks', or 'integrate C/C++ interop in Dart/Flutter'. Helps agents avoid manual toolchain orchestration and configures secure hash-validated binary downloads or advanced linker tree-shaking with package:record_use mapping." +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 29 May 2026 09:10:00 GMT +--- +# Compiling C Code into Code Assets with Native Assets Hooks + +Integrate and automate the compilation and packaging of native C/C++ source code into **Code Assets** under Dart's overarching **Native Assets** feature using build and link hooks. + +## Contents +- [Introduction](#introduction) +- [Constraints](#constraints) +- [Native Interop Packages](#native-interop-packages) +- [Step-by-Step Workflow](#step-by-step-workflow) +- [Choosing an Integration Approach](#choosing-an-integration-approach) +- [Method 1: Local Compilation with Linker Tree-Shaking (Recommended)](#method-1-local-compilation-with-linker-tree-shaking-recommended) + - [Prerequisite Host Compiler Toolchains](#prerequisite-host-compiler-toolchains) + - [C Source and Bindings Setup](#c-source-and-bindings-setup) + - [Defining the C Library Build Spec](#defining-the-c-library-build-spec) + - [Implementing hook/build.dart](#implementing-hookbuilddart) + - [Implementing hook/link.dart](#implementing-hooklinkdart) +- [Method 2: Downloading Precompiled Dynamic Libraries](#method-2-downloading-precompiled-dynamic-libraries) + - [Why Download Precompiled Binaries?](#why-download-precompiled-binaries) + - [Implementing Precompiled Dynamic Downloads](#implementing-precompiled-dynamic-downloads) +- [Verification Checklist](#verification-checklist) + - [1. Local Execution Sandbox](#1-local-execution-sandbox) + - [2. Verify Target Outputs](#2-verify-target-outputs) + - [3. Verify Tree-Shaking Stripping](#3-verify-tree-shaking-stripping) + - [4. Verify Offline Compliance (User Defines)](#4-verify-offline-compliance-user-defines) + +--- + +## Introduction + +Under Dart's **Native Assets** feature, packages can package native code (like C/C++ libraries) as **Code Assets** and bundle them automatically during standard development cycles (e.g., `dart run`, `dart test`, `dart build`, and `flutter run`). The packaging of **Code Assets** is driven by two programmatic hook scripts placed inside a package's `hook/` folder: + +1. `hook/build.dart`: Compiles local C sources to machine code or bundles prebuilt native binaries as code assets for a specific host/target architecture. +2. `hook/link.dart`: Links built code assets, applying advanced tree-shaking optimizations to strip unused native symbols and compress the runtime binary size. + +--- + +## Constraints + +> [!IMPORTANT] +> Keep all file resolving platform-independent. Never hardcode absolute target paths, shell scripts, or system command variables. Always use `Platform.script.resolve()` or `Uri`-based resolution to ensure scripts are fully portable. + +* **Hook Locations**: Compiling and packaging hooks must reside strictly inside the `hook/` directory at the package's root: + * `hook/build.dart` (Build execution phase) + * `hook/link.dart` (Optional packaging/linking/tree-shaking phase) +* **Compile Toolchain Standard**: Use the programmatic APIs from `package:native_toolchain_c` (e.g. `CBuilder` and `CLibrary`) to run compile toolchains. Never invoke raw `gcc`, `clang`, or `msvc` via shell commands. +* **Preamble & License Headers**: Every handcrafted and generated source file (including bindings, helpers, and hooks) must strictly contain the target package's copyright and licensing header. +* **Tree Shaking Mapping**: If utilizing compiler tree-shaking, you must map the target Dart method names (e.g. `Method.name`) back to their raw native C symbol names using a record use mapping generated by FFIgen. The mapping file must reside under `lib/src/third_party/` and strictly use the `.g.dart` extension (e.g., `sqlite3.record_use_mapping.g.dart`). +* **Integrity Safeguards for Precompiled Libraries**: If adopting the dynamic download pattern: + * **Cryptographic Verification**: Downloaded prebuilt binaries must be checked against preconfigured lookup tables containing MD5 or SHA-256 hashes to guarantee binary integrity and prevent tampering. + * **Graceful Recovery**: Support offline developers by providing fallbacks (such as local compiler execution via flags like `local_build`). + +--- + +## Native Interop Packages + +Programmatic build and link hooks for **Code Assets** leverage three specialized native interop packages: + +| Dependency | Purpose | Key API Abstractions | +| :--- | :--- | :--- | +| **`package:hooks`** | Main orchestrator defining execution bounds. | `build(args, callback)`, `link(args, callback)` | +| **`package:native_toolchain_c`** | Detects local compilers (MSVC, Xcode/Clang, GCC) and executes build toolchains. | `CLibrary`, `CBuilder`, `LinkerOptions.treeshake` | +| **`package:code_assets`** | Models code metadata records passed to dynamic loaders. | `CodeAsset`, `DynamicLoadingBundled` | + +--- + +## Step-by-Step Workflow + +### Step 1: Add Dependencies +Add Code Assets hook and toolchain dependencies to your package. You must fetch these dependencies directly from **pub.dev**. + +You can add it automatically using the CLI: +```bash +dart pub add code_assets hooks native_toolchain_c record_use dev:ffigen +``` + +Or manually declare them in your target package's `pubspec.yaml`: +```yaml +dependencies: + code_assets: ^1.0.0 + hooks: ^0.1.0 + native_toolchain_c: ^0.1.0 + record_use: ^0.6.0 + +dev_dependencies: + ffigen: ^20.1.1 +``` + +### Step 2: Define C Specifications +Define your target C library compilation metadata inside `lib/src/c_library.dart`. This lets both the build and link hooks share a single source of truth for assets, names, and sources. + +### Step 3: Implement Build and Link Hook Scripts +Write the compilation orchestration script inside `hook/build.dart` and the dead-code elimination logic inside `hook/link.dart`. + +### Step 4: Run the Hook Cycle +Running standard test suites dynamically launches the build and link hook lifecycle in the background: +```bash +dart test +``` + +--- + +## Choosing an Integration Approach + +There are two primary methods for integrating and delivering C/C++ native assets in Dart. Select the one that matches your project requirements: + +| Aspect | Method 1: Local Compilation & Tree-Shaking | Method 2: Precompiled Downloads | +| :--- | :--- | :--- | +| **Primary Use Case** | When C/C++ source code is included directly in the package and you want maximum size optimization. | When compiling locally is slow/complex, or when avoiding developer host toolchain requirements. | +| **Host Toolchain Requirements** | Requires pre-installed platform C compiler (Xcode tools, MSVC, GCC). | Zero compiler setup required on developer/user machines. | +| **Binary Optimization** | Premium. Unused symbols are completely tree-shaken, decreasing library size. | Standard. Standard compiled binaries are shipped as-is. | +| **Offline Setup** | Fully compliant. Works completely offline. | Requires network access to download libraries, with offline fallback. | + +--- + +## Method 1: Local Compilation with Linker Tree-Shaking (Recommended) + +In this approach, the build hook invokes local toolchains (GCC, Clang, MSVC) to compile source files directly. The link hook subsequently filters output symbols utilizing compiler options, retaining only target methods invoked in user code. This represents the standard, robust SQLite pattern under `pkgs/code_assets/example/sqlite`. + +### Prerequisite Host Compiler Toolchains + +Since `package:native_toolchain_c` delegates actual dynamic compilation to the host operating system's default toolchain, the development machine **must** have one of the following compiler packages pre-installed: + +* **macOS**: Xcode Command Line Tools. Install via: + ```bash + xcode-select --install + ``` +* **Linux**: GCC or Clang. Install via: + ```bash + sudo apt install build-essential + ``` +* **Windows**: MSVC (Microsoft Visual C++). Install the **Visual Studio Installer** and select the **Desktop development with C++** workload. + +*Note: If no compatible toolchain is discovered on the host path, the build hook script will throw a compilation execution exception. Ensure to specify compiler constraints or adopt Method 2 if toolchains cannot be guaranteed.* + +### C Source and Bindings Setup + +Assume a C source defining simple math functions at `third_party/sqlite/sqlite3.c` with its entry point header at `third_party/sqlite/sqlite3.h`: + +```c +#ifndef SQLITE3_H_ +#define SQLITE3_H_ + +const char *sqlite3_libversion(void); + +#endif // SQLITE3_H_ +``` + +We utilize a programmatic FFIgen script (`tool/ffigen.dart`) to create FFI bindings in `lib/src/third_party/sqlite3.g.dart`, enabling recorded usage tracking and producing the lookup metadata map in `lib/src/third_party/sqlite3.record_use_mapping.g.dart`: + +```dart +// AUTO-GENERATED FILE - DO NOT MODIFY. +// Generated via ffigen. + +const recordUseMapping = { + 'sqlite3_libversion': 'sqlite3_libversion', +}; +``` + +### Defining the C Library Build Spec + +Define the centralized library specification in `lib/src/c_library.dart`: + +```dart +import 'package:native_toolchain_c/native_toolchain_c.dart'; + +/// The C build specification for the sqlite library. +final cLibrary = CLibrary( + name: 'sqlite3', + assetName: 'src/third_party/sqlite3.g.dart', + sources: ['third_party/sqlite/sqlite3.c'], +); +``` + +### Implementing `hook/build.dart` + +Implement `hook/build.dart` using `CLibrary.build`. This builds the library to a dynamic library (e.g. `.so`, `.dylib`, or `.dll`) inside the hook's target directory: + +```dart +import 'package:code_assets/code_assets.dart'; +import 'package:hooks/hooks.dart'; +import 'package:sqlite/src/c_library.dart'; + +void main(List args) async { + await build(args, (input, output) async { + if (input.config.buildCodeAssets) { + await cLibrary.build( + input: input, + output: output, + defines: { + if (input.config.code.targetOS == OS.windows) + // Ensure C functions are explicitly exported in the Windows DLL + 'SQLITE_API': '__declspec(dllexport)', + }, + ); + } + }); +} +``` + +### Implementing `hook/link.dart` + +Implement the link optimization phase in `hook/link.dart`. This utilizes compiler tree-shaking options (`LinkerOptions.treeshake`) to compile a minimized, dead-code-eliminated binary based on symbol usage records: + +```dart +import 'package:hooks/hooks.dart'; +import 'package:native_toolchain_c/native_toolchain_c.dart'; +import 'package:record_use/record_use.dart'; +import 'package:sqlite/src/c_library.dart'; +import 'package:sqlite/src/third_party/sqlite3.record_use_mapping.g.dart'; + +void main(List arguments) async { + await link(arguments, (input, output) async { + await cLibrary.link( + input: input, + output: output, + linkerOptions: LinkerOptions.treeshake( + // Map Dart Method references back to raw C symbol names + symbolsToKeep: input.recordedUses?.calls.keys.cast().map( + (e) => recordUseMapping[e.name]!, + ), + ), + ); + }); +} +``` + +--- + +## Method 2: Downloading Precompiled Dynamic Libraries + +An alternative approach compiles binaries beforehand on a central build machine, archives them, and downloads the target binary during the build hook execution. This matches the paradigm demonstrated in the `download_asset` hook package. + +### Why Download Precompiled Binaries? + +* **Host Constraints**: Compiling large C/C++ libraries locally requires a complete compiler setup (GCC, Xcode/SDKs, Visual Studio) that the end-developer's host machine may not possess. +* **Compile Speed**: Precompiled downloads execute in milliseconds compared to potentially long multi-minute compilation processes. +* **Platform Bridging**: Allows cross-compiling constraints to be avoided if host architectures are limited. + +--- + +### Implementing Precompiled Dynamic Downloads + +We configure our build hook to detect local compiler flags (e.g. `local_build`). If not specified, the hook utilizes `HttpClient` to pull down platform-specific libraries, calculates the MD5 hash to confirm download safety against a configured hashes lookup table, and registers the binary file as a `CodeAsset`: + +#### 1. Defining Target Hashes (`lib/src/hook_helpers/hashes.dart`) +Define target MD5 hash checks per platform file in your package sources: + +```dart +const assetHashes = { + 'libnative_add_macos_arm64.dylib': '4a88f50438a98402db2dbd47b59eb412', + 'libnative_add_linux_x64.so': '9f5e15043aa98402dcdbbd47b59ea520', + 'native_add_windows_x64.dll': 'a881e5043ba98402acdebd47b59fa321', +}; +``` + +#### 2. Hook Downloader Helper (`lib/src/hook_helpers/download.dart`) +Implement the downloading and integrity check logic using dynamic target filename matching: + +```dart +import 'dart:io'; +import 'package:code_assets/code_assets.dart'; +import 'package:crypto/crypto.dart'; + +const version = '1.0.0'; + +Uri downloadUri(String target) => Uri.parse( + 'https://github.com/my-org/my-native-repo/releases/download/$version/$target', +); + +Future downloadAsset( + OS targetOS, + Architecture targetArchitecture, + Directory outputDir, +) async { + final fileName = targetOS.dylibFileName('native_add_${targetOS.name}_${targetArchitecture.name}'); + final uri = downloadUri(fileName); + + final client = HttpClient()..findProxy = HttpClient.findProxyFromEnvironment; + final request = await client.getUrl(uri); + final response = await request.close(); + + if (response.statusCode != 200) { + throw ArgumentError('Download target $uri failed: Code ${response.statusCode}'); + } + + final targetFile = File.fromUri(outputDir.uri.resolve(fileName)); + await targetFile.create(recursive: true); + await response.pipe(targetFile.openWrite()); + + return targetFile; +} + +Future hashAsset(File file) async { + return md5.convert(await file.readAsBytes()).toString(); +} +``` + +#### 3. Implementing `hook/build.dart` + +Write the final download build hook incorporating local compilation fallback: + +```dart +import 'dart:io'; +import 'package:code_assets/code_assets.dart'; +import 'package:hooks/hooks.dart'; +import 'package:my_download_package/src/hook_helpers/hashes.dart'; +import 'package:my_download_package/src/hook_helpers/download.dart'; +import 'package:native_toolchain_c/native_toolchain_c.dart'; + +void main(List args) async { + await build(args, (input, output) async { + final localBuild = input.userDefines['local_build'] as bool? ?? false; + + if (localBuild) { + final name = 'native_add_${input.config.code.targetOS.name}_${input.config.code.targetArchitecture.name}'; + final builder = CBuilder.library( + name: name, + assetName: 'native_add.dart', + sources: ['src/native_add.c'], + ); + await builder.run(input: input, output: output); + } else { + final targetOS = input.config.code.targetOS; + final targetArch = input.config.code.targetArchitecture; + final outputDir = Directory.fromUri(input.outputDirectory); + + final file = await downloadAsset(targetOS, targetArch, outputDir); + + final fileHash = await hashAsset(file); + final expectedFileName = targetOS.dylibFileName('native_add_${targetOS.name}_${targetArch.name}'); + final expectedHash = assetHashes[expectedFileName]; + + if (fileHash != expectedHash) { + throw Exception( + 'Security Mismatch: File $expectedFileName hash verification failed! ' + 'Found hash: $fileHash, expected: $expectedHash.' + ); + } + + output.assets.code.add( + CodeAsset( + package: input.packageName, + name: 'native_add.dart', + linkMode: DynamicLoadingBundled(), + file: file.uri, + ), + ); + } + }); +} +``` + +--- + +## Verification Checklist + +Before declaring a build or link hook implementation complete, always perform the following checks: + +### 1. Local Execution Sandbox +Run unit tests and confirm the native assets compile/link process completes with no runtime or build tool exceptions: +```bash +dart test +``` + +### 2. Verify Target Outputs +Navigate to your package target directory and verify that dynamic binary assets are created for the host system: +* **macOS**: Verify `.dart_tool/resources/` or target directories contain `.dylib` files. +* **Linux**: Verify `.dart_tool/resources/` or target directories contain `.so` files. +* **Windows**: Verify `.dart_tool/resources/` or target directories contain `.dll` files. + +### 3. Verify Tree-Shaking Stripping +To ensure the link hook is actually stripping unused native symbols and compressing binary packaging, perform the following validation: + +1. Compile a production bundle of the CLI/app: + ```bash + dart build cli bin/main.dart + ``` +2. Navigate to the compiled build directory containing the dynamic library. +3. Query the exported dynamic symbol tables: + * **macOS**: + ```bash + nm -gU build/cli/lib/libsqlite3.dylib + ``` + * **Linux**: + ```bash + nm -D build/cli/lib/libsqlite3.so + ``` + * **Windows** (using MSVC Developer Command Prompt): + ```cmd + dumpbin /EXPORTS build\cli\lib\sqlite3.dll + ``` +4. **Confirm Target Exports**: Verify that the command outputs **only** the explicitly kept entry point functions (e.g. `sqlite3_libversion`) and does not output any unreferenced/stripped symbols. +5. **No Bundle Scenario**: If the application does not import or invoke any methods from the native library: + - Verify that the link hook logs: `Skipping linking as no symbols are to be kept.` + - Verify that no library was built/placed in the production bundle (the `.dylib`/`.so`/`.dll` file is not generated, saving bundle size). + +### 4. Verify Offline Compliance (User Defines) +Confirm offline compliance is fully active and the download fallback executes perfectly offline: + +1. Configure the `local_build: true` define for your package in the package's `pubspec.yaml` (or the workspace root `pubspec.yaml`): + ```yaml + hooks: + user_defines: + : + local_build: true + ``` +2. Disable the machine's network adapter or run in a sandboxed offline shell. +3. Launch unit tests: + ```bash + dart test + ``` +4. Verify the test suite successfully compiles local source files using host compilers, has no compile errors, and never attempts network download requests. diff --git a/skills/dart-use-ffigen/SKILL.md b/skills/dart-use-ffigen/SKILL.md new file mode 100644 index 0000000..d7b5862 --- /dev/null +++ b/skills/dart-use-ffigen/SKILL.md @@ -0,0 +1,218 @@ +--- +name: dart-use-ffigen +description: Guide agents to use `package:ffigen` to automatically generate FFI bindings instead of writing them manually. Use this skill when a task involves writing new FFI bindings, extending C/Objective-C/Swift integrations, or replacing hand-crafted `dart:ffi` setups. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Thu, 28 May 2026 07:21:07 GMT +--- +# Generating FFI Bindings using package:ffigen + +## Contents +- [Introduction](#introduction) +- [Constraints](#constraints) +- [FFIgen Overview](#ffigen-overview) +- [Step-by-Step Workflow](#step-by-step-workflow) +- [Concrete Example: Binding a C Library](#concrete-example-binding-a-c-library) +- [Verification Checklist](#verification-checklist) + +## Introduction + +Automate and standardize the generation of FFI bindings using `package:ffigen` (`FfiGenerator`). Writing FFI bindings by hand is error-prone, brittle, and highly discouraged. + +## Constraints + +* **No Hand-Written FFI Bindings**: If native headers (`.h` files) exist or are generated by a build step, never write manual `DynamicLibrary.lookup`, `@Native` external functions, or raw struct classes. Always use `FfiGenerator` to generate them. +* **Generator Location**: The generator script should be located at `tool/ffigen.dart` within the target package root. +* **Header Location**: If the native header files are third-party, they should be located in `third_party/` within the target package (otherwise placing them in a `src/` directory at the package root is also acceptable). If the headers are not in one of these standard locations, notify the user that it would be cleaner to move the header files to the standard location (e.g., `third_party/`). +* **Targeted Inclusion Filters**: Avoid importing an entire native library unless specifically needed. Always apply precise inclusion lists using positive matches to minimize the size and cognitive load of the generated code (e.g., using `Functions.includeSet` or filtering matches in `include` closures). +* **Output Setup**: If the generated FFI bindings interface with a third-party library (or reference third-party headers), the generated files must always be placed under `lib/src/third_party/`. The primary generated FFI bindings file must strictly use the `.g.dart` extension (e.g. `sqlite3.g.dart`). +* **Preamble & License Headers**: Always supply a premium `preamble` in the `Output` class to specify the license. This must match the native third-party library's license, explicitly include the copyright header of the target native header file, and contain an automatic generation warning (e.g. `// Generated by package:ffigen. Do not edit manually.`). +* **No Unnecessary Commits of Stale Bindings**: Ensure you run the generator script and check if the generated files have changed *before* finishing your task. Always verify the package by running `dart analyze`. +* **Record Usage and Tree Shaking**: If the package is integrated into standard runtime execution or compiles native assets via native hooks: + * Enable recorded usage on all functions by setting `recordUse: (_) => true` under `Functions`. + * Specify the `recordUseMapping` target in `Output` (which must strictly be a `.g.dart` file under `lib/src/third_party/`, e.g. `lib/src/third_party/sqlite3.record_use_mapping.g.dart`) to register bindings for symbol tree shaking. + +## FFIgen Overview + +To construct the programmatic generator, use the core configuration objects imported from `package:ffigen/ffigen.dart`: + +### 1. `FfiGenerator` +The parent class that orchestrates the configuration, parsing, and code generation. +```dart +FfiGenerator({ + Headers headers = const Headers(), + Enums enums = Enums.excludeAll, + Functions functions = Functions.excludeAll, + Globals globals = Globals.excludeAll, + Integers integers = const Integers(), + Macros macros = Macros.excludeAll, + Structs structs = Structs.excludeAll, + Typedefs typedefs = Typedefs.excludeAll, + Unions unions = Unions.excludeAll, + UnnamedEnums unnamedEnums = UnnamedEnums.excludeAll, + ObjectiveC? objectiveC, + required Output output, +}).generate(); +``` + +### 2. `Headers` +Configures Clang header parsing targets and compiler flags. +* `entryPoints`: A list of target header `Uri` inputs. +* `include`: A filter function `bool Function(Uri header)` that handles transitive header imports. +* `compilerOptions`: Custom preprocessor/include compiler flags to pass directly to libclang. +* `ignoreSourceErrors`: Set to `true` to silence errors occurring inside third-party headers during parsing. + +### 3. `Functions` +Specifies which native C/C++ functions to expose in Dart. +* `include`: A matcher function (e.g. `(decl) => {'my_func'}.contains(decl.originalName)` or `Functions.includeSet({'my_func'})`). +* `isLeaf`: Declares functions as leaf functions (`(decl) => true`) if they do not call back into Dart or block thread execution. +* `recordUse`: Enables metadata generation for native asset tree shaking (essential in `dart-lang/native`). Set to `(_) => true`. + +### 4. `Output` +Configures target generated files. +* `dartFile`: Target `Uri` where the primary FFI bindings will be written. +* `recordUseMapping`: Target `Uri` for recorded usage metadata maps (crucial for linking-time tree shaking). +* `preamble`: Text inserted at the top of the generated file (licensing, annotations). +* `format`: Set to `true` to run the Dart formatter automatically. + +## Step-by-Step Workflow + +### Step 1: Check/Add Dependencies +Open the package's `pubspec.yaml` and verify the `dev_dependencies` contains `ffigen`. Use the Dart MCP server or look up the latest version on [pub.dev](https://pub.dev/packages/ffigen) (e.g., `^20.1.1`). + +You can add it automatically using the CLI: +```bash +dart pub add dev:ffigen +``` + +### Step 2: Formulate Paths Dynamically +Create a programmatic generator script under the package's `tool/` directory (e.g., `tool/ffigen.dart`). +Resolve paths relative to `Platform.script` to make sure it runs successfully from any working directory: + +```dart +final packageRoot = Platform.script.resolve('../'); +final headerFile = packageRoot.resolve('third_party/library.h'); +final targetBindings = packageRoot.resolve('lib/src/third_party/bindings.g.dart'); +``` + +### Step 3: Write the Script (`tool/ffigen.dart`) +Define `void main()` and run `FfiGenerator` with dynamic options (see complete example below). + +### Step 4: Run Code Generation +Execute the script from the terminal inside the target package folder: +```bash +dart run tool/ffigen.dart +``` + +### Step 5: Static Analysis +Verify that the generated bindings are correct and resolve any analysis issues. FFIgen automatically runs the Dart formatter on the output file (via `format: true` configuration), so manual formatting is not required. + +1. Run the static analyzer inside the target package: + ```bash + dart analyze + ``` +2. **Addressing Warnings/Lints**: If `dart analyze` reports style or lint warnings inside the generated file, append the corresponding warning codes to the `ignore_for_file:` list in your generator script's `preamble` configuration (e.g., adding `camel_case_types`, `non_constant_identifier_names`, etc.). Do not modify the package's global rules. +3. **Addressing Compilation Errors**: If `dart analyze` reports actual compiler or analysis errors (not warnings) inside the generated file, do not attempt to edit the generated file manually. Report these error details directly to the user so they can file an issue on the repository at [github.com/dart-lang/native](https://github.com/dart-lang/native). + + +## Concrete Example: Binding a C Library + +Let's assume we are working with the SQLite package under `pkgs/code_assets/example/sqlite`, which embeds SQLite C library sources inside `third_party/sqlite/` and accesses it via FFI. + +### The C Header File (`third_party/sqlite/sqlite3.h`) +```c +// The author disclaims copyright to this source code. + +#ifndef SQLITE3_H_ +#define SQLITE3_H_ + +const char *sqlite3_libversion(void); + +#endif // SQLITE3_H_ +``` + +### BEFORE: Manual FFI Binding (The Anti-Pattern) +A developer might attempt to handcraft this integration. It is fragile, blocks tree-shaking metadata, and is highly prone to ABI and structural mapping issues: + +```dart +// lib/src/sqlite3_manual.dart +import 'dart:ffi' as ffi; +import 'package:ffi/ffi.dart'; + +// Flaw 1: Hardcoded DynamicLibrary lookup blocks integration with modern native asset compilation. +final ffi.DynamicLibrary _dylib = ffi.DynamicLibrary.open('libsqlite3.so'); + +// Flaw 2: Manual function type matching requires writing redundant dynamic lookup boilerplate and lacks tree-shaking metadata. +typedef _sqlite3_libversion_C = ffi.Pointer Function(); +typedef _sqlite3_libversion_Dart = ffi.Pointer Function(); + +final _sqlite3_libversion_Dart sqlite3LibVersion = _dylib + .lookup>('sqlite3_libversion') + .asFunction(); +``` + +### AFTER: Generating via FFIgen (The Correct Pattern) + +Create a programmatic script at `tool/ffigen.dart`: + +```dart +// Copyright (c) 2025, 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:io'; +import 'package:ffigen/ffigen.dart'; + +void main() { + // Resolve paths dynamically relative to Platform.script + final packageRoot = Platform.script.resolve('../'); + final entryHeader = packageRoot.resolve('third_party/sqlite/sqlite3.h'); + final bindingsOutput = packageRoot.resolve('lib/src/third_party/sqlite3.g.dart'); + final treeShakeMapping = packageRoot.resolve('lib/src/third_party/sqlite3.record_use_mapping.g.dart'); + + FfiGenerator( + headers: Headers( + entryPoints: [entryHeader], + ), + functions: Functions( + include: (decl) => {'sqlite3_libversion'}.contains(decl.originalName), + // Essential for package optimization and tree-shaking + recordUse: (_) => true, + ), + output: Output( + dartFile: bindingsOutput, + recordUseMapping: treeShakeMapping, + format: true, + preamble: ''' + +// AUTO-GENERATED FILE - DO NOT MODIFY. +// Generated via ffigen. +// To regenerate: dart run tool/ffigen.dart + +// ignore_for_file: type=lint, unused_import, unused_element, deprecated_member_use_from_same_package, experimental_member_use +''', + ), + ).generate(); + + print('Successfully generated sqlite3 FFI bindings.'); +} +``` + +### Running the Generator script +Run this in the package root directory: +```bash +dart run tool/ffigen.dart +``` + +This will automatically create: +1. `lib/src/third_party/sqlite3.g.dart` +2. `lib/src/third_party/sqlite3.record_use_mapping.g.dart` + +## Verification Checklist + +Always perform the following verification before completing a binding generation task: + +1. **Correct Setup**: Verify the target generated files are inside `lib/src/third_party/` (required for third-party licensed code) and the primary FFI bindings file strictly uses the `.g.dart` extension. +2. **Static Analysis**: Run `dart analyze` and ensure there are zero compiler/analyzer errors or warnings in the package. + * If static warnings are reported in the generated bindings, suppress them by adding `ignore_for_file` rules to the generator's `preamble` configuration (do not modify global package rules). + * If actual compiler or analyzer errors are reported in the generated bindings, do not edit the generated file manually. Report the details to the user and direct them to file an issue at [github.com/dart-lang/native](https://github.com/dart-lang/native). diff --git a/skills/dart-use-pattern-matching/SKILL.md b/skills/dart-use-pattern-matching/SKILL.md new file mode 100644 index 0000000..7455620 --- /dev/null +++ b/skills/dart-use-pattern-matching/SKILL.md @@ -0,0 +1,146 @@ +--- +name: dart-use-pattern-matching +description: Use switch expressions and pattern matching where appropriate +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Fri, 24 Apr 2026 15:08:55 GMT +--- +# Implementing Dart Patterns + +## Contents +- [Pattern Selection Strategy](#pattern-selection-strategy) +- [Switch Statements vs. Expressions](#switch-statements-vs-expressions) +- [Core Pattern Implementations](#core-pattern-implementations) +- [Workflows](#workflows) +- [Examples](#examples) + +## Pattern Selection Strategy + +Apply specific pattern types based on the data structure and desired outcome. Follow these conditional guidelines: + +* **If validating and extracting from deserialized data (e.g., JSON):** Use Map and List patterns to simultaneously check structure and destructure key-value pairs. +* **If handling multiple return values:** Use Record patterns to destructure fields directly into local variables. +* **If executing type-specific behavior (Algebraic Data Types):** Use Object patterns combined with `sealed` classes to ensure exhaustiveness. +* **If matching numeric ranges or conditions:** Use Relational (`>=`, `<=`) and Logical-and (`&&`) patterns. +* **If multiple cases share logic:** Use Logical-or (`||`) patterns to share a single case body or guard clause. +* **If ignoring specific values:** Use the Wildcard pattern (`_`) or a non-matching Rest element (`...`) in collections. + +## Switch Statements vs. Expressions + +Select the appropriate switch construct based on the execution context: + +* **If producing a value:** Use a **switch expression**. + * Syntax: `switch (value) { pattern => expression, }` + * Rule: Each case must be a single expression. No implicit fallthrough. Must be exhaustive. +* **If executing statements or side effects:** Use a **switch statement**. + * Syntax: `switch (value) { case pattern: statements; }` + * Rule: Empty cases fall through to the next case. Non-empty cases implicitly break (no `break` keyword required). + +## Core Pattern Implementations + +Implement patterns using the following syntax and rules: + +* **Logical-or (`||`):** `pattern1 || pattern2`. Both branches must define the exact same set of variables. +* **Logical-and (`&&`):** `pattern1 && pattern2`. Branches must *not* define overlapping variables. +* **Relational:** `==`, `!=`, `<`, `>`, `<=`, `>=` followed by a constant expression. +* **Cast (`as`):** `pattern as Type`. Throws if the value does not match the type. Use to forcibly assert types during destructuring. +* **Null-check (`?`):** `pattern?`. Fails the match if the value is null. Binds the variable to the non-nullable base type. +* **Null-assert (`!`):** `pattern!`. Throws if the value is null. +* **Variable:** `var name` or `Type name`. Binds the matched value to a new local variable. +* **Wildcard (`_`):** Matches any value and discards it. +* **List:** `[pattern1, pattern2]`. Matches lists of exact length unless a Rest element (`...` or `...var rest`) is used. +* **Map:** `{"key": pattern}`. Matches maps containing the specified keys. Ignores unmatched keys. +* **Record:** `(pattern1, named: pattern2)`. Matches records of the exact shape. Use `:var name` to infer the getter name. +* **Object:** `ClassName(field: pattern)`. Matches instances of `ClassName`. Use `:var field` to infer the getter name. + +## Workflows + +### Task Progress: Implementing Pattern Matching +Copy this checklist to track progress when implementing complex pattern matching logic: + +- [ ] Identify the data structure being evaluated (JSON, Record, Class, Enum). +- [ ] Select the appropriate switch construct (Expression for values, Statement for side-effects). +- [ ] Define the required patterns (Object, Map, List, Record). +- [ ] Extract required data using Variable patterns (`var x`, `:var y`). +- [ ] Apply Guard clauses (`when condition`) for logic that cannot be expressed via patterns. +- [ ] Handle unmatched cases using a Wildcard (`_`) or `default` clause (if not using a sealed class). +- [ ] Run exhaustiveness validator. + +### Feedback Loop: Exhaustiveness Checking +When switching over `sealed` classes or enums, you must ensure all subtypes are handled. + +1. **Run validator:** Execute `dart analyze`. +2. **Review errors:** Look for "The type 'X' is not exhaustively matched by the switch cases" errors. +3. **Fix:** Add the missing Object patterns for the unhandled subtypes, or add a Wildcard (`_`) case if a default fallback is acceptable. + +## Examples + +### JSON Validation and Destructuring +Use Map and List patterns to validate structure and extract data in a single step. + +**Input:** +```dart +var data = { + 'user': ['Lily', 13], +}; +``` + +**Implementation:** +```dart +if (data case {'user': [String name, int age]}) { + print('User $name is $age years old.'); +} else { + print('Invalid JSON structure.'); +} +``` + +### Algebraic Data Types (Sealed Classes) +Use Object patterns with switch expressions to handle family types exhaustively. + +**Implementation:** +```dart +sealed class Shape {} + +class Square implements Shape { + final double length; + Square(this.length); +} + +class Circle implements Shape { + final double radius; + Circle(this.radius); +} + +// Switch expression guarantees exhaustiveness due to `sealed` modifier. +double calculateArea(Shape shape) => switch (shape) { + Square(length: var l) => l * l, + Circle(:var radius) => math.pi * radius * radius, +}; +``` + +### Variable Swapping and Destructuring +Use variable assignment patterns to swap values or extract record fields without temporary variables. + +**Implementation:** +```dart +var (a, b) = ('left', 'right'); +(b, a) = (a, b); // Swap values + +// Destructuring a function return +var (name, age) = getUserInfo(); +``` + +### Guard Clauses and Logical-or +Use `when` to evaluate arbitrary conditions after a pattern matches. + +**Implementation:** +```dart +switch (shape) { + case Square(size: var s) || Circle(size: var s) when s > 0: + print('Valid symmetric shape with size $s'); + case Square() || Circle(): + print('Invalid or empty shape'); + default: + print('Unknown shape'); +} +``` diff --git a/skills/dart-use-primary-constructors/SKILL.md b/skills/dart-use-primary-constructors/SKILL.md new file mode 100644 index 0000000..13ba91c --- /dev/null +++ b/skills/dart-use-primary-constructors/SKILL.md @@ -0,0 +1,262 @@ +--- +name: dart-use-primary-constructors +description: > + Help users write syntactically and semantically correct primary constructors in Dart, and migrate/use the new constructor syntax, empty-body semicolon syntax, in-body initializer list syntax, and abbreviated concise constructor syntax. +metadata: + model: models/gemini-3.1-pro-preview + last_modified: Thu, 09 Jul 2026 23:13:25 GMT +--- + +# Dart Primary Constructors & New Constructor Syntax Skill + +Use this skill when helping users write, refactor, or debug code using Dart's **Primary Constructors** feature. + +### Dart Version Requirements +* **Dart 3.13 and above**: Primary constructors are enabled by default. +* **Dart 3.12**: The feature is available but experimental. Users must explicitly enable the experiment flag `primary-constructors` via `--enable-experiment=primary-constructors` or in `analysis_options.yaml`: +```yaml +analyzer: + enable-experiment: + - primary-constructors +``` +* **Dart 3.11 and earlier**: Primary constructors are not supported. + +--- + +## 1. Overview +Primary Constructors allow developers to declare a non-redirecting generative constructor as well as a set of instance variables directly in the class header. This significantly reduces boilerplate and improves code readability. + +### Key Benefits +- Combines field declaration, parameter declaration, and initialization into a single declaration known as a declaring parameter declaration. +- Enables safe reference to constructor parameters in non-late field initializers (Primary Initializer Scope). +- Allows empty declaration bodies to be represented concisely with a semicolon (`;`). +- Introduces abbreviated concise syntax for in-body constructors. + +--- + +## 2. Syntax Reference + +### 2.1 Basic Class Header Syntax +To declare a primary constructor, place a parameter list immediately after the type name (and optional type parameters): + +```dart +// Declares fields x and y, and a generative constructor Point(this.x, this.y) +class Point(var int x, var int y); + +// Declares final fields +class PointFinal(final int x, final int y); +``` + +### 2.2 Declaring, Initializing, and Plain Parameters +A primary constructor parameter list distinguishes between three types of parameters: +1. **Declaring Parameters**: Indicated by the `var` or `final` modifier (e.g., `final int x`). They implicitly create a corresponding instance field in the class. +2. **Initializing Parameters**: Indicated by the `this.` or `super.` prefix (e.g., `this.x` or `super.x`). They initialize an existing field or a super constructor parameter, respectively. +3. **Regular Parameters**: Declared without modifiers (e.g., `int y`). They do not become fields and are only available during initialization (e.g., in field initializers or the `this :` initializer list in the class body). + +```dart +// `x` is a field and a parameter because it has the keyword `final`. In particular, we can use the name `x` in the initializer list in the in-body part of the primary constructor. 'y' is a only parameter because it has neither of the keywords `final` or `var`, but `y` is passed to the super constructor via the `this :` initializer list. +class C(final int x, int y) extends Base { + this : super(y); +} +``` + +Declaring parameters and initializing parameters are two ways of achieving the same goal: declaring a class with instance fields which are set in the constructor. Regular parameters are different in that their values are not automatically routed to an instance field. + +### 2.3 Constant Primary Constructors +To make a primary constructor `const`, place the `const` keyword before the class/type name in the declaration header: + +```dart +class const Point(final int x, final int y); +extension type const Ext(int x); +enum const MyEnum(final int x) { + entry(1); +} +``` + +### 2.4 Extension Types +Extension types **must** use primary constructors. +- The single parameter in the header is the representation field. +- The representation variable cannot use the `var` modifier (using `var` triggers the `representation_field_modifier` error). +- The representation variable can optionally use the `final` modifier. If `final` is not present then it is inferred; that is, the parameter is declaring whether or not it's explicitly `final`. + +### 2.5 Empty Body Semicolon Shorthand (`;`) +When a class, mixin class, mixin, extension or extension type has an empty body, the `{}` braces can be replaced by a semicolon (`;`): + +```dart +class C(int x); +mixin class MC; +extension type ET(int x); +mixin M; +extension Ext on C; +``` + +### 2.6 The In-Body Part of a Primary Constructor (`this ...`) +If a primary constructor requires assertions or custom field initializations, they can be declared in the body using the `this :` syntax: + +```dart +class Point(var int x, var int y) { + // Initializer list in class body + this : assert(x >= 0), y = y * 2; +} +``` + +You can also write a constructor body with this syntax (`this {...}`). + +### 2.7 Abbreviated Concise Constructor Syntax +For constructors declared within the class body, the class name can be omitted and replaced with the `new` or `factory` keywords: + +| Traditional Syntax | Abbreviated Concise Syntax | +| :--- | :--- | +| `MyClass() {}` | `new() {}` | +| `MyClass.name() {}` | `new name() {}` | +| `const MyClass();` | `const new();` | +| `const MyClass.name();` | `const new name();` | +| `factory MyClass() => ...` | `factory() => ...` | +| `factory MyClass.name() => ...` | `factory name() => ...` | + +--- + +## 3. Semantics & Scoping Rules + +### 3.1 Primary Initializer Scope +When a primary constructor is declared, its formal parameters are introduced into the **Primary Initializer Scope**. This scope is the current scope for non-late field initializers in the class body and the primary constructor's initializer list (after `this :`). +This allows non-late fields to reference constructor parameters directly during declaration: + ```dart + class DeltaPoint(final int x, int delta) { + // 'x' and 'delta' are in scope here + final int y = x + delta; + } + ``` + +### 3.2 Late Instance Variables Restriction +The primary initializer scope is **not** active for `late` instance variable initializers. +- Since `late` variables can be evaluated after construction has completed, their initializers cannot safely access constructor parameters. +- Attempting to access a primary constructor parameter in a `late` field initializer results in a compile-time error. + +### 3.3 Shadowing +Primary constructor parameters shadow class members (fields) of the same name within the primary initializer scope: +- In a non-late initializer: `int y = x` refers to parameter `x`. +- In a `late` initializer: `late int y = x` refers to field `x` (if it exists) because the parameter `x` is out of scope. + +### 3.4 Generative Constructor Restrictions +To guarantee that the primary constructor (and the associated initializer scope) always executes: +- A class, mixin class, or enum declaration with a primary constructor **cannot** declare any other non-redirecting generative constructors (except extension types). +- All other generative constructors declared in the body **must** redirect (directly or indirectly) to the primary constructor. + +### 3.5 Parameter Mutation Errors +Primary constructor parameters are non-assignable inside the initialization phase. +- Any assignment to a parameter (e.g., `p = value`, `p++`) inside field initializers or the `this :` initializer list is a compile-time error. + +### 3.6 Double Initialization Errors +Initializing a field twice (e.g., once in the field declaration/initializer and once in the `this :` initializer list or as an initializing formal) is a compile-time error. + +--- + +## 4. Diagnostics & Troubleshooting + +Most errors and lints have quick-fixes, run `dart fix` to fix those violations. For other common errors, fix them using the following table: + +| Error / Lint Code | Common Cause | Resolution | +| :--- | :--- | :--- | +| **Invalid Late Access** | Referencing a primary constructor parameter inside a `late` field initializer. | Make the field non-late, or pass the value through another non-late field. | +| `fieldInitializedInInitializerAndDeclaration` | Initializing a variable both in its declaration and in the `this :` list. | Remove one of the initializations. | +| `nonRedirectingGenerativeConstructorWithPrimary` | Declaring a in-body generative constructor in the body without redirecting to the primary. | Change the in-body constructor such that it is redirecting (e.g. `this(...)`) or remove the in-body constructor. | + +--- + +## 5. Step-by-Step Refactoring Workflows + +### Workflow 5.1: Migrating a Class to a Primary Constructor + +Follow these steps to migrate a verbose class to the new primary constructor syntax: + +1. **Identify Candidate Fields and Constructor**: + Locate generative constructors and the fields they initialize. In this case, this would be the `name` and `age` fields. + ```dart + // Before + class User { + final String name; + final int age; + User(this.name, this.age); + } + ``` + +2. **Move Fields to the Header**: + Place fields in the header with `final` or `var` modifiers and append a semicolon (`;`) if the body is empty. The `name` and `age` fields are now written the primary constructor as declaring parameters `final String name` and `final int age`, respectively. + ```dart + // After + class User(final String name, final int age); + ``` + +3. **Handle Custom Initializers and Assertions**: + If there is an initializer list or assert block, move it to a `this` block inside the body: + ```dart + // Before + class Point { + final int x; + final int y; + Point(this.x, this.y) : assert(x >= 0); + } + + // After + class Point(final int x, final int y) { + this : assert(x >= 0); + } + ``` + +4. **Leverage Primary Initializer Scope for Calculations**: + If a field value is calculated from parameters, declare it inside the body and assign it directly using the parameters: + ```dart + // Before + class Rect { + final double width; + final double height; + final double area; + Rect(this.width, this.height) : area = width * height; + } + + // After + class Rect(final double width, final double height) { + // 'width' and 'height' are in scope here + final double area = width * height; + } + ``` + +5. **Convert In-Body Constructors to Redirecting**: + Ensure all in-body generative constructors redirect to the primary constructor: + ```dart + // Before + class Point { + final int x; + final int y; + Point(this.x, this.y); + Point.zero() : x = 0, y = 0; + } + + // After + class Point(final int x, final int y) { + new zero() : this(0, 0); // Redirects to primary + } + ``` + +### Workflow 5.2: Applying Abbreviated (Concise) In-Body Constructors + +When the user prefers to keep the constructor in the class body but wants to reduce verbosity, suggest the abbreviated constructor syntax: + +```dart +// Before +class DatabaseService { + final String url; + DatabaseService(this.url); + DatabaseService.local() : url = 'localhost'; + factory DatabaseService.create() => DatabaseService('default'); +} + +// After +class DatabaseService { + final String url; + new(this.url); // Omit class name, use 'new' + new local() : url = 'localhost'; // Use 'new local' for named constructors + factory create() => DatabaseService('default'); // Omit class name from factory +} +``` diff --git a/tool/.dart_skills_githash b/tool/.dart_skills_githash new file mode 100644 index 0000000..da758e1 --- /dev/null +++ b/tool/.dart_skills_githash @@ -0,0 +1 @@ +4a2d93bedb363a3d50a6d568dc07f89faa8c9b36 From bdf5159304b8c1e0390f95173f39f5bb6d0d1f77 Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jul 2026 04:37:39 -0700 Subject: [PATCH 3/5] Update workflow to support trigger from dart-lang/skills --- .claude-plugin/plugin.json | 2 +- .github/workflows/sync_skills.yaml | 17 ++++++++++------- README.md | 26 ++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 38866c2..7208a04 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dart-flutter", "displayName": "Dart and Flutter", - "version": "1.0.1", + "version": "1.0.0", "description": "Official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase", "author": { "name": "Dart and Flutter", diff --git a/.github/workflows/sync_skills.yaml b/.github/workflows/sync_skills.yaml index 1b3cd65..e0e693e 100644 --- a/.github/workflows/sync_skills.yaml +++ b/.github/workflows/sync_skills.yaml @@ -2,19 +2,22 @@ name: Sync Skills Directory via Git Hash (Dart) on: schedule: - # Runs every Monday at 06:00 UTC (Monday morning) - - cron: '0 6 * * 1' - workflow_dispatch: - # Allows you to manually trigger the sync anytime from the Actions tab - + - cron: '0 0 * * *' # Keep the daily check as a fallback safety net + workflow_dispatch: # Keep manual run capability + repository_dispatch: + types: [dart-skills-updated] # Listen for this custom ping jobs: sync: runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write steps: - name: Checkout Flutter Skills (Destination) uses: actions/checkout@v4 with: - token: ${{ secrets.SYNC_PAT }} + # Falls back to the default GITHUB_TOKEN if SYNC_PAT is not defined + token: ${{ secrets.SYNC_PAT || github.token }} path: dest_repo - name: Checkout Dart Skills (Source) @@ -53,7 +56,7 @@ jobs: if: steps.sync_engine.outputs.changes_detected == 'true' uses: peter-evans/create-pull-request@v6 with: - token: ${{ secrets.SYNC_PAT }} + token: ${{ secrets.SYNC_PAT || github.token }} path: dest_repo branch: automation/sync-dart-skills title: "🤖 chore: sync skills directory from dart-lang/skills" diff --git a/README.md b/README.md index 1710616..51cdb7d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,29 @@ +# Flutter Agent Plugins + +The plugin provides a collection of Flutter skills and an MCP server for AI coding agents. These resources/tools help agents understand and work more effectively with Flutter and Dart. + +## Installation + +### Claude Code Plugin + +1. Add the marketplace for Claude Code plugins: + +```bash +claude plugin marketplace add flutter/skills +``` + +2. Install the Claude plugin for Dart and Flutter: + +```bash +claude plugin install dart-flutter@dart-flutter +``` + +3. Verify the installation: + +```bash +claude plugin marketplace list +``` + # Flutter Agent Skills Agent skills for Flutter, maintained by the Flutter team. From af41da923663ddaf3c1f3f402a63dfd30b25944f Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jul 2026 09:02:34 -0700 Subject: [PATCH 4/5] Update repo name --- .claude-plugin/plugin.json | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7208a04..3f264b3 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -7,8 +7,8 @@ "name": "Dart and Flutter", "url": "https://flutter.dev" }, - "homepage": "https://github.com/flutter/skills", - "repository": "https://github.com/flutter/skills", + "homepage": "https://github.com/flutter/agent-plugins", + "repository": "https://github.com/flutter/agent-plugins", "license": "BSD-3-Clause", "keywords": [ "flutter", diff --git a/README.md b/README.md index 51cdb7d..09dbc12 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ The plugin provides a collection of Flutter skills and an MCP server for AI codi 1. Add the marketplace for Claude Code plugins: ```bash -claude plugin marketplace add flutter/skills +claude plugin marketplace add flutter/agent-plugins ``` 2. Install the Claude plugin for Dart and Flutter: From 5501fcae18b700f5d871111a96230139991e95da Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jul 2026 10:05:28 -0700 Subject: [PATCH 5/5] Applied suggestions --- tool/sync_skills.dart | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/tool/sync_skills.dart b/tool/sync_skills.dart index dc2ff4f..c545b10 100644 --- a/tool/sync_skills.dart +++ b/tool/sync_skills.dart @@ -20,6 +20,12 @@ void main(List args) async { 'tool/.dart_skills_githash'; const pluginFile = '.claude-plugin/plugin.json'; + // Verify source directory exists + if (!await Directory(srcDir).exists()) { + print('❌ Error: Source directory "$srcDir" does not exist.'); + exit(1); + } + // 1. Get the latest commit hash from the source repository final currentHashResult = await Process.run('git', [ 'rev-parse', @@ -74,12 +80,18 @@ void main(List args) async { final diffResult = await Process.run('git', [ 'diff', '--name-status', + '--no-renames', prevHash, currentHash, '--', 'skills/', ], workingDirectory: srcDir); + if (diffResult.exitCode != 0) { + print('❌ Error running git diff inside source: ${diffResult.stderr}'); + exit(1); + } + final lines = (diffResult.stdout as String).trim().split('\n'); for (final line in lines) { if (line.isEmpty) continue; @@ -122,13 +134,23 @@ void main(List args) async { print( '⚠️ Previous hash was not found in history. Performing fallback full sync.', ); - changesDetected = await _fullSync(srcDir, destDir); + final success = await _fullSync(srcDir, destDir); + if (!success) { + print('❌ Error: Fallback full sync failed.'); + exit(1); + } + changesDetected = true; } } else { print( '🆕 No previous hash tracked. Performing a clean sync of current Dart skills.', ); - changesDetected = await _fullSync(srcDir, destDir); + final success = await _fullSync(srcDir, destDir); + if (!success) { + print('❌ Error: Clean sync failed.'); + exit(1); + } + changesDetected = true; } // 4. Update `.claude-plugin/plugin.json` version if changes were detected