diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cf14195 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,68 @@ +# Source and documentation files +*.dart text eol=lf diff=dart +*.md text eol=lf +*.yaml text eol=lf +*.yml text eol=lf +*.json text eol=lf +*.svg text eol=lf + +# ----------------------------------------------------------------------------- +# Git LFS Tracking for Media Files +# Bracketed case patterns (e.g. *.[pP][nN][gG]) ensure case-insensitive matching +# across Linux, macOS, and Windows environments. +# ----------------------------------------------------------------------------- + +# Image formats +*.[pP][nN][gG] filter=lfs diff=lfs merge=lfs -text +*.[jJ][pP][gG] filter=lfs diff=lfs merge=lfs -text +*.[jJ][pP][eE][gG] filter=lfs diff=lfs merge=lfs -text +*.[gG][iI][fF] filter=lfs diff=lfs merge=lfs -text +*.[wW][eE][bB][pP] filter=lfs diff=lfs merge=lfs -text +*.[aA][vV][iI][fF] filter=lfs diff=lfs merge=lfs -text +*.[iI][cC][oO] filter=lfs diff=lfs merge=lfs -text +*.[bB][mM][pP] filter=lfs diff=lfs merge=lfs -text +*.[tT][iI][fF][fF] filter=lfs diff=lfs merge=lfs -text +*.[tT][iI][fF] filter=lfs diff=lfs merge=lfs -text +*.[hH][eE][iI][cC] filter=lfs diff=lfs merge=lfs -text +*.[hH][eE][iI][fF] filter=lfs diff=lfs merge=lfs -text +*.[aA][pP][nN][gG] filter=lfs diff=lfs merge=lfs -text + +# Video formats +*.[mM][pP]4 filter=lfs diff=lfs merge=lfs -text +*.[wW][eE][bB][mM] filter=lfs diff=lfs merge=lfs -text +*.[mM][oO][vV] filter=lfs diff=lfs merge=lfs -text +*.[aA][vV][iI] filter=lfs diff=lfs merge=lfs -text +*.[mM][kK][vV] filter=lfs diff=lfs merge=lfs -text +*.[mM]4[vV] filter=lfs diff=lfs merge=lfs -text + +# Audio formats +*.[mM][pP]3 filter=lfs diff=lfs merge=lfs -text +*.[wW][aA][vV] filter=lfs diff=lfs merge=lfs -text +*.[oO][gG][gG] filter=lfs diff=lfs merge=lfs -text +*.[mM]4[aA] filter=lfs diff=lfs merge=lfs -text +*.[aA][aA][cC] filter=lfs diff=lfs merge=lfs -text +*.[fF][lL][aA][cC] filter=lfs diff=lfs merge=lfs -text + +# Document formats +*.[pP][dD][fF] filter=lfs diff=lfs merge=lfs -text + +# Font formats +*.[tT][tT][fF] filter=lfs diff=lfs merge=lfs -text +*.[oO][tT][fF] filter=lfs diff=lfs merge=lfs -text +*.[wW][oO][fF][fF] filter=lfs diff=lfs merge=lfs -text +*.[wW][oO][fF][fF]2 filter=lfs diff=lfs merge=lfs -text + +# Archive formats +*.[zZ][iI][pP] filter=lfs diff=lfs merge=lfs -text +*.[tT][aA][rR] filter=lfs diff=lfs merge=lfs -text +*.[tT][gG][zZ] filter=lfs diff=lfs merge=lfs -text +*.[gG][zZ] filter=lfs diff=lfs merge=lfs -text + +# Binary artifacts +*.[jJ][aA][rR] filter=lfs diff=lfs merge=lfs -text +*.[wW][aA][sS][mM] filter=lfs diff=lfs merge=lfs -text +*.[aA][pP][kK] filter=lfs diff=lfs merge=lfs -text + +# Design source files +*.[pP][sS][dD] filter=lfs diff=lfs merge=lfs -text +*.[sS][kK][eE][tT][cC][hH] filter=lfs diff=lfs merge=lfs -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..2a907da --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,14 @@ +# Code owners for the flutter/rfc repository. +# +# Git LFS enforcement is defined by `.gitattributes` and executed by the +# workflows below. Because `git lfs fsck` evaluates `.gitattributes` at the +# revision being checked, a pull request that edits `.gitattributes` can +# disable the very rule that would have blocked it. These paths therefore +# require an explicit owner review. +# +# NOTE: CODEOWNERS is only enforced when branch protection on `main` has +# "Require review from Code Owners" enabled. + +/.gitattributes @flutter/owners @flutter/flutter-engprod +/.github/CODEOWNERS @flutter/owners @flutter/flutter-engprod +/.github/workflows/ @flutter/owners @flutter/flutter-engprod \ No newline at end of file diff --git a/.github/workflows/lfs-verify.yml b/.github/workflows/lfs-verify.yml new file mode 100644 index 0000000..3fcb8f0 --- /dev/null +++ b/.github/workflows/lfs-verify.yml @@ -0,0 +1,45 @@ +name: Git LFS Verification + +on: + pull_request: + branches: [main] + types: [opened, synchronize, reopened] + merge_group: + types: [checks_requested] + push: + branches: [main] + +jobs: + verify-lfs: + name: verify-lfs + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Setup Dart + uses: dart-lang/setup-dart@6afc89df92d6eb3834022f73cd65adc8cdfcb92d # v1.8.1 + + - name: Install Dependencies + run: dart pub get + + - name: Verify Git LFS Pointers (PR Mode) + if: github.event_name == 'pull_request' + env: + BASE_REF: ${{ github.base_ref }} + run: | + dart run bin/lfs_verify.dart \ + --base-branch "origin/${BASE_REF:-main}" \ + --github-actions + + - name: Verify Git LFS Pointers (Merge Queue & Main Mode) + if: github.event_name != 'pull_request' + run: | + dart run bin/lfs_verify.dart \ + --github-actions diff --git a/.github/workflows/rfc-lint.yml b/.github/workflows/rfc-lint.yml index e4faf37..2333f36 100644 --- a/.github/workflows/rfc-lint.yml +++ b/.github/workflows/rfc-lint.yml @@ -23,7 +23,7 @@ jobs: - name: Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: ${{ github.event_name == 'pull_request' && 0 || 1 }} + fetch-depth: 0 persist-credentials: false - name: Setup Dart @@ -38,14 +38,17 @@ jobs: env: BASE_REF: ${{ github.base_ref }} run: | - BASE_TARGET="origin/${BASE_REF:-main}" - if ! git rev-parse --verify "$BASE_TARGET" >/dev/null 2>&1; then - BASE_TARGET="main" - fi - FILES=$(git diff --name-only --diff-filter=ACMR "$BASE_TARGET"...HEAD -- 'rfc/*.md' 2>/dev/null || true) - if [ -z "$FILES" ]; then - FILES=$(git diff --name-only --diff-filter=ACMR "$BASE_TARGET" -- 'rfc/*.md' 2>/dev/null || true) + TARGET_REF="${BASE_REF:-main}" + TARGET_REF="${TARGET_REF#origin/}" + if git rev-parse --verify "origin/$TARGET_REF" >/dev/null 2>&1; then + BASE_TARGET="origin/$TARGET_REF" + elif git rev-parse --verify "$TARGET_REF" >/dev/null 2>&1; then + BASE_TARGET="$TARGET_REF" + else + echo "::error::Cannot resolve base branch ref 'origin/$TARGET_REF' or '$TARGET_REF'." + exit 1 fi + FILES=$(git diff --name-only --diff-filter=ACMR "$BASE_TARGET"...HEAD -- 'rfc/*.md') if [ -n "$FILES" ]; then echo "has_changes=true" >> "$GITHUB_OUTPUT" { diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2195988..23adf86 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,7 +27,7 @@ jobs: - name: Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: ${{ github.event_name == 'pull_request' && 0 || 1 }} + fetch-depth: 0 persist-credentials: false - name: Setup Dart diff --git a/.github/workflows/validate-rfc-number.yml b/.github/workflows/validate-rfc-number.yml index b372970..b161aa3 100644 --- a/.github/workflows/validate-rfc-number.yml +++ b/.github/workflows/validate-rfc-number.yml @@ -22,7 +22,7 @@ jobs: - name: Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: ${{ github.event_name == 'pull_request' && 0 || 1 }} + fetch-depth: 0 persist-credentials: false - name: Setup Dart diff --git a/.vscode/settings.json b/.vscode/settings.json index d173df0..e76151f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,12 @@ { "cSpell.words": [ + "apng", "Basenames", "frontmatter", "octocat", - "Slugified" + "Slugified", + "treeish", + "webp", + "Worktree" ] } \ No newline at end of file diff --git a/bin/lfs_verify.dart b/bin/lfs_verify.dart new file mode 100644 index 0000000..b1d62fb --- /dev/null +++ b/bin/lfs_verify.dart @@ -0,0 +1,116 @@ +// Copyright 2026 The Flutter Authors. +// 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:args/args.dart'; +import 'package:rfc_tools/src/lfs_verifier.dart'; + +final parser = ArgParser() + ..addOption( + 'base-branch', + abbr: 'b', + help: 'Git base branch or ref to compare against in pull request mode.', + ) + ..addFlag( + 'audit-intermediate-commits', + negatable: false, + help: + 'Audit every commit in the PR branch for raw binaries.\n' + 'Only needed for repositories that do not enforce squash merges\n' + '(e.g. merge-commit or rebase-merge).', + ) + ..addFlag( + 'github-actions', + negatable: false, + help: + 'Output errors in GitHub Actions annotation format (::error file=...::).', + ) + ..addFlag( + 'help', + abbr: 'h', + negatable: false, + help: 'Show usage instructions.', + ); + +void main(List arguments) async { + ArgResults results; + try { + results = parser.parse(arguments); + } catch (e) { + stderr.writeln('Error parsing arguments: $e\n'); + stderr.writeln(parser.usage); + exitCode = 1; + return; + } + + if (results.flag('help')) { + stdout.writeln('Git LFS Verifier - Flutter RFC Repository Tooling\n'); + stdout.writeln(parser.usage); + return; + } + + if (results.rest.isNotEmpty) { + stderr.writeln( + 'Error: Positional file arguments are not supported. Git LFS verification audits trees.\n', + ); + stderr.writeln(parser.usage); + exitCode = 1; + return; + } + + final baseBranch = switch (results.option('base-branch')?.trim()) { + null || '' => null, + final branch => branch, + }; + final githubActions = results.flag('github-actions'); + final auditIntermediateCommits = results.flag('audit-intermediate-commits'); + final verifier = LfsVerifier(onLog: stdout.writeln, onError: stderr.writeln); + + final (:isSuccess, :issues) = await verifier.verify( + baseBranch: baseBranch, + auditIntermediateCommits: auditIntermediateCommits, + ); + + if (!isSuccess) { + _reportVerificationErrors(issues: issues, githubActions: githubActions); + exitCode = 1; + return; + } + + stdout.writeln('✅ Git LFS verification passed.'); +} + +void _reportVerificationErrors({ + required List issues, + required bool githubActions, +}) { + stderr.writeln( + 'Git LFS verification failed with ${issues.length} issue(s):\n', + ); + for (final issue in issues) { + stderr.writeln(githubActions ? issue.toGithubAnnotation() : '$issue'); + } + + // Only suppress the remediation block when *every* issue is repository-level + // (e.g. a bad base ref); a single unresolvable file still warrants the steps. + if (issues.every((issue) => issue.filePath.isEmpty)) { + return; + } + + stderr.writeln(''' + +❌ ERROR: One or more files bypassed Git LFS! +To resolve this: + 1. Ensure Git LFS is installed and initialized: + git lfs install + 2. Re-normalize files so Git LFS clean filters are applied: + git add --renormalize . + git commit -m "Fix: properly serialize LFS files" + +This repository squash-merges, so fixing the tip commit is sufficient. +If you are not squash-merging, you must edit history instead: + git lfs migrate import --include="*.png" --everything +'''); +} diff --git a/lib/src/assigner.dart b/lib/src/assigner.dart index db52cb0..3fd1440 100644 --- a/lib/src/assigner.dart +++ b/lib/src/assigner.dart @@ -10,6 +10,7 @@ import 'package:path/path.dart' as p; import 'git_lister.dart'; import 'git_lister.dart' as git_lister; import 'models/rfc_file.dart'; +import 'process_runner.dart'; export 'git_lister.dart' show GitListFunction, defaultGitList; diff --git a/lib/src/git_lister.dart b/lib/src/git_lister.dart index d6eb124..6390aee 100644 --- a/lib/src/git_lister.dart +++ b/lib/src/git_lister.dart @@ -3,11 +3,10 @@ // found in the LICENSE file. import 'dart:convert'; -import 'dart:io' show Process, ProcessResult, stdout, stderr; +import 'dart:io' show Process, ProcessException, ProcessResult; -/// Signature for running an external process asynchronously. -typedef ProcessRunner = - Future Function(String executable, List arguments); +import 'process_logger.dart'; +import 'process_runner.dart'; /// Function signature for discovering RFC filenames in the main branch via git. typedef GitListFunction = Future> Function({String baseBranch}); @@ -21,52 +20,55 @@ Set parseLsTreeOutput(dynamic stdout) { }; } -void _logGitError(ProcessResult result) { - stderr.writeln('exit code: ${result.exitCode}'); - stdout.writeln('git ls-tree stdout:'); - stdout.writeln(result.stdout); - stderr.writeln('git ls-tree stderr:'); - stderr.writeln(result.stderr); -} - /// Discovers RFC filenames in main branch via git. Future> defaultGitList({ String baseBranch = 'origin/main', ProcessRunner processRunner = Process.run, + bool throwOnError = false, }) async { - try { - final result = await processRunner('git', [ - 'ls-tree', - '-r', - '--name-only', - baseBranch, - 'rfc/', - ]); - if (result.exitCode == 0) { - return parseLsTreeOutput(result.stdout); - } + final trimmedBranch = baseBranch.trim(); + final cleanBranch = trimmedBranch.replaceFirst( + RegExp(r'^(?:remotes\/)?(?:origin|upstream)\/'), + '', + ); + final branchesToTry = [ + trimmedBranch, + if (cleanBranch != trimmedBranch) cleanBranch, + ]; - final cleanBranch = baseBranch.replaceFirst( - RegExp(r'^(?:remotes\/)?(?:origin|upstream)\/'), - '', - ); - if (cleanBranch != baseBranch) { - final locResult = await processRunner('git', [ + ProcessResult? lastResult; + String? lastBranch; + for (final branch in branchesToTry) { + lastBranch = branch; + try { + final result = await processRunner('git', [ 'ls-tree', '-r', '--name-only', - cleanBranch, + branch, 'rfc/', ]); - if (locResult.exitCode == 0) { - return parseLsTreeOutput(locResult.stdout); + if (result.exitCode == 0) { + return parseLsTreeOutput(result.stdout); } - _logGitError(locResult); - } else { - _logGitError(result); + lastResult = result; + logProcessResult(result, command: 'git ls-tree'); + } catch (e) { + logProcessError(e, command: 'git ls-tree'); + if (throwOnError) rethrow; } - } catch (e) { - stderr.writeln('git ls-tree exception: $e'); + } + + if (throwOnError && lastResult != null) { + final err = '${lastResult.stderr}'.trim(); + throw ProcessException( + 'git', + ['ls-tree', '-r', '--name-only', lastBranch ?? trimmedBranch, 'rfc/'], + err.isNotEmpty + ? err + : 'git ls-tree failed with exit code ${lastResult.exitCode}', + lastResult.exitCode, + ); } return {}; } diff --git a/lib/src/lfs_verifier.dart b/lib/src/lfs_verifier.dart new file mode 100644 index 0000000..1d4da4d --- /dev/null +++ b/lib/src/lfs_verifier.dart @@ -0,0 +1,318 @@ +// Copyright 2026 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; +import 'dart:io' show Process; + +import 'package:path/path.dart' as p; + +import 'github_annotation.dart'; +import 'process_logger.dart'; +import 'process_runner.dart'; + +String _decodeOutput(dynamic output) => switch (output) { + null => '', + List bytes => utf8.decode(bytes, allowMalformed: true), + String str => str, + _ => '$output', +}; + +/// An issue detected during Git LFS verification. +class LfsIssue implements GithubAnnotatable { + /// The file path associated with this issue, or empty if repository-level. + final String filePath; + + /// The error description. + final String message; + + const LfsIssue({required this.filePath, required this.message}); + + @override + String toGithubAnnotation() => switch (filePath) { + '' => '::error::${message.toGithubWorkflowValue()}', + _ => message.toGithubAnnotation(filePath: filePath), + }; + + @override + String toString() => switch (filePath) { + '' => '[ERROR] $message', + _ => '[ERROR] $filePath: $message', + }; +} + +/// The result of a Git LFS verification run. +typedef LfsVerificationResult = ({bool isSuccess, List issues}); + +/// Verifier that enforces Git LFS pointer consistency for repository trees +/// using `git lfs fsck --pointers`. +/// +/// Rather than maintaining a duplicate allowlist of file extensions in Dart, +/// this tool treats `.gitattributes` as the single source of truth: +/// Git LFS natively parses `.gitattributes` and verifies that all matching files +/// are stored as valid LFS pointers in the Git object database. +class LfsVerifier { + /// Matches diagnostic error lines output by `git lfs fsck --pointers`. + /// + /// Matches lines starting with `pointer:` and containing `unexpectedGitObject:`, + /// capturing the quoted file path in group 1 and any trailing diagnostic detail in group 2: + /// ```text + /// pointer: unexpectedGitObject: "" (treeish ) should have been a pointer but was not + /// ``` + static final _unexpectedGitObjectRegex = RegExp( + r'^pointer:.*unexpectedGitObject:.*"([^"\r\n]+)"(.*)\r?$', + multiLine: true, + ); + + /// Parses `git lfs fsck --pointers` stdout/stderr into structured [LfsIssue]s. + /// + /// ### Git LFS fsck Output Behavior: + /// - **Success** (exit code 0): Emits `Git LFS fsck OK`. + /// - **Failure** (exit code 1): Emits one or more lines matching + /// `pointer: unexpectedGitObject: "" (treeish ) should have been a pointer but was not` + /// when a file tracked in `.gitattributes` was committed as a raw binary blob instead of an LFS pointer. + static List parseFsckOutput(String output) { + final issues = []; + final seen = {}; + for (final match in _unexpectedGitObjectRegex.allMatches(output)) { + final rawPath = match.group(1)!; + final detail = match.group(2)?.trim() ?? ''; + final normalized = p.posix.normalize(rawPath); + if (seen.add(normalized)) { + final message = detail.isNotEmpty + ? detail + : 'should have been a pointer but was not'; + issues.add(LfsIssue(filePath: normalized, message: message)); + } + } + return issues; + } + + final ProcessRunner processRunner; + final void Function(String message)? onLog; + final void Function(String message)? onError; + + LfsVerifier({this.processRunner = Process.run, this.onLog, this.onError}); + + /// Checks whether Git LFS is installed and accessible in the environment. + Future isLfsInstalled() async { + try { + final result = await processRunner('git', ['lfs', 'version']); + return result.exitCode == 0; + } catch (e) { + logProcessError(e, command: 'git lfs version', onError: onError); + return false; + } + } + + /// Resolves the base commit or branch ref to compare against. + Future resolveBaseTarget(String baseBranch) async { + final candidateRefs = [ + baseBranch, + if (baseBranch.startsWith('origin/')) + baseBranch.substring('origin/'.length) + else + 'origin/$baseBranch', + ]; + + for (final candidate in candidateRefs) { + final res = await processRunner('git', [ + 'rev-parse', + '--verify', + candidate, + ]); + if (res.exitCode == 0) { + return candidate; + } + } + return null; + } + + /// Determines the merge base commit between [baseTarget] and `HEAD`. + Future getMergeBase(String baseTarget) async { + final mergeBaseResult = await processRunner('git', [ + 'merge-base', + baseTarget, + 'HEAD', + ]); + if (mergeBaseResult.exitCode != 0) { + logProcessResult( + mergeBaseResult, + command: 'git merge-base', + onLog: onLog, + onError: onError, + ); + return null; + } + return _decodeOutput(mergeBaseResult.stdout).trim(); + } + + Future _runFsck({ + required List revisions, + required List issues, + Set? trackedFiles, + }) async { + final fsckResult = await processRunner('git', [ + 'lfs', + 'fsck', + '--pointers', + ...revisions, + ]); + if (fsckResult.exitCode == 0) { + return; + } + + logProcessResult( + fsckResult, + command: 'git lfs fsck --pointers', + onLog: onLog, + onError: onError, + ); + + final combinedOutput = + '${_decodeOutput(fsckResult.stdout)}\n${_decodeOutput(fsckResult.stderr)}'; + final parsed = parseFsckOutput(combinedOutput); + + // Catch-all: exit code was not successful, but we couldn't parse issues, + // so leave a single issue report. + if (parsed.isEmpty) { + final message = switch (( + _decodeOutput(fsckResult.stderr).trim(), + _decodeOutput(fsckResult.stdout).trim(), + )) { + (final err, _) when err.isNotEmpty => err, + (_, final out) when out.isNotEmpty => out, + (_, _) => 'Git LFS fsck check failed', + }; + issues.add(LfsIssue(filePath: '', message: message)); + return; + } + + for (final issue in parsed) { + if (trackedFiles == null || trackedFiles.contains(issue.filePath)) { + issues.add(issue); + } + } + } + + /// Verifies all commits and modified files in a pull request comparing against [baseBranch]. + /// + /// By default, audits cumulative changes at `HEAD`, aligning with GitHub's + /// squash-and-merge workflow. + /// + /// If [auditIntermediateCommits] is true, audits every intermediate commit on + /// the PR branch for raw binaries. Only needed for repositories that do not + /// enforce squash merges (e.g. merge-commit or rebase-merge). + Future verifyPullRequest({ + required String baseBranch, + bool auditIntermediateCommits = false, + }) async { + final issues = []; + + final baseTarget = await resolveBaseTarget(baseBranch); + if (baseTarget == null) { + issues.add( + LfsIssue( + filePath: '', + message: + "Git base ref '$baseBranch' not found: Could not resolve base target '$baseBranch' for pull request comparison.", + ), + ); + return (isSuccess: false, issues: issues); + } + + final mergeBase = await getMergeBase(baseTarget); + if (mergeBase == null) { + issues.add( + LfsIssue( + filePath: '', + message: + "Could not determine merge base between '$baseTarget' and HEAD.", + ), + ); + return (isSuccess: false, issues: issues); + } + + if (auditIntermediateCommits) { + onLog?.call( + 'Auditing all intermediate commits between $mergeBase and HEAD...', + ); + await _runFsck(revisions: ['$mergeBase..HEAD'], issues: issues); + } else { + onLog?.call('Checking pull request files at HEAD...'); + final diffResult = await processRunner('git', [ + 'diff', + '-z', + '--name-only', + '--diff-filter=ACMR', // cspell:ignore ACMR + mergeBase, + 'HEAD', + ]); + if (diffResult.exitCode != 0) { + logProcessResult( + diffResult, + command: 'git diff', + onLog: onLog, + onError: onError, + ); + issues.add( + LfsIssue( + filePath: '', + message: + 'Failed to diff commits between $mergeBase and HEAD: ${_decodeOutput(diffResult.stderr).trim()}', + ), + ); + return (isSuccess: false, issues: issues); + } + final rawDiff = _decodeOutput(diffResult.stdout); + final normalizedDiffFiles = { + for (final f in rawDiff.split('\u0000')) + if (f.isNotEmpty) p.posix.normalize(f), + }; + await _runFsck( + revisions: ['HEAD'], + issues: issues, + trackedFiles: normalizedDiffFiles, + ); + } + + return (isSuccess: issues.isEmpty, issues: issues); + } + + /// Verifies all tracked repository files at `HEAD`. + Future verifyTrackedFiles() async { + final issues = []; + onLog?.call('Checking all tracked repository files at HEAD...'); + await _runFsck(revisions: ['HEAD'], issues: issues); + return (isSuccess: issues.isEmpty, issues: issues); + } + + /// Unified verification router for tree verification. + /// + /// If [baseBranch] is provided, executes pull request comparison against that branch. + /// Otherwise, audits all tracked files at HEAD. + Future verify({ + String? baseBranch, + bool auditIntermediateCommits = false, + }) async { + if (!await isLfsInstalled()) { + return ( + isSuccess: false, + issues: const [ + LfsIssue( + filePath: '', + message: + 'Git LFS is not installed or not found in PATH. Please install Git LFS (https://git-lfs.com) and run "git lfs install".', + ), + ], + ); + } + return switch (baseBranch?.trim()) { + final branch? when branch.isNotEmpty => verifyPullRequest( + baseBranch: branch, + auditIntermediateCommits: auditIntermediateCommits, + ), + _ => verifyTrackedFiles(), + }; + } +} diff --git a/lib/src/process_logger.dart b/lib/src/process_logger.dart new file mode 100644 index 0000000..ecbf08f --- /dev/null +++ b/lib/src/process_logger.dart @@ -0,0 +1,36 @@ +// Copyright 2026 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' show ProcessResult, stderr, stdout; + +/// Logs the details of an external [ProcessResult] (exit code, stdout, stderr). +/// +/// When [onLog] or [onError] are provided, log lines are dispatched to them; +/// otherwise, exit code and stderr output are sent to [stderr], and stdout +/// output is sent to [stdout]. +void logProcessResult( + ProcessResult result, { + String command = 'process', + void Function(String message)? onLog, + void Function(String message)? onError, +}) { + final out = onLog ?? stdout.writeln; + final err = onError ?? stderr.writeln; + + err('exit code: ${result.exitCode}'); + out('$command stdout:'); + out('${result.stdout}'); + err('$command stderr:'); + err('${result.stderr}'); +} + +/// Logs an exception encountered during process execution. +void logProcessError( + Object error, { + String command = 'process', + void Function(String message)? onError, +}) { + final err = onError ?? stderr.writeln; + err('$command exception: $error'); +} diff --git a/lib/src/process_runner.dart b/lib/src/process_runner.dart new file mode 100644 index 0000000..7d01bdf --- /dev/null +++ b/lib/src/process_runner.dart @@ -0,0 +1,9 @@ +// Copyright 2026 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' show ProcessResult; + +/// Signature for running an external process asynchronously. +typedef ProcessRunner = + Future Function(String executable, List arguments); diff --git a/lib/src/validator.dart b/lib/src/validator.dart index 9611d02..5a8db69 100644 --- a/lib/src/validator.dart +++ b/lib/src/validator.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io' show Process, ProcessException; import 'dart:math'; import 'package:file/file.dart'; import 'package:path/path.dart' as p; @@ -9,6 +10,7 @@ import 'package:path/path.dart' as p; import 'git_lister.dart'; import 'github_annotation.dart'; import 'models/rfc_file.dart'; +import 'process_runner.dart'; export 'git_lister.dart' show GitListFunction, defaultGitList; @@ -64,7 +66,20 @@ class RfcValidator { final FileSystem fs; final GitListFunction gitList; - const RfcValidator({required this.fs, this.gitList = defaultGitList}); + const RfcValidator({ + required this.fs, + this.gitList = RfcValidator.defaultGitListThrows, + }); + + /// Discovers RFC filenames in base branch via git, throwing on failure. + static Future> defaultGitListThrows({ + String baseBranch = 'origin/main', + ProcessRunner processRunner = Process.run, + }) => defaultGitList( + baseBranch: baseBranch, + processRunner: processRunner, + throwOnError: true, + ); /// Runs semantic validation on all RFC files in the repository. /// @@ -131,9 +146,26 @@ class RfcValidator { } // Discover and index base branch RFCs if --check-base is requested. - final baseBranchCategories = { - if (checkBase) ...await _indexBaseBranchBySubsystem(baseBranch), - }; + Map baseBranchCategories = const {}; + if (checkBase) { + try { + baseBranchCategories = await _indexBaseBranchBySubsystem(baseBranch); + } catch (e) { + final message = switch (e) { + ProcessException(:final message, :final errorCode) => + message.isNotEmpty ? message : 'Exit code $errorCode', + _ => '$e', + }; + errors.add( + ValidationError( + filePath: '', + message: + "Failed to discover RFCs on base branch '$baseBranch': $message", + ), + ); + return (isSuccess: false, errors: errors); + } + } // For each category AAA: // - verify no duplicates diff --git a/rfc/media/flutter_header.png b/rfc/media/flutter_header.png new file mode 100644 index 0000000..d2a85b5 --- /dev/null +++ b/rfc/media/flutter_header.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a14b0db34e1622cd3b2120f2661caaea7319992d1d15e10848764f653e8fc1e +size 6749 diff --git a/test/git_lister_test.dart b/test/git_lister_test.dart index 8c06de2..38aec9f 100644 --- a/test/git_lister_test.dart +++ b/test/git_lister_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io' show ProcessException; + import 'package:rfc_tools/src/git_lister.dart'; import 'package:test/test.dart'; @@ -31,31 +33,76 @@ void main() { ); }); - test('returns empty set on non-zero exit code', () async { - final runner = MockProcessRunner( - exitCode: 128, - stderr: 'fatal: not a valid object name', - ); + test( + 'returns empty set on non-zero exit code when throwOnError is false', + () async { + final runner = MockProcessRunner( + exitCode: 128, + stderr: 'fatal: not a valid object name', + ); - final files = await defaultGitList( - baseBranch: 'origin/main', - processRunner: runner.run, - ); + final files = await defaultGitList( + baseBranch: 'origin/main', + processRunner: runner.run, + throwOnError: false, + ); - expect(files, isEmpty); - }); + expect(files, isEmpty); + }, + ); - test('returns empty set when process throws', () async { - final runner = MockProcessRunner( - exceptionToThrow: Exception('process failed'), - ); + test( + 'throws ProcessException on non-zero exit code when throwOnError is true', + () async { + final runner = MockProcessRunner( + exitCode: 128, + stderr: 'fatal: not a valid object name', + ); - final files = await defaultGitList( - baseBranch: 'origin/main', - processRunner: runner.run, - ); + expect( + () => defaultGitList( + baseBranch: 'origin/main', + processRunner: runner.run, + throwOnError: true, + ), + throwsA(isA()), + ); + }, + ); - expect(files, isEmpty); - }); + test( + 'returns empty set when processRunner throws and throwOnError is false', + () async { + final runner = MockProcessRunner( + exceptionToThrow: Exception('process failed'), + ); + + final files = await defaultGitList( + baseBranch: 'origin/main', + processRunner: runner.run, + throwOnError: false, + ); + + expect(files, isEmpty); + }, + ); + + test( + 'rethrows when processRunner throws and throwOnError is true', + () async { + final runner = MockProcessRunner( + exceptionToThrow: Exception('process failed'), + ); + + expect( + () => defaultGitList( + baseBranch: 'origin/main', + processRunner: runner.run, + throwOnError: true, + ), + throwsA(isA()), + ); + }, + ); }); } diff --git a/test/lfs_verify_e2e_test.dart b/test/lfs_verify_e2e_test.dart new file mode 100644 index 0000000..74d6d56 --- /dev/null +++ b/test/lfs_verify_e2e_test.dart @@ -0,0 +1,194 @@ +// Copyright 2026 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// End-to-end verification of `bin/lfs_verify.dart` against a real Git +/// repository and a real `git-lfs` binary. +library; + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +/// Absolute path to the package root, so the spawned CLI resolves correctly +/// regardless of the temporary working directory under test. +final String _packageRoot = Directory.current.absolute.path; + +Future _git( + Directory repo, + List arguments, { + Map? environment, +}) => Process.run( + 'git', + arguments, + workingDirectory: repo.path, + environment: environment, +); + +/// Runs `bin/lfs_verify.dart` inside [repo] and returns the result. +Future _runVerifier( + Directory repo, { + List arguments = const [], +}) => Process.run(Platform.resolvedExecutable, [ + p.join(_packageRoot, 'bin', 'lfs_verify.dart'), + ...arguments, +], workingDirectory: repo.path); + +/// Creates an initialized repository that tracks `*.png` via Git LFS. +Future _createRepo() async { + final repo = await Directory.systemTemp.createTemp('lfs_e2e_'); + await _git(repo, ['init', '--quiet', '--initial-branch=main', '.']); + await _git(repo, ['config', 'user.email', 'test@example.com']); + await _git(repo, ['config', 'user.name', 'Test']); + await _git(repo, ['config', 'commit.gpgsign', 'false']); + await _git(repo, ['lfs', 'install', '--local']); + + File( + p.join(repo.path, '.gitattributes'), + ).writeAsStringSync('*.png filter=lfs diff=lfs merge=lfs -text\n'); + await _git(repo, ['add', '.gitattributes']); + await _git(repo, ['commit', '--quiet', '-m', 'chore: track png via lfs']); + return repo; +} + +/// Stages [name] while disabling the LFS clean filter, reproducing exactly what +/// a contributor without `git-lfs` installed commits: a raw binary blob. +Future _commitRawBinary(Directory repo, String name) async { + File( + p.join(repo.path, name), + ).writeAsBytesSync(List.generate(2048, (i) => i % 256)); + await _git(repo, [ + '-c', + 'filter.lfs.clean=', + '-c', + 'filter.lfs.process=', + '-c', + 'filter.lfs.required=false', + 'add', + name, + ]); + await _git(repo, ['commit', '--quiet', '-m', 'feat: add $name']); +} + +void main() { + late Directory repo; + + setUpAll(() async { + final lfs = await Process.run('git', ['lfs', 'version']); + if (lfs.exitCode != 0) { + throw StateError( + 'git-lfs is required for e2e tests. Install it from https://git-lfs.com', + ); + } + }); + + tearDown(() async { + if (repo.existsSync()) { + repo.deleteSync(recursive: true); + } + }); + + test('passes on a repository with no media files', () async { + repo = await _createRepo(); + + final result = await _runVerifier(repo); + + expect( + result.exitCode, + equals(0), + reason: '${result.stdout}${result.stderr}', + ); + expect(result.stdout, contains('Git LFS verification passed')); + }); + + test('passes when a png is committed through the LFS clean filter', () async { + repo = await _createRepo(); + File( + p.join(repo.path, 'diagram.png'), + ).writeAsBytesSync(List.generate(2048, (i) => i % 256)); + await _git(repo, ['add', 'diagram.png']); + await _git(repo, ['commit', '--quiet', '-m', 'feat: add diagram']); + + final result = await _runVerifier(repo); + + expect( + result.exitCode, + equals(0), + reason: '${result.stdout}${result.stderr}', + ); + }); + + test('detects a raw binary committed without git-lfs installed', () async { + repo = await _createRepo(); + await _commitRawBinary(repo, 'diagram.png'); + + final result = await _runVerifier(repo); + + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('diagram.png')); + expect(result.stderr, contains('bypassed Git LFS')); + expect(result.stderr, contains('git lfs install')); + }); + + test('emits a GitHub annotation naming the offending file', () async { + repo = await _createRepo(); + await _commitRawBinary(repo, 'diagram.png'); + + final result = await _runVerifier(repo, arguments: ['--github-actions']); + + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('::error file=diagram.png::')); + }); + + test( + 'default PR mode ignores a blob added and removed before HEAD', + () async { + repo = await _createRepo(); + await _git(repo, ['checkout', '--quiet', '-b', 'feature']); + await _commitRawBinary(repo, 'scratch.png'); + await _git(repo, ['rm', '--quiet', '--force', 'scratch.png']); + await _git(repo, ['commit', '--quiet', '-m', 'chore: drop scratch']); + + final result = await _runVerifier( + repo, + arguments: ['--base-branch', 'main'], + ); + + expect( + result.exitCode, + equals(0), + reason: 'squash-merge means the intermediate blob never reaches main', + ); + }, + ); + + test('--audit-intermediate-commits catches the same blob', () async { + repo = await _createRepo(); + await _git(repo, ['checkout', '--quiet', '-b', 'feature']); + await _commitRawBinary(repo, 'scratch.png'); + await _git(repo, ['rm', '--quiet', '--force', 'scratch.png']); + await _git(repo, ['commit', '--quiet', '-m', 'chore: drop scratch']); + + final result = await _runVerifier( + repo, + arguments: ['--base-branch', 'main', '--audit-intermediate-commits'], + ); + + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('scratch.png')); + }); + + test('reports an unresolvable base ref without LFS remediation', () async { + repo = await _createRepo(); + + final result = await _runVerifier( + repo, + arguments: ['--base-branch', 'does-not-exist-12345'], + ); + + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('Git base ref')); + expect(result.stderr, isNot(contains('bypassed Git LFS'))); + }); +} diff --git a/test/lfs_verify_test.dart b/test/lfs_verify_test.dart new file mode 100644 index 0000000..104c587 --- /dev/null +++ b/test/lfs_verify_test.dart @@ -0,0 +1,550 @@ +// Copyright 2026 The Flutter Authors. +// 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:rfc_tools/src/lfs_verifier.dart'; +import 'package:test/test.dart'; + +import 'mock_process_runner.dart'; + +MockProcessRunner createGitMockRunner({ + String diffOutput = '', + String mergeBase = 'merge_base_sha\n', + int? fsckExitCode, + String? fsckOutput, + ProcessRunner? customHandler, +}) { + return MockProcessRunner( + handler: (executable, arguments) async { + if (await customHandler?.call(executable, arguments) case final result? + when result.exitCode != -999) { + return result; + } + if (arguments.contains('fsck')) { + if (fsckExitCode != null) { + return ProcessResult( + 1, + fsckExitCode, + fsckOutput ?? (fsckExitCode == 0 ? 'Git LFS fsck OK\n' : ''), + '', + ); + } + return ProcessResult(1, 0, 'Git LFS fsck OK\n', ''); + } + if (arguments.contains('rev-parse')) { + return ProcessResult(1, 0, 'sha123\n', ''); + } + + final stdout = switch (arguments) { + _ when arguments.contains('merge-base') => mergeBase, + _ when arguments.contains('diff') => diffOutput, + _ => '', + }; + return ProcessResult(1, 0, stdout, ''); + }, + ); +} + +void main() { + group('LfsVerifier', () { + group('parseFsckOutput', () { + test('parses unexpectedGitObject lines', () { + const output = ''' +pointer: unexpectedGitObject: "images/banner.png" (treeish 4b825dc642cb6eb9a060e54bf8d69288fbee4904ce6243dabb9c50119e0780f0) should have been a pointer but was not +pointer: unexpectedGitObject: "assets/sub/doc.pdf" (treeish abc12345) should have been a pointer but was not +'''; + final issues = LfsVerifier.parseFsckOutput(output); + expect(issues, hasLength(2)); + expect(issues[0].filePath, 'images/banner.png'); + expect( + issues[0].message, + contains('should have been a pointer but was not'), + ); + expect(issues[1].filePath, 'assets/sub/doc.pdf'); + expect( + issues[1].message, + contains('should have been a pointer but was not'), + ); + }); + + test('deduplicates identical paths across commits', () { + const output = ''' +pointer: unexpectedGitObject: "dup.png" (treeish 1111) should have been a pointer but was not +pointer: unexpectedGitObject: "dup.png" (treeish 2222) should have been a pointer but was not +'''; + final issues = LfsVerifier.parseFsckOutput(output); + expect(issues, hasLength(1)); + expect(issues[0].filePath, 'dup.png'); + }); + + test('returns empty list for clean fsck output', () { + const output = 'Git LFS fsck OK\n'; + final issues = LfsVerifier.parseFsckOutput(output); + expect(issues, isEmpty); + }); + }); + + group('LfsIssue', () { + test('formats standard error message with file path', () { + const issue = LfsIssue( + filePath: 'images/logo.png', + message: 'bypassed Git LFS', + ); + expect( + issue.toString(), + equals('[ERROR] images/logo.png: bypassed Git LFS'), + ); + }); + + test('formats repository-level error message without file path', () { + const issue = LfsIssue(filePath: '', message: 'repository-wide error'); + expect(issue.toString(), equals('[ERROR] repository-wide error')); + }); + + test('formats github annotation with file path', () { + const issue = LfsIssue( + filePath: 'images/logo.png', + message: 'bypassed Git LFS', + ); + expect( + issue.toGithubAnnotation(), + equals('::error file=images/logo.png::bypassed Git LFS'), + ); + }); + + test('formats github annotation without file path', () { + const issue = LfsIssue(filePath: '', message: 'repository-wide error'); + expect( + issue.toGithubAnnotation(), + equals('::error::repository-wide error'), + ); + }); + }); + + group('Base target & merge base resolution', () { + test('resolves branch directly when git rev-parse succeeds', () async { + final mockRunner = createGitMockRunner(); + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.resolveBaseTarget('origin/main'); + expect(result, equals('origin/main')); + }); + + test( + 'falls back to origin prefix when given clean branch name', + () async { + final mockRunner = createGitMockRunner( + customHandler: (executable, arguments) async { + if (arguments.contains('rev-parse')) { + if (arguments.contains('feature')) { + return ProcessResult(1, 1, '', 'not found'); + } + if (arguments.contains('origin/feature')) { + return ProcessResult(1, 0, 'sha456\n', ''); + } + } + return ProcessResult(1, -999, '', ''); + }, + ); + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.resolveBaseTarget('feature'); + expect(result, equals('origin/feature')); + }, + ); + + test('returns merge-base commit sha', () async { + final mockRunner = createGitMockRunner( + mergeBase: 'merge_base_commit_sha\n', + ); + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.getMergeBase('origin/main'); + expect(result, equals('merge_base_commit_sha')); + }); + + test('returns null when merge-base fails', () async { + final mockRunner = createGitMockRunner( + customHandler: (executable, arguments) async { + if (arguments.contains('merge-base')) { + return ProcessResult(1, 1, '', 'fatal: no merge base'); + } + return ProcessResult(1, -999, '', ''); + }, + ); + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.getMergeBase('origin/main'); + expect(result, isNull); + }); + }); + + group('verifyPullRequest', () { + group('pointer and filter validation', () { + test('passes when PR introduces valid LFS pointer', () async { + final mockRunner = createGitMockRunner( + diffOutput: 'assets/logo.png\u0000', + fsckExitCode: 0, + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + ); + expect(result.isSuccess, isTrue); + expect(result.issues, isEmpty); + }); + + test('detects raw binary blob bypassing Git LFS in PR diff', () async { + final mockRunner = createGitMockRunner( + diffOutput: 'assets/photo.jpg\u0000', + fsckExitCode: 1, + fsckOutput: + 'pointer: unexpectedGitObject: "assets/photo.jpg" (treeish sha12345) should have been a pointer but was not\n', + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + ); + + expect(result.isSuccess, isFalse); + expect(result.issues, hasLength(1)); + expect( + result.issues.first.message, + contains('should have been a pointer but was not'), + ); + }); + + test( + 'detects raw binary in intermediate commits when auditIntermediateCommits is true', + () async { + final mockRunner = createGitMockRunner( + diffOutput: 'assets/photo.jpg\u0000', + fsckExitCode: 1, + fsckOutput: + 'pointer: unexpectedGitObject: "assets/photo.jpg" (treeish sha12345) should have been a pointer but was not\n', + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + auditIntermediateCommits: true, + ); + + expect(result.isSuccess, isFalse); + expect(result.issues, hasLength(1)); + expect( + result.issues.first.message, + contains('should have been a pointer but was not'), + ); + }, + ); + + test( + 'ignores intermediate commits by default when auditIntermediateCommits is false', + () async { + final mockRunner = createGitMockRunner( + diffOutput: '', + fsckExitCode: 1, + fsckOutput: + 'pointer: unexpectedGitObject: "assets/photo.jpg" (treeish sha12345) should have been a pointer but was not\n', + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + auditIntermediateCommits: false, + ); + + expect(result.isSuccess, isTrue); + expect(result.issues, isEmpty); + }, + ); + }); + + group('error handling on git failures', () { + test('fails gracefully when base branch cannot be resolved', () async { + final mockRunner = MockProcessRunner(exitCode: 1, stderr: 'fatal'); + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'nonexistent', + ); + + expect(result.isSuccess, isFalse); + expect( + result.issues.first.message, + contains( + "Could not resolve base target 'nonexistent' for pull request comparison", + ), + ); + }); + + test('fails gracefully when merge base cannot be determined', () async { + final mockRunner = createGitMockRunner( + customHandler: (executable, arguments) async { + if (arguments.contains('merge-base')) { + return ProcessResult(1, 1, '', 'merge-base failed'); + } + return ProcessResult(1, -999, '', ''); + }, + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + ); + + expect(result.isSuccess, isFalse); + expect( + result.issues.first.message, + contains('Could not determine merge base between'), + ); + }); + + test('fails gracefully when git diff fails', () async { + final mockRunner = createGitMockRunner( + customHandler: (executable, arguments) async { + if (arguments.contains('diff')) { + return ProcessResult(1, 1, '', 'diff failed'); + } + return ProcessResult(1, -999, '', ''); + }, + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyPullRequest( + baseBranch: 'origin/main', + ); + + expect(result.isSuccess, isFalse); + expect( + result.issues.first.message, + contains('Failed to diff commits between'), + ); + }); + }); + }); + + group('verifyTrackedFiles', () { + test('passes when git lfs fsck succeeds at HEAD', () async { + final mockRunner = createGitMockRunner(fsckExitCode: 0); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyTrackedFiles(); + + expect(result.isSuccess, isTrue); + expect(result.issues, isEmpty); + }); + + test('detects raw binary in tracked files via fsck', () async { + final mockRunner = createGitMockRunner( + fsckExitCode: 1, + fsckOutput: + 'pointer: unexpectedGitObject: "images/banner.png" (treeish 123) should have been a pointer but was not\n', + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyTrackedFiles(); + + expect(result.isSuccess, isFalse); + expect(result.issues, hasLength(1)); + expect(result.issues.first.filePath, equals('images/banner.png')); + expect( + result.issues.first.message, + contains('should have been a pointer but was not'), + ); + }); + + test( + 'handles git lfs fsck failure with repository-level error', + () async { + final mockRunner = createGitMockRunner( + fsckExitCode: 1, + fsckOutput: 'fatal: error during lfs fsck', + ); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verifyTrackedFiles(); + + expect(result.isSuccess, isFalse); + expect( + result.issues.first.message, + contains('fatal: error during lfs fsck'), + ); + }, + ); + }); + + group('invoked git command line', () { + // Guards the argv itself. Without these, dropping `--pointers` or + // mis-scoping the revision would leave every other test green while the + // tool silently verified nothing. + /// Returns the argument vectors of every `git` invocation recorded. + // cspell:ignore Argvs + List> gitArgvs(MockProcessRunner runner) => [ + for (final call in runner.calls) + if (call.executable == 'git') call.arguments, + ]; + + test('trunk mode invokes git lfs fsck --pointers HEAD', () async { + final mockRunner = createGitMockRunner(fsckExitCode: 0); + + await LfsVerifier(processRunner: mockRunner.run).verifyTrackedFiles(); + + expect( + gitArgvs(mockRunner), + contains(equals(['lfs', 'fsck', '--pointers', 'HEAD'])), + ); + }); + + test('intermediate audit scopes fsck to mergeBase..HEAD', () async { + final mockRunner = createGitMockRunner( + fsckExitCode: 0, + mergeBase: 'abc123\n', + ); + + await LfsVerifier(processRunner: mockRunner.run).verifyPullRequest( + baseBranch: 'origin/main', + auditIntermediateCommits: true, + ); + + expect( + gitArgvs(mockRunner), + contains(equals(['lfs', 'fsck', '--pointers', 'abc123..HEAD'])), + ); + }); + + test('probes each base ref candidate at most once', () async { + final mockRunner = MockProcessRunner( + handler: (executable, arguments) async => + ProcessResult(1, arguments.contains('rev-parse') ? 1 : 0, '', ''), + ); + + await LfsVerifier( + processRunner: mockRunner.run, + ).resolveBaseTarget('origin/main'); + + final probed = mockRunner.calls + .where((c) => c.arguments.contains('rev-parse')) + .map((c) => c.arguments.last) + .toList(); + expect(probed, equals(probed.toSet().toList())); + }); + }); + + group('verify routing', () { + test('routes to verifyPullRequest when baseBranch is set', () async { + final mockRunner = createGitMockRunner(); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verify(baseBranch: 'origin/main'); + expect(result.isSuccess, isTrue); + }); + + test('routes to verifyTrackedFiles when no args provided', () async { + final mockRunner = createGitMockRunner(); + + final verifier = LfsVerifier(processRunner: mockRunner.run); + final result = await verifier.verify(); + expect(result.isSuccess, isTrue); + }); + }); + + group('CLI (lfs_verify)', () { + test('shows help output when --help is supplied', () async { + final result = await Process.run(Platform.resolvedExecutable, [ + 'bin/lfs_verify.dart', + '--help', + ]); + expect(result.exitCode, equals(0)); + expect(result.stdout, contains('Git LFS Verifier')); + expect(result.stdout, contains('--base-branch')); + expect(result.stdout, isNot(contains('[...files]'))); + }); + + test('fails with exit code 1 on unrecognized argument', () async { + final result = await Process.run(Platform.resolvedExecutable, [ + 'bin/lfs_verify.dart', + '--unknown-flag', + ]); + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('Error parsing arguments')); + }); + + test( + 'fails with error when positional file arguments are provided', + () async { + final result = await Process.run(Platform.resolvedExecutable, [ + 'bin/lfs_verify.dart', + 'some_file.png', + ]); + expect(result.exitCode, equals(1)); + expect( + result.stderr, + contains('Error: Positional file arguments are not supported'), + ); + }, + ); + + test( + 'omits bypassed Git LFS instructions when failure is a repository-level ref-not-found error', + () async { + final result = await Process.run(Platform.resolvedExecutable, [ + 'bin/lfs_verify.dart', + '--base-branch', + 'nonexistent-ref-12345', + ]); + expect(result.exitCode, equals(1)); + expect(result.stderr, contains('Git base ref')); + expect( + result.stderr, + isNot(contains('❌ ERROR: One or more files bypassed Git LFS!')), + ); + }, + ); + }); + + group('isLfsInstalled', () { + test('returns true when git lfs version succeeds', () async { + final verifier = LfsVerifier( + processRunner: (cmd, args) async => + ProcessResult(1, 0, 'git-lfs/3.5.0\n', ''), + ); + expect(await verifier.isLfsInstalled(), isTrue); + }); + + test('returns false when git lfs version fails', () async { + final verifier = LfsVerifier( + processRunner: (cmd, args) async => + ProcessResult(1, 1, '', 'not a git command'), + ); + expect(await verifier.isLfsInstalled(), isFalse); + }); + + test('returns false when process runner throws', () async { + final verifier = LfsVerifier( + processRunner: (cmd, args) async => + throw ProcessException('git', args, 'not found'), + ); + expect(await verifier.isLfsInstalled(), isFalse); + }); + + test( + 'verify fails with clear issue when git lfs is not installed', + () async { + final verifier = LfsVerifier( + processRunner: (cmd, args) async => + ProcessResult(1, 1, '', 'not found'), + ); + final result = await verifier.verify(); + expect(result.isSuccess, isFalse); + expect(result.issues, hasLength(1)); + expect(result.issues.first.filePath, isEmpty); + expect( + result.issues.first.message, + contains('Git LFS is not installed or not found in PATH'), + ); + }, + ); + }); + }); +} diff --git a/test/mock_process_runner.dart b/test/mock_process_runner.dart index 132b52d..c2ba492 100644 --- a/test/mock_process_runner.dart +++ b/test/mock_process_runner.dart @@ -4,14 +4,15 @@ import 'dart:io'; -typedef MockProcessHandler = - Future Function(String executable, List arguments); +import 'package:rfc_tools/src/process_runner.dart'; + +export 'package:rfc_tools/src/process_runner.dart' show ProcessRunner; /// In-memory mock process runner to record external process invocations and /// control process outputs hermetically in tests. class MockProcessRunner { final List<({String executable, List arguments})> calls = []; - MockProcessHandler? handler; + ProcessRunner? handler; int exitCode; dynamic stdout; dynamic stderr; diff --git a/test/process_logger_test.dart b/test/process_logger_test.dart new file mode 100644 index 0000000..9949360 --- /dev/null +++ b/test/process_logger_test.dart @@ -0,0 +1,45 @@ +// Copyright 2026 The Flutter Authors. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:io' show ProcessResult; + +import 'package:rfc_tools/src/process_logger.dart'; +import 'package:test/test.dart'; + +void main() { + group('process logging utilities', () { + test('logProcessResult logs exit code, stdout, and stderr', () { + final outLines = []; + final errLines = []; + final result = ProcessResult(1234, 1, 'sample stdout', 'sample stderr'); + + logProcessResult( + result, + command: 'test-cmd', + onLog: (m) => outLines.add(m), + onError: (m) => errLines.add(m), + ); + + expect(errLines, contains('exit code: 1')); + expect(outLines, contains('test-cmd stdout:')); + expect(outLines, contains('sample stdout')); + expect(errLines, contains('test-cmd stderr:')); + expect(errLines, contains('sample stderr')); + }); + + test('logProcessError logs exception to onError', () { + final errLines = []; + final exception = Exception('test failure'); + + logProcessError( + exception, + command: 'test-fail-cmd', + onError: (m) => errLines.add(m), + ); + + expect(errLines.first, contains('test-fail-cmd exception:')); + expect(errLines.first, contains('test failure')); + }); + }); +} diff --git a/test/validate_rfc_number_test.dart b/test/validate_rfc_number_test.dart index 4754e0c..8cead0c 100644 --- a/test/validate_rfc_number_test.dart +++ b/test/validate_rfc_number_test.dart @@ -2,10 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io' show ProcessException; + import 'package:file/memory.dart'; import 'package:rfc_tools/src/validator.dart'; import 'package:test/test.dart'; +import 'mock_process_runner.dart'; + void main() { group('RfcValidator', () { late MemoryFileSystem fs; @@ -206,11 +210,29 @@ title: Feature expect(gitListCalled, isFalse); }); - test('default constructor uses defaultGitList', () { + test('default constructor uses RfcValidator.defaultGitList', () { final validator = RfcValidator(fs: fs); - expect(validator.gitList, equals(defaultGitList)); + expect(validator.gitList, equals(RfcValidator.defaultGitListThrows)); }); + test( + 'RfcValidator.defaultGitList throws ProcessException on non-zero exit code', + () async { + final runner = MockProcessRunner( + exitCode: 128, + stderr: 'fatal: not a valid object name', + ); + + expect( + () => RfcValidator.defaultGitListThrows( + baseBranch: 'origin/main', + processRunner: runner.run, + ), + throwsA(isA()), + ); + }, + ); + group('sequential numbering gap checks', () { test('rejects gap when new RFC jumps ahead of baseBranch', () async { await fs.file('rfc/110.0050-jump-ahead.md').writeAsString('''--- @@ -453,6 +475,34 @@ title: Draft expect(result.isValid, isTrue); expect(result.errors, isEmpty); }); + + test('fails with error when gitList throws', () async { + await fs.file('rfc/110.0001-feature.md').writeAsString('''--- +type: rfc +rfc: '110.0001' +title: Feature +--- +'''); + + final validator = RfcValidator( + fs: fs, + gitList: ({String baseBranch = 'origin/main'}) async => + throw ProcessException( + 'git', + ['ls-tree'], + 'fatal: not a valid object name', + 128, + ), + ); + + final result = await validator.validate(checkBase: true); + expect(result.isValid, isFalse); + expect(result.errors, hasLength(1)); + expect( + result.errors.first.message, + contains('Failed to discover RFCs on base branch'), + ); + }); }); group('ValidationError', () {