diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..61fd797 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + merge_group: + types: [checks_requested] + +permissions: + contents: read + +jobs: + checks: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - uses: DeterminateSystems/nix-installer-action@33c9ab3ef95cd57c164d9d6eb1f9a46338538d41 # main + - uses: DeterminateSystems/magic-nix-cache-action@55718cd9ebf1737a061487d5ada21abf31e99a98 # main + - name: Validate commits + if: github.event_name != 'push' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + run: >- + nix run --no-update-lock-file .#validate-commits-bootstrap -- "$BASE_SHA..HEAD" + - name: Run flake checks on main + if: github.event_name == 'push' + run: nix flake check --no-update-lock-file --print-build-logs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d787b70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/result diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..5d74d0b --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,386 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "git2" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddddbf932745a6be37109b6112d3ee09696106f848449069d3a57bba937ab82e" +dependencies = [ + "bitflags", + "libc", + "libgit2-sys", + "log", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libgit2-sys" +version = "0.18.8+1.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f7c568b25d7489bc3fb2988ed69ab111d2944d2f5fec3d5c987fe545ea97b50" +dependencies = [ + "cc", + "libc", + "libz-sys", + "pkg-config", +] + +[[package]] +name = "libz-sys" +version = "1.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "validate-commits" +version = "0.1.0" +dependencies = [ + "clap", + "git2", + "tempfile", + "thiserror", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..594df7d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "validate-commits" +version = "0.1.0" +edition = "2024" +description = "Run Nix flake checks for every commit in a revision range" +license = "MIT" +repository = "https://github.com/fungi-protocol/validate-commits" + +[dependencies] +clap = { version = "4", features = ["derive"] } +git2 = { version = "0.21", default-features = false, features = ["vendored-libgit2"] } +thiserror = "2" + +[dev-dependencies] +tempfile = "3.23.0" diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..39b754f --- /dev/null +++ b/flake.lock @@ -0,0 +1,119 @@ +{ + "nodes": { + "crane": { + "locked": { + "lastModified": 1788465171, + "narHash": "sha256-Y1/TTVXjYXGF068IThQH9fPSZ0SIE74PABlUxnWTUH0=", + "owner": "ipetkov", + "repo": "crane", + "rev": "eb35abda9f232cc6610b1d1e3200d15c49b7ac54", + "type": "github" + }, + "original": { + "owner": "ipetkov", + "repo": "crane", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1788450739, + "narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1789286504, + "narHash": "sha256-eiEK7cKZORNEvX0GeF3RtNEF/JXhgf2RqSp3230q13E=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "ef34387ddd751e1ab8857adf4676492d32eb24ec", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1788057806, + "narHash": "sha256-DTQSMxzDWmT0zhguthvegnVkn7CFqGCv4IHCzk5ZUpM=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "596e2e3940e09b2abbeb03f75fa1828c57fcd72c", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "root": { + "inputs": { + "crane": "crane", + "flake-parts": "flake-parts", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay", + "treefmt-nix": "treefmt-nix" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1789372034, + "narHash": "sha256-mu6atvdBHYpDsFhJkPtSsS6auSWAnWONVJMCvpL0900=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "a5f41d15ba0e9442542c5324fbccd7a87105a90d", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..4acfcbd --- /dev/null +++ b/flake.nix @@ -0,0 +1,35 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + crane.url = "github:ipetkov/crane"; + treefmt-nix = { + url = "github:numtide/treefmt-nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + inputs: + inputs.flake-parts.lib.mkFlake { inherit inputs; } { + systems = [ + "aarch64-darwin" + "aarch64-linux" + "x86_64-linux" + ]; + flake.flakeModules.checks = import ./nix/checks; + imports = [ + ./nix/apps/validate-commits-bootstrap + ./nix/package.nix + ./nix/toolchain.nix + ./nix/treefmt.nix + ./nix/checks/cargo-shear.nix + ./nix/checks/cargo-sort.nix + ./nix/tests/negative-tests.nix + ]; + }; +} diff --git a/nix/apps/validate-commits-bootstrap/default.nix b/nix/apps/validate-commits-bootstrap/default.nix new file mode 100644 index 0000000..a2b1643 --- /dev/null +++ b/nix/apps/validate-commits-bootstrap/default.nix @@ -0,0 +1,22 @@ +{ + perSystem = + { pkgs, ... }: + let + validate-commits-bootstrap = pkgs.writeShellApplication { + name = "validate-commits-bootstrap"; + runtimeInputs = [ + pkgs.git + pkgs.nix + ]; + text = builtins.readFile ./validate-commits.sh; + }; + in + { + packages.validate-commits-bootstrap = validate-commits-bootstrap; + apps.validate-commits-bootstrap = { + type = "app"; + program = "${validate-commits-bootstrap}/bin/validate-commits-bootstrap"; + meta.description = "Validate commits with the bootstrap shell script"; + }; + }; +} diff --git a/nix/apps/validate-commits-bootstrap/validate-commits.sh b/nix/apps/validate-commits-bootstrap/validate-commits.sh new file mode 100644 index 0000000..6ae29d9 --- /dev/null +++ b/nix/apps/validate-commits-bootstrap/validate-commits.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +# Adapted from fungi-protocol/fungi's nix/apps/validate-commits script. +set -euo pipefail + +usage() { + echo "Usage: validate-commits-bootstrap " +} + +if [[ ${1:-} == --help ]]; then + usage + exit 0 +fi + +if [[ $# -ne 1 ]]; then + usage >&2 + exit 2 +fi + +repo_root=$(git rev-parse --show-toplevel) +revision_range=$1 +commits=$(git rev-list --reverse "$revision_range") + +if [[ -z $commits ]]; then + echo "No commits in range." + exit 0 +fi + +while read -r commit; do + echo "Validating $commit" + nix flake check --no-update-lock-file --print-build-logs \ + "git+file://$repo_root?rev=$commit&shallow=1" +done <<<"$commits" diff --git a/nix/checks/aggregates.nix b/nix/checks/aggregates.nix new file mode 100644 index 0000000..b093329 --- /dev/null +++ b/nix/checks/aggregates.nix @@ -0,0 +1,36 @@ +{ + perSystem = + { config, pkgs, ... }: + let + join = + name: names: + pkgs.linkFarm name ( + map (check: { + name = check; + path = config.checks.${check}; + }) names + ); + in + { + checks = { + quick = join "quick-checks" [ + "tests" + "doctests" + "clippy" + ]; + lint = join "lint-checks" [ + "cargo-shear" + "cargo-sort" + "clippy" + "doc" + ]; + nightly = join "nightly-checks" [ + "build" + "tests" + "doctests" + "lint" + "coverage" + ]; + }; + }; +} diff --git a/nix/checks/build.nix b/nix/checks/build.nix new file mode 100644 index 0000000..d5e2618 --- /dev/null +++ b/nix/checks/build.nix @@ -0,0 +1,19 @@ +{ + perSystem = + { + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + { + checks.build = craneLib.buildPackage ( + commonArgs + // { + inherit cargoArtifacts; + # The tests check runs the test suite separately. + doCheck = false; + } + ); + }; +} diff --git a/nix/checks/cargo-shear.nix b/nix/checks/cargo-shear.nix new file mode 100644 index 0000000..e445cc7 --- /dev/null +++ b/nix/checks/cargo-shear.nix @@ -0,0 +1,30 @@ +{ + perSystem = + { + pkgs, + craneLib, + commonArgs, + ... + }: + { + checks.cargo-shear = + pkgs.runCommand "cargo-shear" + { + inherit (commonArgs) src; + cargoVendorDir = craneLib.vendorCargoDeps { inherit (commonArgs) src; }; + nativeBuildInputs = [ + pkgs.cargo + pkgs.cargo-shear + ]; + } + '' + export CARGO_HOME="$TMPDIR/cargo-home" + export CARGO_NET_OFFLINE=true + mkdir -p "$CARGO_HOME" + cp "$cargoVendorDir/config.toml" "$CARGO_HOME/config.toml" + cd "$src" + cargo-shear + mkdir -p "$out" + ''; + }; +} diff --git a/nix/checks/cargo-sort.nix b/nix/checks/cargo-sort.nix new file mode 100644 index 0000000..ad24e65 --- /dev/null +++ b/nix/checks/cargo-sort.nix @@ -0,0 +1,14 @@ +{ + perSystem = { pkgs, commonArgs, ... }: { + checks.cargo-sort = + pkgs.runCommand "cargo-sort" + { + inherit (commonArgs) src; + nativeBuildInputs = [ pkgs.cargo-sort ]; + } + '' + cargo-sort --check --workspace "$src" + mkdir -p "$out" + ''; + }; +} diff --git a/nix/checks/clippy.nix b/nix/checks/clippy.nix new file mode 100644 index 0000000..c10494e --- /dev/null +++ b/nix/checks/clippy.nix @@ -0,0 +1,18 @@ +{ + perSystem = + { + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + { + checks.clippy = craneLib.cargoClippy ( + commonArgs + // { + inherit cargoArtifacts; + cargoClippyExtraArgs = "--all-targets --all-features -- -D warnings -D unused"; + } + ); + }; +} diff --git a/nix/checks/coverage.nix b/nix/checks/coverage.nix new file mode 100644 index 0000000..1f87f31 --- /dev/null +++ b/nix/checks/coverage.nix @@ -0,0 +1,37 @@ +{ + perSystem = + { + pkgs, + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + let + collection = craneLib.mkCargoDerivation ( + commonArgs + // { + inherit cargoArtifacts; + pnameSuffix = "-coverage-collect"; + nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [ + pkgs.cargo-llvm-cov + pkgs.cargo-nextest + ]; + buildPhaseCargoCommand = '' + cargo llvm-cov nextest --workspace --no-report --remap-path-prefix + mkdir -p "$out" + cargo llvm-cov report --lcov --output-path "$out/coverage.lcov" + test -s "$out/coverage.lcov" + ''; + installPhase = "true"; + } + ); + in + { + checks.coverage = pkgs.runCommand "coverage" { nativeBuildInputs = [ pkgs.lcov ]; } '' + mkdir -p "$out" + cp ${collection}/coverage.lcov "$out/coverage.lcov" + lcov --summary "$out/coverage.lcov" --fail-under-lines 100 + ''; + }; +} diff --git a/nix/checks/default.nix b/nix/checks/default.nix new file mode 100644 index 0000000..df15bbc --- /dev/null +++ b/nix/checks/default.nix @@ -0,0 +1,13 @@ +{ + imports = [ + ./aggregates.nix + ./build.nix + ./cargo-shear.nix + ./cargo-sort.nix + ./clippy.nix + ./doc.nix + ./tests.nix + ./coverage.nix + ./mutants.nix + ]; +} diff --git a/nix/checks/doc.nix b/nix/checks/doc.nix new file mode 100644 index 0000000..8c14627 --- /dev/null +++ b/nix/checks/doc.nix @@ -0,0 +1,19 @@ +{ + perSystem = + { + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + { + checks.doc = craneLib.cargoDoc ( + commonArgs + // { + inherit cargoArtifacts; + cargoDocExtraArgs = "--no-deps --all-features"; + RUSTDOCFLAGS = "-D warnings"; + } + ); + }; +} diff --git a/nix/checks/mutants.nix b/nix/checks/mutants.nix new file mode 100644 index 0000000..d8108cb --- /dev/null +++ b/nix/checks/mutants.nix @@ -0,0 +1,25 @@ +{ + perSystem = + { + pkgs, + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + { + checks.mutants = craneLib.mkCargoDerivation ( + commonArgs + // { + inherit cargoArtifacts; + pnameSuffix = "-mutants"; + nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [ + pkgs.cargo-mutants + pkgs.cargo-nextest + ]; + buildPhaseCargoCommand = "cargo mutants --workspace --in-place --test-tool nextest"; + installPhase = "mkdir -p $out"; + } + ); + }; +} diff --git a/nix/checks/nextest-record.toml b/nix/checks/nextest-record.toml new file mode 100644 index 0000000..5acc21a --- /dev/null +++ b/nix/checks/nextest-record.toml @@ -0,0 +1,5 @@ +[experimental] +record = true + +[record] +enabled = true diff --git a/nix/checks/tests.nix b/nix/checks/tests.nix new file mode 100644 index 0000000..c0aa872 --- /dev/null +++ b/nix/checks/tests.nix @@ -0,0 +1,32 @@ +{ + perSystem = + { + pkgs, + craneLib, + commonArgs, + cargoArtifacts, + ... + }: + { + checks.tests = craneLib.cargoNextest ( + commonArgs + // { + inherit cargoArtifacts; + nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [ pkgs.unzip ]; + cargoNextestExtraArgs = "--user-config-file ${./nextest-record.toml}"; + preCheck = '' + export NEXTEST_STATE_DIR="$TMPDIR/nextest-state" + mkdir -p "$NEXTEST_STATE_DIR" + ''; + postCheck = '' + cargo nextest store export --no-pager \ + --user-config-file ${./nextest-record.toml} \ + --archive-file "$out/nextest-run.zip" latest + unzip -tqq "$out/nextest-run.zip" + ''; + } + ); + # nextest does not run doctests. + checks.doctests = craneLib.cargoDocTest (commonArgs // { inherit cargoArtifacts; }); + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..2a0b0fe --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,48 @@ +{ + perSystem = + { + craneLib, + pkgs, + self', + ... + }: + let + commonArgs = { + src = craneLib.cleanCargoSource ../.; + strictDeps = true; + nativeBuildInputs = [ pkgs.pkg-config ]; + buildInputs = [ pkgs.zlib ]; + }; + cargoArtifacts = craneLib.buildDepsOnly commonArgs; + validate-commits = craneLib.buildPackage ( + commonArgs + // { + inherit cargoArtifacts; + nativeBuildInputs = commonArgs.nativeBuildInputs ++ [ pkgs.makeWrapper ]; + postInstall = '' + wrapProgram "$out/bin/validate-commits" \ + --prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.nix ]} + ''; + } + ); + in + { + _module.args = { inherit commonArgs cargoArtifacts; }; + + checks.default = validate-commits; + + packages = { + default = validate-commits; + inherit validate-commits; + }; + + apps = { + default = self'.apps.validate-commits; + validate-commits = { + type = "app"; + program = "${validate-commits}/bin/validate-commits"; + meta.description = "Validate a Nix flake across a range of Git commits"; + }; + }; + }; +} diff --git a/nix/tests/fixtures/cargo-shear.patch b/nix/tests/fixtures/cargo-shear.patch new file mode 100644 index 0000000..709fa7a --- /dev/null +++ b/nix/tests/fixtures/cargo-shear.patch @@ -0,0 +1,14 @@ +diff --git a/Cargo.toml b/Cargo.toml +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -11,2 +11,3 @@ + git2 = { version = "0.21", default-features = false, features = ["vendored-libgit2"] } ++libc = "0.2" + thiserror = "2" +diff --git a/Cargo.lock b/Cargo.lock +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -362,2 +362,3 @@ + "git2", ++ "libc", + "tempfile", diff --git a/nix/tests/fixtures/cargo-sort.patch b/nix/tests/fixtures/cargo-sort.patch new file mode 100644 index 0000000..b01b88c --- /dev/null +++ b/nix/tests/fixtures/cargo-sort.patch @@ -0,0 +1,9 @@ +diff --git a/Cargo.toml b/Cargo.toml +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -9,4 +9,4 @@ + [dependencies] ++git2 = { version = "0.21", default-features = false, features = ["vendored-libgit2"] } + clap = { version = "4", features = ["derive"] } +-git2 = { version = "0.21", default-features = false, features = ["vendored-libgit2"] } + thiserror = "2" diff --git a/nix/tests/negative-tests.nix b/nix/tests/negative-tests.nix new file mode 100644 index 0000000..7ad501f --- /dev/null +++ b/nix/tests/negative-tests.nix @@ -0,0 +1,39 @@ +{ + perSystem = + { + config, + pkgs, + craneLib, + commonArgs, + ... + }: + let + cargoShearSource = pkgs.applyPatches { + name = "cargo-shear-negative-source"; + inherit (commonArgs) src; + patches = [ ./fixtures/cargo-shear.patch ]; + }; + cargoSortSource = pkgs.applyPatches { + name = "cargo-sort-negative-source"; + inherit (commonArgs) src; + patches = [ ./fixtures/cargo-sort.patch ]; + }; + in + { + checks.cargo-shear-negative = pkgs.testers.testBuildFailure' { + drv = config.checks.cargo-shear.overrideAttrs (_: { + src = cargoShearSource; + cargoVendorDir = craneLib.vendorCargoDeps { src = cargoShearSource; }; + }); + expectedBuilderExitCode = 1; + expectedBuilderLogEntries = [ "unused dependency `libc`" ]; + }; + checks.cargo-sort-negative = pkgs.testers.testBuildFailure' { + drv = config.checks.cargo-sort.overrideAttrs (_: { + src = cargoSortSource; + }); + expectedBuilderExitCode = 1; + expectedBuilderLogEntries = [ "Some Cargo.toml files are not sorted or formatted" ]; + }; + }; +} diff --git a/nix/toolchain.nix b/nix/toolchain.nix new file mode 100644 index 0000000..81c67b3 --- /dev/null +++ b/nix/toolchain.nix @@ -0,0 +1,18 @@ +{ inputs, ... }: +{ + perSystem = + { system, ... }: + let + pkgs = import inputs.nixpkgs { + inherit system; + overlays = [ (import inputs.rust-overlay) ]; + }; + rustToolchain = pkgs.rust-bin.stable.latest.default; + in + { + _module.args = { + inherit pkgs rustToolchain; + craneLib = (inputs.crane.mkLib pkgs).overrideToolchain rustToolchain; + }; + }; +} diff --git a/nix/treefmt.nix b/nix/treefmt.nix new file mode 100644 index 0000000..5b9a5bb --- /dev/null +++ b/nix/treefmt.nix @@ -0,0 +1,14 @@ +{ inputs, ... }: +{ + imports = [ inputs.treefmt-nix.flakeModule ]; + + perSystem = + { ... }: + { + treefmt = { + projectRootFile = "flake.nix"; + programs.nixfmt.enable = true; + programs.rustfmt.enable = true; + }; + }; +} diff --git a/src/history.rs b/src/history.rs new file mode 100644 index 0000000..6c9c549 --- /dev/null +++ b/src/history.rs @@ -0,0 +1,103 @@ +use git2::{ErrorCode, Object, Oid, Repository, RevparseMode, Revwalk, Sort}; + +use crate::{CommitId, Error}; + +pub(crate) fn resolve_commits( + repo: &Repository, + revisions: &[&str], + all: bool, +) -> Result, Error> { + if !all + && let [input] = revisions + && let Some(revision) = input.strip_suffix("^!") + { + // A single-commit selection does not need any parent history. + return Ok(vec![CommitId(resolve(repo, revision)?.id())]); + } + + let mut walk = repo.revwalk().map_err(Error::WalkHistory)?; + walk.set_sorting(Sort::TOPOLOGICAL | Sort::REVERSE) + .map_err(Error::WalkHistory)?; + + if all { + walk.push_glob("refs/*").map_err(Error::WalkHistory)?; + match repo.head() { + Ok(head) => { + let commit = head.peel_to_commit().map_err(Error::PeelToCommit)?; + walk.push(commit.id()).map_err(Error::WalkHistory)?; + } + // An empty repository has no HEAD commit to include. + Err(error) if error.code() == ErrorCode::UnbornBranch => {} + Err(error) => return Err(Error::ParseRevision(error)), + } + } + for input in revisions { + add_revision(repo, &mut walk, input)?; + } + + walk.map(|id| id.map(CommitId).map_err(Error::WalkHistory)) + .collect() +} + +fn add_revision(repo: &Repository, walk: &mut Revwalk<'_>, input: &str) -> Result<(), Error> { + // libgit2 parses single revisions and ranges. Expand the remaining + // revision-set shorthands into its native push/hide operations. + if let Some(revision) = input.strip_prefix('^') { + walk.hide(resolve(repo, revision)?.id()) + .map_err(Error::WalkHistory)?; + } else if let Some(revision) = input.strip_suffix("^!") { + let commit = resolve(repo, revision)?; + walk.push(commit.id()).map_err(Error::WalkHistory)?; + for parent in commit.parent_ids() { + walk.hide(parent).map_err(Error::WalkHistory)?; + } + } else if let Some(revision) = input.strip_suffix("^@") { + for parent in resolve(repo, revision)?.parent_ids() { + walk.push(parent).map_err(Error::WalkHistory)?; + } + } else { + let spec = repo.revparse(input).map_err(Error::ParseRevision)?; + let from = peel(spec.from().expect("libgit2 supplies the range start"))?; + match spec.mode() { + mode if mode.contains(RevparseMode::SINGLE) => { + walk.push(from).map_err(Error::WalkHistory)?; + } + mode if mode.contains(RevparseMode::MERGE_BASE) => { + let to = peel(spec.to().expect("libgit2 supplies the range end"))?; + walk.push(from).map_err(Error::WalkHistory)?; + walk.push(to).map_err(Error::WalkHistory)?; + match repo.merge_bases(from, to) { + Ok(bases) => { + for base in bases.iter() { + walk.hide(*base).map_err(Error::WalkHistory)?; + } + } + // Unrelated histories have no common ancestors to hide. + Err(error) if error.code() == ErrorCode::NotFound => {} + Err(error) => return Err(Error::MergeBases(error)), + } + } + mode if mode.contains(RevparseMode::RANGE) => { + let to = peel(spec.to().expect("libgit2 supplies the range end"))?; + walk.hide(from).map_err(Error::WalkHistory)?; + walk.push(to).map_err(Error::WalkHistory)?; + } + mode => return Err(Error::UnsupportedRevisionMode(mode)), + } + } + Ok(()) +} + +fn resolve<'repo>(repo: &'repo Repository, revision: &str) -> Result, Error> { + repo.revparse_single(revision) + .map_err(Error::ParseRevision)? + .peel_to_commit() + .map_err(Error::PeelToCommit) +} + +fn peel(object: &Object<'_>) -> Result { + object + .peel_to_commit() + .map(|commit| commit.id()) + .map_err(Error::PeelToCommit) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..786adf4 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,97 @@ +mod history; +mod nix; + +use std::fmt; +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitStatus; + +pub fn run_revisions(revisions: &[&str], all: bool, output: &mut impl Write) -> Result<(), Error> { + if revisions.is_empty() && !all { + return Err(Error::MissingRevisions); + } + let repository = DiscoverRepository.run()?; + let commits = history::resolve_commits(&repository.git_repo, revisions, all)?; + + if commits.is_empty() { + writeln!(output, "No commits in range.").map_err(Error::WriteOutput)?; + return Ok(()); + } + + for commit in &commits { + writeln!(output, "Validating {commit}").map_err(Error::WriteOutput)?; + output.flush().map_err(Error::WriteOutput)?; + nix::check_flake(&repository, commit)?; + } + + Ok(()) +} + +struct Repository { + git_repo: git2::Repository, + root: PathBuf, +} + +struct DiscoverRepository; + +impl DiscoverRepository { + fn run(self) -> Result { + let git_repo = git2::Repository::discover(".").map_err(Error::DiscoverRepository)?; + let root = git_repo + .workdir() + .ok_or(Error::BareRepository)? + .canonicalize() + .map_err(Error::CanonicalizeRepository)?; + Ok(Repository { git_repo, root }) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CommitId(git2::Oid); + +impl fmt::Display for CommitId { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(formatter) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("provide at least one revision or select all refs")] + MissingRevisions, + #[error("could not discover the Git repository: {0}")] + DiscoverRepository(#[source] git2::Error), + #[error("cannot validate a bare Git repository")] + BareRepository, + #[error("could not resolve the repository path: {0}")] + CanonicalizeRepository(#[source] std::io::Error), + #[error("could not parse the revision: {0}")] + ParseRevision(#[source] git2::Error), + #[error("unsupported revision mode: {0:?}")] + UnsupportedRevisionMode(git2::RevparseMode), + #[error("could not resolve a selected commit: {0}")] + PeelToCommit(#[source] git2::Error), + #[error("could not walk the selected history: {0}")] + WalkHistory(#[source] git2::Error), + #[error("could not find common ancestors: {0}")] + MergeBases(#[source] git2::Error), + #[error("could not write output: {0}")] + WriteOutput(#[source] std::io::Error), + #[error("could not start Nix while checking commit {commit}: {source}")] + SpawnNix { + commit: CommitId, + source: std::io::Error, + }, + #[error("flake checks failed for commit {commit}{}", status_suffix(.status))] + ValidationFailed { + commit: CommitId, + status: ExitStatus, + }, +} + +fn status_suffix(status: &ExitStatus) -> String { + match status.code() { + Some(code) => format!(" with exit status {code}"), + None => " after termination by signal".to_owned(), + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..5e582ab --- /dev/null +++ b/src/main.rs @@ -0,0 +1,26 @@ +use clap::Parser; +use std::io; +use std::process::ExitCode; + +#[derive(Parser)] +#[command(version, about)] +struct Cli { + /// Git revisions or ranges to include; prefix a revision with ^ to exclude it + #[arg(value_name = "REVISION", required_unless_present = "all")] + revisions: Vec, + /// Include history reachable from all Git refs and HEAD + #[arg(long)] + all: bool, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + let revisions: Vec<_> = cli.revisions.iter().map(String::as_str).collect(); + match validate_commits::run_revisions(&revisions, cli.all, &mut io::stdout()) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("error: {error}"); + ExitCode::FAILURE + } + } +} diff --git a/src/nix.rs b/src/nix.rs new file mode 100644 index 0000000..2f3009c --- /dev/null +++ b/src/nix.rs @@ -0,0 +1,35 @@ +use std::process::Command; + +use crate::{CommitId, Error, Repository}; + +// Run the commit's flake checks and preserve Nix's output validation. +pub(super) fn check_flake(repository: &Repository, commit: &CommitId) -> Result<(), Error> { + // Nix resolves this against the repository root and encodes the path. + let mut reference = format!("git+file:./?rev={commit}"); + if repository.git_repo.is_shallow() { + reference.push_str("&shallow=1"); + } + let status = Command::new("nix") + .args([ + "flake", + "check", + "--no-update-lock-file", + "--print-build-logs", + &reference, + ]) + .current_dir(&repository.root) + .status() + .map_err(|source| Error::SpawnNix { + commit: commit.clone(), + source, + })?; + + if status.success() { + Ok(()) + } else { + Err(Error::ValidationFailed { + commit: commit.clone(), + status, + }) + } +} diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..4bf2a28 --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,482 @@ +#![cfg(unix)] + +use git2::{Oid, Repository}; +use std::env; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::process::{Command, Output}; +use tempfile::TempDir; + +// Real libgit2 history exercises revision selection. Only Nix is replaced, so +// these tests can observe requests and force failures without building flakes. +struct Fixture { + root: TempDir, + repo: PathBuf, + repository: Repository, + commits: Vec, +} + +impl Fixture { + fn new() -> Self { + Self::with_repo_name("repo") + } + + fn with_repo_name(repo_name: &str) -> Self { + let root = tempfile::Builder::new() + .prefix("validate-commits.") + .tempdir() + .unwrap(); + let repo = root.path().join(repo_name); + let repository = Repository::init(&repo).unwrap(); + let mut fixture = Self { + root, + repo, + repository, + commits: Vec::new(), + }; + + for message in ["Base", "First", "Second", "Third"] { + fixture.commit(message); + } + + let bin = fixture.root.path().join("bin"); + fs::create_dir(&bin).unwrap(); + let shell = env::split_paths(&env::var_os("PATH").unwrap()) + .map(|directory| directory.join("sh")) + .find(|candidate| candidate.is_file()) + .expect("sh must be available while running tests") + .canonicalize() + .unwrap(); + let script = format!( + "#!{}\n{}", + shell.display(), + r#" +[ "$#" -eq 5 ] || exit 90 +[ "$1" = flake ] && [ "$2" = check ] || exit 91 +[ "$3" = --no-update-lock-file ] || exit 92 +[ "$4" = --print-build-logs ] || exit 93 +printf '%s\n' "$5" >> "$TEST_NIX_LOG" +case "$5" in + *"rev=$TEST_FAIL_COMMIT" | *"rev=$TEST_FAIL_COMMIT&"*) exit 7 ;; +esac +"# + ); + fs::write(bin.join("nix"), script).unwrap(); + fs::set_permissions(bin.join("nix"), fs::Permissions::from_mode(0o755)).unwrap(); + fixture + } + + fn commit(&mut self, message: &str) { + fs::write(self.repo.join("tracked"), message).unwrap(); + let blob = self.repository.blob(message.as_bytes()).unwrap(); + let mut tree = self.repository.treebuilder(None).unwrap(); + tree.insert("tracked", blob, 0o100644).unwrap(); + let tree = tree.write().unwrap(); + let parents = self.commits.last().copied(); + let commit = commit_as( + &self.repository, + Some("HEAD"), + message, + tree, + parents, + self.commits.len() as i64, + ); + self.commits.push(commit); + } + + fn run(&self, range: &str, fail: Option) -> Output { + self.run_args(&[range], fail) + } + + fn run_args(&self, args: &[&str], fail: Option) -> Output { + let paths = std::iter::once(self.root.path().join("bin")) + .chain(env::split_paths(&env::var_os("PATH").unwrap())) + .collect::>(); + Command::new(env!("CARGO_BIN_EXE_validate-commits")) + .args(args) + .current_dir(&self.repo) + .env_clear() + .env("PATH", env::join_paths(paths).unwrap()) + .env("TEST_NIX_LOG", self.root.path().join("calls")) + .env( + "TEST_FAIL_COMMIT", + fail.map(|oid| oid.to_string()).unwrap_or_default(), + ) + .output() + .unwrap() + } + + fn calls(&self) -> Vec { + let path = self.root.path().join("calls"); + if !path.exists() { + return Vec::new(); + } + fs::read_to_string(path) + .unwrap() + .lines() + .map(str::to_owned) + .collect() + } + + fn clear_calls(&self) { + let path = self.root.path().join("calls"); + if path.exists() { + fs::remove_file(path).unwrap(); + } + } + + fn assert_validates(&self, expected: &[Oid]) { + let calls = self.calls(); + let mut actual = calls.clone(); + actual.sort(); + let mut expected_sorted = expected_calls(expected); + expected_sorted.sort(); + assert_eq!(actual, expected_sorted); + // Independent branches may appear in either order, but every selected + // parent must be validated before its selected children. + for (child, call) in expected.iter().zip(expected_calls(expected)) { + let child_position = calls.iter().position(|entry| entry == &call).unwrap(); + for parent in self.repository.find_commit(*child).unwrap().parent_ids() { + let parent_call = expected_calls(&[parent]).pop().unwrap(); + if let Some(parent_position) = calls.iter().position(|entry| entry == &parent_call) + { + assert!( + parent_position < child_position, + "{parent} must precede {child}" + ); + } + } + } + } + + fn dirty_checkout(&self) -> (Oid, Vec, Option>) { + fs::write(self.repo.join("tracked"), "unstaged edit").unwrap(); + fs::write(self.repo.join("untracked"), "keep me").unwrap(); + ( + self.repository.head().unwrap().target().unwrap(), + fs::read(self.repository.path().join("HEAD")).unwrap(), + fs::read(self.repository.path().join("index")).ok(), + ) + } + + fn assert_checkout(&self, before: &(Oid, Vec, Option>)) { + assert_eq!(self.repository.head().unwrap().target().unwrap(), before.0); + assert_eq!( + fs::read(self.repository.path().join("HEAD")).unwrap(), + before.1 + ); + assert_eq!( + fs::read(self.repository.path().join("index")).ok(), + before.2 + ); + assert_eq!( + fs::read_to_string(self.repo.join("tracked")).unwrap(), + "unstaged edit" + ); + assert_eq!( + fs::read_to_string(self.repo.join("untracked")).unwrap(), + "keep me" + ); + } +} + +// The CLI hands Nix a relative reference resolved against the repository root +// it sets as working directory, so Nix percent-encodes the repository path +// itself; absolute `git+file:` URLs built here could not express `[`, `]`, +// `^`, or `|` in a path. +fn expected_calls(commits: &[Oid]) -> Vec { + commits + .iter() + .map(|commit| format!("git+file:./?rev={commit}")) + .collect() +} + +fn signature(timestamp: i64) -> git2::Signature<'static> { + git2::Signature::new("Test", "test@example.com", &git2::Time::new(timestamp, 0)).unwrap() +} + +fn commit_as( + repository: &Repository, + reference: Option<&str>, + message: &str, + tree: Oid, + parents: impl IntoIterator, + timestamp: i64, +) -> Oid { + let signature = signature(timestamp); + let tree = repository.find_tree(tree).unwrap(); + let parents: Vec<_> = parents + .into_iter() + .map(|id| repository.find_commit(id).unwrap()) + .collect(); + let parents: Vec<_> = parents.iter().collect(); + repository + .commit(reference, &signature, &signature, message, &tree, &parents) + .unwrap() +} + +#[test] +fn validates_only_selected_commits_in_order_without_changing_checkout() { + let fixture = Fixture::with_repo_name("repo[a]^b|c"); + let before = fixture.dirty_checkout(); + let output = fixture.run(&format!("{}..HEAD", fixture.commits[0]), None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fixture.calls(), expected_calls(&fixture.commits[1..])); + fixture.assert_checkout(&before); +} + +#[test] +fn orders_merge_parents_with_skewed_dates() { + let fixture = Fixture::new(); + let base = fixture.commits[3]; + let tree = fixture.repository.find_commit(base).unwrap().tree_id(); + let commit = |message, parents: &[Oid], timestamp| { + commit_as( + &fixture.repository, + None, + message, + tree, + parents.iter().copied(), + timestamp, + ) + }; + // Fork is Left's parent, but its timestamp makes it look newer. + // Commit relationships must decide the check order. + let fork = commit("Fork", &[base], 900); + let left = commit("Left", &[fork], 10); + let a = commit("A", &[left], 100); + let b = commit("B", &[a], 100); + let head = commit("Merge", &[b, fork], 100); + + let output = fixture.run(&format!("{b}...{fork}"), None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fixture.calls(), expected_calls(&[left, a, b])); + fs::remove_file(fixture.root.path().join("calls")).unwrap(); + + let output = fixture.run(&format!("{base}..{head}"), None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fixture.calls(), expected_calls(&[fork, left, a, b, head])); +} + +#[test] +fn combines_multiple_revisions_ranges_and_exclusions() { + // Main history: Base -> First -> Second -> Third, where HEAD points. + // Side starts from Base; release points to First. + let fixture = Fixture::new(); + let base = fixture.commits[0]; + let tree = fixture.repository.find_commit(base).unwrap().tree_id(); + let side = commit_as(&fixture.repository, None, "Side", tree, [base], 100); + fixture + .repository + .reference("refs/heads/side", side, false, "test") + .unwrap(); + fixture + .repository + .reference("refs/heads/base", base, false, "test") + .unwrap(); + fixture + .repository + .reference("refs/heads/release", fixture.commits[1], false, "test") + .unwrap(); + let before = fixture.dirty_checkout(); + let cases = [ + (vec!["HEAD", "HEAD"], fixture.commits.clone()), + ( + vec!["HEAD", "side", "^base"], + vec![ + fixture.commits[1], + fixture.commits[2], + fixture.commits[3], + side, + ], + ), + ( + vec!["base..HEAD", "base..side"], + vec![ + fixture.commits[1], + fixture.commits[2], + fixture.commits[3], + side, + ], + ), + ( + vec!["HEAD", "^base", "^release"], + fixture.commits[2..].to_vec(), + ), + ( + vec!["^release", "HEAD", "^base"], + fixture.commits[2..].to_vec(), + ), + (vec!["HEAD^@", "^base"], fixture.commits[1..3].to_vec()), + (vec!["HEAD^!", "side^!"], vec![fixture.commits[3], side]), + // HEAD^! excludes earlier history, including the commit HEAD~2^! selects. + (vec!["HEAD^!", "HEAD~2^!"], fixture.commits[3..].to_vec()), + (vec!["HEAD^!", "^HEAD"], Vec::new()), + (vec!["HEAD", "missing"], Vec::new()), + ]; + for (args, expected) in cases { + let output = fixture.run_args(&args, None); + if args.contains(&"missing") { + assert!(!output.status.success()); + } else { + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + fixture.assert_validates(&expected); + fixture.assert_checkout(&before); + fixture.clear_calls(); + } +} + +#[test] +fn all_includes_refs_and_detached_head_with_optional_exclusions() { + // --all must find commits through branches, tags, and HEAD even when + // no branch points to the checked-out commit. + let fixture = Fixture::new(); + let base = fixture.commits[0]; + let tree = fixture.repository.find_commit(base).unwrap().tree_id(); + let side = commit_as(&fixture.repository, None, "Side", tree, [base], 100); + fixture + .repository + .reference("refs/heads/side", side, false, "test") + .unwrap(); + let tagged = commit_as(&fixture.repository, None, "Tagged", tree, [base], 200); + fixture + .repository + .tag( + "release", + &fixture.repository.find_object(tagged, None).unwrap(), + &signature(200), + "Release", + false, + ) + .unwrap(); + let detached = commit_as(&fixture.repository, None, "Detached", tree, [base], 300); + fixture.repository.set_head_detached(detached).unwrap(); + // A tag can point to file contents; those should not be checked as a commit. + let blob = fixture.repository.blob(b"not a commit").unwrap(); + fixture + .repository + .tag_lightweight( + "blob", + &fixture.repository.find_object(blob, None).unwrap(), + false, + ) + .unwrap(); + let before = fixture.dirty_checkout(); + let mut expected = fixture.commits.clone(); + expected.extend([side, tagged, detached]); + let output = fixture.run_args(&["--all"], None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + fixture.assert_validates(&expected); + fixture.assert_checkout(&before); + fixture.clear_calls(); + + // Remove detached HEAD and its shared Base, keeping the other history. + let output = fixture.run_args(&["--all", "^HEAD"], None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + fixture.assert_validates(&[ + fixture.commits[1], + fixture.commits[2], + fixture.commits[3], + side, + tagged, + ]); + fixture.assert_checkout(&before); +} + +#[test] +fn symmetric_ranges_hide_all_merge_bases_and_allow_unrelated_histories() { + // Left and Right both descend from A and B. Both shared ancestors must + // be excluded, leaving only Left and Right. + let fixture = Fixture::new(); + let base = fixture.commits[0]; + let tree = fixture.repository.find_commit(base).unwrap().tree_id(); + let a = commit_as(&fixture.repository, None, "A", tree, [base], 100); + let b = commit_as(&fixture.repository, None, "B", tree, [base], 900); + let left = commit_as(&fixture.repository, None, "Left", tree, [a, b], 10); + let right = commit_as(&fixture.repository, None, "Right", tree, [b, a], 20); + assert_eq!( + fixture.repository.merge_bases(left, right).unwrap().len(), + 2 + ); + for range in [format!("{left}...{right}"), format!("{right}...{left}")] { + let output = fixture.run(&range, None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + fixture.assert_validates(&[left, right]); + fixture.clear_calls(); + } + + // With no shared ancestor, include both histories without an error. + let unrelated = commit_as(&fixture.repository, None, "Unrelated", tree, [], 5); + let output = fixture.run(&format!("HEAD...{unrelated}"), None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let mut expected = fixture.commits.clone(); + expected.push(unrelated); + fixture.assert_validates(&expected); +} + +#[test] +fn uses_shallow_mode_only_when_the_repository_is_shallow() { + let fixture = Fixture::new(); + let head = fixture.commits[3]; + let output = fixture.run("HEAD^!", None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fixture.calls(), expected_calls(&[head])); + fixture.clear_calls(); + + // Mark HEAD as a shallow boundary; the CLI must allow Nix to read it. + let shallow = fixture.repository.commondir().join("shallow"); + fs::write(&shallow, format!("{head}\n")).unwrap(); + let output = fixture.run("HEAD^!", Some(head)); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("with exit status 7")); + assert_eq!( + fixture.calls(), + vec![format!("git+file:./?rev={head}&shallow=1")] + ); + fixture.clear_calls(); + + // After history becomes complete, stop forcing shallow mode. + fs::remove_file(shallow).unwrap(); + let output = fixture.run("HEAD^!", Some(head)); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("with exit status 7")); + assert_eq!(fixture.calls(), expected_calls(&[head])); +}