diff --git a/flake.nix b/flake.nix index 449f9f9..d02ce07 100644 --- a/flake.nix +++ b/flake.nix @@ -122,8 +122,9 @@ nu-check = { enable = true; settings.libDirs = [ - ./tests/nu-tooling/lib-dirs/libs - ./tests/nu-tooling/lib-dirs/extra + ./lib + ./tests/nu-tooling/lib-dirs/fixtures/first + ./tests/nu-tooling/lib-dirs/fixtures/second ]; }; prettier.enable = true; @@ -158,6 +159,7 @@ # ------------------------------------------------------------------------------------------ devShells.default = pkgs.mkShell { name = "devkit-dev"; + NU_LIB_DIRS = "${./lib}"; packages = [ dk.nushell dk.nu-test diff --git a/lib/pin-check/mod.nu b/lib/pin-check/mod.nu new file mode 100644 index 0000000..73b8521 --- /dev/null +++ b/lib/pin-check/mod.nu @@ -0,0 +1,289 @@ +# ================================================================================================== +# Pinned Version Checks +# ================================================================================================== + +use ./versions.nu newest-version +export use ./versions.nu [version-at-least version-older] + +# -------------------------------------------------------------------------------------------------- +# Dispatch +# -------------------------------------------------------------------------------------------------- + +# List the groups and pin names without authenticating or running any row closures. +export def list [registry: closure, --footer: string]: nothing -> nothing { + print "Manual pins tracked by this script:" + for group in (do $registry) { + print "" + print $group.title + for row in $group.pins { + print $" ($row.pin)" + } + } + if ($footer | is-not-empty) { + print "" + print $footer + } +} + +def die [msg: string] { + print -e $"error: ($msg)" + exit 2 +} + +# Find the current Git checkout or report the expected checkout and exit 2. +export def repo-root [checkout: string]: nothing -> string { + try { + ^git rev-parse --show-toplevel | str trim + } catch { + die $"cannot find the repository root. Run inside the ($checkout) checkout." + } +} + +def require-gh [] { + if (which gh | is-empty) { + die "gh not found. Install GitHub CLI and authenticate to github.com." + } + if (^gh auth status --hostname github.com | complete).exit_code != 0 { + die "GitHub authentication check failed. Check credentials and network access." + } +} + +def warn [pin: string, message: string] { + print -e $"($pin): ($message)" +} + +def query [pin: string, lookup: closure]: nothing -> string { + try { + let raw = (do $lookup) + if $raw == null { + return "" + } + let value = ($raw | into string | str trim) + if ($value | is-empty) { + warn $pin "no value found" + } + $value + } catch {|err| + warn $pin $err.msg + "" + } +} + +def classify [row: record, pinned: string, upstream: string]: nothing -> record { + if ($pinned | is-empty) or ($upstream | is-empty) { + { + status: "UNKNOWN" + outcome: "unknown" + } + } else if ($row.classify? | is-not-empty) { + try { + let result = (do $row.classify $pinned $upstream) + if ($result.status | describe) != "string" or $result.outcome not-in [ + "current" "stale" "unknown" + ] { + error make { + msg: "classifier must return a status string and a current, stale, or unknown outcome" + } + } + $result + } catch {|err| + warn $row.pin $err.msg + { + status: "UNKNOWN" + outcome: "unknown" + } + } + } else if ($row.delegated? | is-not-empty) { + { + status: $row.delegated + outcome: "current" + } + } else if $pinned == $upstream { + { + status: "ok" + outcome: "current" + } + } else { + { + status: "STALE" + outcome: "stale" + } + } +} + +def resolve-row [row: record]: nothing -> record { + let pinned = (query $row.pin $row.local) + let upstream = if ($row.delegated? | is-not-empty) { + $row.delegated + } else { + query $row.pin $row.upstream + } + let result = (classify $row $pinned $upstream) + + { + pin: $row.pin + pinned: ($pinned | default --empty "?") + upstream: ($upstream | default --empty "?") + status: $result.status + outcome: $result.outcome + } +} + +def resolve-group [group: record]: nothing -> record { + let rows = if ($group.pins | is-empty) { + warn $group.title "no pins matched" + [ + { + pin: $group.title + pinned: "?" + upstream: "?" + status: "UNKNOWN" + outcome: "unknown" + } + ] + } else { + $group.pins | par-each --keep-order {|row| resolve-row $row } + } + { + title: $group.title + rows: $rows + } +} + +# Audit the registry after authenticating. Exit 0 for current, 1 for stale, or 2 for incomplete. +export def check [registry: closure] { + require-gh + + let groups = (do $registry | par-each --keep-order {|group| resolve-group $group }) + for group in $groups { + print "" + print $group.title + print ($group.rows | reject outcome | table) + } + let rows = ($groups | each {|group| $group.rows } | flatten) + let stale = ($rows | where outcome == "stale" | length) + let unknown = ($rows | where outcome == "unknown" | length) + + print "" + print $"($stale) stale, ($unknown) unknown." + if $unknown > 0 { + print "UNKNOWN means a lookup failed. Rerun, and fix the printed cause if it persists." + exit 2 + } + if $stale > 0 { + exit 1 + } +} + +# -------------------------------------------------------------------------------------------------- +# GitHub queries +# -------------------------------------------------------------------------------------------------- + +def gh-api [path: string, jq: string, --paginate]: nothing -> string { + let args = if $paginate { ["--paginate"] } else { [] } + let result = ( + ^gh api $path + --hostname github.com + --jq $jq + ...$args + | complete + ) + if $result.exit_code != 0 { + error make {msg: ($result.stderr | str trim | default --empty "GitHub API request failed")} + } + $result.stdout | str trim +} + +# Read the tag GitHub marks as the latest release. +export def gh-latest-release [repo: string]: nothing -> string { + gh-api $"repos/($repo)/releases/latest" ".tag_name" +} + +# Read all published releases in GitHub's API order, including pre-releases. +export def gh-releases [repo: string]: nothing -> list { + let jq = ".[] | select(.draft == false) | @json" + gh-api $"repos/($repo)/releases?per_page=100" $jq --paginate + | from json --objects +} + +# Read the highest version-shaped release tag, allowing pre-releases. +export def gh-newest-release [repo: string]: nothing -> string { + newest-version (gh-releases $repo | get tag_name) --allow-pre-release +} + +# Resolve the highest stable version tag to its commit, including for annotated tags. +export def gh-newest-tag-head [repo: string]: nothing -> string { + let tags = (gh-api $"repos/($repo)/tags" ".[].name" --paginate | lines) + let tag = (newest-version $tags) + + if ($tag | is-empty) { + error make {msg: "no stable version tag found"} + } + gh-api $"repos/($repo)/commits/($tag)" ".sha" +} + +# Read the latest commit on the default branch. +export def gh-default-head [repo: string]: nothing -> string { + gh-api $"repos/($repo)/commits?per_page=1" ".[0].sha" +} + +# -------------------------------------------------------------------------------------------------- +# Source extraction +# -------------------------------------------------------------------------------------------------- + +# Extract the first match of the regex's named capture v from a file under root. +export def nix-attr [root: string, file: string, regex: string]: nothing -> string { + open --raw ($root | path join $file) + | parse --regex $regex + | get v.0 +} + +# Read the first literal version assignment from a Nix file. +export def nix-version [root: string, file: string]: nothing -> string { + nix-attr $root $file '(?m)^\s*version = "(?[^"]+)"' +} + +# -------------------------------------------------------------------------------------------------- +# GitHub Actions +# -------------------------------------------------------------------------------------------------- + +# Read the sorted, unique remote uses refs in workflows and composite actions. +export def action-pins [root: string]: nothing -> list { + [".github/workflows" ".github/actions"] + | each {|dir| glob ($root | path join $dir "**/*") } + | flatten + | where {|p| + ($p | path type) == "file" and ($p | path parse | get extension) in ["yml" "yaml"] + } + | each {|p| + let doc = (open $p) + let jobs = ($doc | get -o jobs | default {} | values) + [ + ($jobs | get -o uses) + ($jobs | each {|job| $job | get -o steps | default [] | get -o uses } | flatten) + ($doc | get -o runs.steps | default [] | get -o uses) + ] + | flatten + } + | flatten + | compact + | where {|pin| + ( + not ($pin | str starts-with "./") + and not ($pin | str starts-with "$/") + and not ($pin | str starts-with "docker://") + ) + } + | uniq + | sort +} + +# Turn a GitHub Actions uses ref into a row delegated to Renovate. +export def action-pin [ref: string]: nothing -> record { + let parts = ($ref | split row "@") + { + pin: ($parts | first) + local: {|| $parts | get 1 } + delegated: "renovate" + } +} diff --git a/lib/pin-check/versions.nu b/lib/pin-check/versions.nu new file mode 100644 index 0000000..4246fac --- /dev/null +++ b/lib/pin-check/versions.nu @@ -0,0 +1,40 @@ +# ================================================================================================== +# Pinned Version Comparison +# ================================================================================================== + +# Whether the left version is at or above the right one. The release core compares first, and a +# final release ranks above the same core's pre-release. +export def version-at-least [left: string, right: string]: nothing -> bool { + let left_core = ($left | split row "-" | first | str replace -r "^v" "") + let right_core = ($right | split row "-" | first | str replace -r "^v" "") + let left_suffix = ($left | split row "-" | skip 1 | str join "-") + let right_suffix = ($right | split row "-" | skip 1 | str join "-") + + if $left_core != $right_core { + ([$left_core $right_core] | sort --natural | last) == $left_core + } else if ($left_suffix | is-empty) != ($right_suffix | is-empty) { + $left_suffix | is-empty + } else { + ([$left_suffix $right_suffix] | sort --natural | last) == $left_suffix + } +} + +# Whether the left version is below the right one. +export def version-older [left: string, right: string]: nothing -> bool { + not (version-at-least $left $right) +} + +# The highest version-shaped tag, optionally including pre-releases. +export def newest-version [tags: list, --allow-pre-release]: nothing -> string { + let pattern = if $allow_pre_release { + '^v?[0-9]+(\.[0-9]+)*(-[0-9A-Za-z.]+)?$' + } else { + '^v?[0-9]+(\.[0-9]+)*$' + } + + $tags + | where {|tag| $tag =~ $pattern } + | reduce --fold "" {|tag, newest| + if ($newest | is-empty) or (version-at-least $tag $newest) { $tag } else { $newest } + } +} diff --git a/tests/default.nix b/tests/default.nix index bd653c8..52c7296 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -16,6 +16,10 @@ in { actions = import ./actions { inherit pkgs dk repo; }; dprint-markdown = import ./dprint-markdown { inherit pkgs repo; }; + pin-check = dk.nuTests { + src = ./pin-check; + libDirs = [ ../lib ]; + }; skill-links = import ./skill-links { inherit pkgs skillSource; }; } // lib.mapAttrs' (name: lib.nameValuePair "nu-tooling-${name}") ( diff --git a/tests/nu-tooling/lib-dirs/default.nix b/tests/nu-tooling/lib-dirs/default.nix index 19bf55a..569f065 100644 --- a/tests/nu-tooling/lib-dirs/default.nix +++ b/tests/nu-tooling/lib-dirs/default.nix @@ -8,8 +8,8 @@ let libDirs = [ - ./libs - ./extra + ./fixtures/first + ./fixtures/second ]; lib-command = dk.writeNuApplication { @@ -23,7 +23,7 @@ let version = "0.1.0"; src = ./lib-app; libDirs = [ - ./libs + ./fixtures/first ]; }; in diff --git a/tests/nu-tooling/lib-dirs/libs/shout.nu b/tests/nu-tooling/lib-dirs/fixtures/first/shout.nu similarity index 100% rename from tests/nu-tooling/lib-dirs/libs/shout.nu rename to tests/nu-tooling/lib-dirs/fixtures/first/shout.nu diff --git a/tests/nu-tooling/lib-dirs/extra/whisper.nu b/tests/nu-tooling/lib-dirs/fixtures/second/whisper.nu similarity index 100% rename from tests/nu-tooling/lib-dirs/extra/whisper.nu rename to tests/nu-tooling/lib-dirs/fixtures/second/whisper.nu diff --git a/tests/pin-check/audit.testlib.nu b/tests/pin-check/audit.testlib.nu new file mode 100644 index 0000000..a30c3dc --- /dev/null +++ b/tests/pin-check/audit.testlib.nu @@ -0,0 +1,79 @@ +use pin-check + +def registry []: nothing -> list { + let sample = { + pin: "sample" + local: {|| "1.0"} + upstream: {|| "2.0"} + } + let pins = match $env.PIN_CASE { + "list" => [ + { + pin: "sample" + local: {|| error make {msg: "local lookup ran"} } + upstream: {|| error make {msg: "upstream lookup ran"} } + } + ] + "current" => [ + ($sample | merge { + classify: {|pinned, upstream| + { + status: $"tracks channel ($pinned) to ($upstream)" + outcome: "current" + } + } + }) + ] + "stale" => [ + ($sample | merge { + classify: {|_pinned, _upstream| + { + status: "pin superseded" + outcome: "stale" + } + } + }) + ] + "mixed" => [ + $sample + { + pin: "failed" + local: {|| "1.0"} + upstream: {|| error make {msg: "upstream unavailable"} } + } + { + pin: "missing" + local: {|| + print -e "cannot read missing version" + null + } + upstream: {|| "2.0"} + } + ] + "blank" => [ + ($sample | merge {upstream: {|| ""}}) + ] + "github" => [ + ($sample | merge {upstream: {|| pin-check gh-latest-release "example/sample"}}) + ] + "empty" => [] + } + [ + { + title: "Packages" + pins: $pins + } + ] +} + +def "main list" [--footer: string] { + pin-check list {|| registry } --footer $footer +} + +def "main root" [] { + pin-check repo-root "example" +} + +def main [] { + pin-check check {|| registry } +} diff --git a/tests/pin-check/gh.stub.nu b/tests/pin-check/gh.stub.nu new file mode 100644 index 0000000..bda34ce --- /dev/null +++ b/tests/pin-check/gh.stub.nu @@ -0,0 +1,28 @@ +#!/usr/bin/env nu + +# ================================================================================================== +# gh Stub +# ================================================================================================== + +def "main auth status" [--hostname: string] { + if $hostname != "github.com" { + exit 1 + } +} + +def "main api" [endpoint: string, --hostname: string, --jq: string] { + if ( + $endpoint != "repos/example/sample/releases/latest" + or $hostname != "github.com" + or $jq != ".tag_name" + ) { + print -e "unexpected GitHub API request" + } else { + print -e "gh: Service unavailable (HTTP 503)" + } + exit 1 +} + +def main [] { + exit 1 +} diff --git a/tests/pin-check/git.stub.nu b/tests/pin-check/git.stub.nu new file mode 100644 index 0000000..81451bf --- /dev/null +++ b/tests/pin-check/git.stub.nu @@ -0,0 +1,8 @@ +#!/usr/bin/env nu + +def main [command: string, --show-toplevel] { + if $command != "rev-parse" or not $show_toplevel { + print -e "unexpected git arguments" + } + exit 128 +} diff --git a/tests/pin-check/pin-check.test.nu b/tests/pin-check/pin-check.test.nu new file mode 100644 index 0000000..97fa388 --- /dev/null +++ b/tests/pin-check/pin-check.test.nu @@ -0,0 +1,95 @@ +use std/assert +use std-rfc/str + +const SCRIPT = path self "audit.testlib.nu" + +def "test list is offline and leaves row closures lazy" [] { + let lib_dirs = ($env.NU_LIB_DIRS | str join (char esep)) + let results = (with-env {NU_LIB_DIRS: $lib_dirs, PIN_CASE: "list", PATH: []} { + [ + (^$nu.current-exe --no-config-file $SCRIPT list | complete) + (^$nu.current-exe --no-config-file $SCRIPT list --footer "See the project guide." | complete) + ] + }) + + let listing = ( + " + Manual pins tracked by this script: + + Packages + sample + + " + | str dedent + ) + let listing_with_footer = ( + " + Manual pins tracked by this script: + + Packages + sample + + See the project guide. + + " + | str dedent + ) + assert equal $results [ + { + stdout: $listing + stderr: "" + exit_code: 0 + } + { + stdout: $listing_with_footer + stderr: "" + exit_code: 0 + } + ] +} + +def "test check derives exit code from outcomes and diagnoses incomplete groups" [] { + let lib_dirs = ($env.NU_LIB_DIRS | str join (char esep)) + let cases = [ + [name code summary label warnings]; + ["current" 0 "0 stale, 0 unknown." "tracks channel 1.0 to 2.0" []] + ["stale" 1 "1 stale, 0 unknown." "pin superseded" []] + [ + "mixed" 2 "1 stale, 2 unknown." "UNKNOWN" + ["cannot read missing version" "failed: upstream unavailable"] + ] + ["blank" 2 "0 stale, 1 unknown." "UNKNOWN" ["sample: no value found"]] + ["github" 2 "0 stale, 1 unknown." "UNKNOWN" ["sample: gh: Service unavailable (HTTP 503)"]] + ["empty" 2 "0 stale, 1 unknown." "UNKNOWN" ["Packages: no pins matched"]] + ] + + for case in $cases { + let result = (with-env { + NU_LIB_DIRS: $lib_dirs + PIN_CASE: $case.name + PATH: [$env.NU_TEST_STUBS] + } { + ^$nu.current-exe --no-config-file $SCRIPT | complete + }) + + assert equal $result.exit_code $case.code $case.name + assert ($result.stdout | str contains $case.summary) $case.name + let table = ($result.stdout | split row $case.summary | first) + assert ($table | str contains $case.label) $case.name + assert (not ($table | str contains "outcome")) $case.name + assert equal ($result.stderr | lines | sort) $case.warnings $case.name + } +} + +def "test repo-root reports the expected checkout when Git fails" [] { + let lib_dirs = ($env.NU_LIB_DIRS | str join (char esep)) + let result = (with-env {NU_LIB_DIRS: $lib_dirs, PATH: [$env.NU_TEST_STUBS]} { + ^$nu.current-exe --no-config-file $SCRIPT root | complete + }) + + assert equal $result { + stdout: "" + stderr: "error: cannot find the repository root. Run inside the example checkout.\n" + exit_code: 2 + } +} diff --git a/tests/pin-check/versions.test.nu b/tests/pin-check/versions.test.nu new file mode 100644 index 0000000..3b067b6 --- /dev/null +++ b/tests/pin-check/versions.test.nu @@ -0,0 +1,102 @@ +use std/assert + +use pin-check/versions.nu * + +def "test version helpers compare naturally and select the newest valid tag" [] { + let selections = [ + { + name: "higher version in original order" + tags: ["1.2.0" "1.3.0"] + allow: false + expected: "1.3.0" + } + { + name: "higher version in reversed order" + tags: ["1.3.0" "1.2.0"] + allow: false + expected: "1.3.0" + } + { + name: "natural core comparison" + tags: ["1.9.0" "1.10.0"] + allow: false + expected: "1.10.0" + } + { + name: "final before same core pre-release" + tags: ["2.0.0" "2.0.0-rc.1"] + allow: true + expected: "2.0.0" + } + { + name: "final after same core pre-release" + tags: ["2.0.0-rc.1" "2.0.0"] + allow: true + expected: "2.0.0" + } + { + name: "pre-release allowed on higher core" + tags: ["1.4.0" "1.5.0-beta.1"] + allow: true + expected: "1.5.0-beta.1" + } + { + name: "later higher beta wins" + tags: ["2.2.0-beta.2" "3.0.0-beta.6"] + allow: true + expected: "3.0.0-beta.6" + } + { + name: "multi digit pre-release comparison" + tags: ["1.0.0-alpha.9" "1.0.0-alpha.10"] + allow: true + expected: "1.0.0-alpha.10" + } + { + name: "bare tags exclude pre-releases" + tags: ["1.9.0" "2.0.0-rc.1"] + allow: false + expected: "1.9.0" + } + { + name: "empty tags" + tags: [] + allow: false + expected: "" + } + { + name: "only non-version tags" + tags: ["release-notes" "macos-27-preview.5"] + allow: false + expected: "" + } + ] + + for case in $selections { + let actual = if $case.allow { + newest-version $case.tags --allow-pre-release + } else { + newest-version $case.tags + } + + assert equal $actual $case.expected $case.name + } + + let comparisons = [ + { + name: "compare numeric core components" + older: "1.9.0" + newer: "1.10.0" + } + { + name: "compare final with same core pre-release" + older: "2.0.0-rc.1" + newer: "2.0.0" + } + ] + + for case in $comparisons { + assert (version-at-least $case.newer $case.older) $case.name + assert (version-older $case.older $case.newer) $case.name + } +}