From 9c97a049fac922e799e3f2024a5753d0d3e79971 Mon Sep 17 00:00:00 2001 From: Mohsen Sarrafan Date: Thu, 29 Oct 2026 10:44:40 -0400 Subject: [PATCH 1/2] Harden tend across every subsystem Fixes found by a full review and by live runs on real repos: base and lock handling, interrupts, process trees, ecosystem parsing and edits, API change detection, PR delivery safety, vetting false positives, OSV fix selection, action token scrubbing, CI and release checks. --- .github/workflows/ci.yml | 67 +++ .github/workflows/release.yml | 27 +- .github/workflows/tend.yml | 28 +- action.yml | 37 +- action/install.sh | 78 ++- action/install_test.sh | 8 +- action/scrub.sh | 35 ++ docs/CONTRIBUTING.md | 6 +- docs/config.md | 28 +- docs/github-actions.md | 48 +- docs/how-it-works.md | 23 +- docs/limitations.md | 3 + docs/pr-anatomy.md | 7 +- docs/self-update.md | 29 +- internal/api/catalog.go | 44 +- internal/api/catalog_test.go | 134 +++-- internal/api/chains.go | 23 +- internal/api/chains_test.go | 40 +- internal/api/changelog.go | 380 ++++++++++++--- internal/api/changelog_test.go | 178 ++++++- internal/api/conform.go | 231 ++++++++- internal/api/conform_test.go | 133 +++++ internal/api/diff.go | 10 +- internal/api/discover.go | 29 +- internal/api/discover_test.go | 55 ++- internal/api/openapi.go | 94 +++- internal/api/openapi_test.go | 170 ++++++- internal/api/providers.yml | 17 +- ...3.digitaloceanspaces.com_2610c7aec8fc.json | 2 +- ...aw.githubusercontent.com_012127149c7b.json | 2 +- ...aw.githubusercontent.com_05d327c9f740.json | 5 + ...aw.githubusercontent.com_0bcbf5ac2dab.json | 5 + ...aw.githubusercontent.com_0c3fbf6148f1.json | 2 +- ...aw.githubusercontent.com_124e896cf8e7.json | 5 + ...aw.githubusercontent.com_1c599e89375c.json | 5 + ...aw.githubusercontent.com_3bbb5588add3.json | 2 +- ...aw.githubusercontent.com_4499f8059f9b.json | 5 + ...aw.githubusercontent.com_4568fa60b87f.json | 5 + ...aw.githubusercontent.com_48d20ee6325e.json | 2 +- ...aw.githubusercontent.com_5828ec494929.json | 2 +- ...aw.githubusercontent.com_74aa1cc1ce8d.json | 5 + ...aw.githubusercontent.com_990eb07e6ba4.json | 5 + ...aw.githubusercontent.com_bedcf2cb8b4a.json | 2 +- ...aw.githubusercontent.com_eca6cb1a084d.json | 2 +- internal/cli/baseline.go | 3 +- internal/cli/catchup_test.go | 37 ++ internal/cli/check.go | 124 ++++- internal/cli/ci.go | 30 +- internal/cli/ci_test.go | 100 ++++ internal/cli/climb.go | 38 +- internal/cli/env.go | 134 ++++- internal/cli/env_test.go | 42 +- internal/cli/init.go | 74 ++- internal/cli/init_test.go | 37 ++ internal/cli/interrupt_test.go | 52 ++ internal/cli/main_test.go | 456 ++++++++++++++++++ internal/cli/onboard.go | 149 +++++- internal/cli/onboard_test.go | 33 ++ internal/cli/output.go | 152 +++--- internal/cli/output_test.go | 67 ++- internal/cli/run.go | 248 ++++++++-- internal/cli/session.go | 155 ++++-- internal/cli/session_test.go | 174 +++++++ internal/cli/track.go | 43 +- internal/cli/update.go | 8 +- internal/cli/watch.go | 56 ++- internal/cli/watch_test.go | 30 ++ internal/config/config.go | 106 +++- internal/config/config_test.go | 62 ++- internal/config/errors.go | 49 ++ internal/core/change.go | 19 +- internal/core/core.go | 16 + internal/core/env.go | 28 +- internal/core/env_test.go | 41 ++ internal/core/id.go | 18 +- internal/core/id_test.go | 4 +- internal/core/scan.go | 28 ++ internal/core/stages.go | 73 ++- internal/core/stages_test.go | 43 ++ internal/deliver/body.go | 285 +++++++++-- internal/deliver/body_test.go | 176 +++++++ internal/deliver/close.go | 42 +- internal/deliver/close_test.go | 51 +- internal/deliver/fake.go | 57 ++- internal/deliver/first.go | 230 ++++++++- internal/deliver/first_test.go | 80 +++ internal/deliver/git.go | 40 +- internal/deliver/git_test.go | 20 + internal/deliver/github.go | 160 ++++-- internal/deliver/github_test.go | 107 +++- internal/deliver/send.go | 123 ++++- internal/deliver/send_test.go | 248 +++++++++- .../testdata/api_field_removed.golden.md | 2 +- .../testdata/broken_install_fixed.golden.md | 33 ++ .../testdata/deprecation_hostile.golden.md | 29 ++ .../testdata/failing_baseline_draft.golden.md | 2 +- internal/deliver/testdata/tidy.golden.md | 5 +- internal/deliver/title.go | 23 +- internal/deliver/title_test.go | 44 +- internal/deliver/track.go | 33 +- internal/deliver/track_test.go | 21 +- internal/e2e/catchup_test.go | 3 + internal/e2e/e2e_test.go | 29 +- .../TestAPIDeprecationThenRemoval/body.md | 4 +- .../check-v1.json | 4 +- .../check-v2.json | 10 +- .../decision-body.md | 2 +- .../TestAPIDeprecationThenRemoval/title.txt | 2 +- internal/e2e/testdata/TestCIImages/check.json | 26 +- .../testdata/TestCIImages/checkout-body.md | 4 +- .../e2e/testdata/TestGoSecurity/check.json | 2 +- internal/e2e/testdata/TestInit/workflow.yml | 2 +- internal/e2e/testdata/TestNodeChoice/body.md | 4 +- .../testdata/TestNodeDecision/applied-body.md | 4 +- .../e2e/testdata/TestNodeDecision/body.md | 4 +- .../e2e/testdata/TestNodeDeprecation/body.md | 4 +- .../testdata/TestNodeDeprecation/check.json | 2 +- .../e2e/testdata/TestOnboardCatchUp/body.md | 2 +- internal/e2e/testdata/TestOnboardNode/body.md | 2 +- .../e2e/testdata/TestOnboardNode/check.txt | 2 +- .../e2e/testdata/TestPinnedInScript/body.md | 40 +- .../e2e/testdata/TestRuntimeMinimum/check.txt | 2 +- .../testdata/TestToolchainEndOfLife/check.txt | 2 +- internal/e2e/testdata/TestUnknownAPIs/body.md | 2 +- .../e2e/testdata/TestUnknownAPIs/title.txt | 2 +- internal/eco/actions.go | 21 + internal/eco/actions_test.go | 22 + internal/eco/cargo.go | 4 +- internal/eco/cargo_test.go | 67 ++- internal/eco/composer.go | 2 +- internal/eco/custom.go | 14 +- internal/eco/custom_test.go | 36 ++ internal/eco/docker.go | 117 +++-- internal/eco/docker_test.go | 87 ++++ internal/eco/eco.go | 127 +++-- internal/eco/eco_test.go | 92 ++++ internal/eco/git.go | 211 +++++++- internal/eco/git_test.go | 84 ++++ internal/eco/github.go | 2 +- internal/eco/github_test.go | 21 + internal/eco/gomod.go | 172 ++++++- internal/eco/gomod_test.go | 133 ++++- internal/eco/gradle.go | 162 ++++++- internal/eco/gradle_test.go | 109 +++++ internal/eco/helm.go | 4 +- internal/eco/lock.go | 22 +- internal/eco/lock_test.go | 41 ++ internal/eco/maven.go | 2 +- internal/eco/npm.go | 94 +++- internal/eco/npm_lock.go | 197 +++++++- internal/eco/npm_test.go | 248 +++++++++- internal/eco/npm_unused.go | 5 +- internal/eco/nuget.go | 4 +- internal/eco/python.go | 367 +++++++++++++- internal/eco/python_lock.go | 101 ++-- internal/eco/python_test.go | 282 ++++++++++- internal/eco/python_unused.go | 39 +- internal/eco/remove_test.go | 36 ++ internal/eco/req.go | 36 +- internal/eco/rubygems.go | 2 +- internal/eco/suite.go | 2 +- internal/eco/terraform.go | 16 +- internal/eco/terraform_test.go | 48 +- .../docker/bump/compose-digest.golden | 4 +- .../testdata/docker/bump/compose-host.golden | 4 +- .../docker/bump/compose-inline-default.golden | 4 +- .../testdata/docker/deps/compose.golden.json | 6 +- .../eco/testdata/docker/project/compose.yaml | 4 +- .../eco/testdata/npm/bump/caret-major.golden | 4 +- .../eco/testdata/npm/bump/caret-v1.golden | 4 +- internal/eco/testdata/npm/bump/exact.golden | 4 +- internal/eco/testdata/npm/bump/member.golden | 4 +- .../eco/testdata/npm/bump/swap-sorted.golden | 4 +- internal/eco/testdata/npm/bump/tilde.golden | 4 +- .../testdata/python/bump/pep621-extra.golden | 4 +- .../python/bump/pep621-single-quoted.golden | 4 +- .../eco/testdata/python/bump/pep621.golden | 4 +- .../testdata/python/bump/pip-compile.golden | 4 +- .../testdata/python/bump/poetry-caret.golden | 4 +- .../testdata/python/bump/poetry-exact.golden | 4 +- .../python/bump/poetry-inline-table.golden | 4 +- .../workspace/packages/a/pyproject.toml | 6 + .../workspace/packages/skip/pyproject.toml | 4 + .../python/projects/workspace/pyproject.toml | 3 + .../python/projects/workspace/uv.lock | 29 ++ internal/eco/toolchain.go | 33 ++ internal/eco/toolchain_test.go | 46 ++ internal/eco/unused.go | 8 +- internal/eco/unused_test.go | 4 + internal/fetch/fetch.go | 79 ++- internal/fetch/fetch_test.go | 155 ++++++ internal/gitx/gitx.go | 74 ++- internal/gitx/gitx_test.go | 19 + internal/model/anthropic.go | 11 +- internal/model/command.go | 2 + internal/model/model.go | 32 +- internal/model/model_test.go | 137 ++++++ internal/model/openai.go | 6 +- internal/patch/agent.go | 69 ++- internal/patch/agent_test.go | 58 +++ internal/patch/apply.go | 14 +- internal/patch/apply_test.go | 53 +- internal/patch/bump.go | 31 +- internal/patch/bump_test.go | 19 + internal/patch/helpers_test.go | 3 + internal/patch/migrate.go | 75 ++- internal/patch/prompt.go | 7 +- internal/patch/prompt.tmpl | 5 + internal/patch/remove.go | 16 +- internal/patch/remove_test.go | 23 + internal/plan/first.go | 23 +- internal/plan/first_test.go | 12 +- internal/plan/merge.go | 38 +- internal/plan/plan.go | 139 +++++- internal/plan/plan_test.go | 169 ++++++- internal/plan/proof.go | 25 +- internal/plan/registry.go | 84 +++- internal/proc/proc.go | 2 + internal/proc/proc_other.go | 11 + internal/proc/proc_unix.go | 23 + internal/scan/index.go | 104 ++-- internal/scan/index_test.go | 86 +++- internal/scan/lexer.go | 47 +- internal/scan/lexer_test.go | 73 +++ internal/scan/scan.go | 2 +- internal/scan/scan_test.go | 10 + internal/scan/testdata/golden/App.cs.json | 3 +- internal/scan/testdata/golden/App.java.json | 3 +- internal/scan/testdata/golden/app.go.json | 3 +- internal/scan/testdata/golden/app.php.json | 6 +- internal/scan/testdata/golden/app.py.json | 12 +- internal/scan/testdata/golden/app.rb.json | 3 +- internal/scan/testdata/golden/app.tsx.json | 9 +- internal/scan/testdata/golden/main.rs.json | 3 +- internal/scan/urls.go | 2 +- internal/selfupdate/action_test.go | 174 +++++++ internal/selfupdate/install_test.go | 98 +++- internal/selfupdate/sign/main.go | 30 +- internal/selfupdate/sign/main_test.go | 67 +++ internal/selfupdate/update.go | 75 ++- internal/selfupdate/update_test.go | 211 +++++++- internal/source/eol.go | 1 + internal/source/notes.go | 45 +- internal/source/notes_test.go | 18 + internal/source/osv.go | 223 ++++++++- internal/source/osv_test.go | 105 +++- internal/source/replace.go | 22 +- internal/source/replace_test.go | 68 ++- internal/source/replacements.yml | 22 +- internal/source/security.go | 4 +- .../POST_api.osv.dev_cef841434851.json | 10 + internal/source/util_test.go | 2 +- internal/state/lock_other.go | 54 +++ internal/state/lock_other_test.go | 66 +++ internal/state/lock_unix.go | 47 ++ internal/state/lock_unix_test.go | 75 +++ internal/state/state.go | 81 ++-- internal/state/state_test.go | 116 +++-- internal/ver/ver.go | 45 +- internal/ver/ver_test.go | 29 +- internal/verify/detect.go | 26 +- internal/verify/detect_test.go | 38 +- internal/verify/env.go | 9 +- internal/verify/env_test.go | 2 +- internal/verify/proc_other.go | 12 - internal/verify/proc_unix.go | 22 - internal/verify/run.go | 46 +- internal/verify/run_test.go | 41 +- internal/verify/worktree.go | 87 +++- internal/verify/worktree_test.go | 41 ++ internal/vet/helpers_test.go | 3 + internal/vet/lang.go | 15 +- internal/vet/lang_test.go | 23 +- internal/vet/lockfile.go | 36 +- internal/vet/scope.go | 22 +- internal/vet/section.go | 12 +- internal/vet/symbols.go | 362 ++++++++++++-- internal/vet/symbols_test.go | 222 ++++++++- internal/vet/tests.go | 109 +++++ internal/vet/tests_test.go | 75 +++ internal/vet/vet.go | 1 + internal/vet/vet_test.go | 28 +- 282 files changed, 13090 insertions(+), 1564 deletions(-) create mode 100755 action/scrub.sh create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_05d327c9f740.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_0bcbf5ac2dab.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_124e896cf8e7.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_1c599e89375c.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_4499f8059f9b.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_4568fa60b87f.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_74aa1cc1ce8d.json create mode 100644 internal/api/testdata/recorded/GET_raw.githubusercontent.com_990eb07e6ba4.json create mode 100644 internal/cli/ci_test.go create mode 100644 internal/cli/interrupt_test.go create mode 100644 internal/cli/main_test.go create mode 100644 internal/cli/session_test.go create mode 100644 internal/cli/watch_test.go create mode 100644 internal/core/env_test.go create mode 100644 internal/core/stages_test.go create mode 100644 internal/deliver/testdata/broken_install_fixed.golden.md create mode 100644 internal/deliver/testdata/deprecation_hostile.golden.md create mode 100644 internal/eco/testdata/python/projects/workspace/packages/a/pyproject.toml create mode 100644 internal/eco/testdata/python/projects/workspace/packages/skip/pyproject.toml create mode 100644 internal/eco/testdata/python/projects/workspace/pyproject.toml create mode 100644 internal/eco/testdata/python/projects/workspace/uv.lock create mode 100644 internal/proc/proc.go create mode 100644 internal/proc/proc_other.go create mode 100644 internal/proc/proc_unix.go create mode 100644 internal/selfupdate/action_test.go create mode 100644 internal/source/testdata/recorded/POST_api.osv.dev_cef841434851.json create mode 100644 internal/state/lock_other.go create mode 100644 internal/state/lock_other_test.go create mode 100644 internal/state/lock_unix.go create mode 100644 internal/state/lock_unix_test.go delete mode 100644 internal/verify/proc_other.go delete mode 100644 internal/verify/proc_unix.go create mode 100644 internal/vet/tests.go create mode 100644 internal/vet/tests_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e52d8d5..5c3d3ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version: stable + check-latest: true - uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0 with: version: v2.15 @@ -23,3 +24,69 @@ jobs: run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; } - run: go vet ./... - run: go test -race ./... + - name: govulncheck + run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... + + # Self-update and the installer differ per OS; the rest of the suite assumes + # unix tools, so only this package runs here. + selfupdate: + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: stable + check-latest: true + - run: go test ./internal/selfupdate/... + + # Runs the composite action the way users do. checkout keeps its credentials + # here so the scrub has something to remove. + action: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + version: 1.0.0 + - os: macos-latest + version: 1.0.0 + - os: windows-latest + version: 1.0.0 + - os: ubuntu-latest + version: "" + runs-on: ${{ matrix.os }} + permissions: + contents: read + pull-requests: read + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ./ + with: + command: check + version: ${{ matrix.version }} + - name: credentials are gone and tend is installed + shell: bash + run: | + if git config --local --get-all http.https://github.com/.extraheader; then + echo "the checkout token is still in the config" >&2 + exit 1 + fi + if git config --local --get-regexp '^includeif\..*\.path$' | grep git-credentials-; then + echo "an include still points at checkout's credentials" >&2 + exit 1 + fi + temp=$RUNNER_TEMP + command -v cygpath >/dev/null && temp=$(cygpath -u "$RUNNER_TEMP") + if ls "$temp"/git-credentials-*.config 2>/dev/null; then + echo "checkout's credentials file is still in RUNNER_TEMP" >&2 + exit 1 + fi + ls "$temp"/tend/bin/tend* + tend version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dc50a94..0f47b4f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,9 @@ on: push: tags: - "v[0-9]+.[0-9]+.[0-9]+" - - "v[0-9]+.[0-9]+.[0-9]+-*" + - "v[0-9]+.[0-9]+.[0-9]+-alpha*" + - "v[0-9]+.[0-9]+.[0-9]+-beta*" + - "v[0-9]+.[0-9]+.[0-9]+-rc*" permissions: contents: read @@ -16,8 +18,16 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod + go-version: stable + check-latest: true + # A shape tend update does not accept would ship binaries that call + # themselves development builds. + - name: tag shape + run: | + [[ $GITHUB_REF_NAME =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-(alpha|beta|rc)\.?[0-9]+)?$ ]] || + { echo "tag $GITHUB_REF_NAME is not vX.Y.Z or vX.Y.Z-(alpha|beta|rc)N" >&2; exit 1; } - run: go test ./... + - run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... build: needs: test @@ -34,7 +44,8 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod + go-version: stable + check-latest: true - name: build and package run: | tag=$GITHUB_REF_NAME @@ -44,6 +55,7 @@ jobs: go build -trimpath \ -ldflags "-s -w -X main.version=$tag -X main.commit=$(git rev-parse --short HEAD) -X main.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ -o "stage/$bin" ./cmd/tend + env -u GOOS -u GOARCH go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 -mode binary "stage/$bin" name=tend_${tag#v}_${GOOS}_${GOARCH} if [ "$GOOS" = windows ]; then (cd stage && zip -q "../dist/$name.zip" "$bin") @@ -68,7 +80,8 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod + go-version: stable + check-latest: true - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: dist-* @@ -80,6 +93,12 @@ jobs: run: | (cd dist && sha256sum tend_* > checksums.txt) go run ./internal/selfupdate/sign -in dist/checksums.txt > dist/checksums.txt.sig + # The same check install.sh makes, on the exact files the Action will read. + - name: verify signature + run: | + base64 -d < dist/checksums.txt.sig > "$RUNNER_TEMP/sig.bin" + openssl pkeyutl -verify -pubin -inkey action/pubkey.pem -rawin \ + -in dist/checksums.txt -sigfile "$RUNNER_TEMP/sig.bin" - name: publish env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/tend.yml b/.github/workflows/tend.yml index f4aa10e..e4fa751 100644 --- a/.github/workflows/tend.yml +++ b/.github/workflows/tend.yml @@ -1,14 +1,20 @@ name: tend +# Runs the action from this checkout on this repository. Its PRs only start +# ci.yml when TEND_TOKEN holds a GitHub App or fine-grained token; with the +# default token, "Allow GitHub Actions to create and approve pull requests" +# has to be on and the PRs get no CI. on: schedule: - - cron: "17 6 * * 1" + - cron: "17 6 * * 1,4" workflow_dispatch: permissions: contents: write pull-requests: write issues: write + checks: read + statuses: read concurrency: group: tend @@ -21,20 +27,12 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + fetch-depth: 0 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod - - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + go-version: stable + check-latest: true + - uses: ./ with: - path: ~/.cache/tend/repos - key: tend-${{ github.repository }}-${{ github.run_id }} - restore-keys: tend-${{ github.repository }}- - - run: go run ./cmd/tend run - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TEND_MODEL_KEY: ${{ secrets.TEND_MODEL_KEY }} - - if: always() - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ~/.cache/tend/repos - key: tend-${{ github.repository }}-${{ github.run_id }} + token: ${{ secrets.TEND_TOKEN || github.token }} + model-key: ${{ secrets.TEND_MODEL_KEY }} diff --git a/action.yml b/action.yml index e8f74de..02183db 100644 --- a/action.yml +++ b/action.yml @@ -5,7 +5,7 @@ branding: color: green inputs: token: - description: Token with contents:write and pull-requests:write. The default token cannot start other workflows or push workflow changes; pass a fine-grained or GitHub App token for those + description: Token with contents:write and pull-requests:write. PRs the default token opens start no other workflows; pass a fine-grained or GitHub App token, with the Workflows permission for Action bumps, to lift that default: ${{ github.token }} command: description: run | check @@ -17,11 +17,14 @@ inputs: description: Path to tend.yml default: "" version: - description: tend version to install; default is the latest release of this action's major + description: tend version to install; default is the release this action is pinned to (a tag, or the release tagged at a pinned commit), or the newest release of its major or minor default: "" model-key: description: API key for the model provider named in tend.yml default: "" + fail-on-unproven: + description: Fail the job when tend cannot prove a change it lists in its tracking issue; by default that is a warning, and the change is tried again when the base moves + default: "false" runs: using: composite steps: @@ -31,17 +34,20 @@ runs: GITHUB_TOKEN: ${{ inputs.token }} run: '"$GITHUB_ACTION_PATH/action/install.sh" "$TEND_VERSION"' # tend pushes with the token it is given. A token that actions/checkout - # left in the repository's config would be readable by the project's own - # install and test commands, so it goes, whatever the checkout step says. + # left behind, in the repository's config or in the credentials file under + # RUNNER_TEMP, would be readable by the project's own install and test + # commands, so both go, whatever the checkout step says. A process running + # as the runner's user can still find tokens elsewhere, through sudo on + # hosted runners for one; verify.container is the real boundary. - shell: bash - run: | - git config --local --unset-all http.https://github.com/.extraheader || true - git config --local --get-regexp '^includeif\..*\.path$' 2>/dev/null | while read -r key val; do - case "$val" in *git-credentials*) git config --local --unset-all "$key" ;; esac - done || true + run: '"$GITHUB_ACTION_PATH/action/scrub.sh"' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: ${{ runner.temp }}/tend/repos + path: | + ${{ runner.temp }}/tend/repos + !${{ runner.temp }}/tend/repos/*/wt + !${{ runner.temp }}/tend/repos/*/baseline + !${{ runner.temp }}/tend/repos/*/lock key: tend-${{ github.repository }}-${{ github.run_id }} restore-keys: tend-${{ github.repository }}- # The user cache dir differs per OS, so state goes where the cache steps look. @@ -54,9 +60,16 @@ runs: TEND_CONFIG: ${{ inputs.config }} TEND_COMMAND: ${{ inputs.command }} TEND_ARGS: ${{ inputs.args }} - run: tend "$TEND_COMMAND" $TEND_ARGS + TEND_FAIL_ON_UNPROVEN: ${{ inputs.fail-on-unproven }} + # exec, so no shell holding these variables stays behind as tend's + # parent for the project's commands to read through /proc. + run: set -f; exec tend "$TEND_COMMAND" $TEND_ARGS - if: always() uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - path: ${{ runner.temp }}/tend/repos + path: | + ${{ runner.temp }}/tend/repos + !${{ runner.temp }}/tend/repos/*/wt + !${{ runner.temp }}/tend/repos/*/baseline + !${{ runner.temp }}/tend/repos/*/lock key: tend-${{ github.repository }}-${{ github.run_id }} diff --git a/action/install.sh b/action/install.sh index 261c71a..d2b6e2a 100755 --- a/action/install.sh +++ b/action/install.sh @@ -24,28 +24,62 @@ tags() { grep -o '"tag_name": *"[^"]*"' | sed 's/.*"\([^"]*\)"$/\1/' || true } -# An explicit version wins. Then a full tag in the action ref. Then the newest -# release inside the ref's major (uses: ...@v1), followed by the one before -# it, else the newest release. +releases() { + local body + body=$(api_get "$api/repos/$repo/releases?per_page=100") || die "could not list releases of $repo" + echo "$body" | tags +} + +# tagged prints the release tags that point at commit $1. /tags gives each +# tag's commit already dereferenced, so annotated tags match too. +tagged() { + local page=1 body count + while [ "$page" -le 50 ]; do + body=$(api_get "$api/repos/$repo/tags?per_page=100&page=$page") || die "could not list tags of $repo" + count=$(echo "$body" | grep -o '"name": *"[^"]*"' | wc -l) + echo "$body" | grep -oE '"(name|sha)": *"[^"]*"' | awk -F'"' -v want="$1" ' + $2 == "name" { name = $4; next } + $2 == "sha" && name != "" { if ($4 == want) print name; name = "" }' + [ "$count" -ge 100 ] || return 0 + page=$((page + 1)) + done +} + +newest() { + sort -t. -k1.2,1nr -k2,2nr -k3,3nr | head -n "$1" +} + +# An explicit version wins. Then the action ref: a full tag is used as is; a +# commit installs the release tagged at that commit; a major (@v1) or a minor +# (@v1.2) installs the newest release inside it, followed by the one before +# it. Any other ref, a branch, gets the latest release. resolve() { - local major list + local list sha found pick if [ -n "${1:-}" ]; then echo "v${1#v}" return fi - case "$ref" in - v[0-9]*.[0-9]*.[0-9]*) + if [[ $ref =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then echo "$ref" - return - ;; - v[0-9]*) - major=${ref%%.*} - list=$(api_get "$api/repos/$repo/releases?per_page=100" | tags) || die "could not list releases of $repo" - { echo "$list" | grep -E "^${major}\.[0-9]+\.[0-9]+\$" || true; } | sort -t. -k2,2nr -k3,3nr | head -n 2 - return - ;; - esac - api_get "$api/repos/$repo/releases/latest" | tags | sed -n 1p + elif [[ $ref =~ ^v[0-9]+$ ]]; then + list=$(releases) || exit 1 + echo "$list" | grep -E "^${ref}\.[0-9]+\.[0-9]+\$" | newest 2 || true + elif [[ $ref =~ ^v[0-9]+\.[0-9]+$ ]]; then + list=$(releases) || exit 1 + echo "$list" | grep -E "^${ref%.*}\.${ref#*.}\.[0-9]+\$" | newest 2 || true + elif [[ $ref =~ ^[0-9a-fA-F]{40}$ ]]; then + sha=$(echo "$ref" | tr A-F a-f) + found=$(tagged "$sha") || exit 1 + pick=$(echo "$found" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | newest 1 || true) + [ -n "$pick" ] || pick=$(echo "$found" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+-[0-9A-Za-z.]+$' | head -n 1 || true) + [ -n "$pick" ] || die "commit $sha of $repo is not a release; pin a release commit or set the version input" + echo "$pick" + elif [[ $ref =~ ^v[0-9] ]]; then + die "action ref $ref is not a release tag; use @vN, @vN.M, @vN.M.P or a release commit, or set the version input" + else + [ -z "$ref" ] || echo "tend install: action ref $ref is not a release; installing the latest release" >&2 + api_get "$api/repos/$repo/releases/latest" | tags | sed -n 1p + fi } find_openssl() { @@ -70,9 +104,8 @@ sha256_of() { tags=$(resolve "${1:-}") tag=$(echo "$tags" | sed -n 1p) [ -n "$tag" ] || die "no release of $repo matches ${1:-${ref:-the latest release}}" -# The newest release of a major may still be uploading its files when a -# scheduled run starts; the one before it is installed instead. Either is -# checked the same way below. +# A major or minor ref falls back to the release before the newest when the +# newest has no signed checksums. Either is checked the same way below. older=$(echo "$tags" | sed -n 2p) if [ -n "$older" ] && ! curl -fsSL --retry 2 -o /dev/null "$dl/$repo/releases/download/$tag/checksums.txt.sig" 2>/dev/null; then echo "tend install: $tag has no signed checksums yet; installing $older" >&2 @@ -128,10 +161,15 @@ else fi dest=${RUNNER_TEMP:-${TMPDIR:-/tmp}}/tend/bin +entry=$dest +if [ "$os" = windows ] && command -v cygpath >/dev/null 2>&1; then + dest=$(cygpath -u "$dest") + entry=$(cygpath -w "$dest") +fi mkdir -p "$dest" install -m 0755 "$work/$bin" "$dest/$bin" if [ -n "${GITHUB_PATH:-}" ]; then - echo "$dest" >>"$GITHUB_PATH" + echo "$entry" >>"$GITHUB_PATH" else echo "add to PATH: $dest" fi diff --git a/action/install_test.sh b/action/install_test.sh index d1c811e..69c0a22 100755 --- a/action/install_test.sh +++ b/action/install_test.sh @@ -20,6 +20,8 @@ mkdir -p "$RUNNER_TEMP" out=$("$here/install.sh" "$@" 2>&1) status=$? dest="$RUNNER_TEMP/tend/bin" +bin=tend +[ "${RUNNER_OS:-}" = Windows ] && bin=tend.exe fail() { echo "FAIL: $*" >&2 @@ -31,14 +33,14 @@ fail() { case "$expect" in ok) [ "$status" -eq 0 ] || fail "exit status $status" - [ -x "$dest/tend" ] || fail "no executable at $dest/tend" - [ "$("$dest/tend")" = "$match" ] || fail "binary printed '$("$dest/tend")', want '$match'" + [ -x "$dest/$bin" ] || fail "no executable at $dest/$bin" + [ "$("$dest/$bin")" = "$match" ] || fail "binary printed '$("$dest/$bin")', want '$match'" grep -qx "$dest" "$GITHUB_PATH" || fail "GITHUB_PATH does not list $dest" ;; fail) [ "$status" -ne 0 ] || fail "install.sh succeeded" echo "$out" | grep -qF -- "$match" || fail "output does not mention '$match'" - [ ! -e "$dest/tend" ] || fail "a binary was installed anyway" + [ ! -e "$dest/$bin" ] || fail "a binary was installed anyway" [ ! -s "$GITHUB_PATH" ] || fail "GITHUB_PATH was written" ;; *) diff --git a/action/scrub.sh b/action/scrub.sh new file mode 100755 index 0000000..0dd4c06 --- /dev/null +++ b/action/scrub.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Removes the token actions/checkout left behind: the extraheader in the +# repository's config and the credentials file its includeIf entries point at. +# Only files under RUNNER_TEMP are deleted, the same rule checkout follows. +# usage: scrub.sh (in the checked-out repository) +set -uo pipefail + +unix() { + if command -v cygpath >/dev/null 2>&1; then + cygpath -u "$1" + else + printf '%s\n' "${1//\\//}" + fi +} + +temp= +[ -z "${RUNNER_TEMP:-}" ] || temp=$(unix "$RUNNER_TEMP") + +git config --local --unset-all http.https://github.com/.extraheader 2>/dev/null || true +git config --local --null --get-regexp '^includeif\..*\.path$' 2>/dev/null | while IFS= read -r -d '' entry; do + key=${entry%%$'\n'*} + val=${entry#*$'\n'} + case "$val" in + *git-credentials-*.config) + git config --local --unset-all "$key" 2>/dev/null || true + file=$(unix "$val") + if [ -n "$temp" ]; then + case "$file" in "$temp"/*) rm -f "$file" ;; esac + fi + ;; + esac +done || true +if [ -n "$temp" ]; then + rm -f "$temp"/git-credentials-*.config +fi diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 1039296..d136e29 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -43,4 +43,8 @@ global: -C --config --home -v -q ``` Exit codes: 0 done or nothing to do, 1 error, 2 usage, 3 `check --fail-on` -matched, 4 `run` could not prove the fix. +matched, 4 `run` could not prove the fix (in a GitHub Action, only with +`fail-on-unproven: true` once the change is in the tracking issue; otherwise +a warning), 5 `run` proved a change but had no +GitHub token to open its PR with, so it is only on a local branch, 130 +interrupted. diff --git a/docs/config.md b/docs/config.md index f48f7ce..d6de946 100644 --- a/docs/config.md +++ b/docs/config.md @@ -2,7 +2,9 @@ tend works with no configuration. Everything below goes in one optional file, `tend.yml` at the repo root. tend looks for `tend.yml`, then `.github/tend.yml`. -`--config ` (or `TEND_CONFIG`) names a file explicitly. +`--config ` (or `TEND_CONFIG`) names a file explicitly. A relative +`--config` is read from the directory tend runs in, after `-C`; a relative +`TEND_CONFIG` from the repository's top level. Every key is optional. An empty file is the same as no file. Unknown keys are errors, so a typo cannot quietly turn something off. `tend init` writes a file @@ -26,7 +28,8 @@ Durations use Go syntax (`20m`, `1h30m`) plus whole days (`3d`). ### base String, default `""`. The branch PRs are opened against and worktrees are cut -from. Empty means the repository's default branch. +from: a branch name, such as `develop`, not `origin/develop`. Empty means the +repository's default branch. ```yaml base: develop @@ -250,7 +253,8 @@ a decision PR when a change needs real code edits. With one, it also writes the migration for call sites no codemod covers, and the tests a catch-up's baseline needs. [how-it-works.md](how-it-works.md#what-leaves-the-machine) says what is sent. -The whole entry can be one line naming the provider and the model it serves: +The whole entry can be one line naming the provider and the model it serves, +or `none` for no model: ```yaml model: groq/openai/gpt-oss-120b @@ -263,7 +267,7 @@ model: groq/openai/gpt-oss-120b | `base_url` | string | `""` | for `openai`: any server that speaks the chat completions API. Empty means the provider's own. A key goes only over https, or over http to this machine | | `key_env` | string | `""` | name of the env var holding the API key. Empty tries `TEND_MODEL_KEY`, then the provider's usual variable (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY`). `ollama` needs none, and sends `TEND_MODEL_KEY` when it is set. `GITHUB_TOKEN`, `GH_TOKEN` and tend's own `TEND_*` variables are refused | | `command` | string | `""` | for `provider: command`: a shell line that reads the prompt on stdin and writes the reply on stdout. It runs without tokens and keys in its environment; name the one it needs in `key_env` | -| `attempts` | int | `2` | tries at a usable diff, for the `command` provider | +| `attempts` | int | `2` | tries at a diff that applies and passes the project's commands, for the `command` provider | | `turns` | int | `30` | tool calls a model with tool calling may make on one change, once more for every 10 call sites the change moves, up to five times | | `tokens` | int | `400000` | tokens it may spend on one change, prompts and replies together, scaled as `turns` is. `0` means no limit | @@ -276,8 +280,10 @@ large or old project is a lot of migration; a stronger model than the example's gets further with it. The `command` provider writes one diff instead; a reply that holds no diff, or -one that does not apply, is sent back with the reason, up to `attempts` times. -The proof then decides. +one that does not apply, is sent back with the reason, and one that applies +but fails the project's commands is taken back and sent back with their +output, up to `attempts` times. The last try's diff stays for the proof to +decide. ```yaml model: @@ -300,7 +306,7 @@ test, and stops at the first failure. | `test` | list of strings | `[]` | replaces the detected test lines | | `timeout` | duration | `20m` | for the whole run | | `container` | string | `""` | image name. When set, each command runs through `docker run` with the worktree mounted. A missing docker is an error, never a silent fallback to the host | -| `env` | list of strings | `[]` | names of env vars to pass through, for what the project's tests genuinely need. Anything that looks like a secret is removed otherwise: names containing token, secret, password, api key, private or credential, and names ending in `_KEY`, `_TOKEN`, `_SECRET`, `_PAT` or `_CREDENTIALS`. `GITHUB_TOKEN`, `GH_TOKEN` and `TEND_*` are tend's own and are refused here | +| `env` | list of strings | `[]` | names of env vars to pass through, for what the project's tests genuinely need. Anything that looks like a secret is removed otherwise: names containing token, secret, password, api key, private or credential, and names ending in `_KEY` or `_PAT`. `GITHUB_TOKEN`, `GH_TOKEN` and `TEND_*` are tend's own and are refused here. The same rule, with the same names kept, holds for the lock and bump tools tend runs itself, so a private registry's token listed here reaches them too | ```yaml verify: @@ -317,7 +323,7 @@ How the result leaves your machine. | key | type | default | meaning | |---|---|---|---| | `mode` | `pr`, `commit` | `pr` | `commit` pushes straight to `branch`, only what passed its proof, and reverts it when the repository's CI fails on it. Opt in only; it skips review | -| `branch` | string | `""` | commit mode: the branch to push to. Empty means `base` | +| `branch` | string | `""` | commit mode: the branch to push to, a branch name. Empty means `base` | | `labels` | list of strings | `[tend]` | added to every PR. Missing labels are created with color `0e8a16` | | `draft` | bool | `false` | open every PR as a draft. A PR is a draft anyway when vetting flags something or the tests already fail on the base | | `automerge` | `none`, `patch`, `minor`, `security` | `none` | turn on GitHub auto-merge for covered changes, see below | @@ -371,9 +377,9 @@ Nothing but these. | variable | use | |---|---| | `GITHUB_TOKEN`, `GH_TOKEN` | token for the GitHub API and for pushing. Without either, tend runs `gh auth token` if `gh` is installed | -| `GITHUB_REPOSITORY` | `owner/name`, used when no git remote says | -| `TEND_CONFIG` | path to the config file | -| `TEND_HOME` | state directory. Default is `tend` under the user cache dir | +| `GITHUB_REPOSITORY` | `owner/name`, used when the repo has no origin remote | +| `TEND_CONFIG` | path to the config file. A relative one is read from the repository's top level; `--config` is read from the directory tend runs in, after `-C`, as `git -C` does | +| `TEND_HOME` | state directory. Default is `tend` under the user cache dir. A relative path, here or in `--home`, is read from the directory tend runs in, after `-C` | | `TEND_LOG` | `debug` logs HTTP requests with tokens removed | | `TEND_MODEL_KEY` | API key for the model provider, after `model.key_env` | | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GROQ_API_KEY` | the providers' usual key variables, read when neither of the above is set | diff --git a/docs/github-actions.md b/docs/github-actions.md index 00150d3..7280a60 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -22,29 +22,35 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - with: {persist-credentials: false} + with: {persist-credentials: false, fetch-depth: 0} - uses: mohsensc/tend-cli@v1 with: {model-key: "${{ secrets.TEND_MODEL_KEY }}"} ``` The `model-key` line is only needed if `tend.yml` names a model. `issues: write` lets tend keep its one tracking issue; `checks: read` and -`statuses: read` let commit mode read your CI on the commits it pushed. On a private +`statuses: read` let commit mode read your CI on the commits it pushed, and +`fetch-depth: 0` gives it the history to find them; a shallow checkout is +deepened when needed, which costs a fetch. On a private repository every run uses Actions minutes. To run weekly, set `schedule: 7d` -before `tend init --ci`, or change the cron to `"17 6 * * 1"`. +before `tend init --ci`, or change the cron to `"17 6 * * 1"`. tend keeps its +state in the Actions cache, and GitHub evicts a cache nobody used for 7 days, +so a weekly run can start from scratch and forget an owed first PR; the daily +default, or a second run mid-week, avoids that. Worktrees are never cached. ## Tokens Turn on "Allow GitHub Actions to create and approve pull requests" under Settings > Actions > General, or GitHub refuses the PR. -The default `GITHUB_TOKEN` has two more limits. PRs it opens do not start -your other workflows, so your CI and auto-merge never run on them. It also -cannot push changes to `.github/workflows`, so Action bumps fail. Pass a -fine-grained token with the workflows permission, or a GitHub App token from -`actions/create-github-app-token`, as `token:` to lift both. In commit mode -this matters more: a push with the default token starts no CI, so tend has no -CI result to revert by. +The default `GITHUB_TOKEN` has one more limit: PRs it opens do not start +your other workflows, so your CI and auto-merge never run on them. Pass a +fine-grained token, or a GitHub App token from +`actions/create-github-app-token`, as `token:` to lift it. Such a token needs +the Workflows (read and write) permission too, or GitHub refuses any Action +bump that edits `.github/workflows`, and tend reports the refusal rather than +retrying. In commit mode this matters more: a push with the default token +starts no CI, so tend has no CI result to revert by. ## Inputs @@ -53,11 +59,21 @@ CI result to revert by. | `token` | `github.token` | the token tend pushes and opens PRs with | | `command` | `run` | `run` or `check` | | `args` | none | extra CLI arguments | -| `config` | `tend.yml` | path to the config | -| `version` | newest release of the action's major | the tend version to install | +| `config` | `tend.yml`, then `.github/tend.yml` | path to the config | +| `version` | the release the action ref names | the tend version to install | | `model-key` | none | the key for the model `tend.yml` names | +| `fail-on-unproven` | `false` | fail the job when tend cannot prove a change; by default it warns, lists the change in its tracking issue and tries it again when the base moves | -`@v1` moves to the newest `v1.x.y`, or to the one before it while the -newest release's files are still being uploaded, so a scheduled run never -fails on a release in progress; pin `@v1.2.3` to stay put. The action -checks the release signature before it puts the binary on the path. +`@v1` installs the newest `v1.x.y` release, or the one before it if the +newest has no signed checksums; `@v1.2` stays inside `v1.2.x`. Pin `@v1.2.3`, +or the commit that release is tagged at (`@ # v1.2.3`), to stay put: a +commit pin installs the release tagged at that commit and fails if there is +none. A branch ref installs the latest release. The action checks the release +signature before it puts the binary on the path. + +Before tend runs, the action removes the token `actions/checkout` left in the +repository's config and the credentials file it wrote under `RUNNER_TEMP`, and +it starts tend with `exec`, so no shell holding the token stays behind as +tend's parent. A process running as the runner's user can still reach tokens +in other ways, through `sudo` on hosted runners for one; set +`verify.container` to keep the project's commands away from them. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 20903f6..e30241a 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -78,7 +78,10 @@ queue belongs to one stage, by the first of these rules that matches: The stages run in that order. Fixes come first because they fix what is wrong now, and the first PR carries the test baseline the rest is proven against. Runtimes and build tools come before majors, since new majors need -new runtimes; the majors are then proven on the runtime they will ship on. +new runtimes. The proof runs on whatever runtime the runner has, or the one +`verify.container` names, not on the pin a change moves; the Proof section +says which it ran on, and warns when that is not the pinned major (see +[limitations](limitations.md)). Migrations come last, written against current libraries. Each catch-up PR carries its stage and whatever is left of the stages @@ -195,8 +198,10 @@ where the base stops; that PR opens as a draft and says so. The commands run on the host by default. A freshly bumped dependency is code that executes during the proof. On Linux, tend makes its own process unreadable to the commands it starts, so they cannot read its token from -`/proc`; on macOS and Windows, a process running as the same user can still -read tend's environment. `verify.container` is the real boundary: set it to an +`/proc`. That holds only when no process above tend holds the token too: a +launcher has to `exec` tend, as the Action does, or run it as a container's +first process. On macOS and Windows, a process running as the same user can +still read tend's environment. `verify.container` is the real boundary: set it to an image and each command runs through `docker run` with only the worktree mounted. If docker is missing the proof fails and says why; it does not fall back to the host. @@ -211,8 +216,10 @@ patch reads exist in the spec? Is the old symbol still used anywhere? Did the lockfile move more than the bump needs? Was debug output or a comment added? A Python debug print that was its block's only statement becomes `pass`. Is anything now unreferenced? Each finding is fixed, dropped, or left flagged in the -PR, and a flag makes the PR a draft. A patch that vetting changed is proven -again. +PR. A flag from symbols, fields, leftovers, lockfile, commands, scope or tests +makes the PR a draft; dead code, debug output that is not a whole statement, +and the model's answers are listed for the reviewer without holding the PR +back. A patch that vetting changed is proven again. ## Model providers @@ -223,7 +230,8 @@ once that it is running without one. With one, the call sites no codemod covers are the model's work. A model with tool calling works the change the way a person would: it reads and searches -the worktree, edits the files the change explains and their tests, and runs +the worktree, edits the files the change explains and the tests that reach +them, never the tests tend wrote, and runs your install, build and test commands, by name and never as a shell line it wrote. It is done when every command passes on the tree it leaves, not when it says so. A failed run goes back to it, and running out of `model.turns` or @@ -324,7 +332,8 @@ tend remembers things in `$TEND_HOME`, by default `~/.cache/tend` on Linux, of HTTP responses, pruned after a week; one `state.json` per repository (what was seen, what you rejected, which PR is open, how far the catch-up got, the tracking issue); spec snapshots; the logs of the -last run of each change; and the worktree while a run is in progress. Nothing +last run of each change; and the worktree while a run is in progress, which a +dry run that prepared a PR, or `--keep`, leaves until the next run. Nothing is written inside your repository. The state is a cache. Deleting it costs a few extra requests: open PRs, and diff --git a/docs/limitations.md b/docs/limitations.md index 0f14c27..def59b5 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -116,3 +116,6 @@ files. Any other host the code names is not reported. - Terraform and Helm changes are proven with `terraform validate` and `helm lint` only where those tools are installed. +- Projects locked with `bun.lock`, `bun.lockb` or `pdm.lock` are read and + listed, but tend does not bump or remove their dependencies, since it + cannot regenerate those lockfiles. diff --git a/docs/pr-anatomy.md b/docs/pr-anatomy.md index 6808551..79d6c74 100644 --- a/docs/pr-anatomy.md +++ b/docs/pr-anatomy.md @@ -106,7 +106,7 @@ reading: the one that failed, else the last that ran. If the project has no build or test command, the section says so instead of showing an empty table. Two lines under the table matter: -- "Tests already fail on `main@abc1234`, so this PR is a draft." The baseline was red before tend touched anything. The PR still opens, as a draft, with both columns visible. +- "`npm test` already fails on `main@abc1234`, so this PR is a draft." The baseline was red before tend touched anything, at the step named. The PR still opens, as a draft, with both columns visible. When the change makes that step pass, it says so instead, and the output below is the base's failure. - "The baseline could not be run." There is nothing to compare the patched column with. **Vetting.** One line per check, saying what it verified: `scope: 3 files, @@ -249,7 +249,7 @@ go: ### Deprecated -- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.* was replaced by paymentIntents.* +- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.\* was replaced by paymentIntents.\* - `src/billing.js:42` `const c = await stripe.charges.create({ amount: order.total })` → `const c = await stripe.paymentIntents.create({ amount: order.total })` - `src/billing.js:88` `return stripe.charges.retrieve(id)` → `return stripe.paymentIntents.retrieve(id)` @@ -270,8 +270,9 @@ Possibly unused, kept: these look unused, but tend cannot prove it, so they are Each comes as a pull request of its own once this one is merged, proven the same way. 2. Runtimes and build tooling + - Carried over from an earlier stage, where they could not be made or proven, and tried again here: + - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1). - `nodejs` 18.20.4 → 22.20.0 in `.nvmrc`: Node.js 18 reached end of life on 2025-04-30. - - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1). 3. Major upgrades - `vitest` 1.6.0 → 3.2.4: a new major release. 4. Migrations and replacements diff --git a/docs/self-update.md b/docs/self-update.md index 2f81bcc..9b00fc0 100644 --- a/docs/self-update.md +++ b/docs/self-update.md @@ -13,15 +13,27 @@ binary. Any mismatch aborts and changes nothing. `tend update --check` only says whether a newer release exists. `run` and `watch` look once a day and print one line on stderr when there is one; they never update by themselves. A binary built by `go install` reports the module version it was built from. +Prereleases (`v1.3.0-rc.1`) update too, to the next full release. If tend +lives in a directory you cannot write, `tend update` says so before it +downloads anything; rerun it with `sudo` or reinstall tend where you own it. The Action does the same check with `openssl` before it puts the binary on -the path. `@v1` is a moving tag that points at the newest `v1.x.y`; while that -release's files are still being uploaded, the Action installs the one before -it. Pin `@v1.2.3` to stay put. +the path. `@v1` installs the newest `v1.x.y` release, or the one before it if +the newest has no signed checksums; `@v1.2` stays inside `v1.2.x`. Pin +`@v1.2.3`, or the commit that release is tagged at, to stay put: a commit pin +installs the release tagged at that commit and fails if there is none. + +The release workflow builds with the newest Go toolchain, so the binaries +carry its security fixes, and refuses to publish when `govulncheck` reports a +reachable vulnerability or when the signature does not verify against +`action/pubkey.pem`. ## Installing by hand -On Linux or macOS: +On Linux or macOS. The `openssl` that ships with macOS is LibreSSL, which +cannot read ed25519 keys; install OpenSSL 3 with `brew install openssl@3` and +set `openssl=$(brew --prefix openssl@3)/bin/openssl`. On Linux, +`openssl=openssl`. ```sh os=$(uname -s | tr A-Z a-z) @@ -31,9 +43,9 @@ file=tend_${tag#v}_${os}_${arch}.tar.gz base=https://github.com/mohsensc/tend-cli/releases/download/$tag curl -fsSLO $base/$file -O $base/checksums.txt -O $base/checksums.txt.sig base64 -d < checksums.txt.sig > sig.bin -openssl pkeyutl -verify -pubin -inkey pubkey.pem -rawin -in checksums.txt -sigfile sig.bin +"$openssl" pkeyutl -verify -pubin -inkey pubkey.pem -rawin -in checksums.txt -sigfile sig.bin grep " $file\$" checksums.txt | sha256sum -c - # macOS: shasum -a 256 -c - -tar -xzf $file tend && install -m 0755 tend ~/.local/bin/tend +mkdir -p ~/.local/bin && tar -xzf $file tend && install -m 0755 tend ~/.local/bin/tend ``` `pubkey.pem` is [action/pubkey.pem](../action/pubkey.pem) from this @@ -46,4 +58,7 @@ the same way. ## Running on its own repository tend maintains itself: [.github/workflows/tend.yml](../.github/workflows/tend.yml) -runs it weekly on this repository, with `updates: {minor: true}`. +runs the action from this checkout twice a week on this repository, with +`updates: {minor: true}`. Its PRs start CI only when the `TEND_TOKEN` secret +holds a GitHub App or fine-grained token; with the default token, "Allow +GitHub Actions to create and approve pull requests" has to be on. diff --git a/internal/api/catalog.go b/internal/api/catalog.go index 8a42386..2871642 100644 --- a/internal/api/catalog.go +++ b/internal/api/catalog.go @@ -23,6 +23,7 @@ type Provider struct { Title string `yaml:"title"` // the name as the provider writes it: "GitHub" Hosts []string `yaml:"hosts"` Spec string `yaml:"spec"` // URL, or a path relative to the repo root + More []string `yaml:"-"` // more specs of the same API, from a spec: list, merged into Spec's Changelog string `yaml:"changelog"` // RSS, Atom or HTML page, for a provider without a spec SDKs []SDK `yaml:"sdks"` Base string `yaml:"base"` // path prefix SDK calls go under: "/v1" @@ -30,6 +31,47 @@ type Provider struct { Sunset string `yaml:"sunset"` // dotted key on an operation holding its removal date } +// UnmarshalYAML takes spec as one URL or a list of them, for an API whose +// provider splits its spec into several files. +func (p *Provider) UnmarshalYAML(n *yaml.Node) error { + type plain Provider + rest := *n + rest.Content = nil + var spec *yaml.Node + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == "spec" { + spec = n.Content[i+1] + continue + } + rest.Content = append(rest.Content, n.Content[i], n.Content[i+1]) + } + if err := rest.Decode((*plain)(p)); err != nil { + return err + } + if spec == nil { + return nil + } + if spec.Kind != yaml.SequenceNode { + return spec.Decode(&p.Spec) + } + var specs []string + if err := spec.Decode(&specs); err != nil { + return err + } + if len(specs) > 0 { + p.Spec, p.More = specs[0], specs[1:] + } + return nil +} + +// Specs are all the spec files of the provider, Spec first. +func (p *Provider) Specs() []string { + if p.Spec == "" { + return nil + } + return append([]string{p.Spec}, p.More...) +} + // Catalog is the built-in list of providers. func Catalog() []Provider { var res []Provider @@ -66,7 +108,7 @@ func Merge(cat []Provider, cfg []config.API) []Provider { res[i].Hosts = a.Hosts } if a.Spec != "" { - res[i].Spec = a.Spec + res[i].Spec, res[i].More = a.Spec, nil } if a.Changelog != "" { res[i].Changelog = a.Changelog diff --git a/internal/api/catalog_test.go b/internal/api/catalog_test.go index adce80a..7ebe64a 100644 --- a/internal/api/catalog_test.go +++ b/internal/api/catalog_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + "gopkg.in/yaml.v3" + "github.com/mohsensc/tend-cli/internal/config" "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/fetch" @@ -91,11 +93,11 @@ var recorded = map[string][]string{ "github": {"GET /repos/{owner}/{repo}", "GET /assignments/{assignment_id}"}, "openai": {"POST /v1/chat/completions"}, "twilio": {"POST /2010-04-01/Accounts/{AccountSid}/Messages.json"}, - "sendgrid": {"POST /v3/mail/send"}, + "sendgrid": {"POST /v3/mail/send", "GET /v3/marketing/contacts", "GET /v3/templates"}, "plaid": {"POST /transactions/get"}, "digitalocean": {"GET /v2/droplets"}, - "cloudflare": {"GET /client/v4/zones"}, - "datadog": {"GET /api/v1/monitor"}, + "cloudflare": {"GET /client/v4/zones", "GET /client/v4/zones/{zone_id}/cache/origin_cloud_regions"}, + "datadog": {"GET /api/v1/monitor", "GET /api/v2/logs/events"}, } const recordDir = "testdata/recorded" @@ -109,31 +111,41 @@ func TestRecord(t *testing.T) { c := fetch.New("", "test") for _, p := range Catalog() { ops := recorded[p.Name] - res, err := c.Get(context.Background(), p.Spec) - if err != nil || res.Status != 200 { - t.Errorf("%s: %s: %v %+v", p.Name, p.Spec, err, res) - continue - } - d, err := load(res.Body, p.Sunset) - if err != nil { - t.Errorf("%s: %v", p.Name, err) - continue + found := map[string]bool{} + for _, spec := range p.Specs() { + res, err := c.Get(context.Background(), spec) + if err != nil || res.Status != 200 { + t.Errorf("%s: %s: %v %+v", p.Name, spec, err, res) + continue + } + d, err := load(res.Body, p.Sunset) + if err != nil { + t.Errorf("%s: %v", p.Name, err) + continue + } + mine := []string{} + for _, k := range ops { + if d.Ops[k] != nil { + found[k] = true + mine = append(mine, k) + } + } + rec, _ := json.MarshalIndent(map[string]any{"url": spec, "status": 200, "body": string(trimSpec(d, mine))}, "", " ") + path := filepath.Join(recordDir, fetch.RecordName("GET", spec, nil)) + if err := os.WriteFile(path, append(rec, '\n'), 0o644); err != nil { + t.Fatal(err) + } } for _, k := range ops { - if d.Ops[k] == nil { + if !found[k] { t.Errorf("%s: no %s", p.Name, k) } } - rec, _ := json.MarshalIndent(map[string]any{"url": p.Spec, "status": 200, "body": string(trimSpec(d, ops))}, "", " ") - path := filepath.Join(recordDir, fetch.RecordName("GET", p.Spec, nil)) - if err := os.WriteFile(path, append(rec, '\n'), 0o644); err != nil { - t.Fatal(err) - } } } func TestRecorded(t *testing.T) { - f := fetch.Replay(recordDir) + s := &Specs{Fetch: fetch.Replay(recordDir)} docs := map[string]*Doc{} for _, p := range Catalog() { ops, ok := recorded[p.Name] @@ -141,21 +153,19 @@ func TestRecorded(t *testing.T) { t.Errorf("%s: not recorded", p.Name) continue } - fi, err := os.Stat(filepath.Join(recordDir, fetch.RecordName("GET", p.Spec, nil))) - if err != nil { - t.Error(err) - continue - } - if fi.Size() > 200<<10 { - t.Errorf("%s: recording is %d KB", p.Name, fi.Size()>>10) - } - res, err := f.Get(context.Background(), p.Spec) - if err != nil { - t.Fatal(err) + for _, spec := range p.Specs() { + fi, err := os.Stat(filepath.Join(recordDir, fetch.RecordName("GET", spec, nil))) + if err != nil { + t.Error(err) + continue + } + if fi.Size() > 200<<10 { + t.Errorf("%s: recording is %d KB", p.Name, fi.Size()>>10) + } } - d, err := load(res.Body, p.Sunset) - if err != nil { - t.Fatalf("%s: %v", p.Name, err) + d, err := s.spec(context.Background(), "", &p) + if err != nil || len(s.Notes()) > 0 { + t.Fatalf("%s: %v %q", p.Name, err, s.Notes()) } if got := slices.Sorted(maps.Keys(d.Ops)); !slices.Equal(got, slices.Sorted(maps.Keys(set(ops)))) { t.Errorf("%s: ops = %q", p.Name, got) @@ -178,6 +188,9 @@ func TestRecorded(t *testing.T) { {"digitalocean", "GET", "https://api.digitalocean.com/v2/droplets?per_page=10", "GET /v2/droplets", []string{"droplets"}}, {"cloudflare", "GET", "https://api.cloudflare.com/client/v4/zones", "GET /client/v4/zones", []string{"result"}}, {"datadog", "GET", "https://api.datadoghq.com/api/v1/monitor", "GET /api/v1/monitor", nil}, + {"datadog", "GET", "https://api.datadoghq.com/api/v2/logs/events?filter[query]=x", "GET /api/v2/logs/events", nil}, + {"sendgrid", "GET", "https://api.sendgrid.com/v3/templates?generations=dynamic", "GET /v3/templates", nil}, + {"sendgrid", "GET", "https://api.sendgrid.com/v3/marketing/contacts", "GET /v3/marketing/contacts", nil}, } for _, tt := range tests { d := docs[tt.provider] @@ -203,6 +216,10 @@ func TestRecorded(t *testing.T) { if op := docs["stripe"].Ops["GET /v1/customers/{customer}/cards"]; !op.Deprecated { t.Error("stripe: customer cards are deprecated") } + cf := docs["cloudflare"].Ops["GET /client/v4/zones/{zone_id}/cache/origin_cloud_regions"] + if !cf.Deprecated || !cf.Sunset.Equal(time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)) { + t.Errorf("cloudflare: origin cloud regions deprecated %v sunset %v", cf.Deprecated, cf.Sunset) + } gh := docs["github"].Ops["GET /assignments/{assignment_id}"] if !gh.Deprecated || !gh.Sunset.Equal(time.Date(2026, 8, 28, 0, 0, 0, 0, time.UTC)) { t.Errorf("github: assignment deprecated %v sunset %v", gh.Deprecated, gh.Sunset) @@ -258,3 +275,54 @@ func TestChangesRecorded(t *testing.T) { t.Errorf("stripe used = %q; payment_intents is not in the recording, so the guess drops out", used) } } + +func TestCloudflareSunsetKey(t *testing.T) { + p := provider(t, "cloudflare") + spec := `{"openapi": "3.0.3", "servers": [{"url": "https://api.cloudflare.com/client/v4"}], "paths": { +"/accounts/{account_id}/access/bookmarks": {"get": {"deprecated": true, "x-cfDeprecation": {"id": "b", "eol": "2023-03-19T00:00:00Z"}}}, +"/zones": {"get": {"x-cfDeprecation": {"id": "z", "description": "no date"}}}}}` + d, err := load([]byte(spec), p.Sunset) + if err != nil { + t.Fatal(err) + } + if got := d.Ops["GET /client/v4/accounts/{account_id}/access/bookmarks"].Sunset; !got.Equal(time.Date(2023, 3, 19, 0, 0, 0, 0, time.UTC)) { + t.Errorf("eol = %v", got) + } + if got := d.Ops["GET /client/v4/zones"].Sunset; !got.IsZero() { + t.Errorf("no eol = %v", got) + } +} + +func TestSpecList(t *testing.T) { + var ps []Provider + err := yaml.Unmarshal([]byte("- {name: a, hosts: [a.test], spec: [https://a.test/1.json, https://a.test/2.json], base: /v1}\n- {name: b, hosts: [b.test], spec: https://b.test/s.json}\n"), &ps) + if err != nil { + t.Fatal(err) + } + if ps[0].Spec != "https://a.test/1.json" || !slices.Equal(ps[0].More, []string{"https://a.test/2.json"}) || ps[0].Base != "/v1" || ps[0].Hosts[0] != "a.test" { + t.Errorf("a = %+v", ps[0]) + } + if ps[1].Spec != "https://b.test/s.json" || ps[1].More != nil || len(ps[1].Specs()) != 1 { + t.Errorf("b = %+v", ps[1]) + } + if got := Merge(ps, []config.API{{Name: "a", Spec: "local.yaml"}}); got[0].Spec != "local.yaml" || got[0].More != nil { + t.Errorf("a spec from tend.yml replaces them all: %+v", got[0]) + } + + one := `{"openapi": "3.0.0", "servers": [{"url": "https://a.test"}], "paths": {"/v1/x": {"get": {}}}}` + two := `{"openapi": "3.0.0", "servers": [{"url": "https://a.test"}], "paths": {"/v2/y": {"get": {}}}}` + s := &Specs{Cat: ps, Fetch: fetcher{"https://a.test/1.json": one, "https://a.test/2.json": two}} + inv := &core.Inventory{Index: &index{urls: []core.URLUse{ + {File: "a.go", Line: 1, Method: "GET", URL: "https://a.test/v1/x"}, + {File: "a.go", Line: 2, Method: "GET", URL: "https://a.test/v2/y"}, + }}} + changes(t, s, inv) + if used := s.runs["a"].used; !slices.Equal(used, []string{"GET /v1/x", "GET /v2/y"}) || len(s.Notes()) != 0 { + t.Errorf("used = %q notes %q", used, s.Notes()) + } + s.Fetch = fetcher{"https://a.test/1.json": one} + changes(t, s, inv) + if n := s.Notes(); len(n) != 2 || !strings.HasPrefix(n[0], "a: https://a.test/2.json: status 404") { + t.Errorf("a missing file is a note, the rest still checked: %q", n) + } +} diff --git a/internal/api/chains.go b/internal/api/chains.go index 7dda07c..dfbbea3 100644 --- a/internal/api/chains.go +++ b/internal/api/chains.go @@ -33,6 +33,20 @@ var aliases = map[string]string{ // to the operation it calls: POST /v1/payment_intents. The result is a guess // until the spec confirms it. func (p *Provider) Operation(chain []string, lang string) (method, path string, ok bool) { + return p.guess(chain, lang, false) +} + +// Nested is Operation's other guess for a chain of several resources, each +// below an item of the one before: customers.sources.create is POST +// /v1/customers/{id}/sources. ok is false for a chain with one resource. +func (p *Provider) Nested(chain []string, lang string) (method, path string, ok bool) { + if len(chain) < 4 { + return "", "", false + } + return p.guess(chain, lang, true) +} + +func (p *Provider) guess(chain []string, lang string, nested bool) (method, path string, ok bool) { if len(chain) < 2 { return "", "", false } @@ -46,6 +60,9 @@ func (p *Provider) Operation(chain []string, lang string) (method, path string, verb = "create" } spec, ok := p.verb(verb) + if !ok && len(chain) > 2 && verb != "new" { + spec, ok = "POST/{id}/"+snake(verb), true + } if !ok { return "", "", false } @@ -73,7 +90,11 @@ func (p *Provider) Operation(chain []string, lang string) (method, path string, if suffix != "" { suffix = "/" + suffix } - return method, strings.TrimRight(p.Base, "/") + "/" + strings.Join(segs, "/") + suffix, true + sep := "/" + if nested { + sep = "/{id}/" + } + return method, strings.TrimRight(p.Base, "/") + "/" + strings.Join(segs, sep) + suffix, true } func (p *Provider) verb(v string) (string, bool) { diff --git a/internal/api/chains_test.go b/internal/api/chains_test.go index 59ec10b..3b6a2d2 100644 --- a/internal/api/chains_test.go +++ b/internal/api/chains_test.go @@ -59,11 +59,12 @@ func TestOperation(t *testing.T) { {github, "octokit.issues.update", "js", "PATCH /issues/{id}"}, {github, "octokit.issues.send", "js", "POST /issues/{id}/send"}, - {stripe, "stripe.charges.frobnicate", "js", ""}, + {stripe, "stripe.charges.frobnicate", "js", "POST /v1/charges/{id}/frobnicate"}, + {stripe, "stripe.issuing.authorizations.approve", "js", "POST /v1/issuing/authorizations/{id}/approve"}, {stripe, "stripe.charges", "js", ""}, {stripe, "stripe", "js", ""}, {stripe, "stripe.Charge.new", "ruby", ""}, - {stripe, "stripe.webhooks.constructEvent", "js", ""}, + {stripe, "stripe.webhooks.constructEvent", "js", "POST /v1/webhooks/{id}/construct_event"}, {openai, "openai.chat.completions.update", "js", "PATCH /v1/chat/completions/{id}"}, } for _, tt := range tests { @@ -83,11 +84,18 @@ func TestOperation(t *testing.T) { func TestOperationNeedsTheSpec(t *testing.T) { stripe := provider(t, "stripe") d := &Doc{Ops: map[string]*Op{ - "POST /v1/charges": {Method: "POST", Path: "/v1/charges"}, - "GET /v1/charges/{charge}": {Method: "GET", Path: "/v1/charges/{charge}"}, - "POST /v1/payment_intents": {Method: "POST", Path: "/v1/payment_intents"}, - "GET /v1/payment_intents/{pi}": {Method: "GET", Path: "/v1/payment_intents/{pi}"}, - "POST /v1/payment_intents/{pi}": {Method: "POST", Path: "/v1/payment_intents/{pi}"}, + "POST /v1/charges": {Method: "POST", Path: "/v1/charges"}, + "GET /v1/charges/{charge}": {Method: "GET", Path: "/v1/charges/{charge}"}, + "POST /v1/payment_intents": {Method: "POST", Path: "/v1/payment_intents"}, + "GET /v1/payment_intents/{pi}": {Method: "GET", Path: "/v1/payment_intents/{pi}"}, + "POST /v1/payment_intents/{pi}": {Method: "POST", Path: "/v1/payment_intents/{pi}"}, + "POST /v1/customers/{customer}": {Method: "POST", Path: "/v1/customers/{customer}"}, + "GET /v1/customers/{customer}": {Method: "GET", Path: "/v1/customers/{customer}"}, + "POST /v1/customers/{customer}/sources": {Method: "POST", Path: "/v1/customers/{customer}/sources"}, + "POST /v1/threads/{thread_id}": {Method: "POST", Path: "/v1/threads/{thread_id}"}, + "POST /v1/threads/{thread_id}/runs": {Method: "POST", Path: "/v1/threads/{thread_id}/runs"}, + "POST /v1/checkout/sessions": {Method: "POST", Path: "/v1/checkout/sessions"}, + "GET /v1/checkout/sessions/{session}": {Method: "GET", Path: "/v1/checkout/sessions/{session}"}, }} tests := []struct { chain, lang, want string @@ -97,11 +105,25 @@ func TestOperationNeedsTheSpec(t *testing.T) { {"paymentintent.Get", "go", "GET /v1/payment_intents/{pi}"}, {"stripe.charges.del", "js", ""}, {"stripe.refunds.create", "js", ""}, + {"stripe.customers.sources.create", "js", "POST /v1/customers/{customer}/sources"}, + {"stripe.customers.balanceTransactions.create", "js", ""}, + {"stripe.customers.balanceTransactions.list", "js", ""}, + {"client.threads.runs.create", "js", "POST /v1/threads/{thread_id}/runs"}, + {"stripe.checkout.sessions.create", "js", "POST /v1/checkout/sessions"}, + {"stripe.checkout.sessions.retrieve", "js", "GET /v1/checkout/sessions/{session}"}, + {"stripe.customers.update", "js", "POST /v1/customers/{customer}"}, } for _, tt := range tests { - method, path, ok := stripe.Operation(strings.Split(tt.chain, "."), tt.lang) + chain := strings.Split(tt.chain, ".") + method, path, ok := stripe.Operation(chain, tt.lang) + op := d.find(method, path, true) + if ok && op == nil { + if method, path, ok = stripe.Nested(chain, tt.lang); ok { + op = d.find(method, path, true) + } + } got := "" - if op := d.find(method, path, true); ok && op != nil { + if ok && op != nil { got = op.Method + " " + op.Path } if got != tt.want { diff --git a/internal/api/changelog.go b/internal/api/changelog.go index 11a7c21..195d66b 100644 --- a/internal/api/changelog.go +++ b/internal/api/changelog.go @@ -1,13 +1,17 @@ package api import ( + "bytes" + "cmp" "context" "crypto/sha256" "encoding/hex" "encoding/json" "encoding/xml" + "errors" "fmt" "html" + "io" "os" "path/filepath" "regexp" @@ -48,7 +52,15 @@ func (s *Changelogs) Name() string { return "changelog" } // Notes lists the changelogs the last Changes could not read. func (s *Changelogs) Notes() []string { return slices.Clone(s.notes) } -var warns = regexp.MustCompile(`(?i)deprecat|sunset|retir|remov|end[- ]of[- ]life|discontinu|no longer (supported|available)|shut(ting)? down`) +// warns are the words that say whatever a sentence names is going away. Removal +// is not among them, since "remove" says as often that something can be removed +// or that a limit was: removed has to apply to the path itself. +var warns = regexp.MustCompile(`(?i)deprecat|sunset|retir|end[- ]of[- ]life|discontinu|no longer (supported|available)|shut(ting)? down`) + +var ( + removedAfter = regexp.MustCompile(`(?i)^[^.;,]{0,80}?\b(?:is|are|was|were|be|being|been|gets?)\s+(?:\w+\s+)?removed\b`) + removedBefore = regexp.MustCompile("(?i)\\b(?:removal of|removing|remove|removed)\\s+(?:the\\s+)?(?:(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\s+)?`?$") +) // mayWarn is looser than warns: it picks the entries worth giving to a // model, which tells the rest apart. @@ -56,6 +68,9 @@ var mayWarn = regexp.MustCompile(`(?i)deprecat|sunset|retir|remov|end[- ]of|disc var isoDay = regexp.MustCompile(`\b(20\d\d-\d\d-\d\d)\b`) +// goes are the words of a sentence that dates a removal, not a deprecation. +var goes = regexp.MustCompile(`(?i)remov|sunset|retir|shut|end[- ]of[- ]life|discontinu|no longer|going away|turn(ed|s)? off`) + type entry struct { Title, Text string At time.Time @@ -78,11 +93,15 @@ func (s *Changelogs) Changes(ctx context.Context, inv *core.Inventory) ([]core.C s.notes = append(s.notes, fmt.Sprintf("%s: changelog unavailable: %v", p.Name, err)) continue } + if len(entries) == 0 { + s.notes = append(s.notes, fmt.Sprintf("%s: changelog %s has no entries tend could read", p.Name, p.Changelog)) + continue + } paths := calledPaths(pu.URLs) news, about := fieldNews(inv.Index, p, pu.URLs, paths, entries) for _, path := range paths { for _, e := range entries { - if warned(e, path, about) { + if warned(e, path, callsTo(pu.URLs, path), about) { res = append(res, changelogChange(p, path, pu.URLs, e)) break } @@ -146,13 +165,17 @@ func (s *Changelogs) asked(ctx context.Context, idx core.ScanIndex, p Provider, continue } for _, it := range items { - path := under(it.Path, paths) + below := under(it.Path, paths) switch { case it.Field != "" && idx != nil: sites := idx.Fields(it.Field, files) if len(sites) == 0 { continue } + path := "" + if len(below) > 0 { + path = below[0] + } add(core.Change{ Kind: core.Deprecation, API: &core.APIChange{Provider: p.Name, Path: path, Field: it.Field, What: "response field deprecated"}, @@ -161,40 +184,49 @@ func (s *Changelogs) asked(ctx context.Context, idx core.ScanIndex, p Provider, Sunset: sunset(e), Sites: sites, }, it) - case it.Field == "" && path != "": - add(changelogChange(p, path, urls, e), it) + case it.Field == "": + for _, path := range below { + add(changelogChange(p, path, urls, e), it) + } } } } return res } -// under is the called path an item names: the same path, or one below a -// path the entry retires as a whole. Placeholders end a path, as they do -// in calledPaths. -func under(item string, paths []string) string { - if i := strings.IndexAny(item, "{:"); i >= 0 { +// under are the called paths an item names: the same path, the exact one +// first, or every one below a path the entry retires as a whole. Placeholders +// end a path, as they do in calledPaths. +func under(item string, paths []string) []string { + if i := strings.IndexAny(item, "{:<"); i >= 0 { item = item[:i] } item = strings.TrimSuffix(item, "/") if item == "" { - return "" + return nil } + var res []string for _, p := range paths { - if p == item || strings.HasPrefix(p, item+"/") { - return p + switch { + case p == item: + res = slices.Insert(res, 0, p) + case strings.HasPrefix(p, item+"/"): + res = append(res, p) } } - return "" + return res } // ask asks the model what an entry says is going away, or reads what it // said before. fresh reports whether the model was asked this time. func (s *Changelogs) ask(ctx context.Context, e entry) (items []item, fresh bool, err error) { sum := sha256.Sum256([]byte(e.Title + "\x00" + e.Text)) - file := filepath.Join(s.Dir, "changelog", hex.EncodeToString(sum[:8])+".json") - if b, err := os.ReadFile(file); err == nil && json.Unmarshal(b, &items) == nil { - return items, false, nil + file := "" + if s.Dir != "" { + file = filepath.Join(s.Dir, "changelog", hex.EncodeToString(sum[:8])+".json") + if b, err := os.ReadFile(file); err == nil && json.Unmarshal(b, &items) == nil { + return items, false, nil + } } reply, err := s.Model.Complete(ctx, readSystem, core.Clip(e.Title+"\n\n"+e.Text, 6000)) if err != nil { @@ -205,24 +237,27 @@ func (s *Changelogs) ask(ctx context.Context, e entry) (items []item, fresh bool } start, end := strings.IndexByte(reply, '{'), strings.LastIndexByte(reply, '}') if start < 0 || end < start { - return nil, true, fmt.Errorf("changelog: no JSON in the reply") + err = errors.New("changelog: no JSON in the reply") + } else if err = json.Unmarshal([]byte(reply[start:end+1]), &out); err != nil { + err = fmt.Errorf("changelog: %w", err) } - if err := json.Unmarshal([]byte(reply[start:end+1]), &out); err != nil { - return nil, true, fmt.Errorf("changelog: %w", err) + if err != nil { + out.Items = nil } - if s.Dir != "" { + if file != "" { b, _ := json.Marshal(out.Items) if os.MkdirAll(filepath.Dir(file), 0o755) == nil { _ = os.WriteFile(file, b, 0o644) } } - return out.Items, true, nil + return out.Items, true, err } var ( ticked = regexp.MustCompile("`([A-Za-z_][\\w.]*)`") snakeCase = regexp.MustCompile(`\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b`) pathLike = regexp.MustCompile(`/[\w/{}.:-]*`) + pathToken = regexp.MustCompile(`/[\w/{}<>.:%~-]+`) ) // fieldNews finds the entries that say a field is going away, where the code @@ -238,26 +273,26 @@ func fieldNews(idx core.ScanIndex, p Provider, urls []core.URLUse, paths []strin files := callers(urls) done := map[string]bool{} for _, e := range entries { - for _, sen := range sentence.FindAllString(e.Title+"\n"+e.Text, -1) { + for _, sen := range sentences(e.Title + "\n" + e.Text) { if !warns.MatchString(sen) { continue } for _, f := range named(sen) { - if instead.MatchString(sen[:strings.Index(sen, f)]) { + if replacement(sen[:f.at]) || after.MatchString(sen[f.end:]) { continue } - sites := idx.Fields(f, files) + sites := idx.Fields(f.name, files) if len(sites) == 0 { continue } about[sen] = true - if done[f] { + if done[f.name] { continue } - done[f] = true + done[f.name] = true c := core.Change{ Kind: core.Deprecation, - API: &core.APIChange{Provider: p.Name, Path: pathIn(sen, paths), Field: f, What: "response field deprecated"}, + API: &core.APIChange{Provider: p.Name, Path: pathIn(sen, paths, urls), Field: f.name, What: "response field deprecated"}, Evidence: []core.Evidence{{Source: "changelog", Title: e.Title, Text: core.Clip(strings.TrimSpace(e.Text), 1200), URL: p.Changelog}}, Published: e.At, Sunset: sunset(e), @@ -282,62 +317,215 @@ func callers(urls []core.URLUse) []string { return res } -// named are the field names a sentence writes, leaving out its paths. -func named(sen string) []string { - var res []string - for _, m := range ticked.FindAllStringSubmatch(sen, -1) { - f := m[1][strings.LastIndexByte(m[1], '.')+1:] - if f != "" && !slices.Contains(res, f) { - res = append(res, f) +// mention is a field a sentence names, and where: at and end take in its +// backticks. +type mention struct { + name string + at, end int +} + +// named are the field names a sentence writes, leaving out its paths. A +// dotted name, `charge.amount`, is its last part. +func named(sen string) []mention { + var res []mention + have := func(f string) bool { + return slices.ContainsFunc(res, func(m mention) bool { return m.name == f }) + } + for _, m := range ticked.FindAllStringSubmatchIndex(sen, -1) { + full := sen[m[2]:m[3]] + f := full[strings.LastIndexByte(full, '.')+1:] + if f != "" && !have(f) { + res = append(res, mention{f, m[0], m[1]}) } } - for _, f := range snakeCase.FindAllString(pathLike.ReplaceAllString(sen, " "), -1) { - if !slices.Contains(res, f) { - res = append(res, f) + blank := pathLike.ReplaceAllStringFunc(sen, func(p string) string { return strings.Repeat(" ", len(p)) }) + for _, m := range snakeCase.FindAllStringIndex(blank, -1) { + if f := blank[m[0]:m[1]]; !have(f) { + res = append(res, mention{f, m[0], m[1]}) } } return res } // pathIn is the called path a sentence names, "" when it names none. -func pathIn(sen string, paths []string) string { +func pathIn(sen string, paths []string, urls []core.URLUse) string { for _, p := range paths { - if strings.Contains(sen, p) { + if len(mentions(sen, p, callsTo(urls, p))) > 0 { return p } } return "" } -// sunset is the first date an entry gives after its own. +// sunset is the date an entry gives for the removal: the latest one after its +// own in a sentence about something going away, else the latest after its own +// anywhere. A removal comes after the deprecation it follows, and a date that +// has passed stays, since that is when it matters most. func sunset(e entry) time.Time { - for _, m := range isoDay.FindAllString(e.Text, -1) { - if t, err := time.Parse(time.DateOnly, m); err == nil && t.After(e.At) { - return t + var gone, latest time.Time + for _, sen := range sentences(e.Text) { + for _, m := range isoDay.FindAllString(sen, -1) { + t, err := time.Parse(time.DateOnly, m) + if err != nil || !t.After(e.At) { + continue + } + if t.After(latest) { + latest = t + } + if goes.MatchString(sen) && t.After(gone) { + gone = t + } } } - return time.Time{} + if !gone.IsZero() { + return gone + } + return latest } -var sentence = regexp.MustCompile(`[^.!?\n]+`) +var ( + sentenceEnd = regexp.MustCompile(`[.!?]+(?:\s+|$)|\n`) + abbrev = regexp.MustCompile(`(?i)(?:^|[\s(])(?:e\.g|i\.e|etc|vs|cf|approx|incl)$`) +) + +// sentences splits text where a sentence ends, so the dots in +// /api/files.upload, `charge.amount` and e.g. stay inside one. +func sentences(text string) []string { + var res []string + start := 0 + add := func(s string) { + if strings.TrimSpace(s) != "" { + res = append(res, s) + } + } + for _, m := range sentenceEnd.FindAllStringIndex(text, -1) { + if text[m[0]] == '.' && abbrev.MatchString(text[start:m[0]]) { + continue + } + add(text[start:m[0]]) + start = m[1] + } + add(text[start:]) + return res +} // warned reports whether an entry says path is going away: one sentence names -// it and a word like deprecated or removed, and does not name it as the thing -// to move to ("use /v2/items instead") or only as where a field lives. -func warned(e entry, path string, about map[string]bool) bool { - for _, s := range sentence.FindAllString(e.Title+"\n"+e.Text, -1) { - i := strings.Index(s, path) - if i < 0 || !warns.MatchString(s) || about[s] { +// it and a word like deprecated, or says it is removed, and does not name it +// as the thing to move to ("use /v2/items instead") or only as where a field +// lives. calls are the URLs the code calls path with, for a sentence that +// names an operation below it. +func warned(e entry, path string, calls []core.URLUse, about map[string]bool) bool { + for _, s := range sentences(e.Title + "\n" + e.Text) { + if about[s] { continue } - if !instead.MatchString(s[:i]) { - return true + for _, m := range mentions(s, path, calls) { + if replacement(s[:m[0]]) { + continue + } + if warns.MatchString(s) || removedAfter.MatchString(s[m[1]:]) || removedBefore.MatchString(s[:m[0]]) { + return true + } } } return false } -var instead = regexp.MustCompile(`(?i)\b(use|try|switch(ing)? to|migrat(e|ing) to|mov(e|ing) to|in favou?r of|replaced by|instead of)\s+\S*\s*$`) +// mentions are where a sentence names path, as [start, end) pairs. A path is +// a whole token: /v1/items, or /v1/items/ with one placeholder after it. +// A token that goes on past a placeholder, /v1/users/{id}/tokens, names that +// deeper operation, which only a call of the same shape makes. +func mentions(sen, path string, calls []core.URLUse) [][2]int { + var res [][2]int + for _, loc := range pathToken.FindAllStringIndex(sen, -1) { + tok := strings.TrimRight(sen[loc[0]:loc[1]], ".:-~") + end := loc[0] + len(tok) + if rest, ok := strings.CutPrefix(tok, "//"); ok { + i := strings.IndexByte(rest, '/') + if i < 0 { + continue + } + tok = rest[i:] + } + if len(tok) > 1 { + tok = strings.TrimRight(tok, "/") + } + segs := strings.Split(tok, "/") + cut := len(segs) + for i, sg := range segs { + if placeholder(sg) { + cut = i + break + } + } + if strings.Join(segs[:cut], "/") != path { + continue + } + if len(segs)-cut <= 1 || slices.ContainsFunc(calls, func(u core.URLUse) bool { return shaped(segs, u.URL) }) { + res = append(res, [2]int{loc[0], end}) + } + } + return res +} + +func placeholder(seg string) bool { + return seg != "" && strings.ContainsAny(seg[:1], "{<:") +} + +// shaped reports whether a called URL has the segments of a path a changelog +// writes, a placeholder on either side standing for any one segment. +func shaped(segs []string, lit string) bool { + p := lit + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + if _, rest, ok := strings.Cut(p, "://"); ok { + _, p, _ = strings.Cut(rest, "/") + p = "/" + p + } + if len(p) > 1 { + p = strings.TrimRight(p, "/") + } + called := strings.Split(p, "/") + if len(called) != len(segs) { + return false + } + for i, sg := range segs { + c := called[i] + if sg != c && !placeholder(sg) && !strings.ContainsAny(c, "%{$<:") { + return false + } + } + return true +} + +// callsTo are the calls whose called path is path. +func callsTo(urls []core.URLUse, path string) []core.URLUse { + var res []core.URLUse + for _, u := range urls { + if slices.Equal(calledPaths([]core.URLUse{u}), []string{path}) { + res = append(res, u) + } + } + return res +} + +const filler = `(?:(?:the|a|an|new|newer|updated|replacement)\s+){0,2}(?:(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+)?` + "`?" + +var ( + instead = regexp.MustCompile(`(?i)\b(?:use|try|switch(?:ing)?(?: over)? to|migrat(?:e|ing) to|mov(?:e|ing) to|upgrad(?:e|ing) to|in favou?r of|replaced (?:by|with))\s+` + filler + `$`) + insteadOf = regexp.MustCompile(`(?i)\binstead of\b[^;]*,\s*(?:please\s+)?(?:call|use|send|request|read)\s+` + filler + `$`) + after = regexp.MustCompile("^`?\\s*(?i:instead|in (?:its|their) place|takes (?:its|their) place|replaces)\\b") +) + +// replacement reports whether the text before a path or field names it as the +// thing to move to: "use the new /v2/items", "in favor of `total`". Only its +// own clause counts, so "/v1/items is deprecated; use /v2/items" names both +// right. The words after "instead of" or "in place of" are the old thing. +func replacement(before string) bool { + clause := before[strings.LastIndexAny(before, ";,")+1:] + return instead.MatchString(clause) || insteadOf.MatchString(before) +} // calledPaths are the literal paths the code calls, cut where a value is // put together: "/v2/items/%s" is called as "/v2/items". @@ -363,10 +551,8 @@ func calledPaths(urls []core.URLUse) []string { func changelogChange(p Provider, path string, urls []core.URLUse, e entry) core.Change { var sites []core.Site - for _, u := range urls { - if strings.Contains(u.URL, path) { - sites = append(sites, core.Site{File: u.File, Line: u.Line, Text: strings.TrimSpace(u.Method + " " + u.URL)}) - } + for _, u := range callsTo(urls, path) { + sites = append(sites, core.Site{File: u.File, Line: u.Line, Text: cmp.Or(u.Text, strings.TrimSpace(u.Method+" "+u.URL))}) } c := core.Change{ Kind: core.Deprecation, @@ -405,30 +591,84 @@ func feed(b []byte) ([]entry, bool) { Date string `xml:"pubDate"` } `xml:"channel>item"` Entries []struct { - Title string `xml:"title"` - Summary string `xml:"summary"` - Content string `xml:"content"` - Updated string `xml:"updated"` + Title string `xml:"title"` + Summary string `xml:"summary"` + Content string `xml:"content"` + Published string `xml:"published"` + Updated string `xml:"updated"` } `xml:"entry"` } - if xml.Unmarshal(b, &doc) != nil || doc.XMLName.Local != "rss" && doc.XMLName.Local != "feed" { + dec := xml.NewDecoder(bytes.NewReader(b)) + dec.CharsetReader = charset + if dec.Decode(&doc) != nil || doc.XMLName.Local != "rss" && doc.XMLName.Local != "feed" { return nil, false } var res []entry for _, it := range doc.Items { - at, err := time.Parse(time.RFC1123Z, it.Date) - if err != nil { - at, _ = time.Parse(time.RFC1123, it.Date) // "GMT" in place of "+0000" - } - res = append(res, entry{it.Title, text(it.Desc), at}) + res = append(res, entry{it.Title, text(it.Desc), pubDate(it.Date)}) } for _, e := range doc.Entries { - at, _ := time.Parse(time.RFC3339, e.Updated) + at, err := time.Parse(time.RFC3339, strings.TrimSpace(e.Published)) + if err != nil { + at, _ = time.Parse(time.RFC3339, strings.TrimSpace(e.Updated)) + } res = append(res, entry{e.Title, text(e.Summary + "\n" + e.Content), at}) } return res, true } +// rssDates are the RFC 822 dates feeds write, the day in one digit or two, +// the weekday there or not, the zone a name or an offset. +var rssDates = []string{ + "Mon, 2 Jan 2006 15:04:05 -0700", + "Mon, 2 Jan 2006 15:04:05 MST", + "2 Jan 2006 15:04:05 -0700", + "2 Jan 2006 15:04:05 MST", + "Mon, 2 Jan 2006 15:04 -0700", + "Mon, 2 Jan 2006 15:04 MST", +} + +func pubDate(s string) time.Time { + s = strings.TrimSpace(s) + for _, layout := range rssDates { + if t, err := time.Parse(layout, s); err == nil { + return t + } + } + return time.Time{} +} + +// charset reads the single-byte encodings feeds still declare, so a Latin-1 +// feed is not taken for a page with no entries. +func charset(label string, r io.Reader) (io.Reader, error) { + var high *[32]rune + switch strings.ToLower(label) { + case "iso-8859-1", "iso8859-1", "latin1", "latin-1", "us-ascii", "ascii": + case "windows-1252", "cp1252": + high = &cp1252 + default: + return nil, fmt.Errorf("changelog: charset %s", label) + } + b, err := io.ReadAll(r) + if err != nil { + return nil, err + } + var out strings.Builder + for _, c := range b { + if high != nil && c >= 0x80 && c < 0xa0 && high[c-0x80] != 0 { + out.WriteRune(high[c-0x80]) + continue + } + out.WriteRune(rune(c)) + } + return strings.NewReader(out.String()), nil +} + +var cp1252 = [32]rune{ + '€', 0, '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', 0, 'Ž', 0, + 0, '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', 0, 'ž', 'Ÿ', +} + var ( heading = regexp.MustCompile(`(?is)]*>(.*?)`) tag = regexp.MustCompile(`(?s)<[^>]+>`) diff --git a/internal/api/changelog_test.go b/internal/api/changelog_test.go index 05af65d..a2d0701 100644 --- a/internal/api/changelog_test.go +++ b/internal/api/changelog_test.go @@ -135,6 +135,7 @@ func TestChangelogsReadByModel(t *testing.T) { inv := &core.Inventory{ Providers: []core.ProviderUse{{Provider: "acme", URLs: []core.URLUse{ {File: "src/a.js", Line: 3, URL: "https://api.acme.test/v1/things/list"}, + {File: "src/b.js", Line: 5, URL: "https://api.acme.test/v1/things/search"}, {File: "src/a.js", Line: 9, URL: "https://api.acme.test/v1/orders"}, }}}, Index: &index{fields: []core.Site{field("src/a.js", 12, "legacy_total")}}, @@ -152,13 +153,16 @@ func TestChangelogsReadByModel(t *testing.T) { for _, c := range got { ids = append(ids, c.ID+" "+c.Sunset.Format(time.DateOnly)) } - want := []string{"api/acme//v1/things/list 2027-03-31", "api/acme//v1/orders#legacy_total 0001-01-01"} + want := []string{"api/acme//v1/things/list 2027-03-31", "api/acme//v1/things/search 2027-03-31", "api/acme//v1/orders#legacy_total 0001-01-01"} if !slices.Equal(ids, want) { t.Fatalf("changes = %q, want %q", ids, want) } if title := got[0].Evidence[0].Title; title != "The Things API retires (as fake read it)" { t.Errorf("evidence title = %q", title) } + if s := got[1].Sites; len(s) != 1 || s[0].File != "src/b.js" { + t.Errorf("each called path has its own sites: %+v", s) + } if m.calls != 2 { t.Errorf("the model was asked %d times; only entries that warn go to it", m.calls) } @@ -247,3 +251,175 @@ func TestChangelogsOneFails(t *testing.T) { t.Errorf("notes from an earlier run were kept: %q, %v", s.Notes(), err) } } + +func TestWarned(t *testing.T) { + tests := []struct { + sentence, path string + calls []string + want bool + }{ + {"/v1/things is deprecated and will be removed on 2027-01-31.", "/v1/things", nil, true}, + {"/v1/things and every endpoint under it will be removed in March.", "/v1/things", nil, true}, + {"Removal of /v1/things is planned for March.", "/v1/things", nil, true}, + {"We removed GET /v1/things.", "/v1/things", nil, true}, + {"GET /v1/items/ is deprecated.", "/v1/items", nil, true}, + {"See https://api.acme.test/v1/items, which is deprecated.", "/v1/items", nil, true}, + {"You can now remove labels with DELETE /v1/labels.", "/v1/labels", nil, false}, + {"Removed the 100-item limit on /v1/orders.", "/v1/orders", nil, false}, + {"We removed a bug where /v1/charges returned 500.", "/v1/charges", nil, false}, + {"/v1/users/{id}/legacy-tokens is deprecated.", "/v1/users", []string{"https://api.acme.test/v1/users/%s"}, false}, + {"/v1/users/{id}/legacy-tokens is deprecated.", "/v1/users", []string{"https://api.acme.test/v1/users/%s/legacy-tokens"}, true}, + {"/v2/items-archive is deprecated", "/v2/items", nil, false}, + {"/v3/legacy-report is no longer supported after 2026-09-30.", "/v3/report", nil, false}, + {"/api/files.upload is deprecated and will be removed.", "/api/files.upload", nil, true}, + {"The /v1/reports.json endpoint is deprecated.", "/v1/reports.json", nil, true}, + {"Deprecated, e.g. /v1/old is going away soon.", "/v1/old", nil, true}, + {"/v1/items is deprecated; use the new /v2/items endpoint.", "/v2/items", nil, false}, + {"/v1/items is deprecated; use the new /v2/items endpoint.", "/v1/items", nil, true}, + {"/v1/items is deprecated in favor of the new /v2/items.", "/v2/items", nil, false}, + {"Use /v2/items instead of /v1/items, which is deprecated.", "/v1/items", nil, true}, + {"Use /v2/items instead of /v1/items, which is deprecated.", "/v2/items", nil, false}, + {"Instead of /v1/items, which is deprecated, call /v2/items.", "/v1/items", nil, true}, + {"Instead of /v1/items, which is deprecated, call /v2/items.", "/v2/items", nil, false}, + {"Use of /v1/items is deprecated.", "/v1/items", nil, true}, + {"Calls that use the legacy /v1/items endpoint are deprecated.", "/v1/items", nil, true}, + } + for _, tt := range tests { + var calls []core.URLUse + for _, u := range tt.calls { + calls = append(calls, core.URLUse{File: "a.js", Line: 1, URL: u}) + } + if got := warned(entry{Text: tt.sentence}, tt.path, calls, map[string]bool{}); got != tt.want { + t.Errorf("warned(%q, %s) = %v, want %v", tt.sentence, tt.path, got, tt.want) + } + } +} + +func TestFieldNewsPhrasing(t *testing.T) { + tests := []struct { + text string + want []string + }{ + {"The `charge.amount` field is deprecated.", []string{"amount"}}, + {"The `amount` field is deprecated.", []string{"amount"}}, + {"`total_cents` is deprecated; use `total` instead.", []string{"total_cents"}}, + {"Deprecated: use `total` instead of `total_cents`.", []string{"total_cents"}}, + {"`total_cents` is deprecated; use the new `total`.", []string{"total_cents"}}, + {"`total_cents` is deprecated in favor of the new `total`.", []string{"total_cents"}}, + {"Instead of `total_cents`, which is deprecated, read `total`.", []string{"total_cents"}}, + {"The field `total_cents` is deprecated, e.g. on orders, and `total` takes its place.", []string{"total_cents"}}, + } + for _, tt := range tests { + idx := &index{fields: []core.Site{field("app.py", 1, "total_cents"), field("app.py", 2, "total"), field("app.py", 3, "amount")}} + urls := []core.URLUse{{File: "app.py", Line: 7, URL: "https://orders.test/v1/orders"}} + got, _ := fieldNews(idx, Provider{Name: "orders"}, urls, calledPaths(urls), []entry{{Text: tt.text}}) + var have []string + for _, c := range got { + have = append(have, c.API.Field) + } + if !slices.Equal(have, tt.want) { + t.Errorf("%q: fields %q, want %q", tt.text, have, tt.want) + } + } +} + +func TestChangelogSites(t *testing.T) { + feed := `Items/v2/items is deprecated.` + cat := []Provider{{Name: "acme", Hosts: []string{"api.acme.test"}, Changelog: "https://acme.test/changes.rss"}} + inv := &core.Inventory{Providers: []core.ProviderUse{{Provider: "acme", URLs: []core.URLUse{ + {File: "a.js", Line: 3, URL: "https://api.acme.test/v2/items"}, + {File: "a.js", Line: 4, URL: "https://api.acme.test/v2/items/%s"}, + {File: "a.js", Line: 5, URL: "https://api.acme.test/v2/items-archive"}, + }}}} + got, err := (&Changelogs{Cat: cat, Fetch: fetcher{"https://acme.test/changes.rss": feed}}).Changes(context.Background(), inv) + if err != nil || len(got) != 1 { + t.Fatalf("got %+v, %v", got, err) + } + var lines []int + for _, s := range got[0].Sites { + lines = append(lines, s.Line) + } + if !slices.Equal(lines, []int{3, 4}) { + t.Errorf("sites = %v; a call to /v2/items-archive is not one to /v2/items", lines) + } +} + +func TestUnder(t *testing.T) { + paths := []string{"/v1/things", "/v1/things/list", "/v1/things/search", "/v1/thingsx"} + tests := map[string][]string{ + "/v1/things": {"/v1/things", "/v1/things/list", "/v1/things/search"}, + "/v1/things/{id}": {"/v1/things", "/v1/things/list", "/v1/things/search"}, + "/v1/things/search/": {"/v1/things/search"}, + "/v2": nil, + "": nil, + } + for item, want := range tests { + if got := under(item, paths); !slices.Equal(got, want) { + t.Errorf("under(%q) = %q, want %q", item, got, want) + } + } +} + +func TestSunset(t *testing.T) { + sep := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC) + tests := []struct { + text string + at time.Time + want string + }{ + {"Deprecated on 2024-01-05, removed 2027-03-01.", time.Time{}, "2027-03-01"}, + {"Deprecated on 2026-10-05. It is removed on 2027-03-01. Docs updated 2027-04-01.", sep, "2027-03-01"}, + {"Removed on 2025-06-01.", time.Time{}, "2025-06-01"}, + {"Deprecated. Migrate by 2027-01-01.", sep, "2027-01-01"}, + {"Deprecated on 2026-08-01.", sep, "0001-01-01"}, + } + for _, tt := range tests { + if got := sunset(entry{Text: tt.text, At: tt.at}).Format(time.DateOnly); got != tt.want { + t.Errorf("sunset(%q) = %s, want %s", tt.text, got, tt.want) + } + } +} + +func TestFeedFormats(t *testing.T) { + latin := "\nCaf\xe9Mon, 6 Oct 2026 10:00:00 GMT" + + "b6 Oct 2026 10:00:00 +0200" + got, ok := feed([]byte(latin)) + if !ok || len(got) != 2 || got[0].Title != "Café" { + t.Fatalf("feed = %+v, %v", got, ok) + } + if want := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC); !got[0].At.Equal(want) || !got[1].At.Equal(want.Add(-2*time.Hour)) { + t.Errorf("dates = %v, %v", got[0].At, got[1].At) + } + cp := "\x93a\x94" + if got, ok := feed([]byte(cp)); !ok || got[0].Title != "\u201ca\u201d" { + t.Errorf("windows-1252 = %+v", got) + } + atom := `a2026-08-01T00:00:00Z2026-09-01T00:00:00Z` + if got, ok := feed([]byte(atom)); !ok || got[0].At.Month() != time.August { + t.Errorf("atom = %+v", got) + } +} + +func TestChangelogNoEntries(t *testing.T) { + cat := []Provider{{Name: "acme", Hosts: []string{"api.acme.test"}, Changelog: "https://acme.test/changes"}} + inv := &core.Inventory{Providers: []core.ProviderUse{{Provider: "acme", URLs: []core.URLUse{{File: "a.js", Line: 3, URL: "https://api.acme.test/v1/things"}}}}} + s := &Changelogs{Cat: cat, Fetch: fetcher{"https://acme.test/changes": "

nothing here

"}} + if _, err := s.Changes(context.Background(), inv); err != nil { + t.Fatal(err) + } + if n := s.Notes(); len(n) != 1 || n[0] != "acme: changelog https://acme.test/changes has no entries tend could read" { + t.Errorf("notes = %q", n) + } +} + +func TestAskKeepsBadReplies(t *testing.T) { + m := &reader{replies: map[string]string{"Odd": "I could not read that."}} + s := &Changelogs{Model: m, Dir: t.TempDir()} + e := entry{Title: "Odd", Text: "Something is deprecated."} + if _, fresh, err := s.ask(context.Background(), e); err == nil || !fresh { + t.Fatalf("a reply with no JSON should fail once: %v %v", fresh, err) + } + if items, fresh, err := s.ask(context.Background(), e); err != nil || fresh || len(items) != 0 || m.calls != 1 { + t.Errorf("a bad reply should cost one call: %v %v %v %d", items, fresh, err, m.calls) + } +} diff --git a/internal/api/conform.go b/internal/api/conform.go index 733daad..d1f1f2a 100644 --- a/internal/api/conform.go +++ b/internal/api/conform.go @@ -37,6 +37,11 @@ type Specs struct { Fetch core.Fetcher Dir string // snapshots, one .json each Now func() time.Time + // Done reports whether a change has been dealt with: delivered, rejected or + // ignored. A field's type change that was is no longer reported, and + // Snapshot lets it go, since code fixed for the new type reads the field + // just as before. Nil means none was. + Done func(id string) bool notes []string runs map[string]*run @@ -46,7 +51,12 @@ type Specs struct { type run struct { cur, old *Doc used []string - pinned map[string]bool // ops whose breaking changes must survive the next snapshot + pinned map[string][]pin // by op: the breaking changes that must survive the next snapshot +} + +// pin is one breaking change the snapshot keeps the old side of. +type pin struct { + What, Field, Detail, ID string } var _ core.Source = (*Specs)(nil) @@ -94,13 +104,13 @@ func (s *Specs) Changes(ctx context.Context, inv *core.Inventory) ([]core.Change if n := len(cur.Missing); n > 0 { s.note("%s: %d unresolved $ref in the spec, first %s", p.Name, n, cur.Missing[0]) } - r := &run{cur: cur, old: s.snapshot(p.Name), pinned: map[string]bool{}} + r := &run{cur: cur, old: s.snapshot(p.Name), pinned: map[string][]pin{}} s.runs[p.Name] = r used := s.usages(p, pu, r) for _, u := range used { r.used = append(r.used, u.Method+" "+u.Path) } - for _, c := range check(p, inv.Index, used, r) { + for _, c := range check(p, inv.Index, used, r, s.Done) { if prev, ok := byID[c.ID]; ok { c = combine(*prev, c) } @@ -122,24 +132,58 @@ func (s *Specs) spec(ctx context.Context, root string, p *Provider) (*Doc, error if p.Spec == "" { return nil, errors.New("no spec configured") } - if !remote(p.Spec) { - b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(p.Spec))) + res, err := s.load(ctx, root, p.Spec, p.Sunset) + if err != nil { + return nil, err + } + for _, more := range p.More { + d, err := s.load(ctx, root, more, p.Sunset) + if err != nil { + s.note("%s: %v", p.Name, err) + continue + } + res = join(res, d) + } + return res, nil +} + +func (s *Specs) load(ctx context.Context, root, spec, sunset string) (*Doc, error) { + if !remote(spec) { + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(spec))) if err != nil { return nil, err } - return load(b, p.Sunset) + return load(b, sunset) } if s.Fetch == nil { return nil, errors.New("no fetcher") } - res, err := s.Fetch.Get(ctx, p.Spec, fetch.TTL(specTTL)) + res, err := s.Fetch.Get(ctx, spec, fetch.TTL(specTTL)) if err != nil { return nil, err } if res.Status != 200 { - return nil, fmt.Errorf("%s: status %d", p.Spec, res.Status) + return nil, fmt.Errorf("%s: status %d", spec, res.Status) } - return load(res.Body, p.Sunset) + return load(res.Body, sunset) +} + +// join adds the operations of another file of the same API to d. Each op is +// resolved already, so the schemas, which may clash by name across files, stay +// d's own. A base the files do not share is no base. +func join(d, more *Doc) *Doc { + res := *d + res.Ops = maps.Clone(d.Ops) + for k, o := range more.Ops { + if _, ok := res.Ops[k]; !ok { + res.Ops[k] = o + } + } + if res.Base != more.Base { + res.Base = "" + } + res.Missing = slices.Compact(slices.Sorted(slices.Values(append(slices.Clone(d.Missing), more.Missing...)))) + return &res } func remote(spec string) bool { @@ -170,9 +214,10 @@ func (s *Specs) snapshot(provider string) *Doc { } // Snapshot records the operations the last Changes saw in use, as doc has them, -// for the next run to diff against. An operation with an unresolved breaking -// change keeps its old version, so the change stays visible until the code no -// longer depends on it. Call it only after a run completed, so a crash never +// for the next run to diff against. The part of an operation with an unresolved +// breaking change keeps its old version, so the change stays visible until the +// code no longer depends on it, or, for a field whose type changed, until Done +// says it was dealt with. Call it only after a run completed, so a crash never // loses the old snapshot. func (s *Specs) Snapshot(provider string, doc *Doc) error { r := s.runs[provider] @@ -186,8 +231,8 @@ func (s *Specs) Snapshot(provider string, doc *Doc) error { snap := &Doc{Version: doc.Version, Base: doc.Base, Ops: map[string]*Op{}, At: now()} for _, k := range r.used { o := doc.Ops[k] - if old := op(r.old, k); old != nil && (o == nil || r.pinned[k]) { - o = old + if old := op(r.old, k); old != nil { + o = s.keep(o, old, r.pinned[k]) } if o != nil { snap.Ops[k] = o @@ -207,6 +252,122 @@ func (s *Specs) Snapshot(provider string, doc *Doc) error { return nil } +// keep is cur with the old side of each pinned change put back. +func (s *Specs) keep(cur, old *Op, pins []pin) *Op { + if cur == nil { + return old + } + if len(pins) == 0 { + return cur + } + cp := *cur + cp.Params = slices.Clone(cur.Params) + for _, p := range pins { + switch p.What { + case "operation removed": + return old + case "parameter removed": + i := slices.IndexFunc(old.Params, func(x Param) bool { return x.Name == p.Field && x.In == p.Detail }) + if i >= 0 && !slices.ContainsFunc(cp.Params, func(x Param) bool { return x.Name == p.Field && x.In == p.Detail }) { + cp.Params = append(cp.Params, old.Params[i]) + } + case "required parameter added": + if p.Detail == "body" { + if cp.Request != nil && (old.Request == nil || !slices.Contains(old.Request.Required, p.Field)) { + req := *cp.Request + req.Required = slices.DeleteFunc(slices.Clone(req.Required), func(n string) bool { return n == p.Field }) + cp.Request = &req + } + continue + } + same := func(x Param) bool { return x.Name == p.Field && x.In == p.Detail } + cp.Params = slices.DeleteFunc(cp.Params, same) + if i := slices.IndexFunc(old.Params, same); i >= 0 { + cp.Params = append(cp.Params, old.Params[i]) + } + case "request field removed": + cp.Request = graft(cp.Request, old.Request, p.Field) + case "response field type changed": + if s.Done != nil && s.Done(p.ID) { + continue + } + cp.Response = graft(cp.Response, old.Response, p.Field) + case "response field removed": + cp.Response = graft(cp.Response, old.Response, p.Field) + } + } + slices.SortFunc(cp.Params, func(a, b Param) int { return strings.Compare(a.In+" "+a.Name, b.In+" "+b.Name) }) + return &cp +} + +// graft is cur with the field old has under name, found the way walk finds +// it, put back where old has it. cur is copied, never changed, along the way. +func graft(cur, old *Schema, name string) *Schema { + path, v := locate(old, name) + if v == nil { + return cur + } + return put(cur, old, path, v) +} + +// locate is where walk first meets name in s: the property names down to it, +// "" for an array's items. +func locate(s *Schema, name string) ([]string, *Schema) { + type node struct { + s *Schema + path []string + } + queue := []node{{s, nil}} + for len(queue) > 0 { + curr := queue[0] + queue = queue[1:] + if curr.s == nil || len(curr.path) >= depth { + continue + } + if curr.s.Items != nil { + queue = append(queue, node{curr.s.Items, append(slices.Clone(curr.path), "")}) + } + for _, k := range slices.Sorted(maps.Keys(curr.s.Props)) { + path := append(slices.Clone(curr.path), k) + if k == name { + return path, curr.s.Props[k] + } + queue = append(queue, node{curr.s.Props[k], path}) + } + } + return nil, nil +} + +func put(cur, old *Schema, path []string, v *Schema) *Schema { + if len(path) == 0 { + return v + } + var cp Schema + if cur != nil { + cp = *cur + } else if old != nil { + cp = Schema{Type: old.Type} + } + var next *Schema + if old != nil { + next = old.Items + if path[0] != "" { + next = old.Props[path[0]] + } + } + if path[0] == "" { + cp.Items = put(cp.Items, next, path[1:], v) + return &cp + } + props := maps.Clone(cp.Props) + if props == nil { + props = map[string]*Schema{} + } + props[path[0]] = put(props[path[0]], next, path[1:], v) + cp.Props = props + return &cp +} + // usages maps every URL literal and SDK call of a provider to an operation in // the current spec, else the snapshot. SDK chains are guesses and drop out // quietly, and so do path literals, whose host is only a guess from the file @@ -236,11 +397,18 @@ func (s *Specs) usages(p *Provider, pu core.ProviderUse, r *run) []Usage { if !site.Call { continue } - method, path, ok := p.Operation(site.Chain, scan.Lang(site.File)) + lang := scan.Lang(site.File) + method, path, ok := p.Operation(site.Chain, lang) if !ok { continue } - if o := lookup(r, method, path, true); o != nil { + o := lookup(r, method, path, true) + if o == nil { + if method, path, ok = p.Nested(site.Chain, lang); ok { + o = lookup(r, method, path, true) + } + } + if o != nil { us := at(o) us.Sites = append(us.Sites, site) us.Files = append(us.Files, site.File) @@ -296,7 +464,10 @@ func lookup(r *run, method, path string, loose bool) *Op { } // check turns the used operations of one provider into changes. -func check(p *Provider, idx core.ScanIndex, used []Usage, r *run) []core.Change { +func check(p *Provider, idx core.ScanIndex, used []Usage, r *run, done func(id string) bool) []core.Change { + if done == nil { + done = func(string) bool { return false } + } reads := func(name string, files []string) []core.Site { if idx == nil { return nil @@ -316,7 +487,7 @@ func check(p *Provider, idx core.ScanIndex, used []Usage, r *run) []core.Change add := func(o *Op, kind core.Kind, what, field string, sites []core.Site) { c := change(p, r, u, o, kind, what, field, mine, sites) if kind == core.Breaking { - r.pinned[key] = true + r.pin(key, what, field, c.ID, mine) } res = append(res, c) } @@ -351,9 +522,13 @@ func check(p *Provider, idx core.ScanIndex, used []Usage, r *run) []core.Change if named { add(cur, core.Breaking, l.What, l.Field, hits) } - case "response field removed", "response field type changed": + case "response field removed": if len(hits) > 0 { - add(cur, core.Breaking, "response field removed", l.Field, hits) + add(cur, core.Breaking, l.What, l.Field, hits) + } + case "response field type changed": + if len(hits) > 0 && !done(core.ChangeID(&core.Change{API: &core.APIChange{Provider: p.Name, Method: u.Method, Path: u.Path, Field: l.Field}})) { + add(cur, core.Breaking, l.What, l.Field, hits) } case "required parameter added": if !named { @@ -365,6 +540,20 @@ func check(p *Provider, idx core.ScanIndex, used []Usage, r *run) []core.Change return res } +// pin keeps the old side of a breaking change, and of every diff line behind it, +// in the next snapshot. +func (r *run) pin(key, what, field, id string, lines []Line) { + if field == "" { + r.pinned[key] = append(r.pinned[key], pin{What: what, ID: id}) + return + } + for _, l := range lines { + if l.Field == field && l.What == what { + r.pinned[key] = append(r.pinned[key], pin{What: l.What, Field: l.Field, Detail: l.Detail, ID: id}) + } + } +} + // query reports whether a URL literal of u sets the parameter in its query string. func query(u Usage, name string) bool { for _, x := range u.URLs { @@ -415,7 +604,7 @@ func change(p *Provider, r *run, u Usage, o *Op, kind core.Kind, what, field str func sites(u Usage, extra []core.Site) []core.Site { res := slices.Clone(u.Sites) for _, x := range u.URLs { - res = append(res, core.Site{File: x.File, Line: x.Line, Text: strings.TrimSpace(x.Method + " " + x.URL)}) + res = append(res, core.Site{File: x.File, Line: x.Line, Text: cmp.Or(x.Text, strings.TrimSpace(x.Method+" "+x.URL))}) } res = append(res, extra...) slices.SortFunc(res, func(a, b core.Site) int { diff --git a/internal/api/conform_test.go b/internal/api/conform_test.go index 8109ad1..b5d71c2 100644 --- a/internal/api/conform_test.go +++ b/internal/api/conform_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "flag" "fmt" + "maps" "os" "path/filepath" "slices" @@ -434,3 +435,135 @@ func TestCombine(t *testing.T) { } } } + +func TestTypeChangePinnedUntilDone(t *testing.T) { + v1 := read(t, "testdata/fixture/v1.yaml") + retyped := strings.Replace(v1, "total_cents: {type: integer}", "total_cents: {type: string}", 1) + inv := pyAPI(nil, "total_cents") + s := specs(t, "v1") + inv.Providers = Detect(inv, s.Cat) + changes(t, s, inv) + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + s.Fetch = fetcher{fixtureSpec: retyped} + want := []string{"breaking api/fixture/GET /v1/orders#total_cents"} + for run := range 3 { + got := changes(t, s, inv) + if !slices.Equal(ids(got), want) { + t.Fatalf("run %d = %q", run, ids(got)) + } + if a := got[0].API; a.What != "response field type changed" || !strings.Contains(got[0].Evidence[0].Text, "(integer -> string)") { + t.Errorf("run %d change = %+v %q", run, a, got[0].Evidence[0].Text) + } + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + } + + s.Done = func(id string) bool { return id == "api/fixture/GET /v1/orders#total_cents" } + if got := changes(t, s, inv); len(got) != 0 { + t.Errorf("a delivered type change is not reported again: %q", ids(got)) + } + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + s.Done = nil + if got := changes(t, s, inv); len(got) != 0 { + t.Errorf("a delivered type change should go after one snapshot: %q", ids(got)) + } +} + +func TestTypeChangeReleasedAtSnapshot(t *testing.T) { + v1 := read(t, "testdata/fixture/v1.yaml") + inv := pyAPI(nil, "total_cents") + s := specs(t, "v1") + inv.Providers = Detect(inv, s.Cat) + changes(t, s, inv) + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + s.Fetch = fetcher{fixtureSpec: strings.Replace(v1, "total_cents: {type: integer}", "total_cents: {type: string}", 1)} + if got := changes(t, s, inv); len(got) != 1 { + t.Fatalf("changes = %q", ids(got)) + } + s.Done = func(id string) bool { return id == "api/fixture/GET /v1/orders#total_cents" } + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + s.Done = nil + if got := changes(t, s, inv); len(got) != 0 { + t.Errorf("a type change done by snapshot time should go: %q", ids(got)) + } +} + +func TestPinOnlyTheField(t *testing.T) { + v1 := read(t, "testdata/fixture/v1.yaml") + inv := pyAPI(nil, "total_cents") + s := specs(t, "v1") + inv.Providers = Detect(inv, s.Cat) + changes(t, s, inv) + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + v2 := strings.NewReplacer( + "total_cents: {type: integer}", "total_cents: {type: string}\n note: {type: string}", + " status: {type: string}\n", "", + "- {name: status, in: query}", "- {name: status, in: query}\n - {name: page, in: query}", + ).Replace(v1) + s.Fetch = fetcher{fixtureSpec: v2} + if got := ids(changes(t, s, inv)); !slices.Equal(got, []string{"breaking api/fixture/GET /v1/orders#total_cents"}) { + t.Fatalf("changes = %q", got) + } + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + snap, err := Load([]byte(read(t, s.File("fixture")))) + if err != nil { + t.Fatal(err) + } + o := snap.Ops["GET /v1/orders"] + order := o.Response.Items + if order == nil || order.Props["total_cents"] == nil || order.Props["total_cents"].Type != "integer" { + t.Fatalf("the pinned field should keep its old type: %+v", order) + } + if order.Props["status"] != nil || order.Props["note"] == nil { + t.Errorf("the rest of the op should move on: %q", slices.Sorted(maps.Keys(order.Props))) + } + if !slices.ContainsFunc(o.Params, func(p Param) bool { return p.Name == "page" }) { + t.Errorf("params should move on: %+v", o.Params) + } + if got := ids(changes(t, s, inv)); !slices.Equal(got, []string{"breaking api/fixture/GET /v1/orders#total_cents"}) { + t.Errorf("after the snapshot = %q", got) + } +} + +func TestPinParams(t *testing.T) { + v1 := read(t, "testdata/fixture/v1.yaml") + idx := &index{urls: []core.URLUse{{File: "app/orders.py", Line: 8, Method: "GET", URL: "https://api.fixture.dev/v1/orders?status=open"}}} + inv := &core.Inventory{Index: idx} + s := specs(t, "v1") + changes(t, s, inv) + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + s.Fetch = fetcher{fixtureSpec: strings.Replace(v1, "- {name: status, in: query}", "- {name: state, in: query}\n - {name: cursor, in: query, required: true}", 1)} + want := []string{"breaking api/fixture/GET /v1/orders#cursor", "breaking api/fixture/GET /v1/orders#status"} + for run := range 2 { + if got := ids(changes(t, s, inv)); !slices.Equal(got, want) { + t.Fatalf("run %d = %q", run, got) + } + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + } + idx.urls[0].URL = "https://api.fixture.dev/v1/orders?state=open&cursor=x" + changes(t, s, inv) + if err := s.Snapshot("fixture", s.Current("fixture")); err != nil { + t.Fatal(err) + } + idx.urls[0].URL = "https://api.fixture.dev/v1/orders" + if got := ids(changes(t, s, inv)); len(got) != 0 { + t.Errorf("once fixed the snapshot moves on: %q", got) + } +} diff --git a/internal/api/diff.go b/internal/api/diff.go index 92ce638..af1c4e8 100644 --- a/internal/api/diff.go +++ b/internal/api/diff.go @@ -25,8 +25,8 @@ func (l Line) String() string { } // Diff compares two versions of a spec over the operations in used only. A -// changed response field type is reported as such; the caller treats it as the -// old field being gone. +// response field whose type changed is reported as such; a field of no single +// type, such as a union of a string and an object, has no type to compare. func Diff(old, cur *Doc, used []Usage) []Line { var res []Line for _, u := range used { @@ -111,7 +111,7 @@ func diffOp(key string, o, n *Op) []Line { switch { case !ok: add("response field removed", name, "") - case was.Type != "" && now.Type != "" && was.Type != now.Type: + case typed(was.Type) && typed(now.Type) && was.Type != now.Type: add("response field type changed", name, was.Type+" -> "+now.Type) case now.Deprecated && !was.Deprecated: add("response field deprecated", name, "") @@ -120,6 +120,10 @@ func diffOp(key string, o, n *Op) []Line { return res } +// typed reports whether a field has a type to compare. "null" is none: older +// snapshots took it from the first member of a nullable union. +func typed(t string) bool { return t != "" && t != "null" } + func fields(s *Schema) map[string]*Schema { res := map[string]*Schema{} walk(s, func(name string, p *Schema) { res[name] = p }) diff --git a/internal/api/discover.go b/internal/api/discover.go index 0b7223a..411760a 100644 --- a/internal/api/discover.go +++ b/internal/api/discover.go @@ -74,8 +74,11 @@ func apiLike(host, lit string) bool { // Discover looks for an OpenAPI spec for each host: in the APIs.guru // directory, then at the usual paths on the host and on its docs and // developer siblings. Hosts are looked up a few at a time. It never sends -// credentials, and trusts what it found, or did not, for a week. It returns -// what is known about every host, the old findings included. +// credentials, and trusts what it found, or did not, for a week. A lookup +// that could not finish, because the directory was out of reach or ctx ended, +// is not a finding: such a host keeps what was known of it, or is left out, +// and is looked up again next time. It returns what is known about every +// host, the old findings included. func Discover(ctx context.Context, f core.Fetcher, hosts []string, known map[string]state.Found, now time.Time) map[string]state.Found { res := map[string]state.Found{} var todo []string @@ -89,15 +92,21 @@ func Discover(ctx context.Context, f core.Fetcher, hosts []string, known map[str if len(todo) == 0 { return res } - dir := directory(ctx, f) + dir, ok := directory(ctx, f) specs := make([]string, len(todo)) source.Parallel(len(todo), func(i int) { if specs[i] = guru(dir, todo[i]); specs[i] == "" { specs[i] = probe(ctx, f, todo[i]) } }) + sure := ok && ctx.Err() == nil for i, h := range todo { - res[h] = state.Found{Spec: specs[i], At: now} + switch { + case specs[i] != "" || sure: + res[h] = state.Found{Spec: specs[i], At: now} + case !known[h].At.IsZero(): + res[h] = known[h] + } } return res } @@ -116,15 +125,17 @@ type guruAPI struct { } `json:"versions"` } -// directory is APIs.guru's list, empty when it cannot be had. -func directory(ctx context.Context, f core.Fetcher) map[string]guruAPI { +// directory is APIs.guru's list; ok is false when it could not be had. +func directory(ctx context.Context, f core.Fetcher) (map[string]guruAPI, bool) { res := map[string]guruAPI{} got, err := f.Get(ctx, apisGuru, fetch.TTL(foundFor)) if err != nil || got.Status != 200 { - return res + return res, false } - _ = json.Unmarshal(got.Body, &res) - return res + if json.Unmarshal(got.Body, &res) != nil { + return map[string]guruAPI{}, false + } + return res, true } // guru finds the directory's spec for a host: the entry named for the host diff --git a/internal/api/discover_test.go b/internal/api/discover_test.go index ed05b26..e61b3d1 100644 --- a/internal/api/discover_test.go +++ b/internal/api/discover_test.go @@ -41,7 +41,10 @@ const guruList = `{ }` func TestGuru(t *testing.T) { - dir := directory(context.Background(), &pages{body: map[string]string{apisGuru: guruList}}) + dir, ok := directory(context.Background(), &pages{body: map[string]string{apisGuru: guruList}}) + if !ok { + t.Fatal("the directory should load") + } tests := []struct{ host, want string }{ {"api.example-unknown.com", "https://api.apis.guru/v2/specs/example-unknown.com/2.0.0/openapi.json"}, {"gmail.googleapis.com", "https://api.apis.guru/v2/specs/googleapis.com/gmail/v1/openapi.json"}, @@ -163,3 +166,53 @@ func TestDiscoverDeadHosts(t *testing.T) { t.Error("a probe went out with no deadline of its own") } } + +// outage fails the directory and serves nothing else. +type outage struct { + mu sync.Mutex + asked []string +} + +func (o *outage) Get(ctx context.Context, u string, opts ...core.FetchOpt) (*core.Response, error) { + o.mu.Lock() + o.asked = append(o.asked, u) + o.mu.Unlock() + if u == apisGuru { + return nil, errors.New("api.apis.guru: HTTP 503") + } + if err := ctx.Err(); err != nil { + return nil, err + } + return &core.Response{Status: 404}, nil +} + +func (o *outage) Post(context.Context, string, []byte, ...core.FetchOpt) (*core.Response, error) { + panic("discovery never posts") +} + +func TestDiscoverOutage(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + known := map[string]state.Found{"api.stale.com": {Spec: "https://stale.test/spec.json", At: now.Add(-8 * 24 * time.Hour)}} + f := &outage{} + got := Discover(context.Background(), f, []string{"api.stripe-like.com", "api.stale.com"}, known, now) + if _, ok := got["api.stripe-like.com"]; ok { + t.Errorf("a miss while the directory was down was kept: %+v", got) + } + if got["api.stale.com"] != known["api.stale.com"] { + t.Errorf("a host looked up during an outage should keep what was known: %+v", got["api.stale.com"]) + } + before := len(f.asked) + Discover(context.Background(), f, []string{"api.stripe-like.com"}, got, now.Add(24*time.Hour)) + if !slices.Contains(f.asked[before:], apisGuru) { + t.Error("the next run should look the host up again") + } +} + +func TestDiscoverCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + f := &pages{body: map[string]string{apisGuru: guruList}} + if got := Discover(ctx, f, []string{"api.foo.dev"}, nil, time.Now()); len(got) != 0 { + t.Errorf("a canceled lookup found %+v", got) + } +} diff --git a/internal/api/openapi.go b/internal/api/openapi.go index db56182..873e488 100644 --- a/internal/api/openapi.go +++ b/internal/api/openapi.go @@ -27,9 +27,9 @@ type Doc struct { type Op struct { Method, Path string - Summary string // the summary and the description, at most 600 bytes - Deprecated bool - Sunset time.Time // from x-sunset, the catalog's sunset key, or x-deprecated-at + Summary string // the summary and the description, at most 600 bytes + Deprecated bool // also set by x-deprecated-at, which dates the deprecation, not the removal + Sunset time.Time // from x-sunset or the catalog's sunset key Params []Param // path, query and header Request *Schema // first JSON (else form) request body schema, resolved Response *Schema // first 2xx JSON response schema, resolved @@ -158,16 +158,34 @@ func load(b []byte, sunset string) (*Doc, error) { } // toJSON converts YAML to JSON so one decoder serves both. JSON passes through, -// which keeps the big specs (GitHub, Cloudflare) off the slower YAML path. +// which keeps the big specs (GitHub, Cloudflare) off the slower YAML path. An +// unquoted info.version keeps its text: 2.10 stays "2.10", not the float 2.1. func toJSON(b []byte) ([]byte, error) { if t := bytes.TrimSpace(b); len(t) > 0 && t[0] == '{' { return b, nil } + var node yaml.Node + if err := yaml.Unmarshal(b, &node); err != nil { + return nil, fmt.Errorf("openapi: %w", err) + } var v any - if err := yaml.Unmarshal(b, &v); err != nil { + if err := node.Decode(&v); err != nil { return nil, fmt.Errorf("openapi: %w", err) } - res, err := json.Marshal(plain(v)) + v = plain(v) + var head struct { + Info struct { + Version string `yaml:"version"` + } `yaml:"info"` + } + if node.Decode(&head) == nil && head.Info.Version != "" { + if m, ok := v.(map[string]any); ok { + if info, ok := m["info"].(map[string]any); ok { + info["version"] = head.Info.Version + } + } + } + res, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("openapi: %w", err) } @@ -249,8 +267,8 @@ func (l *loader) op(raw json.RawMessage, shared []json.RawMessage) *Op { if op.Sunset.IsZero() && l.sunset != nil { op.Sunset = date(dig(m, l.sunset)) } - if op.Sunset.IsZero() { - op.Sunset = date(m["x-deprecated-at"]) + if !date(m["x-deprecated-at"]).IsZero() { + op.Deprecated = true } var own []json.RawMessage @@ -296,7 +314,8 @@ func (l *loader) param(raw json.RawMessage) (Param, bool) { } // body picks the schema of a request body or a response: JSON first, then forms, -// because some providers (Stripe, Twilio) only take form-encoded requests. +// because some providers (Stripe, Twilio) only take form-encoded requests, then +// a wildcard. func (l *loader) body(raw json.RawMessage, kind string) *Schema { var b rawBody decode(raw, &b) @@ -320,16 +339,21 @@ func (l *loader) body(raw json.RawMessage, kind string) *Schema { return l.schema(b.Content[best].Schema) } +// rank orders the media types a body may come in. A wildcard, which springdoc +// writes for every response by default, counts only when nothing better is there. func rank(mt string) int { mt, _, _ = strings.Cut(mt, ";") + mt = strings.ToLower(strings.TrimSpace(mt)) switch { case mt == "application/json": + return 5 + case strings.HasSuffix(mt, "+json"), mt == "text/json": return 4 - case strings.HasSuffix(mt, "+json"): - return 3 case mt == "application/x-www-form-urlencoded": - return 2 + return 3 case mt == "multipart/form-data": + return 2 + case mt == "*/*", mt == "application/*": return 1 } return 0 @@ -404,8 +428,23 @@ func (l *loader) schema(raw json.RawMessage) *Schema { for _, part := range r.AllOf { s.merge(l.schema(part), true) } + var kinds []string for _, part := range append(r.OneOf, r.AnyOf...) { - s.merge(l.schema(part), false) + p := l.schema(part) + if p == nil { + continue + } + s.merge(p, false) + t := p.Type + if t == "" && len(p.Props) > 0 { + t = "object" + } + if t != "" && t != "null" && !slices.Contains(kinds, t) { + kinds = append(kinds, t) + } + } + if s.Type == "" && len(kinds) == 1 { + s.Type = kinds[0] } return s } @@ -417,8 +456,9 @@ func (s *Schema) prop(name string, p *Schema) { s.Props[name] = p } -// merge folds part into s. allOf parts all apply, so their required fields do -// too; oneOf and anyOf only contribute the fields that may appear. +// merge folds part into s. allOf parts all apply, so their required fields and +// type do too; oneOf and anyOf only contribute the fields that may appear, and +// schema works out their type from all the members at once. func (s *Schema) merge(part *Schema, all bool) { if part == nil { return @@ -434,9 +474,9 @@ func (s *Schema) merge(part *Schema, all bool) { s.Required = append(s.Required, r) } } - } - if s.Type == "" { - s.Type = part.Type + if s.Type == "" { + s.Type = part.Type + } } if s.Items == nil { s.Items = part.Items @@ -490,7 +530,9 @@ func date(raw json.RawMessage) time.Time { func (d *Doc) Find(method, path string) *Op { return d.find(method, path, false) } // find with loose compares literal segments without case, "_" and "-", for -// SDK packages named like "paymentintent". +// SDK packages named like "paymentintent". A loose path is a guess, so its +// {placeholders} stand only for template params, and a param never takes one of +// its literal segments: customers/sources is not customers/{customer}. func (d *Doc) find(method, path string, loose bool) *Op { if d == nil { return nil @@ -530,7 +572,11 @@ func (d *Doc) match(method, path string, loose bool) *Op { if method != "" && op.Method != method { continue } - score, ok := fit(strings.Split(op.Path, "/"), segs, loose) + tp := op.Path + if len(tp) > 1 { + tp = strings.TrimRight(tp, "/") + } + score, ok := fit(strings.Split(tp, "/"), segs, loose) if !ok { continue } @@ -560,6 +606,14 @@ func fit(tmpl, segs []string, loose bool) (int, bool) { parts := split(t) s := segs[i] if loose { + hasParam := slices.ContainsFunc(parts, func(p part) bool { return p.param }) + placeholder := strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}") + if hasParam != placeholder { + return 0, false + } + if placeholder { + continue + } for j := range parts { parts[j].lit = fold(parts[j].lit) } diff --git a/internal/api/openapi_test.go b/internal/api/openapi_test.go index 4ca5763..4dbfb7e 100644 --- a/internal/api/openapi_test.go +++ b/internal/api/openapi_test.go @@ -4,6 +4,7 @@ import ( "maps" "os" "slices" + "strings" "testing" "time" ) @@ -55,8 +56,8 @@ func TestLoad(t *testing.T) { if !get.Deprecated || !get.Sunset.Equal(time.Date(2027, 3, 1, 0, 0, 0, 0, time.UTC)) { t.Errorf("get deprecated %v sunset %v", get.Deprecated, get.Sunset) } - if got := d.Ops["POST /v2/orders/{id}/refund"].Sunset; !got.Equal(time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)) { - t.Errorf("x-deprecated-at sunset = %v", got) + if refund := d.Ops["POST /v2/orders/{id}/refund"]; !refund.Deprecated || !refund.Sunset.IsZero() { + t.Errorf("x-deprecated-at should deprecate without a sunset: %+v", refund) } legacy := d.Ops["GET /v2/orders/legacy"] if !legacy.Sunset.Equal(time.Date(2026, 8, 28, 0, 0, 0, 0, time.UTC)) || legacy.Summary != "Old listing, kept for one more year." { @@ -292,3 +293,168 @@ func TestSplit(t *testing.T) { } } } + +func load3(t *testing.T, spec string) *Doc { + t.Helper() + d, err := Load([]byte(spec)) + if err != nil { + t.Fatal(err) + } + return d +} + +func customerSpec(customer string) string { + return `openapi: 3.1.0 +info: {version: "1"} +paths: + /v1/o: + get: + responses: + "200": + content: + application/json: + schema: + type: object + properties: + customer: ` + customer + ` +components: + schemas: + C: + type: object + properties: + id: {type: string} + Untyped: + properties: + id: {type: string} +` +} + +func TestUnionType(t *testing.T) { + tests := []struct { + name, customer, want string + }{ + {"ref", `{$ref: '#/components/schemas/C'}`, "object"}, + {"nullable ref", `{anyOf: [{type: "null"}, {$ref: '#/components/schemas/C'}]}`, "object"}, + {"ref then null", `{anyOf: [{$ref: '#/components/schemas/C'}, {type: "null"}]}`, "object"}, + {"untyped ref and null", `{anyOf: [{type: "null"}, {$ref: '#/components/schemas/Untyped'}]}`, "object"}, + {"only null", `{oneOf: [{type: "null"}]}`, ""}, + {"string or object", `{anyOf: [{type: string}, {$ref: '#/components/schemas/C'}]}`, ""}, + {"object or string", `{anyOf: [{$ref: '#/components/schemas/C'}, {type: string}]}`, ""}, + {"allOf", `{allOf: [{type: integer}]}`, "integer"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + d := load3(t, customerSpec(tt.customer)) + got := d.Ops["GET /v1/o"].Response.Props["customer"] + if got == nil || got.Type != tt.want { + t.Fatalf("customer = %+v, want type %q", got, tt.want) + } + }) + } +} + +func TestUnionTypeDiff(t *testing.T) { + ref := `{$ref: '#/components/schemas/C'}` + tests := []struct{ old, cur string }{ + {ref, `{anyOf: [{type: "null"}, {$ref: '#/components/schemas/C'}]}`}, + {ref, `{anyOf: [{$ref: '#/components/schemas/C'}, {type: "null"}]}`}, + {`{anyOf: [{type: string}, {$ref: '#/components/schemas/C'}]}`, `{anyOf: [{$ref: '#/components/schemas/C'}, {type: string}]}`}, + {`{anyOf: [{type: "null"}, {$ref: '#/components/schemas/Untyped'}]}`, ref}, + {`{type: "null"}`, ref}, + } + used := []Usage{{Method: "GET", Path: "/v1/o"}} + for _, tt := range tests { + old, cur := load3(t, customerSpec(tt.old)), load3(t, customerSpec(tt.cur)) + if got := Diff(old, cur, used); len(got) != 0 { + t.Errorf("%s -> %s: %v", tt.old, tt.cur, got) + } + snap := load3(t, string(trimSpec(old, nil))) + if got := Diff(snap, cur, used); len(got) != 0 { + t.Errorf("snapshot of %s -> %s: %v", tt.old, tt.cur, got) + } + } +} + +const wildcardSpec = `openapi: 3.0.1 +info: {version: "1"} +paths: + /a: + get: + responses: + "200": + content: + "*/*": + schema: + type: object + properties: + x: {type: string} + y: {type: integer} + /b: + get: + responses: + "200": + content: + "*/*": + schema: {properties: {wild: {type: string}}} + "Application/JSON ; charset=utf-8": + schema: {properties: {json: {type: string}}} +` + +func TestLoadWildcardBody(t *testing.T) { + d := load3(t, wildcardSpec) + a := d.Find("GET", "/a") + if a == nil || a.Response == nil || a.Response.Props["x"] == nil { + t.Fatalf("a */* response should have a schema: %+v", a) + } + if b := d.Find("GET", "/b").Response; b == nil || b.Props["json"] == nil { + t.Errorf("JSON should win over */*, whatever its case: %+v", b) + } + cur := load3(t, strings.Replace(wildcardSpec, " x: {type: string}\n", "", 1)) + got := Diff(d, cur, []Usage{{Method: "GET", Path: "/a"}}) + if len(got) != 1 || got[0].What != "response field removed" || got[0].Field != "x" { + t.Errorf("diff = %v", got) + } +} + +func TestLoadUnquotedVersion(t *testing.T) { + d := load3(t, "openapi: 3.0.0\ninfo: {title: x, version: 2.10}\npaths: {}\n") + if d.Version != "2.10" { + t.Errorf("version = %q", d.Version) + } + d = load3(t, "openapi: 3.0.0\ninfo:\n version: 2026-09-30\npaths: {}\n") + if d.Version != "2026-09-30" { + t.Errorf("version = %q", d.Version) + } +} + +func TestFindTrailingSlash(t *testing.T) { + d := load3(t, `openapi: 3.0.0 +info: {version: "1"} +servers: [{url: "https://x.test/v1"}] +paths: + /: + get: {responses: {}} + /users/: + get: {responses: {}} +`) + tests := []struct{ path, want string }{ + {"https://x.test/v1/", "GET /v1/"}, + {"/v1", "GET /v1/"}, + {"/v1/users/", "GET /v1/users/"}, + {"https://x.test/v1/users/?a=1", "GET /v1/users/"}, + {"/users", "GET /v1/users/"}, + } + for _, tt := range tests { + got := "" + if op := d.Find("GET", tt.path); op != nil { + got = op.Method + " " + op.Path + } + if got != tt.want { + t.Errorf("Find(%q) = %q, want %q", tt.path, got, tt.want) + } + } + plain := load3(t, "openapi: 3.0.0\ninfo: {version: \"1\"}\npaths:\n /users/:\n get: {responses: {}}\n") + if plain.Find("GET", "https://api.x/users/?a=1") == nil || plain.Find("GET", "/users/") == nil { + t.Error("a /users/ template should be found") + } +} diff --git a/internal/api/providers.yml b/internal/api/providers.yml index 8a88e61..0cbc134 100644 --- a/internal/api/providers.yml +++ b/internal/api/providers.yml @@ -26,8 +26,16 @@ - name: sendgrid title: SendGrid hosts: [api.sendgrid.com] - spec: https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mail_v3.json - sdks: [{eco: npm, name: "@sendgrid/mail"}, {eco: pip, name: sendgrid}] + spec: + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mail_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mc_contacts_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mc_lists_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_templates_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_suppressions_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_api_keys_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_stats_v3.json + - https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_webhooks_v3.json + sdks: [{eco: npm, name: "@sendgrid/mail"}, {eco: npm, name: "@sendgrid/client"}, {eco: pip, name: sendgrid}] - name: plaid title: Plaid hosts: [production.plaid.com, sandbox.plaid.com] @@ -42,9 +50,12 @@ title: Cloudflare hosts: [api.cloudflare.com] spec: https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json + sunset: x-cfDeprecation.eol sdks: [{eco: npm, name: cloudflare}, {eco: go, name: github.com/cloudflare/cloudflare-go}, {eco: pip, name: cloudflare}] - name: datadog title: Datadog hosts: [api.datadoghq.com] - spec: https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v1/openapi.yaml + spec: + - https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v1/openapi.yaml + - https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v2/openapi.yaml sdks: [{eco: go, name: github.com/DataDog/datadog-api-client-go}, {eco: pip, name: datadog-api-client}] diff --git a/internal/api/testdata/recorded/GET_api-engineering.nyc3.digitaloceanspaces.com_2610c7aec8fc.json b/internal/api/testdata/recorded/GET_api-engineering.nyc3.digitaloceanspaces.com_2610c7aec8fc.json index 8bb0dad..28d8646 100644 --- a/internal/api/testdata/recorded/GET_api-engineering.nyc3.digitaloceanspaces.com_2610c7aec8fc.json +++ b/internal/api/testdata/recorded/GET_api-engineering.nyc3.digitaloceanspaces.com_2610c7aec8fc.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v2/droplets\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"per_page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"tag_name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"type\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"droplets\": {\n \"items\": {\n \"properties\": {\n \"backup_ids\": {\n \"type\": \"array\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"disk\": {\n \"type\": \"integer\"\n },\n \"disk_info\": {\n \"type\": \"array\"\n },\n \"features\": {\n \"type\": \"array\"\n },\n \"gpu_info\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"image\": {\n \"type\": \"object\"\n },\n \"kernel\": {\n \"deprecated\": true,\n \"type\": \"object\"\n },\n \"locked\": {\n \"type\": \"boolean\"\n },\n \"memory\": {\n \"type\": \"integer\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"networks\": {\n \"type\": \"object\"\n },\n \"next_backup_window\": {\n \"type\": \"object\"\n },\n \"region\": {\n \"type\": \"object\"\n },\n \"size\": {\n \"type\": \"object\"\n },\n \"size_slug\": {\n \"type\": \"string\"\n },\n \"snapshot_ids\": {\n \"type\": \"array\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"subnet_uuid\": {\n \"type\": \"string\"\n },\n \"tags\": {\n \"type\": \"array\"\n },\n \"vcpus\": {\n \"type\": \"integer\"\n },\n \"volume_ids\": {\n \"type\": \"array\"\n },\n \"vpc_uuid\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"backup_ids\",\n \"created_at\",\n \"disk\",\n \"features\",\n \"id\",\n \"image\",\n \"locked\",\n \"memory\",\n \"name\",\n \"networks\",\n \"next_backup_window\",\n \"region\",\n \"size\",\n \"size_slug\",\n \"snapshot_ids\",\n \"status\",\n \"tags\",\n \"vcpus\",\n \"volume_ids\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"links\": {\n \"properties\": {\n \"pages\": {\n \"properties\": {\n \"first\": {\n \"type\": \"string\"\n },\n \"last\": {\n \"type\": \"string\"\n },\n \"next\": {\n \"type\": \"string\"\n },\n \"prev\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"meta\": {\n \"properties\": {\n \"total\": {\n \"type\": \"integer\"\n }\n },\n \"required\": [\n \"total\"\n ],\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"meta\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List All Droplets\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v2/droplets\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"per_page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"tag_name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"type\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"droplets\": {\n \"items\": {\n \"properties\": {\n \"backup_ids\": {\n \"type\": \"array\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"disk\": {\n \"type\": \"integer\"\n },\n \"disk_info\": {\n \"type\": \"array\"\n },\n \"features\": {\n \"type\": \"array\"\n },\n \"gpu_info\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"image\": {\n \"type\": \"object\"\n },\n \"kernel\": {\n \"deprecated\": true,\n \"type\": \"object\"\n },\n \"locked\": {\n \"type\": \"boolean\"\n },\n \"memory\": {\n \"type\": \"integer\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"networks\": {\n \"type\": \"object\"\n },\n \"next_backup_window\": {\n \"type\": \"object\"\n },\n \"region\": {\n \"type\": \"object\"\n },\n \"size\": {\n \"type\": \"object\"\n },\n \"size_slug\": {\n \"type\": \"string\"\n },\n \"snapshot_ids\": {\n \"type\": \"array\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"subnet_uuid\": {\n \"type\": \"string\"\n },\n \"tags\": {\n \"type\": \"array\"\n },\n \"vcpus\": {\n \"type\": \"integer\"\n },\n \"volume_ids\": {\n \"type\": \"array\"\n },\n \"vpc_uuid\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"backup_ids\",\n \"created_at\",\n \"disk\",\n \"features\",\n \"id\",\n \"image\",\n \"locked\",\n \"memory\",\n \"name\",\n \"networks\",\n \"next_backup_window\",\n \"region\",\n \"size\",\n \"size_slug\",\n \"snapshot_ids\",\n \"status\",\n \"tags\",\n \"vcpus\",\n \"volume_ids\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"links\": {\n \"properties\": {\n \"pages\": {\n \"properties\": {\n \"first\": {\n \"type\": \"string\"\n },\n \"last\": {\n \"type\": \"string\"\n },\n \"next\": {\n \"type\": \"string\"\n },\n \"prev\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"meta\": {\n \"properties\": {\n \"total\": {\n \"type\": \"integer\"\n }\n },\n \"required\": [\n \"total\"\n ],\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"meta\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List All Droplets\\n\\nTo list all Droplets in your account, send a GET request to `/v2/droplets`.\\n\\nThe response body will be a JSON object with a key of `droplets`. This will be\\nset to an array containing objects each representing a Droplet. These will\\ncontain the standard Droplet attributes.\\n\\n### Filtering Results by Tag\\n\\nIt's possible to request filtered results by including certain query parameters.\\nTo only list Droplets assigned to a specific tag, include the `tag_name` query\\nparameter set to the name of the tag in your GET request. For example,\\n`/v2/droplets?tag_name=$TAG_NAME`.\\n\\n### GPU Dro\"\n }\n }\n }\n}\n", "status": 200, "url": "https://api-engineering.nyc3.digitaloceanspaces.com/spec-ci/DigitalOcean-public.v2.yaml" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_012127149c7b.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_012127149c7b.json index dbbcedd..f798722 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_012127149c7b.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_012127149c7b.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v3/mail/send\": {\n \"post\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"header\",\n \"name\": \"Content-Encoding\",\n \"required\": false\n }\n ],\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"asm\": {\n \"properties\": {\n \"group_id\": {\n \"type\": \"integer\"\n },\n \"groups_to_display\": {\n \"items\": {\n \"type\": \"integer\"\n },\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"group_id\"\n ],\n \"type\": \"object\"\n },\n \"attachments\": {\n \"items\": {\n \"properties\": {\n \"content\": {\n \"type\": \"string\"\n },\n \"content_id\": {\n \"type\": \"string\"\n },\n \"disposition\": {\n \"type\": \"string\"\n },\n \"filename\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"content\",\n \"filename\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"batch_id\": {\n \"type\": \"string\"\n },\n \"categories\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"content\": {\n \"items\": {\n \"properties\": {\n \"type\": {\n \"type\": \"string\"\n },\n \"value\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"type\",\n \"value\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"custom_args\": {\n \"type\": \"string\"\n },\n \"from\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"headers\": {\n \"type\": \"object\"\n },\n \"ip_pool_name\": {\n \"type\": \"string\"\n },\n \"mail_settings\": {\n \"properties\": {\n \"bypass_bounce_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_list_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_spam_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_unsubscribe_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"footer\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"html\": {\n \"type\": \"string\"\n },\n \"text\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sandbox_mode\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"personalizations\": {\n \"items\": {\n \"properties\": {\n \"bcc\": {\n \"type\": \"array\"\n },\n \"cc\": {\n \"type\": \"array\"\n },\n \"custom_args\": {\n \"type\": \"object\"\n },\n \"dynamic_template_data\": {\n \"type\": \"object\"\n },\n \"from\": {\n \"type\": \"object\"\n },\n \"headers\": {\n \"type\": \"object\"\n },\n \"send_at\": {\n \"type\": \"integer\"\n },\n \"subject\": {\n \"type\": \"string\"\n },\n \"substitutions\": {\n \"type\": \"object\"\n },\n \"to\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"to\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"reply_to\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"reply_to_list\": {\n \"items\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"send_at\": {\n \"type\": \"integer\"\n },\n \"subject\": {\n \"type\": \"string\"\n },\n \"template_id\": {\n \"type\": \"string\"\n },\n \"tracking_settings\": {\n \"properties\": {\n \"click_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"enable_text\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"ganalytics\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"utm_campaign\": {\n \"type\": \"string\"\n },\n \"utm_content\": {\n \"type\": \"string\"\n },\n \"utm_medium\": {\n \"type\": \"string\"\n },\n \"utm_source\": {\n \"type\": \"string\"\n },\n \"utm_term\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"open_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"substitution_tag\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"subscription_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"html\": {\n \"type\": \"string\"\n },\n \"substitution_tag\": {\n \"type\": \"string\"\n },\n \"text\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"from\",\n \"personalizations\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {},\n \"summary\": \"Send Email with Twilio SendGrid.\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v3/mail/send\": {\n \"post\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"header\",\n \"name\": \"Content-Encoding\",\n \"required\": false\n }\n ],\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"asm\": {\n \"properties\": {\n \"group_id\": {\n \"type\": \"integer\"\n },\n \"groups_to_display\": {\n \"items\": {\n \"type\": \"integer\"\n },\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"group_id\"\n ],\n \"type\": \"object\"\n },\n \"attachments\": {\n \"items\": {\n \"properties\": {\n \"content\": {\n \"type\": \"string\"\n },\n \"content_id\": {\n \"type\": \"string\"\n },\n \"disposition\": {\n \"type\": \"string\"\n },\n \"filename\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"content\",\n \"filename\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"batch_id\": {\n \"type\": \"string\"\n },\n \"categories\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"content\": {\n \"items\": {\n \"properties\": {\n \"type\": {\n \"type\": \"string\"\n },\n \"value\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"type\",\n \"value\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"custom_args\": {\n \"type\": \"string\"\n },\n \"from\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"headers\": {\n \"type\": \"object\"\n },\n \"ip_pool_name\": {\n \"type\": \"string\"\n },\n \"mail_settings\": {\n \"properties\": {\n \"bypass_bounce_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_list_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_spam_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"bypass_unsubscribe_management\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"footer\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"html\": {\n \"type\": \"string\"\n },\n \"text\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sandbox_mode\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"personalizations\": {\n \"items\": {\n \"properties\": {\n \"bcc\": {\n \"type\": \"array\"\n },\n \"cc\": {\n \"type\": \"array\"\n },\n \"custom_args\": {\n \"type\": \"object\"\n },\n \"dynamic_template_data\": {\n \"type\": \"object\"\n },\n \"from\": {\n \"type\": \"object\"\n },\n \"headers\": {\n \"type\": \"object\"\n },\n \"send_at\": {\n \"type\": \"integer\"\n },\n \"subject\": {\n \"type\": \"string\"\n },\n \"substitutions\": {\n \"type\": \"object\"\n },\n \"to\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"to\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"reply_to\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"reply_to_list\": {\n \"items\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"email\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"send_at\": {\n \"type\": \"integer\"\n },\n \"subject\": {\n \"type\": \"string\"\n },\n \"template_id\": {\n \"type\": \"string\"\n },\n \"tracking_settings\": {\n \"properties\": {\n \"click_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"enable_text\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"ganalytics\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"utm_campaign\": {\n \"type\": \"string\"\n },\n \"utm_content\": {\n \"type\": \"string\"\n },\n \"utm_medium\": {\n \"type\": \"string\"\n },\n \"utm_source\": {\n \"type\": \"string\"\n },\n \"utm_term\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"open_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"substitution_tag\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"subscription_tracking\": {\n \"properties\": {\n \"enable\": {\n \"type\": \"boolean\"\n },\n \"html\": {\n \"type\": \"string\"\n },\n \"substitution_tag\": {\n \"type\": \"string\"\n },\n \"text\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"from\",\n \"personalizations\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {},\n \"summary\": \"Send Email with Twilio SendGrid.\\n\\n*The Mail Send operation allows you to send email over SendGrid's v3 Web API*\\n\\nFor an overview of this API, including its features and limitations, please see the [Mail Send API overview page](https://www.twilio.com/docs/sendgrid/api-reference/mail-send)\\n\\nThe overview page also includes links to SendGrid's Email API quickstarts and helper libraries to get you working with this endpoint even faster.\"\n }\n }\n }\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mail_v3.json" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_05d327c9f740.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_05d327c9f740.json new file mode 100644 index 0000000..e04f070 --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_05d327c9f740.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {}\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_stats_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0bcbf5ac2dab.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0bcbf5ac2dab.json new file mode 100644 index 0000000..899db57 --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0bcbf5ac2dab.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {}\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mc_lists_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0c3fbf6148f1.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0c3fbf6148f1.json index 460dc86..4e73b24 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0c3fbf6148f1.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_0c3fbf6148f1.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2.3.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/chat/completions\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"audio\": {\n \"properties\": {\n \"format\": {\n \"type\": \"string\"\n },\n \"voice\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"format\",\n \"voice\"\n ],\n \"type\": \"object\"\n },\n \"frequency_penalty\": {\n \"type\": \"number\"\n },\n \"function_call\": {\n \"deprecated\": true,\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"functions\": {\n \"deprecated\": true,\n \"items\": {\n \"deprecated\": true,\n \"properties\": {\n \"description\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"parameters\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"logit_bias\": {\n \"type\": \"object\"\n },\n \"logprobs\": {\n \"type\": \"boolean\"\n },\n \"max_completion_tokens\": {\n \"type\": \"integer\"\n },\n \"max_tokens\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"messages\": {\n \"items\": {\n \"properties\": {\n \"audio\": {\n \"type\": \"object\"\n },\n \"content\": {\n \"type\": \"string\"\n },\n \"function_call\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"refusal\": {\n \"type\": \"string\"\n },\n \"role\": {\n \"type\": \"string\"\n },\n \"tool_call_id\": {\n \"type\": \"string\"\n },\n \"tool_calls\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"modalities\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"moderation\": {\n \"properties\": {\n \"model\": {\n \"type\": \"string\"\n },\n \"policy\": {\n \"properties\": {\n \"input\": {\n \"type\": \"object\"\n },\n \"output\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"n\": {\n \"type\": \"integer\"\n },\n \"parallel_tool_calls\": {\n \"type\": \"boolean\"\n },\n \"prediction\": {\n \"properties\": {\n \"content\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"presence_penalty\": {\n \"type\": \"number\"\n },\n \"prompt_cache_key\": {\n \"type\": \"string\"\n },\n \"prompt_cache_options\": {\n \"properties\": {\n \"mode\": {\n \"type\": \"string\"\n },\n \"ttl\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"prompt_cache_retention\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"reasoning_effort\": {\n \"type\": \"string\"\n },\n \"response_format\": {\n \"properties\": {\n \"json_schema\": {\n \"properties\": {\n \"description\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"schema\": {\n \"type\": \"object\"\n },\n \"strict\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"safety_identifier\": {\n \"type\": \"string\"\n },\n \"seed\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"service_tier\": {\n \"type\": \"string\"\n },\n \"stop\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"string\"\n },\n \"store\": {\n \"type\": \"boolean\"\n },\n \"stream\": {\n \"type\": \"boolean\"\n },\n \"stream_options\": {\n \"properties\": {\n \"include_obfuscation\": {\n \"type\": \"boolean\"\n },\n \"include_usage\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"temperature\": {\n \"type\": \"number\"\n },\n \"tool_choice\": {\n \"properties\": {\n \"allowed_tools\": {\n \"properties\": {\n \"mode\": {\n \"type\": \"string\"\n },\n \"tools\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"mode\",\n \"tools\"\n ],\n \"type\": \"object\"\n },\n \"custom\": {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"function\": {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"tools\": {\n \"items\": {\n \"properties\": {\n \"custom\": {\n \"type\": \"object\"\n },\n \"function\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"top_logprobs\": {\n \"type\": \"integer\"\n },\n \"top_p\": {\n \"type\": \"number\"\n },\n \"user\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"verbosity\": {\n \"type\": \"string\"\n },\n \"web_search_options\": {\n \"properties\": {\n \"search_context_size\": {\n \"type\": \"string\"\n },\n \"user_location\": {\n \"properties\": {\n \"approximate\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"approximate\",\n \"type\"\n ],\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"messages\",\n \"model\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"choices\": {\n \"items\": {\n \"properties\": {\n \"finish_reason\": {\n \"type\": \"string\"\n },\n \"index\": {\n \"type\": \"integer\"\n },\n \"logprobs\": {\n \"type\": \"object\"\n },\n \"message\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"finish_reason\",\n \"index\",\n \"logprobs\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"moderation\": {\n \"properties\": {\n \"input\": {\n \"properties\": {\n \"code\": {\n \"type\": \"string\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"output\": {\n \"properties\": {\n \"code\": {\n \"type\": \"string\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"service_tier\": {\n \"type\": \"string\"\n },\n \"system_fingerprint\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"usage\": {\n \"properties\": {\n \"completion_tokens\": {\n \"type\": \"integer\"\n },\n \"completion_tokens_details\": {\n \"properties\": {\n \"accepted_prediction_tokens\": {\n \"type\": \"integer\"\n },\n \"audio_tokens\": {\n \"type\": \"integer\"\n },\n \"reasoning_tokens\": {\n \"type\": \"integer\"\n },\n \"rejected_prediction_tokens\": {\n \"type\": \"integer\"\n },\n \"text_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"type\": \"object\"\n },\n \"prompt_tokens\": {\n \"type\": \"integer\"\n },\n \"prompt_tokens_details\": {\n \"properties\": {\n \"audio_tokens\": {\n \"type\": \"integer\"\n },\n \"cache_write_tokens\": {\n \"type\": \"integer\"\n },\n \"cached_tokens\": {\n \"type\": \"integer\"\n },\n \"image_tokens\": {\n \"type\": \"integer\"\n },\n \"text_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"type\": \"object\"\n },\n \"total_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"required\": [\n \"completion_tokens\",\n \"prompt_tokens\",\n \"total_tokens\"\n ],\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"choices\",\n \"created\",\n \"id\",\n \"model\",\n \"object\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Create chat completion\"\n }\n }\n },\n \"servers\": [\n {\n \"url\": \"/v1\"\n }\n ]\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2.3.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/chat/completions\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"audio\": {\n \"properties\": {\n \"format\": {\n \"type\": \"string\"\n },\n \"voice\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"required\": [\n \"format\",\n \"voice\"\n ],\n \"type\": \"object\"\n },\n \"frequency_penalty\": {\n \"type\": \"number\"\n },\n \"function_call\": {\n \"deprecated\": true,\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n }\n },\n \"functions\": {\n \"deprecated\": true,\n \"items\": {\n \"deprecated\": true,\n \"properties\": {\n \"description\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"parameters\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"logit_bias\": {\n \"type\": \"object\"\n },\n \"logprobs\": {\n \"type\": \"boolean\"\n },\n \"max_completion_tokens\": {\n \"type\": \"integer\"\n },\n \"max_tokens\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"messages\": {\n \"items\": {\n \"properties\": {\n \"audio\": {\n \"type\": \"object\"\n },\n \"content\": {},\n \"function_call\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"refusal\": {\n \"type\": \"string\"\n },\n \"role\": {\n \"type\": \"string\"\n },\n \"tool_call_id\": {\n \"type\": \"string\"\n },\n \"tool_calls\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"modalities\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"moderation\": {\n \"properties\": {\n \"model\": {\n \"type\": \"string\"\n },\n \"policy\": {\n \"properties\": {\n \"input\": {\n \"type\": \"object\"\n },\n \"output\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"n\": {\n \"type\": \"integer\"\n },\n \"parallel_tool_calls\": {\n \"type\": \"boolean\"\n },\n \"prediction\": {\n \"properties\": {\n \"content\": {\n \"items\": {\n \"type\": \"object\"\n }\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"presence_penalty\": {\n \"type\": \"number\"\n },\n \"prompt_cache_key\": {\n \"type\": \"string\"\n },\n \"prompt_cache_options\": {\n \"properties\": {\n \"mode\": {\n \"type\": \"string\"\n },\n \"ttl\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"prompt_cache_retention\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"reasoning_effort\": {\n \"type\": \"string\"\n },\n \"response_format\": {\n \"properties\": {\n \"json_schema\": {\n \"properties\": {\n \"description\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"schema\": {\n \"type\": \"object\"\n },\n \"strict\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"safety_identifier\": {\n \"type\": \"string\"\n },\n \"seed\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"service_tier\": {\n \"type\": \"string\"\n },\n \"stop\": {\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"store\": {\n \"type\": \"boolean\"\n },\n \"stream\": {\n \"type\": \"boolean\"\n },\n \"stream_options\": {\n \"properties\": {\n \"include_obfuscation\": {\n \"type\": \"boolean\"\n },\n \"include_usage\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"temperature\": {\n \"type\": \"number\"\n },\n \"tool_choice\": {\n \"properties\": {\n \"allowed_tools\": {\n \"properties\": {\n \"mode\": {\n \"type\": \"string\"\n },\n \"tools\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"mode\",\n \"tools\"\n ],\n \"type\": \"object\"\n },\n \"custom\": {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"function\": {\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"tools\": {\n \"items\": {\n \"properties\": {\n \"custom\": {\n \"type\": \"object\"\n },\n \"function\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"top_logprobs\": {\n \"type\": \"integer\"\n },\n \"top_p\": {\n \"type\": \"number\"\n },\n \"user\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"verbosity\": {\n \"type\": \"string\"\n },\n \"web_search_options\": {\n \"properties\": {\n \"search_context_size\": {\n \"type\": \"string\"\n },\n \"user_location\": {\n \"properties\": {\n \"approximate\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"approximate\",\n \"type\"\n ],\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"messages\",\n \"model\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"choices\": {\n \"items\": {\n \"properties\": {\n \"finish_reason\": {\n \"type\": \"string\"\n },\n \"index\": {\n \"type\": \"integer\"\n },\n \"logprobs\": {\n \"type\": \"object\"\n },\n \"message\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"finish_reason\",\n \"index\",\n \"logprobs\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"moderation\": {\n \"properties\": {\n \"input\": {\n \"properties\": {\n \"code\": {\n \"type\": \"string\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"output\": {\n \"properties\": {\n \"code\": {\n \"type\": \"string\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"model\": {\n \"type\": \"string\"\n },\n \"results\": {\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"service_tier\": {\n \"type\": \"string\"\n },\n \"system_fingerprint\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"usage\": {\n \"properties\": {\n \"completion_tokens\": {\n \"type\": \"integer\"\n },\n \"completion_tokens_details\": {\n \"properties\": {\n \"accepted_prediction_tokens\": {\n \"type\": \"integer\"\n },\n \"audio_tokens\": {\n \"type\": \"integer\"\n },\n \"reasoning_tokens\": {\n \"type\": \"integer\"\n },\n \"rejected_prediction_tokens\": {\n \"type\": \"integer\"\n },\n \"text_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"type\": \"object\"\n },\n \"prompt_tokens\": {\n \"type\": \"integer\"\n },\n \"prompt_tokens_details\": {\n \"properties\": {\n \"audio_tokens\": {\n \"type\": \"integer\"\n },\n \"cache_write_tokens\": {\n \"type\": \"integer\"\n },\n \"cached_tokens\": {\n \"type\": \"integer\"\n },\n \"image_tokens\": {\n \"type\": \"integer\"\n },\n \"text_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"type\": \"object\"\n },\n \"total_tokens\": {\n \"type\": \"integer\"\n }\n },\n \"required\": [\n \"completion_tokens\",\n \"prompt_tokens\",\n \"total_tokens\"\n ],\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"choices\",\n \"created\",\n \"id\",\n \"model\",\n \"object\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Create chat completion\\n\\n**Starting a new project?** We recommend trying [Responses](https://developers.openai.com/api/reference/resources/responses)\\nto take advantage of the latest OpenAI platform features. Compare\\n[Chat Completions with Responses](https://developers.openai.com/api/docs/guides/migrate-to-responses?api-mode=responses).\\n\\n---\\n\\nCreates a model response for the given chat conversation. Learn more in the\\n[text generation](https://developers.openai.com/api/docs/guides/text), [vision](https://developers.openai.com/api/docs/guides/images-vision),\\nand [audio](https://developers.openai.c\"\n }\n }\n },\n \"servers\": [\n {\n \"url\": \"/v1\"\n }\n ]\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/openai/openai-openapi/main/openapi.yaml" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_124e896cf8e7.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_124e896cf8e7.json new file mode 100644 index 0000000..d9ecc8e --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_124e896cf8e7.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/api/v2/logs/events\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"filter[from]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"filter[indexes]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"filter[query]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"filter[storage_tier]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"filter[to]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page[cursor]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page[limit]\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"sort\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"data\": {\n \"items\": {\n \"properties\": {\n \"attributes\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"links\": {\n \"properties\": {\n \"next\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"meta\": {\n \"properties\": {\n \"elapsed\": {\n \"type\": \"integer\"\n },\n \"page\": {\n \"properties\": {\n \"after\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"request_id\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"warnings\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Search logs (GET)\\n\\nList endpoint returns logs that match a log search query.\\n[Results are paginated][1].\\n\\nUse this endpoint to search and filter your logs.\\n\\n**If you are considering archiving logs for your organization,\\nconsider use of the Datadog archive capabilities instead of the log list API.\\nSee [Datadog Logs Archive documentation][2].**\\n\\n[1]: /logs/guide/collect-multiple-logs-with-pagination\\n[2]: https://docs.datadoghq.com/logs/archives\"\n }\n }\n }\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v2/openapi.yaml" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_1c599e89375c.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_1c599e89375c.json new file mode 100644 index 0000000..9706cb6 --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_1c599e89375c.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v3/marketing/contacts\": {\n \"get\": {\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"_metadata\": {\n \"properties\": {\n \"self\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"contact_count\": {\n \"type\": \"integer\"\n },\n \"result\": {\n \"items\": {\n \"properties\": {\n \"_metadata\": {\n \"type\": \"object\"\n },\n \"address_line_1\": {\n \"type\": \"string\"\n },\n \"address_line_2\": {\n \"type\": \"string\"\n },\n \"alternate_emails\": {\n \"type\": \"array\"\n },\n \"anonymous_id\": {\n \"type\": \"string\"\n },\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"custom_fields\": {\n \"type\": \"object\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_id\": {\n \"type\": \"string\"\n },\n \"facebook\": {\n \"type\": \"string\"\n },\n \"first_name\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"last_name\": {\n \"type\": \"string\"\n },\n \"line\": {\n \"type\": \"string\"\n },\n \"list_ids\": {\n \"type\": \"array\"\n },\n \"phone_number\": {\n \"type\": \"string\"\n },\n \"phone_number_id\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"segment_ids\": {\n \"type\": \"array\"\n },\n \"state_province_region\": {\n \"type\": \"string\"\n },\n \"unique_name\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"whatsapp\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"created_at\",\n \"id\",\n \"list_ids\",\n \"segment_ids\",\n \"updated_at\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Get Sample Contacts\\n\\n**This endpoint will return up to 50 of the most recent contacts uploaded or attached to a list**. \\n\\nThis list will then be sorted by email address.\\n\\nThe full contact count is also returned.\\n\\nPlease note that pagination of the contacts has been deprecated.\\n\\nTwilio SendGrid recommends exporting your contacts regularly as a backup to avoid issues or lost data.\"\n }\n }\n }\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_mc_contacts_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_3bbb5588add3.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_3bbb5588add3.json index 8d5841c..2bfc184 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_3bbb5588add3.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_3bbb5588add3.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2020-09-14_1.778.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/transactions/get\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"access_token\": {\n \"type\": \"string\"\n },\n \"client_id\": {\n \"type\": \"string\"\n },\n \"end_date\": {\n \"type\": \"string\"\n },\n \"options\": {\n \"properties\": {\n \"account_ids\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"count\": {\n \"type\": \"integer\"\n },\n \"days_requested\": {\n \"type\": \"integer\"\n },\n \"include_logo_and_counterparty_beta\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_original_description\": {\n \"type\": \"boolean\"\n },\n \"include_personal_finance_category\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_personal_finance_category_beta\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"offset\": {\n \"type\": \"integer\"\n },\n \"personal_finance_category_version\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret\": {\n \"type\": \"string\"\n },\n \"start_date\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"access_token\",\n \"end_date\",\n \"start_date\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"accounts\": {\n \"items\": {\n \"properties\": {\n \"account_id\": {\n \"type\": \"string\"\n },\n \"apy\": {\n \"type\": \"number\"\n },\n \"balances\": {\n \"type\": \"object\"\n },\n \"holder_category\": {\n \"type\": \"string\"\n },\n \"mask\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"official_name\": {\n \"type\": \"string\"\n },\n \"paired_account_id\": {\n \"type\": \"string\"\n },\n \"persistent_account_id\": {\n \"type\": \"string\"\n },\n \"subtype\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"verification_insights\": {\n \"type\": \"object\"\n },\n \"verification_name\": {\n \"type\": \"string\"\n },\n \"verification_status\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account_id\",\n \"balances\",\n \"mask\",\n \"name\",\n \"official_name\",\n \"subtype\",\n \"type\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"item\": {\n \"properties\": {\n \"auth_method\": {\n \"type\": \"string\"\n },\n \"available_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"billed_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"consent_expiration_time\": {\n \"type\": \"string\"\n },\n \"consented_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"error\": {\n \"properties\": {\n \"causes\": {\n \"type\": \"array\"\n },\n \"display_message\": {\n \"type\": \"string\"\n },\n \"documentation_url\": {\n \"type\": \"string\"\n },\n \"error_code\": {\n \"type\": \"string\"\n },\n \"error_code_reason\": {\n \"type\": \"string\"\n },\n \"error_message\": {\n \"type\": \"string\"\n },\n \"error_type\": {\n \"type\": \"string\"\n },\n \"provided_account_subtypes\": {\n \"type\": \"array\"\n },\n \"request_id\": {\n \"type\": \"string\"\n },\n \"required_account_subtypes\": {\n \"type\": \"array\"\n },\n \"status\": {\n \"type\": \"integer\"\n },\n \"suggested_action\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"display_message\",\n \"error_code\",\n \"error_message\",\n \"error_type\"\n ],\n \"type\": \"object\"\n },\n \"institution_id\": {\n \"type\": \"string\"\n },\n \"institution_name\": {\n \"type\": \"string\"\n },\n \"item_id\": {\n \"type\": \"string\"\n },\n \"paired_item_id\": {\n \"type\": \"string\"\n },\n \"products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"update_type\": {\n \"type\": \"string\"\n },\n \"webhook\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"available_products\",\n \"billed_products\",\n \"consent_expiration_time\",\n \"error\",\n \"item_id\",\n \"update_type\",\n \"webhook\"\n ],\n \"type\": \"object\"\n },\n \"request_id\": {\n \"type\": \"string\"\n },\n \"total_transactions\": {\n \"type\": \"integer\"\n },\n \"transactions\": {\n \"items\": {\n \"properties\": {\n \"account_id\": {\n \"type\": \"string\"\n },\n \"account_owner\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"number\"\n },\n \"authorized_date\": {\n \"type\": \"string\"\n },\n \"authorized_datetime\": {\n \"type\": \"string\"\n },\n \"business_finance_category\": {\n \"type\": \"object\"\n },\n \"category\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"category_id\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"check_number\": {\n \"type\": \"string\"\n },\n \"client_customization\": {\n \"type\": \"object\"\n },\n \"counterparties\": {\n \"type\": \"array\"\n },\n \"date\": {\n \"type\": \"string\"\n },\n \"datetime\": {\n \"type\": \"string\"\n },\n \"iso_currency_code\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"object\"\n },\n \"logo_url\": {\n \"type\": \"string\"\n },\n \"merchant_category_code\": {\n \"type\": \"string\"\n },\n \"merchant_entity_id\": {\n \"type\": \"string\"\n },\n \"merchant_name\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"original_description\": {\n \"type\": \"string\"\n },\n \"payment_channel\": {\n \"type\": \"string\"\n },\n \"payment_meta\": {\n \"type\": \"object\"\n },\n \"pending\": {\n \"type\": \"boolean\"\n },\n \"pending_transaction_id\": {\n \"type\": \"string\"\n },\n \"personal_finance_category\": {\n \"type\": \"object\"\n },\n \"personal_finance_category_icon_url\": {\n \"type\": \"string\"\n },\n \"running_balance\": {\n \"type\": \"number\"\n },\n \"transaction_code\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n },\n \"transaction_type\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"unofficial_currency_code\": {\n \"type\": \"string\"\n },\n \"website\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account_id\",\n \"account_owner\",\n \"amount\",\n \"authorized_date\",\n \"authorized_datetime\",\n \"date\",\n \"datetime\",\n \"iso_currency_code\",\n \"location\",\n \"name\",\n \"payment_channel\",\n \"payment_meta\",\n \"pending\",\n \"pending_transaction_id\",\n \"transaction_code\",\n \"transaction_id\",\n \"unofficial_currency_code\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"accounts\",\n \"item\",\n \"request_id\",\n \"total_transactions\",\n \"transactions\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Get transaction data\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2020-09-14_1.778.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/transactions/get\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"access_token\": {\n \"type\": \"string\"\n },\n \"client_id\": {\n \"type\": \"string\"\n },\n \"end_date\": {\n \"type\": \"string\"\n },\n \"options\": {\n \"properties\": {\n \"account_ids\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"count\": {\n \"type\": \"integer\"\n },\n \"days_requested\": {\n \"type\": \"integer\"\n },\n \"include_logo_and_counterparty_beta\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_original_description\": {\n \"type\": \"boolean\"\n },\n \"include_personal_finance_category\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_personal_finance_category_beta\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"offset\": {\n \"type\": \"integer\"\n },\n \"personal_finance_category_version\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret\": {\n \"type\": \"string\"\n },\n \"start_date\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"access_token\",\n \"end_date\",\n \"start_date\"\n ],\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"accounts\": {\n \"items\": {\n \"properties\": {\n \"account_id\": {\n \"type\": \"string\"\n },\n \"apy\": {\n \"type\": \"number\"\n },\n \"balances\": {\n \"type\": \"object\"\n },\n \"holder_category\": {\n \"type\": \"string\"\n },\n \"mask\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"official_name\": {\n \"type\": \"string\"\n },\n \"paired_account_id\": {\n \"type\": \"string\"\n },\n \"persistent_account_id\": {\n \"type\": \"string\"\n },\n \"subtype\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"verification_insights\": {\n \"type\": \"object\"\n },\n \"verification_name\": {\n \"type\": \"string\"\n },\n \"verification_status\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account_id\",\n \"balances\",\n \"mask\",\n \"name\",\n \"official_name\",\n \"subtype\",\n \"type\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"item\": {\n \"properties\": {\n \"auth_method\": {\n \"type\": \"string\"\n },\n \"available_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"billed_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"consent_expiration_time\": {\n \"type\": \"string\"\n },\n \"consented_products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"error\": {\n \"properties\": {\n \"causes\": {\n \"type\": \"array\"\n },\n \"display_message\": {\n \"type\": \"string\"\n },\n \"documentation_url\": {\n \"type\": \"string\"\n },\n \"error_code\": {\n \"type\": \"string\"\n },\n \"error_code_reason\": {\n \"type\": \"string\"\n },\n \"error_message\": {\n \"type\": \"string\"\n },\n \"error_type\": {\n \"type\": \"string\"\n },\n \"provided_account_subtypes\": {\n \"type\": \"array\"\n },\n \"request_id\": {\n \"type\": \"string\"\n },\n \"required_account_subtypes\": {\n \"type\": \"array\"\n },\n \"status\": {\n \"type\": \"integer\"\n },\n \"suggested_action\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"display_message\",\n \"error_code\",\n \"error_message\",\n \"error_type\"\n ],\n \"type\": \"object\"\n },\n \"institution_id\": {\n \"type\": \"string\"\n },\n \"institution_name\": {\n \"type\": \"string\"\n },\n \"item_id\": {\n \"type\": \"string\"\n },\n \"paired_item_id\": {\n \"type\": \"string\"\n },\n \"products\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"update_type\": {\n \"type\": \"string\"\n },\n \"webhook\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"available_products\",\n \"billed_products\",\n \"consent_expiration_time\",\n \"error\",\n \"item_id\",\n \"update_type\",\n \"webhook\"\n ],\n \"type\": \"object\"\n },\n \"request_id\": {\n \"type\": \"string\"\n },\n \"total_transactions\": {\n \"type\": \"integer\"\n },\n \"transactions\": {\n \"items\": {\n \"properties\": {\n \"account_id\": {\n \"type\": \"string\"\n },\n \"account_owner\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"number\"\n },\n \"authorized_date\": {\n \"type\": \"string\"\n },\n \"authorized_datetime\": {\n \"type\": \"string\"\n },\n \"business_finance_category\": {\n \"type\": \"object\"\n },\n \"category\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"category_id\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"check_number\": {\n \"type\": \"string\"\n },\n \"client_customization\": {\n \"type\": \"object\"\n },\n \"counterparties\": {\n \"type\": \"array\"\n },\n \"date\": {\n \"type\": \"string\"\n },\n \"datetime\": {\n \"type\": \"string\"\n },\n \"iso_currency_code\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"object\"\n },\n \"logo_url\": {\n \"type\": \"string\"\n },\n \"merchant_category_code\": {\n \"type\": \"string\"\n },\n \"merchant_entity_id\": {\n \"type\": \"string\"\n },\n \"merchant_name\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"original_description\": {\n \"type\": \"string\"\n },\n \"payment_channel\": {\n \"type\": \"string\"\n },\n \"payment_meta\": {\n \"type\": \"object\"\n },\n \"pending\": {\n \"type\": \"boolean\"\n },\n \"pending_transaction_id\": {\n \"type\": \"string\"\n },\n \"personal_finance_category\": {\n \"type\": \"object\"\n },\n \"personal_finance_category_icon_url\": {\n \"type\": \"string\"\n },\n \"running_balance\": {\n \"type\": \"number\"\n },\n \"transaction_code\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n },\n \"transaction_type\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"unofficial_currency_code\": {\n \"type\": \"string\"\n },\n \"website\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account_id\",\n \"account_owner\",\n \"amount\",\n \"authorized_date\",\n \"authorized_datetime\",\n \"date\",\n \"datetime\",\n \"iso_currency_code\",\n \"location\",\n \"name\",\n \"payment_channel\",\n \"payment_meta\",\n \"pending\",\n \"pending_transaction_id\",\n \"transaction_code\",\n \"transaction_id\",\n \"unofficial_currency_code\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"accounts\",\n \"item\",\n \"request_id\",\n \"total_transactions\",\n \"transactions\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Get transaction data\\n\\nNote: All new implementations are encouraged to use `/transactions/sync` rather than `/transactions/get`. `/transactions/sync` provides the same functionality as `/transactions/get` and improves developer ease-of-use for handling transactions updates.\\nThe `/transactions/get` endpoint allows developers to receive user-authorized transaction data for credit, depository, and loan-type accounts (coverage may be limited). For transaction history from investment accounts, use the [Investments endpoint](https://plaid.com/docs/api/products/investments/) instead. Transaction data \"\n }\n }\n }\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/plaid/plaid-openapi/master/2020-09-14.yml" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4499f8059f9b.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4499f8059f9b.json new file mode 100644 index 0000000..c8f88a7 --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4499f8059f9b.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {}\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_webhooks_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4568fa60b87f.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4568fa60b87f.json new file mode 100644 index 0000000..e5eda53 --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_4568fa60b87f.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v3/templates\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"header\",\n \"name\": \"on-behalf-of\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"generations\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page_size\",\n \"required\": true\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page_token\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"_metadata\": {\n \"properties\": {\n \"count\": {\n \"type\": \"integer\"\n },\n \"next\": {\n \"type\": \"string\"\n },\n \"prev\": {\n \"type\": \"string\"\n },\n \"self\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"result\": {\n \"items\": {\n \"properties\": {\n \"generation\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"versions\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"generation\",\n \"id\",\n \"name\",\n \"updated_at\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Retrieve paged transactional templates.\\n\\n**This endpoint allows you to retrieve all transactional templates.**\"\n }\n }\n }\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_templates_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_48d20ee6325e.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_48d20ee6325e.json index c79caaf..4fe7802 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_48d20ee6325e.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_48d20ee6325e.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2026-09-30.endive\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v1/charges\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"application_fee\": {\n \"type\": \"integer\"\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"capture\": {\n \"type\": \"boolean\"\n },\n \"card\": {\n \"properties\": {\n \"address_city\": {\n \"type\": \"string\"\n },\n \"address_country\": {\n \"type\": \"string\"\n },\n \"address_line1\": {\n \"type\": \"string\"\n },\n \"address_line2\": {\n \"type\": \"string\"\n },\n \"address_state\": {\n \"type\": \"string\"\n },\n \"address_zip\": {\n \"type\": \"string\"\n },\n \"cvc\": {\n \"type\": \"string\"\n },\n \"encrypted\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"network_token\": {\n \"properties\": {\n \"number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"number\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"swipe_data\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"integer\"\n }\n },\n \"type\": \"object\"\n },\n \"expand\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"on_behalf_of\": {\n \"type\": \"string\"\n },\n \"radar_options\": {\n \"properties\": {\n \"session\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"receipt_email\": {\n \"type\": \"string\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"address\",\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"source\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"statement_descriptor_suffix\": {\n \"type\": \"string\"\n },\n \"transfer_data\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"destination\"\n ],\n \"type\": \"object\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_captured\": {\n \"type\": \"integer\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"application_fee\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"properties\": {\n \"charge\": {\n \"type\": \"string\"\n },\n \"payout\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunds\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n }\n },\n \"type\": \"string\"\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"adjusted_for_overdraft\": {\n \"type\": \"object\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_details\": {\n \"type\": \"object\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"type\": \"string\"\n },\n \"application_fee\": {\n \"type\": \"string\"\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"applied_to_payment\": {\n \"type\": \"object\"\n },\n \"approved\": {\n \"type\": \"boolean\"\n },\n \"arrival_date\": {\n \"type\": \"integer\"\n },\n \"authorization\": {\n \"type\": \"string\"\n },\n \"authorization_method\": {\n \"type\": \"string\"\n },\n \"automatic\": {\n \"type\": \"boolean\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"balance_transactions\": {\n \"type\": \"array\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_presence\": {\n \"type\": \"string\"\n },\n \"cardholder\": {\n \"type\": \"string\"\n },\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n },\n \"dispute\": {\n \"type\": \"string\"\n },\n \"ending_balance\": {\n \"type\": \"integer\"\n },\n \"enhanced_eligibility_types\": {\n \"type\": \"array\"\n },\n \"evidence\": {\n \"type\": \"object\"\n },\n \"evidence_details\": {\n \"type\": \"object\"\n },\n \"expected_availability_date\": {\n \"type\": \"integer\"\n },\n \"failure_balance_transaction\": {\n \"type\": \"string\"\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"fee\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"type\": \"object\"\n },\n \"fleet\": {\n \"type\": \"object\"\n },\n \"fraud_challenges\": {\n \"type\": \"array\"\n },\n \"fuel\": {\n \"type\": \"object\"\n },\n \"funded\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"initiated_by\": {\n \"type\": \"string\"\n },\n \"is_charge_refundable\": {\n \"type\": \"boolean\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"loss_reason\": {\n \"type\": \"string\"\n },\n \"merchant_amount\": {\n \"type\": \"integer\"\n },\n \"merchant_currency\": {\n \"type\": \"string\"\n },\n \"merchant_data\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"method\": {\n \"type\": \"string\"\n },\n \"net_amount\": {\n \"type\": \"integer\"\n },\n \"network_data\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"original_payout\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"payment_intent\": {\n \"type\": \"string\"\n },\n \"payment_method\": {\n \"type\": \"string\"\n },\n \"payment_method_details\": {\n \"type\": \"object\"\n },\n \"payment_method_options\": {\n \"type\": \"object\"\n },\n \"payout_method\": {\n \"type\": \"string\"\n },\n \"pending_request\": {\n \"type\": \"object\"\n },\n \"period_end\": {\n \"type\": \"integer\"\n },\n \"period_start\": {\n \"type\": \"integer\"\n },\n \"purchase_details\": {\n \"type\": \"object\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"reconciliation_status\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunded_from_payment\": {\n \"type\": \"object\"\n },\n \"refunds\": {\n \"type\": \"object\"\n },\n \"request_history\": {\n \"type\": \"array\"\n },\n \"reversed_by\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"object\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tax_deduction_account_number\": {\n \"type\": \"string\"\n },\n \"token\": {\n \"type\": \"string\"\n },\n \"trace_id\": {\n \"type\": \"object\"\n },\n \"transaction\": {\n \"type\": \"string\"\n },\n \"transactions\": {\n \"type\": \"array\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n },\n \"transferred_to_balance\": {\n \"type\": \"object\"\n },\n \"treasury\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"unapplied_from_payment\": {\n \"type\": \"object\"\n },\n \"verification_data\": {\n \"type\": \"object\"\n },\n \"verified_by_fraud_challenge\": {\n \"type\": \"boolean\"\n },\n \"wallet\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"billing_details\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tax_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"calculated_statement_descriptor\": {\n \"type\": \"string\"\n },\n \"captured\": {\n \"type\": \"boolean\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"properties\": {\n \"deleted\": {\n \"type\": \"boolean\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disputed\": {\n \"type\": \"boolean\"\n },\n \"failure_balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"adjusted_for_overdraft\": {\n \"type\": \"object\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_details\": {\n \"type\": \"object\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"type\": \"string\"\n },\n \"application_fee\": {\n \"type\": \"string\"\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"applied_to_payment\": {\n \"type\": \"object\"\n },\n \"approved\": {\n \"type\": \"boolean\"\n },\n \"arrival_date\": {\n \"type\": \"integer\"\n },\n \"authorization\": {\n \"type\": \"string\"\n },\n \"authorization_method\": {\n \"type\": \"string\"\n },\n \"automatic\": {\n \"type\": \"boolean\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"balance_transactions\": {\n \"type\": \"array\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_presence\": {\n \"type\": \"string\"\n },\n \"cardholder\": {\n \"type\": \"string\"\n },\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n },\n \"dispute\": {\n \"type\": \"string\"\n },\n \"ending_balance\": {\n \"type\": \"integer\"\n },\n \"enhanced_eligibility_types\": {\n \"type\": \"array\"\n },\n \"evidence\": {\n \"type\": \"object\"\n },\n \"evidence_details\": {\n \"type\": \"object\"\n },\n \"expected_availability_date\": {\n \"type\": \"integer\"\n },\n \"failure_balance_transaction\": {\n \"type\": \"string\"\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"fee\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"type\": \"object\"\n },\n \"fleet\": {\n \"type\": \"object\"\n },\n \"fraud_challenges\": {\n \"type\": \"array\"\n },\n \"fuel\": {\n \"type\": \"object\"\n },\n \"funded\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"initiated_by\": {\n \"type\": \"string\"\n },\n \"is_charge_refundable\": {\n \"type\": \"boolean\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"loss_reason\": {\n \"type\": \"string\"\n },\n \"merchant_amount\": {\n \"type\": \"integer\"\n },\n \"merchant_currency\": {\n \"type\": \"string\"\n },\n \"merchant_data\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"method\": {\n \"type\": \"string\"\n },\n \"net_amount\": {\n \"type\": \"integer\"\n },\n \"network_data\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"original_payout\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"payment_intent\": {\n \"type\": \"string\"\n },\n \"payment_method\": {\n \"type\": \"string\"\n },\n \"payment_method_details\": {\n \"type\": \"object\"\n },\n \"payment_method_options\": {\n \"type\": \"object\"\n },\n \"payout_method\": {\n \"type\": \"string\"\n },\n \"pending_request\": {\n \"type\": \"object\"\n },\n \"period_end\": {\n \"type\": \"integer\"\n },\n \"period_start\": {\n \"type\": \"integer\"\n },\n \"purchase_details\": {\n \"type\": \"object\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"reconciliation_status\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunded_from_payment\": {\n \"type\": \"object\"\n },\n \"refunds\": {\n \"type\": \"object\"\n },\n \"request_history\": {\n \"type\": \"array\"\n },\n \"reversed_by\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"object\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tax_deduction_account_number\": {\n \"type\": \"string\"\n },\n \"token\": {\n \"type\": \"string\"\n },\n \"trace_id\": {\n \"type\": \"object\"\n },\n \"transaction\": {\n \"type\": \"string\"\n },\n \"transactions\": {\n \"type\": \"array\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n },\n \"transferred_to_balance\": {\n \"type\": \"object\"\n },\n \"treasury\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"unapplied_from_payment\": {\n \"type\": \"object\"\n },\n \"verification_data\": {\n \"type\": \"object\"\n },\n \"verified_by_fraud_challenge\": {\n \"type\": \"boolean\"\n },\n \"wallet\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"fraud_details\": {\n \"properties\": {\n \"stripe_report\": {\n \"type\": \"string\"\n },\n \"user_report\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"on_behalf_of\": {\n \"type\": \"string\"\n },\n \"outcome\": {\n \"properties\": {\n \"advice_code\": {\n \"type\": \"string\"\n },\n \"network_advice_code\": {\n \"type\": \"string\"\n },\n \"network_decline_code\": {\n \"type\": \"string\"\n },\n \"network_status\": {\n \"type\": \"string\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"risk_level\": {\n \"type\": \"string\"\n },\n \"risk_score\": {\n \"type\": \"integer\"\n },\n \"rule\": {\n \"properties\": {\n \"action\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"predicate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"seller_message\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paid\": {\n \"type\": \"boolean\"\n },\n \"payment_intent\": {\n \"type\": \"string\"\n },\n \"payment_method\": {\n \"type\": \"string\"\n },\n \"payment_method_details\": {\n \"properties\": {\n \"ach_credit_transfer\": {\n \"properties\": {\n \"account_number\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n },\n \"swift_code\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"ach_debit\": {\n \"properties\": {\n \"account_holder_type\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"acss_debit\": {\n \"properties\": {\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"institution_number\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"transit_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"affirm\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"afterpay_clearpay\": {\n \"properties\": {\n \"order_id\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"alipay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"alma\": {\n \"properties\": {\n \"installments\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"amazon_pay\": {\n \"properties\": {\n \"funding\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"au_becs_debit\": {\n \"properties\": {\n \"bsb_number\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bacs_debit\": {\n \"properties\": {\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"sort_code\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bancontact\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit_mandate\": {\n \"type\": \"string\"\n },\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"preferred_language\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"billie\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bizum\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"blik\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"boleto\": {\n \"properties\": {\n \"tax_id\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"tax_id\"\n ],\n \"type\": \"object\"\n },\n \"card\": {\n \"properties\": {\n \"amount_authorized\": {\n \"type\": \"integer\"\n },\n \"authorization_code\": {\n \"type\": \"string\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"capture_before\": {\n \"type\": \"integer\"\n },\n \"checks\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"electronic_commerce_indicator\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"extended_authorization\": {\n \"type\": \"object\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"incremental_authorization\": {\n \"type\": \"object\"\n },\n \"installments\": {\n \"type\": \"object\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"multicapture\": {\n \"type\": \"object\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_token\": {\n \"type\": \"object\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"overcapture\": {\n \"type\": \"object\"\n },\n \"regulated_status\": {\n \"type\": \"string\"\n },\n \"three_d_secure\": {\n \"type\": \"object\"\n },\n \"transaction_link_id\": {\n \"type\": \"string\"\n },\n \"wallet\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\"\n ],\n \"type\": \"object\"\n },\n \"card_present\": {\n \"properties\": {\n \"amount_authorized\": {\n \"type\": \"integer\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"brand_product\": {\n \"type\": \"string\"\n },\n \"capture_before\": {\n \"type\": \"integer\"\n },\n \"cardholder_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"emv_auth_data\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"generated_card\": {\n \"type\": \"string\"\n },\n \"incremental_authorization_supported\": {\n \"type\": \"boolean\"\n },\n \"issuer\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"offline\": {\n \"type\": \"object\"\n },\n \"overcapture_supported\": {\n \"type\": \"boolean\"\n },\n \"preferred_locales\": {\n \"type\": \"array\"\n },\n \"read_method\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"receipt\": {\n \"type\": \"object\"\n },\n \"wallet\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\",\n \"incremental_authorization_supported\",\n \"overcapture_supported\"\n ],\n \"type\": \"object\"\n },\n \"cashapp\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"cashtag\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"crypto\": {\n \"properties\": {\n \"buyer_address\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"token_currency\": {\n \"type\": \"string\"\n },\n \"transaction_hash\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"customer_balance\": {\n \"type\": \"object\"\n },\n \"eps\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"fpx\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"bank\"\n ],\n \"type\": \"object\"\n },\n \"giropay\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"grabpay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"ideal\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit_mandate\": {\n \"type\": \"string\"\n },\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"interac_present\": {\n \"properties\": {\n \"brand\": {\n \"type\": \"string\"\n },\n \"cardholder_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"emv_auth_data\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"generated_card\": {\n \"type\": \"string\"\n },\n \"issuer\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"preferred_locales\": {\n \"type\": \"array\"\n },\n \"read_method\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"receipt\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\"\n ],\n \"type\": \"object\"\n },\n \"kakao_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"klarna\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"payer_details\": {\n \"type\": \"object\"\n },\n \"payment_method_category\": {\n \"type\": \"string\"\n },\n \"preferred_locale\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"konbini\": {\n \"properties\": {\n \"store\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"kr_card\": {\n \"properties\": {\n \"brand\": {\n \"type\": \"string\"\n },\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"link\": {\n \"properties\": {\n \"country\": {\n \"type\": \"string\"\n },\n \"funding_source_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"mb_way\": {\n \"type\": \"object\"\n },\n \"mobilepay\": {\n \"properties\": {\n \"card\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"multibanco\": {\n \"properties\": {\n \"entity\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"naver_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"nz_bank_account\": {\n \"properties\": {\n \"account_holder_name\": {\n \"type\": \"string\"\n },\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"branch_code\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"suffix\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"bank_code\",\n \"bank_name\",\n \"branch_code\",\n \"last4\"\n ],\n \"type\": \"object\"\n },\n \"oxxo\": {\n \"properties\": {\n \"number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"p24\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"pay_by_bank\": {\n \"type\": \"object\"\n },\n \"payco\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paynow\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paypal\": {\n \"properties\": {\n \"country\": {\n \"type\": \"string\"\n },\n \"payer_email\": {\n \"type\": \"string\"\n },\n \"payer_id\": {\n \"type\": \"string\"\n },\n \"payer_name\": {\n \"type\": \"string\"\n },\n \"seller_protection\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paypay\": {\n \"type\": \"object\"\n },\n \"payto\": {\n \"properties\": {\n \"bsb_number\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"pay_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"pix\": {\n \"properties\": {\n \"bank_transaction_id\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"promptpay\": {\n \"properties\": {\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"revolut_pay\": {\n \"properties\": {\n \"funding\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"samsung_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"satispay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"scalapay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sepa_debit\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"branch_code\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sequra\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sofort\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit_mandate\": {\n \"type\": \"string\"\n },\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"preferred_language\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"stripe_account\": {\n \"type\": \"object\"\n },\n \"sunbit\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"swish\": {\n \"properties\": {\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"payment_reference\": {\n \"type\": \"string\"\n },\n \"verified_phone_last4\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"twint\": {\n \"properties\": {\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"upi\": {\n \"properties\": {\n \"vpa\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"us_bank_account\": {\n \"properties\": {\n \"account_holder_type\": {\n \"type\": \"string\"\n },\n \"account_type\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"payment_reference\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"wechat\": {\n \"type\": \"object\"\n },\n \"wechat_pay\": {\n \"properties\": {\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"zip\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"presentment_details\": {\n \"properties\": {\n \"presentment_amount\": {\n \"type\": \"integer\"\n },\n \"presentment_currency\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"presentment_amount\",\n \"presentment_currency\"\n ],\n \"type\": \"object\"\n },\n \"radar_options\": {\n \"properties\": {\n \"session\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"receipt_email\": {\n \"type\": \"string\"\n },\n \"receipt_number\": {\n \"type\": \"string\"\n },\n \"receipt_url\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunds\": {\n \"properties\": {\n \"data\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"review\": {\n \"properties\": {\n \"billing_zip\": {\n \"type\": \"string\"\n },\n \"charge\": {\n \"type\": \"string\"\n },\n \"closed_reason\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"ip_address\": {\n \"type\": \"string\"\n },\n \"ip_address_location\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"latitude\": {\n \"type\": \"number\"\n },\n \"longitude\": {\n \"type\": \"number\"\n },\n \"region\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"open\": {\n \"type\": \"boolean\"\n },\n \"opened_reason\": {\n \"type\": \"string\"\n },\n \"payment_intent\": {\n \"type\": \"string\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"session\": {\n \"properties\": {\n \"browser\": {\n \"type\": \"string\"\n },\n \"device\": {\n \"type\": \"string\"\n },\n \"platform\": {\n \"type\": \"string\"\n },\n \"version\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"string\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"source_transfer\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reversals\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"statement_descriptor_suffix\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"transfer\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reversals\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"string\"\n },\n \"transfer_data\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"destination\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"amount\",\n \"amount_captured\",\n \"amount_refunded\",\n \"billing_details\",\n \"captured\",\n \"created\",\n \"currency\",\n \"disputed\",\n \"id\",\n \"livemode\",\n \"metadata\",\n \"object\",\n \"paid\",\n \"refunded\",\n \"status\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Create a charge\"\n }\n },\n \"/v1/customers/{customer}/cards\": {\n \"get\": {\n \"deprecated\": true,\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"customer\",\n \"required\": true\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"ending_before\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"expand\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"limit\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"starting_after\",\n \"required\": false\n }\n ],\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"data\": {\n \"items\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"address_city\": {\n \"type\": \"string\"\n },\n \"address_country\": {\n \"type\": \"string\"\n },\n \"address_line1\": {\n \"type\": \"string\"\n },\n \"address_line1_check\": {\n \"type\": \"string\"\n },\n \"address_line2\": {\n \"type\": \"string\"\n },\n \"address_state\": {\n \"type\": \"string\"\n },\n \"address_zip\": {\n \"type\": \"string\"\n },\n \"address_zip_check\": {\n \"type\": \"string\"\n },\n \"allow_redisplay\": {\n \"type\": \"string\"\n },\n \"available_payout_methods\": {\n \"type\": \"array\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"cvc_check\": {\n \"type\": \"string\"\n },\n \"default_for_currency\": {\n \"type\": \"boolean\"\n },\n \"dynamic_last4\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"networks\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"regulated_status\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tokenization_method\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"brand\",\n \"exp_month\",\n \"exp_year\",\n \"funding\",\n \"id\",\n \"last4\",\n \"object\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List all cards\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"2026-09-30.endive\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/v1/charges\": {\n \"post\": {\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"application_fee\": {\n \"type\": \"integer\"\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"capture\": {\n \"type\": \"boolean\"\n },\n \"card\": {\n \"properties\": {\n \"address_city\": {\n \"type\": \"string\"\n },\n \"address_country\": {\n \"type\": \"string\"\n },\n \"address_line1\": {\n \"type\": \"string\"\n },\n \"address_line2\": {\n \"type\": \"string\"\n },\n \"address_state\": {\n \"type\": \"string\"\n },\n \"address_zip\": {\n \"type\": \"string\"\n },\n \"cvc\": {\n \"type\": \"string\"\n },\n \"encrypted\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"network_token\": {\n \"properties\": {\n \"number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"number\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"swipe_data\": {\n \"type\": \"string\"\n }\n }\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"integer\"\n }\n }\n },\n \"expand\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"metadata\": {},\n \"on_behalf_of\": {\n \"type\": \"string\"\n },\n \"radar_options\": {\n \"properties\": {\n \"session\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"receipt_email\": {\n \"type\": \"string\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"address\",\n \"name\"\n ],\n \"type\": \"object\"\n },\n \"source\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"statement_descriptor_suffix\": {\n \"type\": \"string\"\n },\n \"transfer_data\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"destination\"\n ],\n \"type\": \"object\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_captured\": {\n \"type\": \"integer\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n }\n },\n \"application_fee\": {\n \"properties\": {\n \"account\": {\n \"properties\": {\n \"business_profile\": {\n \"type\": \"object\"\n },\n \"business_type\": {\n \"type\": \"string\"\n },\n \"capabilities\": {\n \"type\": \"object\"\n },\n \"charges_enabled\": {\n \"type\": \"boolean\"\n },\n \"company\": {\n \"type\": \"object\"\n },\n \"controller\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"default_currency\": {\n \"type\": \"string\"\n },\n \"details_submitted\": {\n \"type\": \"boolean\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_accounts\": {\n \"type\": \"object\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"groups\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payouts_enabled\": {\n \"type\": \"boolean\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"settings\": {\n \"type\": \"object\"\n },\n \"tos_acceptance\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n }\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"properties\": {\n \"charge\": {\n \"type\": \"string\"\n },\n \"payout\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunds\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n }\n }\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"properties\": {\n \"account\": {},\n \"adjusted_for_overdraft\": {\n \"type\": \"object\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_details\": {\n \"type\": \"object\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"application\": {},\n \"application_fee\": {},\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"applied_to_payment\": {\n \"type\": \"object\"\n },\n \"approved\": {\n \"type\": \"boolean\"\n },\n \"arrival_date\": {\n \"type\": \"integer\"\n },\n \"authorization\": {\n \"type\": \"string\"\n },\n \"authorization_method\": {\n \"type\": \"string\"\n },\n \"automatic\": {\n \"type\": \"boolean\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"balance_transactions\": {\n \"type\": \"array\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_presence\": {\n \"type\": \"string\"\n },\n \"cardholder\": {},\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {},\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {},\n \"destination_details\": {\n \"type\": \"object\"\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"destination_payment_refund\": {\n \"type\": \"string\"\n },\n \"dispute\": {},\n \"ending_balance\": {\n \"type\": \"integer\"\n },\n \"enhanced_eligibility_types\": {\n \"type\": \"array\"\n },\n \"evidence\": {\n \"type\": \"object\"\n },\n \"evidence_details\": {\n \"type\": \"object\"\n },\n \"expected_availability_date\": {\n \"type\": \"integer\"\n },\n \"failure_balance_transaction\": {\n \"type\": \"string\"\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"failure_reason\": {\n \"type\": \"string\"\n },\n \"fee\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"type\": \"object\"\n },\n \"fleet\": {\n \"type\": \"object\"\n },\n \"fraud_challenges\": {\n \"type\": \"array\"\n },\n \"fuel\": {\n \"type\": \"object\"\n },\n \"funded\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"initiated_by\": {\n \"type\": \"string\"\n },\n \"instructions_email\": {\n \"type\": \"string\"\n },\n \"is_charge_refundable\": {\n \"type\": \"boolean\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"loss_reason\": {\n \"type\": \"string\"\n },\n \"merchant_amount\": {\n \"type\": \"integer\"\n },\n \"merchant_currency\": {\n \"type\": \"string\"\n },\n \"merchant_data\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"method\": {\n \"type\": \"string\"\n },\n \"net_amount\": {\n \"type\": \"integer\"\n },\n \"network_data\": {\n \"type\": \"object\"\n },\n \"next_action\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"original_payout\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"payment_intent\": {},\n \"payment_method\": {},\n \"payment_method_details\": {\n \"type\": \"object\"\n },\n \"payment_method_options\": {\n \"type\": \"object\"\n },\n \"payout_method\": {\n \"type\": \"string\"\n },\n \"pending_reason\": {\n \"type\": \"string\"\n },\n \"pending_request\": {\n \"type\": \"object\"\n },\n \"period_end\": {\n \"type\": \"integer\"\n },\n \"period_start\": {\n \"type\": \"integer\"\n },\n \"presentment_details\": {\n \"type\": \"object\"\n },\n \"purchase_details\": {\n \"type\": \"object\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"receipt_number\": {\n \"type\": \"string\"\n },\n \"reconciliation_status\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunded_from_payment\": {\n \"type\": \"object\"\n },\n \"refunds\": {\n \"type\": \"object\"\n },\n \"request_history\": {\n \"type\": \"array\"\n },\n \"reversals\": {\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"reversed_by\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"object\"\n },\n \"source_refund\": {\n \"type\": \"string\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_transfer_reversal\": {},\n \"source_type\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tax_deduction_account_number\": {\n \"type\": \"string\"\n },\n \"token\": {},\n \"trace_id\": {\n \"type\": \"object\"\n },\n \"transaction\": {\n \"type\": \"string\"\n },\n \"transactions\": {\n \"type\": \"array\"\n },\n \"transfer\": {},\n \"transfer_group\": {\n \"type\": \"string\"\n },\n \"transfer_reversal\": {},\n \"transferred_to_balance\": {\n \"type\": \"object\"\n },\n \"treasury\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"unapplied_from_payment\": {\n \"type\": \"object\"\n },\n \"verification_data\": {\n \"type\": \"object\"\n },\n \"verified_by_fraud_challenge\": {\n \"type\": \"boolean\"\n },\n \"wallet\": {\n \"type\": \"string\"\n }\n }\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"billing_details\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tax_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"calculated_statement_descriptor\": {\n \"type\": \"string\"\n },\n \"captured\": {\n \"type\": \"boolean\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"balance\": {\n \"type\": \"integer\"\n },\n \"business_name\": {\n \"type\": \"string\"\n },\n \"cash_balance\": {\n \"properties\": {\n \"available\": {\n \"type\": \"object\"\n },\n \"customer\": {\n \"type\": \"string\"\n },\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"settings\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"default_source\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"account_holder_name\": {\n \"type\": \"string\"\n },\n \"account_holder_type\": {\n \"type\": \"string\"\n },\n \"account_type\": {\n \"type\": \"string\"\n },\n \"ach_credit_transfer\": {\n \"type\": \"object\"\n },\n \"ach_debit\": {\n \"type\": \"object\"\n },\n \"acss_debit\": {\n \"type\": \"object\"\n },\n \"address_city\": {\n \"type\": \"string\"\n },\n \"address_country\": {\n \"type\": \"string\"\n },\n \"address_line1\": {\n \"type\": \"string\"\n },\n \"address_line1_check\": {\n \"type\": \"string\"\n },\n \"address_line2\": {\n \"type\": \"string\"\n },\n \"address_state\": {\n \"type\": \"string\"\n },\n \"address_zip\": {\n \"type\": \"string\"\n },\n \"address_zip_check\": {\n \"type\": \"string\"\n },\n \"alipay\": {\n \"type\": \"object\"\n },\n \"allow_redisplay\": {\n \"type\": \"string\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"au_becs_debit\": {\n \"type\": \"object\"\n },\n \"available_payout_methods\": {\n \"type\": \"array\"\n },\n \"bancontact\": {\n \"type\": \"object\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_present\": {\n \"type\": \"object\"\n },\n \"client_secret\": {\n \"type\": \"string\"\n },\n \"code_verification\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {},\n \"cvc_check\": {\n \"type\": \"string\"\n },\n \"default_for_currency\": {\n \"type\": \"boolean\"\n },\n \"dynamic_last4\": {\n \"type\": \"string\"\n },\n \"eps\": {\n \"type\": \"object\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"flow\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"giropay\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"ideal\": {\n \"type\": \"object\"\n },\n \"klarna\": {\n \"type\": \"object\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"multibanco\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"networks\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"owner\": {\n \"type\": \"object\"\n },\n \"p24\": {\n \"type\": \"object\"\n },\n \"receiver\": {\n \"type\": \"object\"\n },\n \"redirect\": {\n \"type\": \"object\"\n },\n \"regulated_status\": {\n \"type\": \"string\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n },\n \"sepa_debit\": {\n \"type\": \"object\"\n },\n \"sofort\": {\n \"type\": \"object\"\n },\n \"source_order\": {\n \"type\": \"object\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"three_d_secure\": {\n \"type\": \"object\"\n },\n \"tokenization_method\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"usage\": {\n \"type\": \"string\"\n },\n \"wechat\": {\n \"type\": \"object\"\n }\n }\n },\n \"deleted\": {\n \"type\": \"boolean\"\n },\n \"delinquent\": {\n \"type\": \"boolean\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"discount\": {\n \"properties\": {\n \"checkout_session\": {\n \"type\": \"string\"\n },\n \"customer\": {},\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"end\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"invoice\": {\n \"type\": \"string\"\n },\n \"invoice_item\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"promotion_code\": {},\n \"source\": {\n \"type\": \"object\"\n },\n \"start\": {\n \"type\": \"integer\"\n },\n \"subscription\": {\n \"type\": \"string\"\n },\n \"subscription_item\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual_name\": {\n \"type\": \"string\"\n },\n \"invoice_credit_balance\": {\n \"type\": \"object\"\n },\n \"invoice_prefix\": {\n \"type\": \"string\"\n },\n \"invoice_settings\": {\n \"properties\": {\n \"custom_fields\": {\n \"type\": \"array\"\n },\n \"default_payment_method\": {},\n \"footer\": {\n \"type\": \"string\"\n },\n \"rendering_options\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"next_invoice_sequence\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"preferred_locales\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sources\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"subscriptions\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"tax\": {\n \"properties\": {\n \"automatic_tax\": {\n \"type\": \"string\"\n },\n \"ip_address\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"object\"\n },\n \"provider\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"automatic_tax\",\n \"provider\"\n ],\n \"type\": \"object\"\n },\n \"tax_exempt\": {\n \"type\": \"string\"\n },\n \"tax_ids\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"test_clock\": {\n \"properties\": {\n \"created\": {\n \"type\": \"integer\"\n },\n \"deletes_after\": {\n \"type\": \"integer\"\n },\n \"frozen_time\": {\n \"type\": \"integer\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"status_details\": {\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disputed\": {\n \"type\": \"boolean\"\n },\n \"failure_balance_transaction\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"available_on\": {\n \"type\": \"integer\"\n },\n \"balance_type\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"exchange_rate\": {\n \"type\": \"number\"\n },\n \"fee\": {\n \"type\": \"integer\"\n },\n \"fee_details\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"net\": {\n \"type\": \"integer\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reporting_category\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"properties\": {\n \"account\": {},\n \"adjusted_for_overdraft\": {\n \"type\": \"object\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_details\": {\n \"type\": \"object\"\n },\n \"amount_refunded\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"application\": {},\n \"application_fee\": {},\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"applied_to_payment\": {\n \"type\": \"object\"\n },\n \"approved\": {\n \"type\": \"boolean\"\n },\n \"arrival_date\": {\n \"type\": \"integer\"\n },\n \"authorization\": {\n \"type\": \"string\"\n },\n \"authorization_method\": {\n \"type\": \"string\"\n },\n \"automatic\": {\n \"type\": \"boolean\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"balance_transactions\": {\n \"type\": \"array\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_presence\": {\n \"type\": \"string\"\n },\n \"cardholder\": {},\n \"charge\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {},\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {},\n \"destination_details\": {\n \"type\": \"object\"\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"destination_payment_refund\": {\n \"type\": \"string\"\n },\n \"dispute\": {},\n \"ending_balance\": {\n \"type\": \"integer\"\n },\n \"enhanced_eligibility_types\": {\n \"type\": \"array\"\n },\n \"evidence\": {\n \"type\": \"object\"\n },\n \"evidence_details\": {\n \"type\": \"object\"\n },\n \"expected_availability_date\": {\n \"type\": \"integer\"\n },\n \"failure_balance_transaction\": {\n \"type\": \"string\"\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"failure_reason\": {\n \"type\": \"string\"\n },\n \"fee\": {\n \"type\": \"string\"\n },\n \"fee_source\": {\n \"type\": \"object\"\n },\n \"fleet\": {\n \"type\": \"object\"\n },\n \"fraud_challenges\": {\n \"type\": \"array\"\n },\n \"fuel\": {\n \"type\": \"object\"\n },\n \"funded\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"initiated_by\": {\n \"type\": \"string\"\n },\n \"instructions_email\": {\n \"type\": \"string\"\n },\n \"is_charge_refundable\": {\n \"type\": \"boolean\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"loss_reason\": {\n \"type\": \"string\"\n },\n \"merchant_amount\": {\n \"type\": \"integer\"\n },\n \"merchant_currency\": {\n \"type\": \"string\"\n },\n \"merchant_data\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"method\": {\n \"type\": \"string\"\n },\n \"net_amount\": {\n \"type\": \"integer\"\n },\n \"network_data\": {\n \"type\": \"object\"\n },\n \"next_action\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"original_payout\": {\n \"type\": \"string\"\n },\n \"originating_transaction\": {\n \"type\": \"string\"\n },\n \"payment_intent\": {},\n \"payment_method\": {},\n \"payment_method_details\": {\n \"type\": \"object\"\n },\n \"payment_method_options\": {\n \"type\": \"object\"\n },\n \"payout_method\": {\n \"type\": \"string\"\n },\n \"pending_reason\": {\n \"type\": \"string\"\n },\n \"pending_request\": {\n \"type\": \"object\"\n },\n \"period_end\": {\n \"type\": \"integer\"\n },\n \"period_start\": {\n \"type\": \"integer\"\n },\n \"presentment_details\": {\n \"type\": \"object\"\n },\n \"purchase_details\": {\n \"type\": \"object\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"receipt_number\": {\n \"type\": \"string\"\n },\n \"reconciliation_status\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunded_from_payment\": {\n \"type\": \"object\"\n },\n \"refunds\": {\n \"type\": \"object\"\n },\n \"request_history\": {\n \"type\": \"array\"\n },\n \"reversals\": {\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"reversed_by\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"object\"\n },\n \"source_refund\": {\n \"type\": \"string\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_transfer_reversal\": {},\n \"source_type\": {\n \"type\": \"string\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tax_deduction_account_number\": {\n \"type\": \"string\"\n },\n \"token\": {},\n \"trace_id\": {\n \"type\": \"object\"\n },\n \"transaction\": {\n \"type\": \"string\"\n },\n \"transactions\": {\n \"type\": \"array\"\n },\n \"transfer\": {},\n \"transfer_group\": {\n \"type\": \"string\"\n },\n \"transfer_reversal\": {},\n \"transferred_to_balance\": {\n \"type\": \"object\"\n },\n \"treasury\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"unapplied_from_payment\": {\n \"type\": \"object\"\n },\n \"verification_data\": {\n \"type\": \"object\"\n },\n \"verified_by_fraud_challenge\": {\n \"type\": \"boolean\"\n },\n \"wallet\": {\n \"type\": \"string\"\n }\n }\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"failure_code\": {\n \"type\": \"string\"\n },\n \"failure_message\": {\n \"type\": \"string\"\n },\n \"fraud_details\": {\n \"properties\": {\n \"stripe_report\": {\n \"type\": \"string\"\n },\n \"user_report\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"on_behalf_of\": {\n \"properties\": {\n \"business_profile\": {\n \"properties\": {\n \"annual_revenue\": {\n \"type\": \"object\"\n },\n \"estimated_worker_count\": {\n \"type\": \"integer\"\n },\n \"mcc\": {\n \"type\": \"string\"\n },\n \"minority_owned_business_designation\": {\n \"type\": \"array\"\n },\n \"monthly_estimated_revenue\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"product_description\": {\n \"type\": \"string\"\n },\n \"specified_commercial_transactions_act_url\": {\n \"type\": \"string\"\n },\n \"support_address\": {\n \"type\": \"object\"\n },\n \"support_email\": {\n \"type\": \"string\"\n },\n \"support_phone\": {\n \"type\": \"string\"\n },\n \"support_url\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"business_type\": {\n \"type\": \"string\"\n },\n \"capabilities\": {\n \"properties\": {\n \"acss_debit_payments\": {\n \"type\": \"string\"\n },\n \"affirm_payments\": {\n \"type\": \"string\"\n },\n \"afterpay_clearpay_payments\": {\n \"type\": \"string\"\n },\n \"alma_payments\": {\n \"type\": \"string\"\n },\n \"amazon_pay_payments\": {\n \"type\": \"string\"\n },\n \"app_distribution\": {\n \"type\": \"string\"\n },\n \"au_becs_debit_payments\": {\n \"type\": \"string\"\n },\n \"bacs_debit_payments\": {\n \"type\": \"string\"\n },\n \"bancontact_payments\": {\n \"type\": \"string\"\n },\n \"bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"billie_payments\": {\n \"type\": \"string\"\n },\n \"bizum_payments\": {\n \"type\": \"string\"\n },\n \"blik_payments\": {\n \"type\": \"string\"\n },\n \"blik_recurring_payments\": {\n \"type\": \"string\"\n },\n \"boleto_payments\": {\n \"type\": \"string\"\n },\n \"card_issuing\": {\n \"type\": \"string\"\n },\n \"card_payments\": {\n \"type\": \"string\"\n },\n \"cartes_bancaires_payments\": {\n \"type\": \"string\"\n },\n \"cashapp_payments\": {\n \"type\": \"string\"\n },\n \"crypto_payments\": {\n \"type\": \"string\"\n },\n \"eps_payments\": {\n \"type\": \"string\"\n },\n \"fpx_payments\": {\n \"type\": \"string\"\n },\n \"gb_bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"giropay_payments\": {\n \"type\": \"string\"\n },\n \"grabpay_payments\": {\n \"type\": \"string\"\n },\n \"ideal_payments\": {\n \"type\": \"string\"\n },\n \"india_international_payments\": {\n \"type\": \"string\"\n },\n \"jcb_payments\": {\n \"type\": \"string\"\n },\n \"jp_bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"kakao_pay_payments\": {\n \"type\": \"string\"\n },\n \"klarna_payments\": {\n \"type\": \"string\"\n },\n \"konbini_payments\": {\n \"type\": \"string\"\n },\n \"kr_card_payments\": {\n \"type\": \"string\"\n },\n \"legacy_payments\": {\n \"type\": \"string\"\n },\n \"link_payments\": {\n \"type\": \"string\"\n },\n \"mb_way_payments\": {\n \"type\": \"string\"\n },\n \"mobilepay_payments\": {\n \"type\": \"string\"\n },\n \"multibanco_payments\": {\n \"type\": \"string\"\n },\n \"mx_bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"naver_pay_payments\": {\n \"type\": \"string\"\n },\n \"nz_bank_account_becs_debit_payments\": {\n \"type\": \"string\"\n },\n \"oxxo_payments\": {\n \"type\": \"string\"\n },\n \"p24_payments\": {\n \"type\": \"string\"\n },\n \"pay_by_bank_payments\": {\n \"type\": \"string\"\n },\n \"payco_payments\": {\n \"type\": \"string\"\n },\n \"paynow_payments\": {\n \"type\": \"string\"\n },\n \"paypay_payments\": {\n \"type\": \"string\"\n },\n \"payto_payments\": {\n \"type\": \"string\"\n },\n \"pix_payments\": {\n \"type\": \"string\"\n },\n \"promptpay_payments\": {\n \"type\": \"string\"\n },\n \"revolut_pay_payments\": {\n \"type\": \"string\"\n },\n \"samsung_pay_payments\": {\n \"type\": \"string\"\n },\n \"satispay_payments\": {\n \"type\": \"string\"\n },\n \"scalapay_payments\": {\n \"type\": \"string\"\n },\n \"sepa_bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"sepa_debit_payments\": {\n \"type\": \"string\"\n },\n \"sequra_payments\": {\n \"type\": \"string\"\n },\n \"sofort_payments\": {\n \"type\": \"string\"\n },\n \"sunbit_payments\": {\n \"type\": \"string\"\n },\n \"swish_payments\": {\n \"type\": \"string\"\n },\n \"tax_reporting_us_1099_k\": {\n \"type\": \"string\"\n },\n \"tax_reporting_us_1099_misc\": {\n \"type\": \"string\"\n },\n \"transfers\": {\n \"type\": \"string\"\n },\n \"treasury\": {\n \"type\": \"string\"\n },\n \"twint_payments\": {\n \"type\": \"string\"\n },\n \"upi_payments\": {\n \"type\": \"string\"\n },\n \"us_bank_account_ach_payments\": {\n \"type\": \"string\"\n },\n \"us_bank_transfer_payments\": {\n \"type\": \"string\"\n },\n \"zip_payments\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"charges_enabled\": {\n \"type\": \"boolean\"\n },\n \"company\": {\n \"properties\": {\n \"address\": {\n \"type\": \"object\"\n },\n \"address_kana\": {\n \"type\": \"object\"\n },\n \"address_kanji\": {\n \"type\": \"object\"\n },\n \"administrative_address\": {\n \"type\": \"object\"\n },\n \"directors_provided\": {\n \"type\": \"boolean\"\n },\n \"directorship_declaration\": {\n \"type\": \"object\"\n },\n \"executives_provided\": {\n \"type\": \"boolean\"\n },\n \"export_license_id\": {\n \"type\": \"string\"\n },\n \"export_purpose_code\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"name_kana\": {\n \"type\": \"string\"\n },\n \"name_kanji\": {\n \"type\": \"string\"\n },\n \"owners_provided\": {\n \"type\": \"boolean\"\n },\n \"ownership_declaration\": {\n \"type\": \"object\"\n },\n \"ownership_exemption_reason\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"principal_place_of_business\": {\n \"type\": \"object\"\n },\n \"registration_date\": {\n \"type\": \"object\"\n },\n \"representative_declaration\": {\n \"type\": \"object\"\n },\n \"structure\": {\n \"type\": \"string\"\n },\n \"tax_id_provided\": {\n \"type\": \"boolean\"\n },\n \"tax_id_registrar\": {\n \"type\": \"string\"\n },\n \"vat_id_provided\": {\n \"type\": \"boolean\"\n },\n \"verification\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"controller\": {\n \"properties\": {\n \"fees\": {\n \"type\": \"object\"\n },\n \"is_controller\": {\n \"type\": \"boolean\"\n },\n \"losses\": {\n \"type\": \"object\"\n },\n \"requirement_collection\": {\n \"type\": \"string\"\n },\n \"stripe_dashboard\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"default_currency\": {\n \"type\": \"string\"\n },\n \"details_submitted\": {\n \"type\": \"boolean\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_accounts\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"future_requirements\": {\n \"properties\": {\n \"alternatives\": {\n \"type\": \"array\"\n },\n \"current_deadline\": {\n \"type\": \"integer\"\n },\n \"currently_due\": {\n \"type\": \"array\"\n },\n \"disabled_reason\": {\n \"type\": \"string\"\n },\n \"errors\": {\n \"type\": \"array\"\n },\n \"eventually_due\": {\n \"type\": \"array\"\n },\n \"past_due\": {\n \"type\": \"array\"\n },\n \"pending_verification\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"groups\": {\n \"properties\": {\n \"payments_pricing\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"additional_tos_acceptances\": {\n \"type\": \"object\"\n },\n \"address\": {\n \"type\": \"object\"\n },\n \"address_kana\": {\n \"type\": \"object\"\n },\n \"address_kanji\": {\n \"type\": \"object\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"dob\": {\n \"type\": \"object\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"first_name\": {\n \"type\": \"string\"\n },\n \"first_name_kana\": {\n \"type\": \"string\"\n },\n \"first_name_kanji\": {\n \"type\": \"string\"\n },\n \"full_name_aliases\": {\n \"type\": \"array\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"gender\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"id_number_provided\": {\n \"type\": \"boolean\"\n },\n \"id_number_secondary_provided\": {\n \"type\": \"boolean\"\n },\n \"last_name\": {\n \"type\": \"string\"\n },\n \"last_name_kana\": {\n \"type\": \"string\"\n },\n \"last_name_kanji\": {\n \"type\": \"string\"\n },\n \"maiden_name\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"nationality\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"political_exposure\": {\n \"type\": \"string\"\n },\n \"registered_address\": {\n \"type\": \"object\"\n },\n \"relationship\": {\n \"type\": \"object\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"ssn_last_4_provided\": {\n \"type\": \"boolean\"\n },\n \"us_cfpb_data\": {\n \"type\": \"object\"\n },\n \"verification\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"account\",\n \"created\",\n \"id\",\n \"object\"\n ],\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payouts_enabled\": {\n \"type\": \"boolean\"\n },\n \"requirements\": {\n \"properties\": {\n \"alternatives\": {\n \"type\": \"array\"\n },\n \"current_deadline\": {\n \"type\": \"integer\"\n },\n \"currently_due\": {\n \"type\": \"array\"\n },\n \"disabled_reason\": {\n \"type\": \"string\"\n },\n \"errors\": {\n \"type\": \"array\"\n },\n \"eventually_due\": {\n \"type\": \"array\"\n },\n \"past_due\": {\n \"type\": \"array\"\n },\n \"pending_verification\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"settings\": {\n \"properties\": {\n \"bacs_debit_payments\": {\n \"type\": \"object\"\n },\n \"branding\": {\n \"type\": \"object\"\n },\n \"card_issuing\": {\n \"type\": \"object\"\n },\n \"card_payments\": {\n \"type\": \"object\"\n },\n \"dashboard\": {\n \"type\": \"object\"\n },\n \"invoices\": {\n \"type\": \"object\"\n },\n \"payments\": {\n \"type\": \"object\"\n },\n \"payouts\": {\n \"type\": \"object\"\n },\n \"paypay_payments\": {\n \"type\": \"object\"\n },\n \"sepa_debit_payments\": {\n \"type\": \"object\"\n },\n \"treasury\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"tos_acceptance\": {\n \"properties\": {\n \"date\": {\n \"type\": \"integer\"\n },\n \"ip\": {\n \"type\": \"string\"\n },\n \"service_agreement\": {\n \"type\": \"string\"\n },\n \"user_agent\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"outcome\": {\n \"properties\": {\n \"advice_code\": {\n \"type\": \"string\"\n },\n \"network_advice_code\": {\n \"type\": \"string\"\n },\n \"network_decline_code\": {\n \"type\": \"string\"\n },\n \"network_status\": {\n \"type\": \"string\"\n },\n \"reason\": {\n \"type\": \"string\"\n },\n \"risk_level\": {\n \"type\": \"string\"\n },\n \"risk_score\": {\n \"type\": \"integer\"\n },\n \"rule\": {\n \"properties\": {\n \"action\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"predicate\": {\n \"type\": \"string\"\n }\n }\n },\n \"seller_message\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paid\": {\n \"type\": \"boolean\"\n },\n \"payment_intent\": {\n \"properties\": {\n \"allowed_payment_method_types\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_capturable\": {\n \"type\": \"integer\"\n },\n \"amount_details\": {\n \"properties\": {\n \"discount_amount\": {\n \"type\": \"integer\"\n },\n \"error\": {\n \"type\": \"object\"\n },\n \"line_items\": {\n \"type\": \"object\"\n },\n \"shipping\": {\n \"type\": \"object\"\n },\n \"tax\": {\n \"type\": \"object\"\n },\n \"tip\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"amount_received\": {\n \"type\": \"integer\"\n },\n \"application\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n }\n },\n \"application_fee_amount\": {\n \"type\": \"integer\"\n },\n \"automatic_payment_methods\": {\n \"properties\": {\n \"allow_redirects\": {\n \"type\": \"string\"\n },\n \"enabled\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"canceled_at\": {\n \"type\": \"integer\"\n },\n \"cancellation_reason\": {\n \"type\": \"string\"\n },\n \"capture_method\": {\n \"type\": \"string\"\n },\n \"client_secret\": {\n \"type\": \"string\"\n },\n \"confirmation_method\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {\n \"properties\": {\n \"deleted\": {\n \"type\": \"boolean\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"object\": {\n \"type\": \"string\"\n }\n }\n },\n \"customer_account\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"excluded_payment_method_types\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"hooks\": {\n \"properties\": {\n \"inputs\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"last_payment_error\": {},\n \"latest_charge\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"managed_payments\": {\n \"properties\": {\n \"enabled\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"next_action\": {\n \"properties\": {\n \"alipay_handle_redirect\": {\n \"type\": \"object\"\n },\n \"blik_authorize\": {\n \"type\": \"object\"\n },\n \"boleto_display_details\": {\n \"type\": \"object\"\n },\n \"card_await_notification\": {\n \"type\": \"object\"\n },\n \"cashapp_handle_redirect_or_display_qr_code\": {\n \"type\": \"object\"\n },\n \"display_bank_transfer_instructions\": {\n \"type\": \"object\"\n },\n \"klarna_display_qr_code\": {\n \"type\": \"object\"\n },\n \"konbini_display_details\": {\n \"type\": \"object\"\n },\n \"multibanco_display_details\": {\n \"type\": \"object\"\n },\n \"oxxo_display_details\": {\n \"type\": \"object\"\n },\n \"paynow_display_qr_code\": {\n \"type\": \"object\"\n },\n \"pix_display_qr_code\": {\n \"type\": \"object\"\n },\n \"promptpay_display_qr_code\": {\n \"type\": \"object\"\n },\n \"redirect_to_url\": {\n \"type\": \"object\"\n },\n \"swish_handle_redirect_or_display_qr_code\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"upi_handle_redirect_or_display_qr_code\": {\n \"type\": \"object\"\n },\n \"use_stripe_sdk\": {\n \"type\": \"object\"\n },\n \"verify_with_microdeposits\": {\n \"type\": \"object\"\n },\n \"wechat_pay_display_qr_code\": {\n \"type\": \"object\"\n },\n \"wechat_pay_redirect_to_android_app\": {\n \"type\": \"object\"\n },\n \"wechat_pay_redirect_to_ios_app\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"on_behalf_of\": {\n \"type\": \"string\"\n },\n \"payment_details\": {\n \"properties\": {\n \"customer_reference\": {\n \"type\": \"string\"\n },\n \"order_reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"payment_method\": {\n \"type\": \"string\"\n },\n \"payment_method_configuration_details\": {\n \"properties\": {\n \"id\": {\n \"type\": \"string\"\n },\n \"parent\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"payment_method_options\": {\n \"properties\": {\n \"acss_debit\": {\n \"type\": \"object\"\n },\n \"affirm\": {\n \"type\": \"object\"\n },\n \"afterpay_clearpay\": {\n \"type\": \"object\"\n },\n \"alipay\": {\n \"type\": \"object\"\n },\n \"alma\": {\n \"type\": \"object\"\n },\n \"amazon_pay\": {\n \"type\": \"object\"\n },\n \"au_becs_debit\": {\n \"type\": \"object\"\n },\n \"bacs_debit\": {\n \"type\": \"object\"\n },\n \"bancontact\": {\n \"type\": \"object\"\n },\n \"billie\": {\n \"type\": \"object\"\n },\n \"bizum\": {\n \"type\": \"object\"\n },\n \"blik\": {\n \"type\": \"object\"\n },\n \"boleto\": {\n \"type\": \"object\"\n },\n \"card\": {\n \"type\": \"object\"\n },\n \"card_present\": {\n \"type\": \"object\"\n },\n \"cashapp\": {\n \"type\": \"object\"\n },\n \"crypto\": {\n \"type\": \"object\"\n },\n \"customer_balance\": {\n \"type\": \"object\"\n },\n \"eps\": {\n \"type\": \"object\"\n },\n \"fpx\": {\n \"type\": \"object\"\n },\n \"giropay\": {\n \"type\": \"object\"\n },\n \"grabpay\": {\n \"type\": \"object\"\n },\n \"ideal\": {\n \"type\": \"object\"\n },\n \"interac_present\": {\n \"type\": \"object\"\n },\n \"kakao_pay\": {\n \"type\": \"object\"\n },\n \"klarna\": {\n \"type\": \"object\"\n },\n \"konbini\": {\n \"type\": \"object\"\n },\n \"kr_card\": {\n \"type\": \"object\"\n },\n \"link\": {\n \"type\": \"object\"\n },\n \"mb_way\": {\n \"type\": \"object\"\n },\n \"mobilepay\": {\n \"type\": \"object\"\n },\n \"multibanco\": {\n \"type\": \"object\"\n },\n \"naver_pay\": {\n \"type\": \"object\"\n },\n \"nz_bank_account\": {\n \"type\": \"object\"\n },\n \"oxxo\": {\n \"type\": \"object\"\n },\n \"p24\": {\n \"type\": \"object\"\n },\n \"pay_by_bank\": {\n \"type\": \"object\"\n },\n \"payco\": {\n \"type\": \"object\"\n },\n \"paynow\": {\n \"type\": \"object\"\n },\n \"paypal\": {\n \"type\": \"object\"\n },\n \"paypay\": {\n \"type\": \"object\"\n },\n \"payto\": {\n \"type\": \"object\"\n },\n \"pix\": {\n \"type\": \"object\"\n },\n \"promptpay\": {\n \"type\": \"object\"\n },\n \"revolut_pay\": {\n \"type\": \"object\"\n },\n \"samsung_pay\": {\n \"type\": \"object\"\n },\n \"satispay\": {\n \"type\": \"object\"\n },\n \"scalapay\": {\n \"type\": \"object\"\n },\n \"sepa_debit\": {\n \"type\": \"object\"\n },\n \"sequra\": {\n \"type\": \"object\"\n },\n \"sofort\": {\n \"type\": \"object\"\n },\n \"sunbit\": {\n \"type\": \"object\"\n },\n \"swish\": {\n \"type\": \"object\"\n },\n \"twint\": {\n \"type\": \"object\"\n },\n \"upi\": {\n \"type\": \"object\"\n },\n \"us_bank_account\": {\n \"type\": \"object\"\n },\n \"wechat_pay\": {\n \"type\": \"object\"\n },\n \"zip\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"payment_method_types\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"payment_record\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"object\"\n },\n \"amount_authorized\": {\n \"type\": \"object\"\n },\n \"amount_canceled\": {\n \"type\": \"object\"\n },\n \"amount_failed\": {\n \"type\": \"object\"\n },\n \"amount_guaranteed\": {\n \"type\": \"object\"\n },\n \"amount_refunded\": {\n \"type\": \"object\"\n },\n \"amount_requested\": {\n \"type\": \"object\"\n },\n \"application\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"customer_details\": {\n \"type\": \"object\"\n },\n \"customer_presence\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"latest_payment_attempt_record\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payment_method_details\": {\n \"type\": \"object\"\n },\n \"processor_details\": {\n \"type\": \"object\"\n },\n \"reported_by\": {\n \"type\": \"string\"\n },\n \"shipping_details\": {\n \"type\": \"object\"\n }\n }\n },\n \"presentment_details\": {\n \"properties\": {\n \"presentment_amount\": {\n \"type\": \"integer\"\n },\n \"presentment_currency\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"presentment_amount\",\n \"presentment_currency\"\n ],\n \"type\": \"object\"\n },\n \"processing\": {\n \"properties\": {\n \"card\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"receipt_email\": {\n \"type\": \"string\"\n },\n \"review\": {\n \"type\": \"string\"\n },\n \"setup_future_usage\": {\n \"type\": \"string\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"statement_descriptor_suffix\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"transfer_data\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"payment_data\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n }\n },\n \"payment_method\": {\n \"type\": \"string\"\n },\n \"payment_method_details\": {\n \"properties\": {\n \"ach_credit_transfer\": {\n \"properties\": {\n \"account_number\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n },\n \"swift_code\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"ach_debit\": {\n \"properties\": {\n \"account_holder_type\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"acss_debit\": {\n \"properties\": {\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"institution_number\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"transit_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"affirm\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"afterpay_clearpay\": {\n \"properties\": {\n \"order_id\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"alipay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"alma\": {\n \"properties\": {\n \"installments\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"amazon_pay\": {\n \"properties\": {\n \"funding\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"au_becs_debit\": {\n \"properties\": {\n \"bsb_number\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bacs_debit\": {\n \"properties\": {\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"sort_code\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bancontact\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {},\n \"generated_sepa_debit_mandate\": {},\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"preferred_language\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"billie\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"bizum\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"blik\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"boleto\": {\n \"properties\": {\n \"tax_id\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"tax_id\"\n ],\n \"type\": \"object\"\n },\n \"card\": {\n \"properties\": {\n \"amount_authorized\": {\n \"type\": \"integer\"\n },\n \"authorization_code\": {\n \"type\": \"string\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"capture_before\": {\n \"type\": \"integer\"\n },\n \"checks\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"electronic_commerce_indicator\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"extended_authorization\": {\n \"type\": \"object\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"incremental_authorization\": {\n \"type\": \"object\"\n },\n \"installments\": {\n \"type\": \"object\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {},\n \"multicapture\": {\n \"type\": \"object\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_token\": {\n \"type\": \"object\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"overcapture\": {\n \"type\": \"object\"\n },\n \"regulated_status\": {\n \"type\": \"string\"\n },\n \"three_d_secure\": {\n \"type\": \"object\"\n },\n \"transaction_link_id\": {\n \"type\": \"string\"\n },\n \"wallet\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\"\n ],\n \"type\": \"object\"\n },\n \"card_present\": {\n \"properties\": {\n \"amount_authorized\": {\n \"type\": \"integer\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"brand_product\": {\n \"type\": \"string\"\n },\n \"capture_before\": {\n \"type\": \"integer\"\n },\n \"cardholder_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"emv_auth_data\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"generated_card\": {\n \"type\": \"string\"\n },\n \"incremental_authorization_supported\": {\n \"type\": \"boolean\"\n },\n \"issuer\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"offline\": {\n \"type\": \"object\"\n },\n \"overcapture_supported\": {\n \"type\": \"boolean\"\n },\n \"preferred_locales\": {\n \"type\": \"array\"\n },\n \"read_method\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"receipt\": {\n \"type\": \"object\"\n },\n \"wallet\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\",\n \"incremental_authorization_supported\",\n \"overcapture_supported\"\n ],\n \"type\": \"object\"\n },\n \"cashapp\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"cashtag\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"crypto\": {\n \"properties\": {\n \"buyer_address\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"token_currency\": {\n \"type\": \"string\"\n },\n \"transaction_hash\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"customer_balance\": {\n \"type\": \"object\"\n },\n \"eps\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"fpx\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"bank\"\n ],\n \"type\": \"object\"\n },\n \"giropay\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"grabpay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"ideal\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {},\n \"generated_sepa_debit_mandate\": {},\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"interac_present\": {\n \"properties\": {\n \"brand\": {\n \"type\": \"string\"\n },\n \"cardholder_name\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"emv_auth_data\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"generated_card\": {\n \"type\": \"string\"\n },\n \"issuer\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"network\": {\n \"type\": \"string\"\n },\n \"network_transaction_id\": {\n \"type\": \"string\"\n },\n \"preferred_locales\": {\n \"type\": \"array\"\n },\n \"read_method\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"receipt\": {\n \"type\": \"object\"\n }\n },\n \"required\": [\n \"exp_month\",\n \"exp_year\"\n ],\n \"type\": \"object\"\n },\n \"kakao_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"klarna\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"payer_details\": {\n \"type\": \"object\"\n },\n \"payment_method_category\": {\n \"type\": \"string\"\n },\n \"preferred_locale\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"konbini\": {\n \"properties\": {\n \"store\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"kr_card\": {\n \"properties\": {\n \"brand\": {\n \"type\": \"string\"\n },\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"link\": {\n \"properties\": {\n \"country\": {\n \"type\": \"string\"\n },\n \"funding_source_group\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"mb_way\": {\n \"type\": \"object\"\n },\n \"mobilepay\": {\n \"properties\": {\n \"card\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"multibanco\": {\n \"properties\": {\n \"entity\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"naver_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"nz_bank_account\": {\n \"properties\": {\n \"account_holder_name\": {\n \"type\": \"string\"\n },\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"branch_code\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"suffix\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"bank_code\",\n \"bank_name\",\n \"branch_code\",\n \"last4\"\n ],\n \"type\": \"object\"\n },\n \"oxxo\": {\n \"properties\": {\n \"number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"p24\": {\n \"properties\": {\n \"bank\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"pay_by_bank\": {\n \"type\": \"object\"\n },\n \"payco\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paynow\": {\n \"properties\": {\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paypal\": {\n \"properties\": {\n \"country\": {\n \"type\": \"string\"\n },\n \"payer_email\": {\n \"type\": \"string\"\n },\n \"payer_id\": {\n \"type\": \"string\"\n },\n \"payer_name\": {\n \"type\": \"string\"\n },\n \"seller_protection\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"paypay\": {\n \"type\": \"object\"\n },\n \"payto\": {\n \"properties\": {\n \"bsb_number\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n },\n \"pay_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"pix\": {\n \"properties\": {\n \"bank_transaction_id\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"promptpay\": {\n \"properties\": {\n \"reference\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"revolut_pay\": {\n \"properties\": {\n \"funding\": {\n \"type\": \"object\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"samsung_pay\": {\n \"properties\": {\n \"buyer_id\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"satispay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"scalapay\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sepa_debit\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"branch_code\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sequra\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"sofort\": {\n \"properties\": {\n \"bank_code\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"bic\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"generated_sepa_debit\": {},\n \"generated_sepa_debit_mandate\": {},\n \"iban_last4\": {\n \"type\": \"string\"\n },\n \"preferred_language\": {\n \"type\": \"string\"\n },\n \"verified_name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"stripe_account\": {\n \"type\": \"object\"\n },\n \"sunbit\": {\n \"properties\": {\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"swish\": {\n \"properties\": {\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"payment_reference\": {\n \"type\": \"string\"\n },\n \"verified_phone_last4\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"twint\": {\n \"properties\": {\n \"mandate\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"upi\": {\n \"properties\": {\n \"vpa\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"us_bank_account\": {\n \"properties\": {\n \"account_holder_type\": {\n \"type\": \"string\"\n },\n \"account_type\": {\n \"type\": \"string\"\n },\n \"bank_name\": {\n \"type\": \"string\"\n },\n \"expected_debit_date\": {\n \"type\": \"string\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"mandate\": {},\n \"payment_reference\": {\n \"type\": \"string\"\n },\n \"routing_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"wechat\": {\n \"type\": \"object\"\n },\n \"wechat_pay\": {\n \"properties\": {\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"location\": {\n \"type\": \"string\"\n },\n \"reader\": {\n \"type\": \"string\"\n },\n \"transaction_id\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"zip\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"presentment_details\": {\n \"properties\": {\n \"presentment_amount\": {\n \"type\": \"integer\"\n },\n \"presentment_currency\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"presentment_amount\",\n \"presentment_currency\"\n ],\n \"type\": \"object\"\n },\n \"radar_options\": {\n \"properties\": {\n \"session\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"receipt_email\": {\n \"type\": \"string\"\n },\n \"receipt_number\": {\n \"type\": \"string\"\n },\n \"receipt_url\": {\n \"type\": \"string\"\n },\n \"refunded\": {\n \"type\": \"boolean\"\n },\n \"refunds\": {\n \"properties\": {\n \"data\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"review\": {\n \"type\": \"string\"\n },\n \"shipping\": {\n \"properties\": {\n \"address\": {\n \"properties\": {\n \"city\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"line1\": {\n \"type\": \"string\"\n },\n \"line2\": {\n \"type\": \"string\"\n },\n \"postal_code\": {\n \"type\": \"string\"\n },\n \"state\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"carrier\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"phone\": {\n \"type\": \"string\"\n },\n \"tracking_number\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"source_transfer\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"properties\": {\n \"business_profile\": {\n \"type\": \"object\"\n },\n \"business_type\": {\n \"type\": \"string\"\n },\n \"capabilities\": {\n \"type\": \"object\"\n },\n \"charges_enabled\": {\n \"type\": \"boolean\"\n },\n \"company\": {\n \"type\": \"object\"\n },\n \"controller\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"default_currency\": {\n \"type\": \"string\"\n },\n \"details_submitted\": {\n \"type\": \"boolean\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_accounts\": {\n \"type\": \"object\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"groups\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payouts_enabled\": {\n \"type\": \"boolean\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"settings\": {\n \"type\": \"object\"\n },\n \"tos_acceptance\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reversals\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n }\n },\n \"statement_descriptor\": {\n \"type\": \"string\"\n },\n \"statement_descriptor_suffix\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"transfer\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"amount_reversed\": {\n \"type\": \"integer\"\n },\n \"balance_transaction\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"destination\": {\n \"properties\": {\n \"business_profile\": {\n \"type\": \"object\"\n },\n \"business_type\": {\n \"type\": \"string\"\n },\n \"capabilities\": {\n \"type\": \"object\"\n },\n \"charges_enabled\": {\n \"type\": \"boolean\"\n },\n \"company\": {\n \"type\": \"object\"\n },\n \"controller\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"default_currency\": {\n \"type\": \"string\"\n },\n \"details_submitted\": {\n \"type\": \"boolean\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_accounts\": {\n \"type\": \"object\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"groups\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payouts_enabled\": {\n \"type\": \"boolean\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"settings\": {\n \"type\": \"object\"\n },\n \"tos_acceptance\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n },\n \"destination_payment\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"livemode\": {\n \"type\": \"boolean\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"reversals\": {\n \"properties\": {\n \"data\": {\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"reversed\": {\n \"type\": \"boolean\"\n },\n \"source_transaction\": {\n \"type\": \"string\"\n },\n \"source_type\": {\n \"type\": \"string\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n }\n },\n \"transfer_data\": {\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\"\n },\n \"destination\": {\n \"properties\": {\n \"business_profile\": {\n \"type\": \"object\"\n },\n \"business_type\": {\n \"type\": \"string\"\n },\n \"capabilities\": {\n \"type\": \"object\"\n },\n \"charges_enabled\": {\n \"type\": \"boolean\"\n },\n \"company\": {\n \"type\": \"object\"\n },\n \"controller\": {\n \"type\": \"object\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"created\": {\n \"type\": \"integer\"\n },\n \"default_currency\": {\n \"type\": \"string\"\n },\n \"details_submitted\": {\n \"type\": \"boolean\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"external_accounts\": {\n \"type\": \"object\"\n },\n \"future_requirements\": {\n \"type\": \"object\"\n },\n \"groups\": {\n \"type\": \"object\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"individual\": {\n \"type\": \"object\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"payouts_enabled\": {\n \"type\": \"boolean\"\n },\n \"requirements\": {\n \"type\": \"object\"\n },\n \"settings\": {\n \"type\": \"object\"\n },\n \"tos_acceptance\": {\n \"type\": \"object\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"type\": \"object\"\n },\n \"transfer_group\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"amount\",\n \"amount_captured\",\n \"amount_refunded\",\n \"billing_details\",\n \"captured\",\n \"created\",\n \"currency\",\n \"disputed\",\n \"id\",\n \"livemode\",\n \"metadata\",\n \"object\",\n \"paid\",\n \"refunded\",\n \"status\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Create a charge\\n\\n\\u003cp\\u003eThis method is deprecated and will be removed soon. If your integration uses it, you need to update it to use a different payment flow, such as \\u003ca href=\\\"/docs/payments/payment-intents\\\"\\u003ethe Payment Intents API\\u003c/a\\u003e.\\u003c/p\\u003e\"\n }\n },\n \"/v1/customers/{customer}/cards\": {\n \"get\": {\n \"deprecated\": true,\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"customer\",\n \"required\": true\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"ending_before\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"expand\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"limit\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"starting_after\",\n \"required\": false\n }\n ],\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\"\n }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"data\": {\n \"items\": {\n \"properties\": {\n \"account\": {\n \"type\": \"string\"\n },\n \"address_city\": {\n \"type\": \"string\"\n },\n \"address_country\": {\n \"type\": \"string\"\n },\n \"address_line1\": {\n \"type\": \"string\"\n },\n \"address_line1_check\": {\n \"type\": \"string\"\n },\n \"address_line2\": {\n \"type\": \"string\"\n },\n \"address_state\": {\n \"type\": \"string\"\n },\n \"address_zip\": {\n \"type\": \"string\"\n },\n \"address_zip_check\": {\n \"type\": \"string\"\n },\n \"allow_redisplay\": {\n \"type\": \"string\"\n },\n \"available_payout_methods\": {\n \"type\": \"array\"\n },\n \"brand\": {\n \"type\": \"string\"\n },\n \"country\": {\n \"type\": \"string\"\n },\n \"currency\": {\n \"type\": \"string\"\n },\n \"customer\": {},\n \"cvc_check\": {\n \"type\": \"string\"\n },\n \"default_for_currency\": {\n \"type\": \"boolean\"\n },\n \"dynamic_last4\": {\n \"type\": \"string\"\n },\n \"exp_month\": {\n \"type\": \"integer\"\n },\n \"exp_year\": {\n \"type\": \"integer\"\n },\n \"fingerprint\": {\n \"type\": \"string\"\n },\n \"funding\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"last4\": {\n \"type\": \"string\"\n },\n \"metadata\": {\n \"type\": \"object\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"networks\": {\n \"type\": \"object\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"regulated_status\": {\n \"type\": \"string\"\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tokenization_method\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"brand\",\n \"exp_month\",\n \"exp_year\",\n \"funding\",\n \"id\",\n \"last4\",\n \"object\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"has_more\": {\n \"type\": \"boolean\"\n },\n \"object\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"data\",\n \"has_more\",\n \"object\",\n \"url\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List all cards\\n\\n\\u003cp\\u003eYou can see a list of the cards belonging to a customer.\\nNote that the 10 most recent sources are always available on the \\u003ccode\\u003eCustomer\\u003c/code\\u003e object.\\nIf you need more than those 10, you can use this API method and the \\u003ccode\\u003elimit\\u003c/code\\u003e and \\u003ccode\\u003estarting_after\\u003c/code\\u003e parameters to page through additional cards.\\u003c/p\\u003e\"\n }\n }\n }\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_5828ec494929.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_5828ec494929.json index 3da2ebe..60972a6 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_5828ec494929.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_5828ec494929.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/api/v1/monitor\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"group_states\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"id_offset\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"monitor_tags\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page_size\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"tags\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"with_downtimes\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"items\": {\n \"properties\": {\n \"assets\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"created\": {\n \"type\": \"string\"\n },\n \"creator\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"handle\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"deleted\": {\n \"type\": \"string\"\n },\n \"draft_status\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"matching_downtimes\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"modified\": {\n \"type\": \"string\"\n },\n \"multi\": {\n \"type\": \"boolean\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"options\": {\n \"properties\": {\n \"aggregation\": {\n \"type\": \"object\"\n },\n \"device_ids\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"enable_logs_sample\": {\n \"type\": \"boolean\"\n },\n \"enable_samples\": {\n \"type\": \"boolean\"\n },\n \"escalation_message\": {\n \"type\": \"string\"\n },\n \"evaluation_delay\": {\n \"type\": \"integer\"\n },\n \"group_retention_duration\": {\n \"type\": \"string\"\n },\n \"groupby_simple_monitor\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_tags\": {\n \"type\": \"boolean\"\n },\n \"locked\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"min_failure_duration\": {\n \"type\": \"integer\"\n },\n \"min_location_failed\": {\n \"type\": \"integer\"\n },\n \"new_group_delay\": {\n \"type\": \"integer\"\n },\n \"new_host_delay\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"no_data_timeframe\": {\n \"type\": \"integer\"\n },\n \"notification_preset_name\": {\n \"type\": \"string\"\n },\n \"notify_audit\": {\n \"type\": \"boolean\"\n },\n \"notify_by\": {\n \"type\": \"array\"\n },\n \"notify_no_data\": {\n \"type\": \"boolean\"\n },\n \"on_missing_data\": {\n \"type\": \"string\"\n },\n \"renotify_interval\": {\n \"type\": \"integer\"\n },\n \"renotify_occurrences\": {\n \"type\": \"integer\"\n },\n \"renotify_statuses\": {\n \"type\": \"array\"\n },\n \"require_full_window\": {\n \"type\": \"boolean\"\n },\n \"scheduling_options\": {\n \"type\": \"object\"\n },\n \"silenced\": {\n \"deprecated\": true,\n \"type\": \"object\"\n },\n \"synthetics_check_id\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"threshold_windows\": {\n \"type\": \"object\"\n },\n \"thresholds\": {\n \"type\": \"object\"\n },\n \"timeout_h\": {\n \"type\": \"integer\"\n },\n \"variables\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"overall_state\": {\n \"type\": \"string\"\n },\n \"priority\": {\n \"type\": \"integer\"\n },\n \"query\": {\n \"type\": \"string\"\n },\n \"restricted_roles\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"state\": {\n \"properties\": {\n \"groups\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"tags\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"query\",\n \"type\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n }\n }\n }\n },\n \"summary\": \"Get all monitors\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/api/v1/monitor\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"group_states\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"id_offset\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"monitor_tags\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page_size\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"tags\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"with_downtimes\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"items\": {\n \"properties\": {\n \"assets\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"created\": {\n \"type\": \"string\"\n },\n \"creator\": {\n \"properties\": {\n \"email\": {\n \"type\": \"string\"\n },\n \"handle\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"deleted\": {\n \"type\": \"string\"\n },\n \"draft_status\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"matching_downtimes\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"message\": {\n \"type\": \"string\"\n },\n \"modified\": {\n \"type\": \"string\"\n },\n \"multi\": {\n \"type\": \"boolean\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"options\": {\n \"properties\": {\n \"aggregation\": {\n \"type\": \"object\"\n },\n \"device_ids\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"enable_logs_sample\": {\n \"type\": \"boolean\"\n },\n \"enable_samples\": {\n \"type\": \"boolean\"\n },\n \"escalation_message\": {\n \"type\": \"string\"\n },\n \"evaluation_delay\": {\n \"type\": \"integer\"\n },\n \"group_retention_duration\": {\n \"type\": \"string\"\n },\n \"groupby_simple_monitor\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"include_tags\": {\n \"type\": \"boolean\"\n },\n \"locked\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"min_failure_duration\": {\n \"type\": \"integer\"\n },\n \"min_location_failed\": {\n \"type\": \"integer\"\n },\n \"new_group_delay\": {\n \"type\": \"integer\"\n },\n \"new_host_delay\": {\n \"deprecated\": true,\n \"type\": \"integer\"\n },\n \"no_data_timeframe\": {\n \"type\": \"integer\"\n },\n \"notification_preset_name\": {\n \"type\": \"string\"\n },\n \"notify_audit\": {\n \"type\": \"boolean\"\n },\n \"notify_by\": {\n \"type\": \"array\"\n },\n \"notify_no_data\": {\n \"type\": \"boolean\"\n },\n \"on_missing_data\": {\n \"type\": \"string\"\n },\n \"renotify_interval\": {\n \"type\": \"integer\"\n },\n \"renotify_occurrences\": {\n \"type\": \"integer\"\n },\n \"renotify_statuses\": {\n \"type\": \"array\"\n },\n \"require_full_window\": {\n \"type\": \"boolean\"\n },\n \"scheduling_options\": {\n \"type\": \"object\"\n },\n \"silenced\": {\n \"deprecated\": true,\n \"type\": \"object\"\n },\n \"synthetics_check_id\": {\n \"deprecated\": true,\n \"type\": \"string\"\n },\n \"threshold_windows\": {\n \"type\": \"object\"\n },\n \"thresholds\": {\n \"type\": \"object\"\n },\n \"timeout_h\": {\n \"type\": \"integer\"\n },\n \"variables\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"overall_state\": {\n \"type\": \"string\"\n },\n \"priority\": {\n \"type\": \"integer\"\n },\n \"query\": {\n \"type\": \"string\"\n },\n \"restricted_roles\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"state\": {\n \"properties\": {\n \"groups\": {\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"tags\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"query\",\n \"type\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n }\n }\n }\n },\n \"summary\": \"Get all monitors\\n\\nGet all monitors from your organization.\"\n }\n }\n }\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v1/openapi.yaml" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_74aa1cc1ce8d.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_74aa1cc1ce8d.json new file mode 100644 index 0000000..0bdf96f --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_74aa1cc1ce8d.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {}\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_api_keys_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_990eb07e6ba4.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_990eb07e6ba4.json new file mode 100644 index 0000000..7d6b41e --- /dev/null +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_990eb07e6ba4.json @@ -0,0 +1,5 @@ +{ + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {}\n}\n", + "status": 200, + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/main/spec/json/tsg_suppressions_v3.json" +} diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_bedcf2cb8b4a.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_bedcf2cb8b4a.json index ff186ba..8abba80 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_bedcf2cb8b4a.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_bedcf2cb8b4a.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"4.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/zones\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"account.id\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"account.name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"direction\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"match\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"order\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"per_page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"status\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"type\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"errors\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"messages\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"result\": {\n \"items\": {\n \"properties\": {\n \"account\": {\n \"type\": \"object\"\n },\n \"activated_on\": {\n \"type\": \"string\"\n },\n \"cname_suffix\": {\n \"type\": \"string\"\n },\n \"created_on\": {\n \"type\": \"string\"\n },\n \"development_mode\": {\n \"type\": \"number\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"meta\": {\n \"type\": \"object\"\n },\n \"modified_on\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"name_servers\": {\n \"type\": \"array\"\n },\n \"original_dnshost\": {\n \"type\": \"string\"\n },\n \"original_name_servers\": {\n \"type\": \"array\"\n },\n \"original_registrar\": {\n \"type\": \"string\"\n },\n \"owner\": {\n \"type\": \"object\"\n },\n \"paused\": {\n \"type\": \"boolean\"\n },\n \"permissions\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"plan\": {\n \"deprecated\": true\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tenant\": {},\n \"tenant_unit\": {},\n \"type\": {\n \"type\": \"string\"\n },\n \"vanity_name_servers\": {\n \"type\": \"array\"\n },\n \"verification_key\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account\",\n \"activated_on\",\n \"created_on\",\n \"development_mode\",\n \"id\",\n \"meta\",\n \"modified_on\",\n \"name\",\n \"name_servers\",\n \"original_dnshost\",\n \"original_name_servers\",\n \"original_registrar\",\n \"owner\",\n \"plan\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"result_info\": {\n \"properties\": {\n \"count\": {\n \"type\": \"number\"\n },\n \"page\": {\n \"type\": \"number\"\n },\n \"per_page\": {\n \"type\": \"number\"\n },\n \"total_count\": {\n \"type\": \"number\"\n },\n \"total_pages\": {\n \"type\": \"number\"\n }\n },\n \"type\": \"object\"\n },\n \"success\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"errors\",\n \"messages\",\n \"success\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List Zones\"\n }\n }\n },\n \"servers\": [\n {\n \"url\": \"/client/v4\"\n }\n ]\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"4.0.0\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/zones\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"account.id\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"account.name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"direction\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"match\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"name\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"order\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"per_page\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"status\",\n \"required\": false\n },\n {\n \"deprecated\": false,\n \"in\": \"query\",\n \"name\": \"type\",\n \"required\": false\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"errors\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"messages\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"result\": {\n \"items\": {\n \"properties\": {\n \"account\": {\n \"type\": \"object\"\n },\n \"activated_on\": {\n \"type\": \"string\"\n },\n \"cname_suffix\": {\n \"type\": \"string\"\n },\n \"created_on\": {\n \"type\": \"string\"\n },\n \"development_mode\": {\n \"type\": \"number\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"meta\": {\n \"type\": \"object\"\n },\n \"modified_on\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"name_servers\": {\n \"type\": \"array\"\n },\n \"original_dnshost\": {\n \"type\": \"string\"\n },\n \"original_name_servers\": {\n \"type\": \"array\"\n },\n \"original_registrar\": {\n \"type\": \"string\"\n },\n \"owner\": {\n \"type\": \"object\"\n },\n \"paused\": {\n \"type\": \"boolean\"\n },\n \"permissions\": {\n \"deprecated\": true,\n \"type\": \"array\"\n },\n \"plan\": {\n \"deprecated\": true\n },\n \"status\": {\n \"type\": \"string\"\n },\n \"tenant\": {},\n \"tenant_unit\": {},\n \"type\": {\n \"type\": \"string\"\n },\n \"vanity_name_servers\": {\n \"type\": \"array\"\n },\n \"verification_key\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"account\",\n \"activated_on\",\n \"created_on\",\n \"development_mode\",\n \"id\",\n \"meta\",\n \"modified_on\",\n \"name\",\n \"name_servers\",\n \"original_dnshost\",\n \"original_name_servers\",\n \"original_registrar\",\n \"owner\",\n \"plan\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"result_info\": {\n \"properties\": {\n \"count\": {\n \"type\": \"number\"\n },\n \"page\": {\n \"type\": \"number\"\n },\n \"per_page\": {\n \"type\": \"number\"\n },\n \"total_count\": {\n \"type\": \"number\"\n },\n \"total_pages\": {\n \"type\": \"number\"\n }\n },\n \"type\": \"object\"\n },\n \"success\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"errors\",\n \"messages\",\n \"success\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List Zones\\n\\nLists, searches, sorts, and filters your zones. Listing zones across more than 500 accounts\\nis currently not allowed.\"\n }\n },\n \"/zones/{zone_id}/cache/origin_cloud_regions\": {\n \"get\": {\n \"deprecated\": true,\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"zone_id\",\n \"required\": true\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"errors\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"messages\": {\n \"items\": {\n \"properties\": {\n \"code\": {\n \"type\": \"integer\"\n },\n \"message\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"code\",\n \"message\"\n ],\n \"type\": \"object\"\n },\n \"type\": \"array\"\n },\n \"result\": {\n \"properties\": {\n \"editable\": {\n \"type\": \"boolean\"\n },\n \"id\": {\n \"type\": \"string\"\n },\n \"modified_on\": {\n \"type\": \"string\"\n },\n \"value\": {\n \"items\": {\n \"type\": \"object\"\n },\n \"type\": \"array\"\n }\n },\n \"required\": [\n \"editable\",\n \"id\",\n \"value\"\n ],\n \"type\": \"object\"\n },\n \"success\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"errors\",\n \"messages\",\n \"success\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"List origin cloud region mappings\\n\\nReturns all IP-to-cloud-region mappings configured for the zone. Each mapping tells Cloudflare which cloud vendor and region hosts the origin at that IP, enabling the edge to route via the nearest Tiered Cache upper-tier co-located with that cloud provider. Returns an empty array when no mappings exist.\",\n \"x-sunset\": \"2026-10-01T00:00:00Z\"\n }\n }\n },\n \"servers\": [\n {\n \"url\": \"/client/v4\"\n }\n ]\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json" } diff --git a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_eca6cb1a084d.json b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_eca6cb1a084d.json index 7bf2240..9f4e805 100644 --- a/internal/api/testdata/recorded/GET_raw.githubusercontent.com_eca6cb1a084d.json +++ b/internal/api/testdata/recorded/GET_raw.githubusercontent.com_eca6cb1a084d.json @@ -1,5 +1,5 @@ { - "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.1.4\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/assignments/{assignment_id}\": {\n \"get\": {\n \"deprecated\": true,\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"assignment_id\",\n \"required\": true\n }\n ],\n \"responses\": {},\n \"summary\": \"Closed - Get an assignment\",\n \"x-sunset\": \"2026-08-28T00:00:00Z\"\n }\n },\n \"/repos/{owner}/{repo}\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"owner\",\n \"required\": true\n },\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"repo\",\n \"required\": true\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_of_conduct\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"html_url\",\n \"key\",\n \"name\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"custom_properties\": {\n \"type\": \"object\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"network_count\": {\n \"type\": \"integer\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"organization\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"parent\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"security_and_analysis\": {\n \"properties\": {\n \"advanced_security\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"code_security\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"dependabot_security_updates\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_ai_detection\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_alert_dismissal\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_bypass\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_bypass_options\": {\n \"properties\": {\n \"reviewers\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_non_provider_patterns\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_push_protection\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"source\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_count\": {\n \"type\": \"integer\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"template_repository\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_discussions\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"network_count\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_count\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Get a repository\"\n }\n }\n }\n}\n", + "body": "{\n \"info\": {\n \"title\": \"trimmed\",\n \"version\": \"1.1.4\"\n },\n \"openapi\": \"3.1.0\",\n \"paths\": {\n \"/assignments/{assignment_id}\": {\n \"get\": {\n \"deprecated\": true,\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"assignment_id\",\n \"required\": true\n }\n ],\n \"responses\": {},\n \"summary\": \"Closed - Get an assignment\\n\\n\\u003e [!WARNING]\\n\\u003e **Closed notice:** This operation is no longer available as of August 28, 2026.\\n\\u003e For more information, see the [GitHub Classroom sunset notice](https://gh.io/classroom-sunset).\",\n \"x-sunset\": \"2026-08-28T00:00:00Z\"\n }\n },\n \"/repos/{owner}/{repo}\": {\n \"get\": {\n \"parameters\": [\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"owner\",\n \"required\": true\n },\n {\n \"deprecated\": false,\n \"in\": \"path\",\n \"name\": \"repo\",\n \"required\": true\n }\n ],\n \"responses\": {\n \"200\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_of_conduct\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"html_url\",\n \"key\",\n \"name\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"custom_properties\": {\n \"type\": \"object\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"network_count\": {\n \"type\": \"integer\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"organization\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"parent\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"security_and_analysis\": {\n \"properties\": {\n \"advanced_security\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"code_security\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"dependabot_security_updates\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_ai_detection\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_alert_dismissal\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_bypass\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_delegated_bypass_options\": {\n \"properties\": {\n \"reviewers\": {\n \"type\": \"array\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_non_provider_patterns\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n },\n \"secret_scanning_push_protection\": {\n \"properties\": {\n \"status\": {\n \"type\": \"string\"\n }\n },\n \"type\": \"object\"\n }\n },\n \"type\": \"object\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"source\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_count\": {\n \"type\": \"integer\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"template_repository\": {\n \"properties\": {\n \"allow_auto_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_forking\": {\n \"type\": \"boolean\"\n },\n \"allow_merge_commit\": {\n \"type\": \"boolean\"\n },\n \"allow_rebase_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_squash_merge\": {\n \"type\": \"boolean\"\n },\n \"allow_update_branch\": {\n \"type\": \"boolean\"\n },\n \"anonymous_access_enabled\": {\n \"type\": \"boolean\"\n },\n \"archive_url\": {\n \"type\": \"string\"\n },\n \"archived\": {\n \"type\": \"boolean\"\n },\n \"assignees_url\": {\n \"type\": \"string\"\n },\n \"blobs_url\": {\n \"type\": \"string\"\n },\n \"branches_url\": {\n \"type\": \"string\"\n },\n \"clone_url\": {\n \"type\": \"string\"\n },\n \"code_search_index_status\": {\n \"properties\": {\n \"lexical_commit_sha\": {\n \"type\": \"string\"\n },\n \"lexical_search_ok\": {\n \"type\": \"boolean\"\n }\n },\n \"type\": \"object\"\n },\n \"collaborators_url\": {\n \"type\": \"string\"\n },\n \"comments_url\": {\n \"type\": \"string\"\n },\n \"commits_url\": {\n \"type\": \"string\"\n },\n \"compare_url\": {\n \"type\": \"string\"\n },\n \"contents_url\": {\n \"type\": \"string\"\n },\n \"contributors_url\": {\n \"type\": \"string\"\n },\n \"created_at\": {\n \"type\": \"string\"\n },\n \"default_branch\": {\n \"type\": \"string\"\n },\n \"delete_branch_on_merge\": {\n \"type\": \"boolean\"\n },\n \"deployments_url\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"disabled\": {\n \"type\": \"boolean\"\n },\n \"downloads_url\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"fork\": {\n \"type\": \"boolean\"\n },\n \"forks\": {\n \"type\": \"integer\"\n },\n \"forks_count\": {\n \"type\": \"integer\"\n },\n \"forks_url\": {\n \"type\": \"string\"\n },\n \"full_name\": {\n \"type\": \"string\"\n },\n \"git_commits_url\": {\n \"type\": \"string\"\n },\n \"git_refs_url\": {\n \"type\": \"string\"\n },\n \"git_tags_url\": {\n \"type\": \"string\"\n },\n \"git_url\": {\n \"type\": \"string\"\n },\n \"has_discussions\": {\n \"type\": \"boolean\"\n },\n \"has_downloads\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"has_issues\": {\n \"type\": \"boolean\"\n },\n \"has_pages\": {\n \"type\": \"boolean\"\n },\n \"has_projects\": {\n \"type\": \"boolean\"\n },\n \"has_pull_requests\": {\n \"type\": \"boolean\"\n },\n \"has_wiki\": {\n \"type\": \"boolean\"\n },\n \"homepage\": {\n \"type\": \"string\"\n },\n \"hooks_url\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"is_template\": {\n \"type\": \"boolean\"\n },\n \"issue_comment_url\": {\n \"type\": \"string\"\n },\n \"issue_events_url\": {\n \"type\": \"string\"\n },\n \"issues_url\": {\n \"type\": \"string\"\n },\n \"keys_url\": {\n \"type\": \"string\"\n },\n \"labels_url\": {\n \"type\": \"string\"\n },\n \"language\": {\n \"type\": \"string\"\n },\n \"languages_url\": {\n \"type\": \"string\"\n },\n \"license\": {\n \"properties\": {\n \"html_url\": {\n \"type\": \"string\"\n },\n \"key\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"spdx_id\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"key\",\n \"name\",\n \"node_id\",\n \"spdx_id\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"master_branch\": {\n \"type\": \"string\"\n },\n \"merge_commit_message\": {\n \"type\": \"string\"\n },\n \"merge_commit_title\": {\n \"type\": \"string\"\n },\n \"merges_url\": {\n \"type\": \"string\"\n },\n \"milestones_url\": {\n \"type\": \"string\"\n },\n \"mirror_url\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"notifications_url\": {\n \"type\": \"string\"\n },\n \"open_issues\": {\n \"type\": \"integer\"\n },\n \"open_issues_count\": {\n \"type\": \"integer\"\n },\n \"owner\": {\n \"properties\": {\n \"avatar_url\": {\n \"type\": \"string\"\n },\n \"email\": {\n \"type\": \"string\"\n },\n \"events_url\": {\n \"type\": \"string\"\n },\n \"followers_url\": {\n \"type\": \"string\"\n },\n \"following_url\": {\n \"type\": \"string\"\n },\n \"gists_url\": {\n \"type\": \"string\"\n },\n \"gravatar_id\": {\n \"type\": \"string\"\n },\n \"html_url\": {\n \"type\": \"string\"\n },\n \"id\": {\n \"type\": \"integer\"\n },\n \"login\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"node_id\": {\n \"type\": \"string\"\n },\n \"organizations_url\": {\n \"type\": \"string\"\n },\n \"received_events_url\": {\n \"type\": \"string\"\n },\n \"repos_url\": {\n \"type\": \"string\"\n },\n \"site_admin\": {\n \"type\": \"boolean\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"starred_url\": {\n \"type\": \"string\"\n },\n \"subscriptions_url\": {\n \"type\": \"string\"\n },\n \"type\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"user_view_type\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"avatar_url\",\n \"events_url\",\n \"followers_url\",\n \"following_url\",\n \"gists_url\",\n \"gravatar_id\",\n \"html_url\",\n \"id\",\n \"login\",\n \"node_id\",\n \"organizations_url\",\n \"received_events_url\",\n \"repos_url\",\n \"site_admin\",\n \"starred_url\",\n \"subscriptions_url\",\n \"type\",\n \"url\"\n ],\n \"type\": \"object\"\n },\n \"permissions\": {\n \"properties\": {\n \"admin\": {\n \"type\": \"boolean\"\n },\n \"maintain\": {\n \"type\": \"boolean\"\n },\n \"pull\": {\n \"type\": \"boolean\"\n },\n \"push\": {\n \"type\": \"boolean\"\n },\n \"triage\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"admin\",\n \"pull\",\n \"push\"\n ],\n \"type\": \"object\"\n },\n \"private\": {\n \"type\": \"boolean\"\n },\n \"pull_request_creation_policy\": {\n \"type\": \"string\"\n },\n \"pulls_url\": {\n \"type\": \"string\"\n },\n \"pushed_at\": {\n \"type\": \"string\"\n },\n \"releases_url\": {\n \"type\": \"string\"\n },\n \"size\": {\n \"type\": \"integer\"\n },\n \"squash_merge_commit_message\": {\n \"type\": \"string\"\n },\n \"squash_merge_commit_title\": {\n \"type\": \"string\"\n },\n \"ssh_url\": {\n \"type\": \"string\"\n },\n \"stargazers_count\": {\n \"type\": \"integer\"\n },\n \"stargazers_url\": {\n \"type\": \"string\"\n },\n \"starred_at\": {\n \"type\": \"string\"\n },\n \"statuses_url\": {\n \"type\": \"string\"\n },\n \"subscribers_url\": {\n \"type\": \"string\"\n },\n \"subscription_url\": {\n \"type\": \"string\"\n },\n \"svn_url\": {\n \"type\": \"string\"\n },\n \"tags_url\": {\n \"type\": \"string\"\n },\n \"teams_url\": {\n \"type\": \"string\"\n },\n \"temp_clone_token\": {\n \"type\": \"string\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"deprecated\": true,\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_downloads\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n },\n \"topics\": {\n \"items\": {\n \"type\": \"string\"\n },\n \"type\": \"array\"\n },\n \"trees_url\": {\n \"type\": \"string\"\n },\n \"updated_at\": {\n \"type\": \"string\"\n },\n \"url\": {\n \"type\": \"string\"\n },\n \"use_squash_pr_title_as_default\": {\n \"type\": \"boolean\"\n },\n \"visibility\": {\n \"type\": \"string\"\n },\n \"watchers\": {\n \"type\": \"integer\"\n },\n \"watchers_count\": {\n \"type\": \"integer\"\n },\n \"web_commit_signoff_required\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\n \"archive_url\",\n \"archived\",\n \"assignees_url\",\n \"blobs_url\",\n \"branches_url\",\n \"clone_url\",\n \"collaborators_url\",\n \"comments_url\",\n \"commits_url\",\n \"compare_url\",\n \"contents_url\",\n \"contributors_url\",\n \"created_at\",\n \"default_branch\",\n \"deployments_url\",\n \"description\",\n \"disabled\",\n \"downloads_url\",\n \"events_url\",\n \"fork\",\n \"forks\",\n \"forks_count\",\n \"forks_url\",\n \"full_name\",\n \"git_commits_url\",\n \"git_refs_url\",\n \"git_tags_url\",\n \"git_url\",\n \"has_discussions\",\n \"has_issues\",\n \"has_pages\",\n \"has_projects\",\n \"has_wiki\",\n \"homepage\",\n \"hooks_url\",\n \"html_url\",\n \"id\",\n \"issue_comment_url\",\n \"issue_events_url\",\n \"issues_url\",\n \"keys_url\",\n \"labels_url\",\n \"language\",\n \"languages_url\",\n \"license\",\n \"merges_url\",\n \"milestones_url\",\n \"mirror_url\",\n \"name\",\n \"network_count\",\n \"node_id\",\n \"notifications_url\",\n \"open_issues\",\n \"open_issues_count\",\n \"owner\",\n \"private\",\n \"pulls_url\",\n \"pushed_at\",\n \"releases_url\",\n \"size\",\n \"ssh_url\",\n \"stargazers_count\",\n \"stargazers_url\",\n \"statuses_url\",\n \"subscribers_count\",\n \"subscribers_url\",\n \"subscription_url\",\n \"svn_url\",\n \"tags_url\",\n \"teams_url\",\n \"trees_url\",\n \"updated_at\",\n \"url\",\n \"watchers\",\n \"watchers_count\"\n ],\n \"type\": \"object\"\n }\n }\n }\n }\n },\n \"summary\": \"Get a repository\\n\\nThe `parent` and `source` objects are present when the repository is a fork. `parent` is the repository this repository was forked from, `source` is the ultimate source for the network.\\n\\nWhen present and non-empty, `temp_clone_token` is a temporary credential for read-only Git access to this repository. It expires five minutes after generation and cannot be used to push changes. Treat this value as sensitive and avoid recording it in logs.\\n\\n\\u003e [!NOTE]\\n\\u003e - In order to see the `security_and_analysis` block for a repository you must have admin permissions for the repository or be\"\n }\n }\n }\n}\n", "status": 200, "url": "https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json" } diff --git a/internal/cli/baseline.go b/internal/cli/baseline.go index f6acfe8..c1a88c3 100644 --- a/internal/cli/baseline.go +++ b/internal/cli/baseline.go @@ -35,6 +35,7 @@ func (r *runner) groundwork(ctx context.Context, ch *core.Change, t *trial) (*pa if why == "" || len(ch.Batch.Changes)+len(ch.Batch.Next) == 0 { return nil, nil } + t.thin = why su := r.suite() if su == nil { s.logf("the tests are thin (%s), and tend has no way to add a baseline for this project", why) @@ -124,7 +125,7 @@ func (r *runner) groundwork(ctx context.Context, ch *core.Change, t *trial) (*pa if err != nil { return nil, err } - t.cmds, t.proof.Base, t.proof.Nothing = cmds, run, false + t.cmds, t.proof.Base, t.proof.Nothing, t.thin = cmds, run, false, "" if line != "" { r.tests = []string{line} } diff --git a/internal/cli/catchup_test.go b/internal/cli/catchup_test.go index 8acb295..04cdd42 100644 --- a/internal/cli/catchup_test.go +++ b/internal/cli/catchup_test.go @@ -156,6 +156,13 @@ func TestTrack(t *testing.T) { if is := f.Issues(); len(is) != 1 || !is[0].Open || !strings.Contains(is[0].Body, "npm/a@2.0.0") { t.Errorf("after losing state: %+v", is) } + // An issue a maintainer deleted or moved is replaced in the same run. + f.DeleteIssue(1000) + s.st.Fail("npm/d@2.0.0", "npm test failed", "base2", now) + s.track(ctx, &plan.Plan{}, "base2") + if is := f.Issues(); len(is) != 1 || is[0].Number == 1000 || !is[0].Open || !strings.Contains(is[0].Body, "npm/d@2.0.0") || s.st.Issue.Number != is[0].Number { + t.Errorf("after the issue went: %+v, state %+v", is, s.st.Issue) + } } // Each part of a catch-up PR is made on top of the baseline the PR adds, so @@ -202,3 +209,33 @@ func TestRestart(t *testing.T) { t.Errorf("the baseline is not there after a run's clean-up: %q, %v", b, err) } } + +// A change that failed stays on the tracking issue when the base moves, +// until a run tries it again; a catch-up stage is never called deprecated. +func TestTrackKeepsFailuresAcrossBases(t *testing.T) { + ctx := context.Background() + f := deliver.NewFake("acme", "shop", "main") + var errs bytes.Buffer + s := &session{e: Env{Stderr: &errs}, cfg: config.Default(), st: state.New(), forge: f} + now := time.Now() + s.st.Fail("npm/chalk@6.0.1", "No model is configured to move the call site.", "base1", now) + axios := core.Change{ID: "npm/axios@1.20.0", Kind: core.Breaking, Level: "major", To: "1.20.0", Deps: []core.Dep{{Name: "axios"}}} + stage := core.Change{ID: core.StageID(2), Kind: core.First, Batch: &core.Batch{Stage: 2, Changes: []core.Change{axios}}} + plan.Refit(&stage) + moment := core.Change{ID: "npm/moment@", Kind: core.Deprecation, Deps: []core.Dep{{Name: "moment"}}} + chalk := core.Change{ID: "npm/chalk@6.0.1", Kind: core.Breaking, To: "6.0.1", Deps: []core.Dep{{Name: "chalk"}}} + p := &plan.Plan{Queue: []core.Change{stage, moment, chalk}} + s.track(ctx, p, "base1") + s.st.See("npm/chalk@6.0.1", "queued", "", now) + s.track(ctx, p, "base2") + is := f.Issues() + if len(is) != 1 || !is[0].Open { + t.Fatalf("issues = %+v; log %s", is, errs.String()) + } + if want := "- `npm/chalk@6.0.1`: could not be made or proven on base1 (the base has moved on since; tend tries it again): no model is configured to move the call site\n"; !strings.Contains(is[0].Body, want) { + t.Errorf("the issue lacks %q:\n%s", want, is[0].Body) + } + if strings.Contains(is[0].Body, "`axios`") || !strings.Contains(is[0].Body, "`moment`") { + t.Errorf("deprecations listed:\n%s", is[0].Body) + } +} diff --git a/internal/cli/check.go b/internal/cli/check.go index 567affc..fdfba20 100644 --- a/internal/cli/check.go +++ b/internal/cli/check.go @@ -2,60 +2,134 @@ package cli import ( "context" + "errors" "fmt" "slices" + "strings" + "time" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/deliver" "github.com/mohsensc/tend-cli/internal/gitx" "github.com/mohsensc/tend-cli/internal/plan" "github.com/mohsensc/tend-cli/internal/verify" ) func check(ctx context.Context, e Env, o opts) int { - s, err := open(ctx, e, o) + s, err := open(ctx, e, o, true) if err != nil { return fail(e, err) } defer s.close() + reached := s.reach(ctx) base, berr := s.baseName(ctx) - sha, _ := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", s.baseRev(ctx, base, false)+"^{commit}") + if berr == nil { + berr = reached + } + rev, rerr := s.baseRev(ctx, base, false) + if rerr != nil { + rev = "HEAD" + } + sha, _ := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", rev+"^{commit}") p, inv, err := s.plan(ctx, s.root, sha, nil) if err != nil { return fail(e, err) } + p.Notes = append(p.Notes, s.away(ctx, base, rev, rerr, sha)...) if berr != nil { p.Notes = append(p.Notes, fmt.Sprintf("cannot read the default branch: %v", berr)) } if s.forge == nil { - p.Notes = append(p.Notes, "open pull requests unknown: "+s.why) + s.openWhy = s.why } else if p.Open, err = newestOpen(ctx, s.forge); err != nil { + s.openWhy = "cannot list them" p.Notes = append(p.Notes, fmt.Sprintf("cannot list open pull requests: %v", err)) } + // Like run, check owes no first PR where there is nothing to watch. + empty := len(inv.Manifests) == 0 && len(inv.Providers) == 0 && len(p.Untracked) == 0 // check reads the checkout, local edits and all, not the base commit, so - // what it finds shows the first PR but does not settle it. - was := s.st.Onboard - if err := s.onboard(ctx, inv, p, sha); err != nil { - p.Notes = append(p.Notes, fmt.Sprintf("cannot tell whether the first PR is due: %v", err)) + // what it finds shows the catch-up but does not settle it. + was, stage := s.st.Onboard, s.st.Stage + s.mergedStage(ctx) + if !empty { + if err := s.onboard(ctx, inv, p, sha); err != nil { + p.Notes = append(p.Notes, fmt.Sprintf("cannot tell whether the first PR is due: %v", err)) + } + } + s.st.Onboard, s.st.Stage = was, stage + if ctx.Err() != nil { + return interrupted(e) + } + if !s.readOnly { + s.snapshot(inv) } - s.st.Onboard = was - s.snapshot(inv) s.save() if o.json { err = writeJSON(e.Stdout, checkJSON(s.repo, base, p)) } else { - err = writeCheck(e.Stdout, s, p, len(inv.Manifests) == 0 && len(inv.Providers) == 0 && len(p.Untracked) == 0) + err = writeCheck(e.Stdout, s, p, empty) } if err != nil { return fail(e, err) } - if o.failOn != "" && slices.ContainsFunc(p.Queue, func(ch core.Change) bool { - return o.failOn == "any" || string(ch.Kind) == o.failOn - }) { + if o.failOn != "" && slices.ContainsFunc(p.Queue, func(ch core.Change) bool { return fails(ch, o.failOn, s.e.Now()) }) { return exitFound } return exitOK } +// mergedStage counts a merged catch-up PR's stage as done, as run's +// reconcile does, for this check only: without it, check lists a stage PR +// that the next run, seeing the merge, never opens. +func (s *session) mergedStage(ctx context.Context) { + o := s.st.Open + if s.forge == nil || o == nil || !core.CatchUp(o.ID) || o.Branch == "" { + return + } + pr, err := s.forge.FindPR(ctx, o.Branch) + if err != nil || pr == nil || pr.State != "merged" || pr.Number != o.PR { + return + } + s.st.Stage = max(s.st.Stage, o.Stage, deliver.StageOf(pr.Body)) +} + +// away says when the checkout check reads is not what run works on: the +// base branch is not here yet and run fetches it, or the checkout is behind +// the base or apart from it. A branch built on the base says nothing. +func (s *session) away(ctx context.Context, base, rev string, rerr error, sha string) []string { + head, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", "HEAD^{commit}") + switch { + case err != nil || head == "": + return nil + case rerr != nil && s.remote != "": + return []string{fmt.Sprintf("base branch %q is not in this clone; showing the checkout at %s, but run fetches %s/%s first and works on that", base, core.Short(head), s.remote, base)} + case rerr != nil: + return []string{fmt.Sprintf("%v; showing the checkout at %s", rerr, core.Short(head))} + case sha == "" || sha == head: + return nil + } + if _, err := gitx.Run(ctx, s.root, "merge-base", "--is-ancestor", sha, "HEAD"); err == nil { + return nil + } + where := strings.TrimPrefix(strings.TrimPrefix(rev, "refs/remotes/"), "refs/heads/") + note := fmt.Sprintf("showing the checkout at %s; run works on %s at %s", core.Short(head), where, core.Short(sha)) + if strings.HasPrefix(rev, "refs/remotes/") { + note += ", fetched fresh first" + } + return []string{note} +} + +// fails says whether ch trips --fail-on kind; breaking takes in deprecations +// whose sunset is near or past. The first PR's own changes are +// in the queue on their own; what it adds is removals, and a tend.yml that +// changes nothing, which is no work upstream. +func fails(ch core.Change, kind string, now time.Time) bool { + if ch.Kind == core.First { + return kind == "any" && ch.Batch != nil && len(ch.Batch.Unused) > 0 + } + return kind == "any" || string(ch.Kind) == kind || kind == "breaking" && plan.Urgent(&ch, now) +} + // plan inventories root, asks upstream and builds the queue against the base // commit sha. base, when set, runs the base commit once the inventory is // known and returns the deprecation warnings it printed; without it, the last @@ -71,8 +145,15 @@ func (s *session) plan(ctx context.Context, root, sha string, base func(*core.In } else if b := s.st.Baseline; b != nil { warned = b.Run.Warnings } + if err := ctx.Err(); err != nil { + return nil, nil, err + } extra, unknown := plan.Discover(ctx, inv, s.cfg, s.st, s.fetch, s.e.Now()) + if err := ctx.Err(); err != nil { + return nil, nil, err + } srcs, specs := plan.Sources(s.dir, s.cfg, s.fetch, s.llm(), s.e.Now, extra...) + specs.Done = s.done if len(warned) > 0 { srcs = append(srcs, &verify.Runtime{Warnings: warned}) } @@ -93,6 +174,13 @@ func (s *session) snapshot(inv *core.Inventory) { } } +// done reports whether the change id was dealt with: delivered, ignored, or +// declined by a maintainer. +func (s *session) done(id string) bool { + v := s.st.Seen[id].Verdict + return v == "delivered" || v == "ignored" || s.st.Parked[id].Reason == "rejected" +} + func newestOpen(ctx context.Context, forge core.Forge) (*core.PR, error) { prs, err := forge.OpenPRs(ctx, "tend/") if err != nil || len(prs) == 0 { @@ -108,6 +196,16 @@ func newestOpen(ctx context.Context, forge core.Forge) (*core.PR, error) { } func fail(e Env, err error) int { + if errors.Is(err, context.Canceled) { + return interrupted(e) + } fmt.Fprintf(e.Stderr, "tend: %v\n", err) return exitErr } + +// interrupted ends a command a signal cut short, with the code a shell +// gives a process an interrupt stopped. +func interrupted(e Env) int { + fmt.Fprintln(e.Stderr, "tend: interrupted") + return exitInterrupted +} diff --git a/internal/cli/ci.go b/internal/cli/ci.go index 0167888..d79fbf5 100644 --- a/internal/cli/ci.go +++ b/internal/cli/ci.go @@ -38,8 +38,16 @@ func (s *session) settleCommit(ctx context.Context) (*outcome, error) { s.logf("cannot fetch %s to look for %s: %v", o.Branch, core.Short(o.Commit), err) return nil, nil } + if err := s.push.Deepen(ctx, o.Branch, o.Commit, o.At); err != nil { + s.logf("cannot fetch the history of %s to look for %s: %v", o.Branch, core.Short(o.Commit), err) + return &outcome{Action: "waiting", Summary: fmt.Sprintf("waiting to find %s on %s, which tend pushed there", core.Short(o.Commit), o.Branch)}, nil + } ref := "refs/remotes/" + s.remote + "/" + o.Branch if _, err := gitx.Run(ctx, s.root, "merge-base", "--is-ancestor", o.Commit, ref); err != nil { + if gitx.Code(err) != 1 { + s.logf("cannot tell whether %s is still on %s: %v", core.Short(o.Commit), o.Branch, err) + return &outcome{Action: "waiting", Summary: fmt.Sprintf("waiting to find %s on %s, which tend pushed there", core.Short(o.Commit), o.Branch)}, nil + } s.st.Open = nil s.st.Parked[o.ID] = state.Parked{Reason: "rejected", To: core.TargetOf(o.ID), At: s.e.Now()} if core.CatchUp(o.ID) { @@ -52,16 +60,24 @@ func (s *session) settleCommit(ctx context.Context) (*outcome, error) { switch { case err != nil && waited < ciWait: s.logf("cannot read CI on %s: %v", core.Short(o.Commit), err) - return &outcome{Action: "waiting", line: fmt.Sprintf("waiting to read CI on %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil + return &outcome{Action: "waiting", Summary: fmt.Sprintf("waiting to read CI on %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil case err != nil: s.logf("cannot read CI on %s after %s, so tend takes it as passed: %v", core.Short(o.Commit), ciWait, err) case ci.State == "pending" && waited < ciWait: - return &outcome{Action: "waiting", line: fmt.Sprintf("waiting on CI for %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil + return &outcome{Action: "waiting", Summary: fmt.Sprintf("waiting on CI for %s, which tend pushed to %s", core.Short(o.Commit), o.Branch)}, nil case ci.State == "pending": s.logf("CI on %s has not finished after %s, so tend takes it as passed", core.Short(o.Commit), ciWait) case ci.State == "failure": before, err := s.checks(ctx, o.Commit+"^") - if err == nil && before.State == "failure" { + if err != nil && waited < ciWait { + s.logf("cannot read CI on the commit before %s: %v", core.Short(o.Commit), err) + return &outcome{Action: "waiting", Summary: fmt.Sprintf("CI fails on %s; waiting to read CI on the commit before it", core.Short(o.Commit))}, nil + } + if err != nil { + s.logf("CI fails on %s, and after %s tend still cannot read CI on the commit before it, so it leaves the commit in place: %v", core.Short(o.Commit), ciWait, err) + break + } + if before.State == "failure" { s.logf("CI fails on %s, as it did on the commit before it, so tend's change is not what broke it", core.Short(o.Commit)) break } @@ -130,7 +146,7 @@ func (s *session) revert(ctx context.Context, o *state.OpenPR, ci core.CI) (*out } if _, err := gitx.Run(ctx, wt.Dir, "revert", "--no-commit", o.Commit); err != nil { park(fmt.Sprintf("CI failed on %s (%s), and reverting it does not apply cleanly; revert it by hand", short, failed)) - return &outcome{Action: "unproven", line: fmt.Sprintf("CI fails on %s and tend cannot revert it cleanly", short), code: exitUnproven}, nil + return &outcome{Action: "unproven", Summary: fmt.Sprintf("CI fails on %s and tend cannot revert it cleanly", short), code: exitUnproven}, nil } if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil { return nil, err @@ -157,7 +173,7 @@ func (s *session) revert(ctx context.Context, o *state.OpenPR, ci core.CI) (*out } if !run.Pass { park(fmt.Sprintf("CI failed on %s (%s), and the revert does not pass the project's commands either: %s; revert it by hand", short, failed, broke(run))) - return &outcome{Action: "unproven", line: fmt.Sprintf("CI fails on %s and its revert fails too", short), code: exitUnproven}, nil + return &outcome{Action: "unproven", Summary: fmt.Sprintf("CI fails on %s and its revert fails too", short), code: exitUnproven}, nil } } subject, err := gitx.Run(ctx, s.root, "log", "-1", "--format=%s", o.Commit) @@ -172,11 +188,11 @@ func (s *session) revert(ctx context.Context, o *state.OpenPR, ci core.CI) (*out sha, err := deliver.Commit(ctx, wt, s.push, o.Branch) switch { case errors.Is(err, deliver.ErrMoved): - return &outcome{Action: "moved", line: err.Error() + "; the next run reverts on the new tip"}, nil + return &outcome{Action: "moved", Summary: err.Error() + "; the next run reverts on the new tip"}, nil case err != nil: return nil, err } park(fmt.Sprintf("reverted in %s: CI failed on %s (%s)", core.Short(sha), short, failed)) s.logf("CI failed on %s (%s); reverted it in %s", short, failed, core.Short(sha)) - return &outcome{Action: "reverted", Commit: sha, Branch: o.Branch, line: fmt.Sprintf("reverted %s on %s: CI failed (%s)", short, o.Branch, failed)}, nil + return &outcome{Action: "reverted", Commit: sha, Branch: o.Branch, Summary: fmt.Sprintf("reverted %s on %s: CI failed (%s)", short, o.Branch, failed)}, nil } diff --git a/internal/cli/ci_test.go b/internal/cli/ci_test.go new file mode 100644 index 0000000..19bd826 --- /dev/null +++ b/internal/cli/ci_test.go @@ -0,0 +1,100 @@ +package cli + +import ( + "bytes" + "context" + "path/filepath" + "testing" + "time" + + "github.com/mohsensc/tend-cli/internal/config" + "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/deliver" + "github.com/mohsensc/tend-cli/internal/state" +) + +// shallow is a depth-1 clone of a remote where someone pushed on top of the +// commit tend pushed, so that commit and the one before it are not in the +// clone. It returns the clone, tend's commit and the one before it. +func shallow(t *testing.T) (string, string, string) { + t.Helper() + src := repo(t, map[string]string{"a.txt": "a\n"}) + parent := gitIn(t, src, "rev-parse", "HEAD") + writeFiles(t, src, map[string]string{"a.txt": "b\n"}) + gitIn(t, src, "commit", "--quiet", "-am", "tend's change") + mine := gitIn(t, src, "rev-parse", "HEAD") + writeFiles(t, src, map[string]string{"a.txt": "c\n"}) + gitIn(t, src, "commit", "--quiet", "-am", "someone else's") + bare := filepath.Join(t.TempDir(), "origin.git") + gitIn(t, src, "clone", "--quiet", "--bare", src, bare) + clone := filepath.Join(t.TempDir(), "clone") + gitIn(t, src, "clone", "--quiet", "--depth", "1", "file://"+bare, clone) + return clone, mine, parent +} + +func settleIn(t *testing.T, clone, mine string, ci map[string]core.CI) (*session, *outcome, string) { + t.Helper() + ctx := context.Background() + remote, err := deliver.NewRemote(ctx, clone, "origin", "", "", "") + if err != nil { + t.Fatal(err) + } + f := deliver.NewFake("acme", "shop", "main") + f.CI = ci + now := time.Now() + var errs bytes.Buffer + s := &session{e: Env{Stderr: &errs, Now: func() time.Time { return now }}, cfg: config.Default(), st: state.New(), forge: f, root: clone, remote: "origin", push: remote} + s.st.Open = &state.OpenPR{ID: "npm/a@2.0.0", Branch: "main", Commit: mine, At: now.Add(-time.Hour)} + res, err := s.settleCommit(ctx) + if err != nil { + t.Fatal(err) + } + return s, res, errs.String() +} + +// A shallow checkout, as actions/checkout makes by default, does not hold +// tend's commit once someone pushed on top of it; that is no sign the +// commit was taken off again. +func TestSettleShallow(t *testing.T) { + clone, mine, _ := shallow(t) + s, res, logged := settleIn(t, clone, mine, map[string]core.CI{mine: {State: "success"}}) + if res != nil || s.st.Open != nil { + t.Fatalf("outcome %+v, open %+v; logged %s", res, s.st.Open, logged) + } + if _, ok := s.st.Parked["npm/a@2.0.0"]; ok { + t.Errorf("a commit still on the branch was parked as rejected: %+v", s.st.Parked) + } + if s.st.Seen["npm/a@2.0.0"].Verdict != "delivered" { + t.Errorf("seen = %+v", s.st.Seen) + } +} + +// CI that failed on the commit before tend's too is not tend's doing, and +// the commit before it is found in a shallow checkout as well. +func TestSettleShallowParentRed(t *testing.T) { + clone, mine, parent := shallow(t) + red := core.CI{State: "failure", Failed: []string{"test"}} + s, res, logged := settleIn(t, clone, mine, map[string]core.CI{mine: red, parent: red}) + if res != nil || s.st.Open != nil || s.st.Seen["npm/a@2.0.0"].Verdict != "delivered" { + t.Fatalf("outcome %+v, open %+v, seen %+v; logged %s", res, s.st.Open, s.st.Seen, logged) + } +} + +// A commit that is no longer on the branch was taken off by someone, and is +// not tried again. +func TestSettleRemoved(t *testing.T) { + clone, _, _ := shallow(t) + gone := "1111111111111111111111111111111111111111" + s, res, logged := settleIn(t, clone, gone, nil) + if res == nil || res.Action != "waiting" || s.st.Open == nil { + t.Fatalf("an unknown commit: outcome %+v, open %+v; logged %s", res, s.st.Open, logged) + } + top := gitIn(t, clone, "rev-parse", "HEAD") + gitIn(t, clone, "commit", "--quiet", "--allow-empty", "-m", "local only") + local := gitIn(t, clone, "rev-parse", "HEAD") + gitIn(t, clone, "reset", "--quiet", "--hard", top) + s, res, logged = settleIn(t, clone, local, nil) + if res != nil || s.st.Open != nil || s.st.Parked["npm/a@2.0.0"].Reason != "rejected" { + t.Fatalf("a commit off the branch: outcome %+v, open %+v, parked %+v; logged %s", res, s.st.Open, s.st.Parked, logged) + } +} diff --git a/internal/cli/climb.go b/internal/cli/climb.go index 7852e77..3bb7185 100644 --- a/internal/cli/climb.go +++ b/internal/cli/climb.go @@ -41,6 +41,9 @@ func scale(o *patch.Options, n int) { // is named in the why. It returns nil when none passed, with the worktree // back on the base. func (r *runner) decide(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof, left *int) (*core.Change, *core.Patch, error) { + if untestable(proof) != "" { + return nil, nil, nil + } var failed []string for _, t := range plan.Ranked(ch, r.inv.Deps) { if left != nil && *left <= 0 { @@ -60,8 +63,7 @@ func (r *runner) decide(ctx context.Context, ch *core.Change, cmds core.Commands case err != nil && ctx.Err() != nil: return nil, nil, ctx.Err() case err != nil: - first, _, _ := strings.Cut(err.Error(), "\n") - failed = append(failed, fmt.Sprintf("option %d could not be made (%s)", t.N, first)) + failed = append(failed, fmt.Sprintf("option %d could not be made (%s)", t.N, whyFailed(err))) case pt.Decision: failed = append(failed, fmt.Sprintf("option %d could not be made (%s)", t.N, deliver.Clause(pt.Note))) case len(pt.Files) == 0: @@ -84,9 +86,13 @@ func (r *runner) decide(ctx context.Context, ch *core.Change, cmds core.Commands // call sites from it. It stops at the first step that fails and returns // the change as far as it got, with the steps it climbed through in Via, // its patch staged against the base and the run that proved it, or a nil -// change when not even the first step passed. why says where it stopped. +// change when not even the first step passed, or when a security fix stops +// short of the release that fixes it. why says where it stopped. func (r *runner) climb(ctx context.Context, ch *core.Change, cmds core.Commands, proof *core.Proof, left *int) (*core.Change, *core.Patch, *core.Run, string, error) { wt := r.wt + if why := untestable(proof); why != "" { + return nil, nil, nil, why, nil + } if err := r.restart(ctx); err != nil { return nil, nil, nil, "", err } @@ -109,7 +115,7 @@ func (r *runner) climb(ctx context.Context, ch *core.Change, cmds core.Commands, case err != nil && ctx.Err() != nil: return nil, nil, nil, "", ctx.Err() case err != nil: - why, _, _ = strings.Cut(err.Error(), "\n") + why = whyFailed(err) case pt.Decision: why = pt.Note case len(pt.Files) == 0: @@ -152,6 +158,10 @@ func (r *runner) climb(ctx context.Context, ch *core.Change, cmds core.Commands, return nil, nil, nil, "", err } } + if shortOfFix(ch, done) { + why = fmt.Sprintf("climbed to %s, short of %s, the least release that fixes the advisories; %s", done[len(done)-1], ch.To, why) + done = nil + } if len(done) == 0 { return nil, nil, nil, why, r.restart(ctx) } @@ -163,10 +173,26 @@ func (r *runner) climb(ctx context.Context, ch *core.Change, cmds core.Commands, res.Edited = slices.Compact(res.Edited) c := *ch c.To, c.Via = done[len(done)-1], done[:len(done)-1] - c.Level = ver.Step(plan.Lowest(ch.Deps), c.To) + c.Level = ver.StepIn(ch.Deps[0].Ecosystem, plan.Lowest(ch.Deps), c.To) return &c, res, run, why, nil } +// shortOfFix says whether a climb of a security fix stopped below the +// release that fixes it: each major in between is still vulnerable, so +// that is no fix at all. +func shortOfFix(ch *core.Change, done []string) bool { + return len(done) > 0 && ch.Kind == core.Security && ver.Less(done[len(done)-1], ch.To) +} + +// untestable says why no patch can be proven against a base that fails +// before any of its tests run, "" when one can. +func untestable(proof *core.Proof) string { + if proof == nil || proof.Nothing || proof.Base == nil || proof.Base.Pass || proof.Base.Tested() || proof.Base.Last() == nil { + return "" + } + return fmt.Sprintf("the base fails at `%s` before its tests run, so no step can be proven", proof.Base.Last().Cmd) +} + // rung is ch as one step of a climb: from deps, as the last step left them, // to to, with the call sites as they read now and only the release notes of // the releases the step crosses. @@ -174,7 +200,7 @@ func rung(ch *core.Change, deps []core.Dep, sites []core.Site, to string) core.C c := *ch from := plan.Lowest(deps) c.Deps, c.Sites, c.To, c.Steps = deps, sites, to, nil - c.Level = ver.Step(from, to) + c.Level = ver.StepIn(ch.Deps[0].Ecosystem, from, to) c.Evidence = nil for _, ev := range ch.Evidence { if v, ok := noted(ev); !ok || ver.Less(from, v) && !ver.Less(to, v) { diff --git a/internal/cli/env.go b/internal/cli/env.go index 2effec6..378d9c5 100644 --- a/internal/cli/env.go +++ b/internal/cli/env.go @@ -8,11 +8,13 @@ import ( "fmt" "io" "os" + "os/exec" "os/signal" "path/filepath" "slices" "strings" "syscall" + "text/tabwriter" "time" "github.com/mohsensc/tend-cli/internal/core" @@ -31,6 +33,7 @@ type Env struct { Now func() time.Time Home string Getenv func(string) string + Runtime func(ctx context.Context, dir, line string) string Version string Commit, Date string } @@ -48,10 +51,24 @@ func DefaultEnv() Env { Now: time.Now, Home: state.Home(os.Getenv), Getenv: os.Getenv, + Runtime: runtimeVersion, Version: "dev", } } +// runtimeVersion runs line in dir for a few seconds at most. +func runtimeVersion(ctx context.Context, dir, line string) string { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "sh", "-c", line) + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + return "" + } + return string(out) +} + const usage = `tend keeps the dependencies and the APIs your code calls current, one proven PR at a time. usage: tend [flags] @@ -79,6 +96,10 @@ const ( exitUsage = 2 exitFound = 3 // check --fail-on matched a queued change exitUnproven = 4 // run could not prove the fix + + exitUndelivered = 5 // run proved a change, but with no GitHub token it opened no PR + + exitInterrupted = 130 // an interrupt or a SIGTERM stopped the command ) type opts struct { @@ -103,7 +124,7 @@ var commands = map[string]command{ "check": {"list what would change, most important first", func(fs *flag.FlagSet, o *opts) { fs.BoolVar(&o.json, "json", false, "print JSON") fs.BoolVar(&o.all, "all", false, "list skipped changes too") - fs.StringVar(&o.failOn, "fail-on", "", "exit 3 when a change of this kind is queued: security|breaking|deprecation|any") + fs.StringVar(&o.failOn, "fail-on", "", "exit 3 when a change of this `kind` is queued: security|breaking|deprecation|any; breaking takes in deprecations whose sunset is within 30 days or past") fs.BoolVar(&o.reset, "reset", false, "forget everything tend remembers about this repo first") }, check}, "run": {"fix the top change, prove it, and open or update its PR", func(fs *flag.FlagSet, o *opts) { @@ -127,10 +148,39 @@ var commands = map[string]command{ }, version}, } -var valued = map[string]bool{"-C": true, "-config": true, "--config": true, "-home": true, "--home": true, "-every": true, "--every": true, "-fail-on": true, "--fail-on": true} +var valued = map[string]bool{"-C": true, "--C": true, "-config": true, "--config": true, "-home": true, "--home": true, "-every": true, "--every": true, "-fail-on": true, "--fail-on": true} func isHelp(a string) bool { return a == "-h" || a == "-help" || a == "--help" } +func isVersion(a string) bool { return a == "-version" || a == "--version" } + +// globals are the flags every command takes. +func globals(fs *flag.FlagSet, o *opts) { + fs.StringVar(&o.dir, "C", "", "run as if started in `dir`") + fs.StringVar(&o.config, "config", "", "`path` to tend.yml") + fs.StringVar(&o.home, "home", "", "state `dir`; default $TEND_HOME or the user cache dir") + fs.BoolVar(&o.verbose, "v", false, "stream command output") + fs.BoolVar(&o.quiet, "q", false, "print only the final line") +} + +// printFlags lists fs's flags as the docs write them: --name, or -C for a +// one-letter one, then what it takes and what it does. +func printFlags(w io.Writer, fs *flag.FlagSet) { + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + fs.VisitAll(func(f *flag.Flag) { + arg, about := flag.UnquoteUsage(f) + spec := "--" + f.Name + if len(f.Name) == 1 { + spec = "-" + f.Name + } + if arg != "" { + spec += " " + arg + } + fmt.Fprintf(tw, " %s\t%s\n", spec, about) + }) + tw.Flush() +} + // split finds the command among the arguments, so global flags may come // before or after it. func split(args []string) (string, []string) { @@ -151,14 +201,29 @@ func split(args []string) (string, []string) { // Main runs one command and returns the process exit code. func Main(args []string, e Env) int { name, rest := split(args) - if name == "help" || name == "" && slices.ContainsFunc(rest, isHelp) { + if name == "help" { + if name, rest = split(rest); name == "" { + fmt.Fprint(e.Stdout, usage) + return exitOK + } + rest = append(rest, "--help") + } + if name == "" && slices.ContainsFunc(rest, isHelp) { fmt.Fprint(e.Stdout, usage) return exitOK } + if name == "" && slices.ContainsFunc(rest, isVersion) { + name, rest = "version", slices.DeleteFunc(rest, isVersion) + } c, ok := commands[name] if !ok { - if name != "" { + switch { + case name != "": fmt.Fprintf(e.Stderr, "tend: unknown command %q\n", name) + case len(rest) > 0 && valued[rest[len(rest)-1]]: + fmt.Fprintf(e.Stderr, "tend: flag needs an argument: %s\n", rest[len(rest)-1]) + case len(rest) > 0: + fmt.Fprintln(e.Stderr, "tend: missing command") } fmt.Fprint(e.Stderr, usage) return exitUsage @@ -170,21 +235,19 @@ func Main(args []string, e Env) int { fs.SetOutput(e.Stderr) fs.Usage = func() {} own.VisitAll(func(f *flag.Flag) { fs.Var(f.Value, f.Name, f.Usage) }) - fs.StringVar(&o.dir, "C", "", "run as if started in `dir`") - fs.StringVar(&o.config, "config", "", "path to tend.yml") - fs.StringVar(&o.home, "home", "", "state `dir`; default $TEND_HOME or the user cache dir") - fs.BoolVar(&o.verbose, "v", false, "stream command output") - fs.BoolVar(&o.quiet, "q", false, "print only the final line") + globals(fs, &o) help := func(w io.Writer) { fmt.Fprintf(w, "usage: tend %s [flags]\n\n%s\n", name, c.about) n := 0 own.VisitAll(func(*flag.Flag) { n++ }) if n > 0 { fmt.Fprintf(w, "\nflags:\n") - own.SetOutput(w) - own.PrintDefaults() + printFlags(w, own) } - fmt.Fprintf(w, "\nglobal flags: see tend --help\n") + g := flag.NewFlagSet("", flag.ContinueOnError) + globals(g, &opts{}) + fmt.Fprintf(w, "\nglobal flags:\n") + printFlags(w, g) } if err := fs.Parse(rest); err != nil { if errors.Is(err, flag.ErrHelp) { @@ -194,23 +257,45 @@ func Main(args []string, e Env) int { help(e.Stderr) return exitUsage } - switch { - case o.dir == "": + if o.dir == "" { o.dir = e.Dir - case !filepath.IsAbs(o.dir): - o.dir = filepath.Join(e.Dir, o.dir) + } else { + given := o.dir + if !filepath.IsAbs(o.dir) { + o.dir = filepath.Join(e.Dir, o.dir) + } + if fi, err := os.Stat(o.dir); err != nil { + fmt.Fprintf(e.Stderr, "tend: -C %s: no such directory\n", given) + return exitUsage + } else if !fi.IsDir() { + fmt.Fprintf(e.Stderr, "tend: -C %s: not a directory\n", given) + return exitUsage + } + } + // A relative home is the same place for every git call and every file + // tend writes, wherever they run: under the dir tend runs as if in. + if o.home != "" { + e.Home = o.home + } + if e.Home != "" && !filepath.IsAbs(e.Home) { + e.Home = filepath.Join(o.dir, e.Home) + } + if fi, err := os.Stat(e.Home); err == nil && !fi.IsDir() { + fmt.Fprintf(e.Stderr, "tend: --home %s: not a directory\n", e.Home) + return exitUsage } if fs.NArg() > 0 { fmt.Fprintf(e.Stderr, "tend %s: unexpected argument %q\n", name, fs.Arg(0)) return exitUsage } + if o.every < 0 { + fmt.Fprintf(e.Stderr, "tend watch: --every wants a positive duration, or 0 for tend.yml's schedule, not %s\n", o.every) + return exitUsage + } if o.failOn != "" && !slices.Contains([]string{"security", "breaking", "deprecation", "any"}, o.failOn) { fmt.Fprintf(e.Stderr, "tend check: --fail-on wants security, breaking, deprecation or any, not %q\n", o.failOn) return exitUsage } - if o.home != "" { - e.Home = o.home - } if e.Now == nil { e.Now = time.Now } @@ -219,5 +304,14 @@ func Main(args []string, e Env) int { } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() - return c.run(ctx, e, o) + if name == "watch" { + return c.run(ctx, e, o) + } + // Once interrupted, a second interrupt ends tend at once. + context.AfterFunc(ctx, stop) + code := c.run(ctx, e, o) + if ctx.Err() != nil && code != exitInterrupted { + return interrupted(e) + } + return code } diff --git a/internal/cli/env_test.go b/internal/cli/env_test.go index cce185c..c41f3c1 100644 --- a/internal/cli/env_test.go +++ b/internal/cli/env_test.go @@ -57,6 +57,28 @@ func TestSplit(t *testing.T) { } } +// Every flag that takes a value, in both spellings, may come before the +// command without its value being read as the command. +func TestSplitValued(t *testing.T) { + names := map[string]bool{"C": true, "config": true, "home": true} + for _, c := range commands { + fs := flag.NewFlagSet("", flag.ContinueOnError) + c.flags(fs, &opts{}) + fs.VisitAll(func(f *flag.Flag) { + if b, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !b.IsBoolFlag() { + names[f.Name] = true + } + }) + } + for name := range names { + for _, a := range []string{"-" + name, "--" + name} { + if cmd, rest := split([]string{a, "x", "check"}); cmd != "check" || !slices.Equal(rest, []string{a, "x"}) { + t.Errorf("split(%s x check) = %q, %q", a, cmd, rest) + } + } + } +} + func TestMainUsage(t *testing.T) { tests := []struct { args []string @@ -68,6 +90,9 @@ func TestMainUsage(t *testing.T) { {[]string{"check", "--nope"}, exitUsage, "flag provided but not defined: -nope"}, {[]string{"check", "extra"}, exitUsage, `unexpected argument "extra"`}, {[]string{"check", "--fail-on", "minor"}, exitUsage, "--fail-on wants"}, + {[]string{"--config"}, exitUsage, "tend: flag needs an argument: --config\n"}, + {[]string{"-v"}, exitUsage, "tend: missing command\n"}, + {[]string{"help", "frobnicate"}, exitUsage, `unknown command "frobnicate"`}, } for _, tt := range tests { var out, errs bytes.Buffer @@ -88,8 +113,10 @@ func TestMainHelp(t *testing.T) { {[]string{"help"}, []string{"one proven PR at a time", "tend run --dry-run"}, "unknown command"}, {[]string{"--help"}, []string{"usage: tend "}, ""}, {[]string{"-h"}, []string{"usage: tend "}, ""}, - {[]string{"run", "-h"}, []string{"usage: tend run [flags]", "fix the top change", "-dry-run", "global flags: see tend --help"}, "-home"}, - {[]string{"version", "--help"}, []string{"print the version", "-check"}, "-config"}, + {[]string{"run", "-h"}, []string{"usage: tend run [flags]", "fix the top change", " --dry-run ", "global flags:\n", " -C dir ", " --home dir "}, " -dry-run"}, + {[]string{"version", "--help"}, []string{"print the version", " --check "}, "usage: tend "}, + {[]string{"help", "check"}, []string{"usage: tend check [flags]", " --fail-on kind "}, "usage: tend "}, + {[]string{"-C", "x", "help", "run"}, []string{"usage: tend run [flags]"}, ""}, } for _, tt := range tests { var out, errs bytes.Buffer @@ -127,3 +154,14 @@ func TestVersion(t *testing.T) { } } } + +func TestMainVersionFlag(t *testing.T) { + for _, args := range [][]string{{"--version"}, {"-version"}} { + var out, errs bytes.Buffer + e := DefaultEnv() + e.Stdout, e.Stderr, e.Version = &out, &errs, "1.2.3" + if code := Main(args, e); code != exitOK || !strings.HasPrefix(out.String(), "tend 1.2.3") || errs.Len() > 0 { + t.Errorf("Main(%q) = %d, %q, %q", args, code, out.String(), errs.String()) + } + } +} diff --git a/internal/cli/init.go b/internal/cli/init.go index 387f67d..3b11f8b 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -39,27 +39,29 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - with: {persist-credentials: false} + with: {persist-credentials: false, fetch-depth: 0} - uses: mohsensc/tend-cli@v1 with: {model-key: "${{ secrets.TEND_MODEL_KEY }}"} ` func initRepo(ctx context.Context, e Env, o opts) int { - cfg, root, _, err := settings(ctx, e, o) - if err != nil && o.ci { - return fail(e, err) - } - name, body := "tend.yml", config.Sample + var p string + var body []byte if o.ci { - name, body = filepath.Join(".github", "workflows", "tend.yml"), fmt.Appendf(nil, workflow, branch(ctx, root, cfg), cron(time.Duration(cfg.Schedule))) - } - p := filepath.Join(root, name) - _, err = os.Stat(p) - if err == nil && !o.force { - return fail(e, fmt.Errorf("%s exists; --force overwrites it", name)) - } - if err != nil && !errors.Is(err, os.ErrNotExist) { - return fail(e, err) + cfg, root, _, err := settings(ctx, e, o) + if err != nil { + return fail(e, err) + } + p, body = filepath.Join(root, ".github", "workflows", "tend.yml"), fmt.Appendf(nil, workflow, branch(ctx, root, cfg), cron(time.Duration(cfg.Schedule))) + if err := fresh(p, root, o.force); err != nil { + return fail(e, err) + } + } else { + var err error + if p, err = configTarget(ctx, e, o); err != nil { + return fail(e, err) + } + body = config.Sample } if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { return fail(e, err) @@ -68,14 +70,52 @@ func initRepo(ctx context.Context, e Env, o opts) int { return fail(e, err) } if !o.quiet { - fmt.Fprintf(e.Stdout, "tend: wrote %s\n", name) + root, _ := top(ctx, o.dir) + fmt.Fprintf(e.Stdout, "tend: wrote %s\n", config.Shown(root, p)) } if o.now || !o.quiet && ask(e, "Run tend now? Its first pull request tidies up what it finds. [y/N] ") { - return run(ctx, e, opts{dir: o.dir, config: o.config, verbose: o.verbose, quiet: o.quiet}) + return run(ctx, e, opts{dir: o.dir, config: o.config, home: o.home, verbose: o.verbose, quiet: o.quiet}) } return exitOK } +// configTarget is where init writes tend.yml: the file --config or TEND_CONFIG +// names, else the one tend reads. A config already there is overwritten +// only with --force, so a sample never sits in front of the real one. +func configTarget(ctx context.Context, e Env, o opts) (string, error) { + root, _ := top(ctx, o.dir) + if p := configPath(e, o, root); p != "" { + return p, fresh(p, root, o.force) + } + for _, name := range config.Files { + p := filepath.Join(root, name) + _, err := os.Stat(p) + switch { + case err == nil && o.force: + return p, nil + case err == nil && name == config.Files[0]: + return "", fmt.Errorf("%s exists; --force overwrites it", name) + case err == nil: + return "", fmt.Errorf("%s exists, and tend reads it; --force overwrites it", name) + case !errors.Is(err, os.ErrNotExist): + return "", err + } + } + return filepath.Join(root, config.Files[0]), nil +} + +// fresh says whether init may write p: when nothing is there, or --force. +func fresh(p, root string, force bool) error { + _, err := os.Stat(p) + if err == nil && !force { + return fmt.Errorf("%s exists; --force overwrites it", config.Shown(root, p)) + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + // ask puts a yes or no question to a person at a terminal. Anything but yes // is no, and so is a stdin that is not a terminal, such as CI's. func ask(e Env, q string) bool { diff --git a/internal/cli/init_test.go b/internal/cli/init_test.go index 9c0c0b2..02d3f74 100644 --- a/internal/cli/init_test.go +++ b/internal/cli/init_test.go @@ -140,3 +140,40 @@ func TestCron(t *testing.T) { } } } + +// A config tend already reads is never put behind a new tend.yml. +func TestInitExisting(t *testing.T) { + dir := repo(t, map[string]string{".github/tend.yml": "onboarding: off\n"}) + res := tend(t, dir, t.TempDir(), offline{}, "init") + if res.code != exitErr || !strings.Contains(res.stderr, ".github/tend.yml exists, and tend reads it") { + t.Errorf("init = %d, %q", res.code, res.stderr) + } + if _, err := os.Stat(filepath.Join(dir, "tend.yml")); !os.IsNotExist(err) { + t.Errorf("init wrote tend.yml in front of .github/tend.yml: %v", err) + } + res = tend(t, dir, t.TempDir(), offline{}, "init", "--force") + if res.code != exitOK || !strings.Contains(res.out, "wrote .github/tend.yml") { + t.Errorf("init --force = %d, %q, %q", res.code, res.out, res.stderr) + } + if _, err := os.Stat(filepath.Join(dir, "tend.yml")); !os.IsNotExist(err) { + t.Errorf("init --force wrote a second config: %v", err) + } +} + +// init writes the file --config names, and the run it offers reads it. +func TestInitConfig(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n"}) + res := tend(t, dir, t.TempDir(), offline{}, "init", "--config", "sub/custom.yml") + if res.code != exitOK || !strings.Contains(res.out, "wrote sub/custom.yml") { + t.Fatalf("init = %d, %q, %q", res.code, res.out, res.stderr) + } + if _, err := os.Stat(filepath.Join(dir, "tend.yml")); !os.IsNotExist(err) { + t.Errorf("init wrote tend.yml too: %v", err) + } + if res := tend(t, dir, t.TempDir(), offline{}, "check", "--config", "sub/custom.yml"); res.code != exitOK { + t.Errorf("check = %d, %q", res.code, res.stderr) + } + if res := tend(t, dir, t.TempDir(), offline{}, "check", "--config", "nope.yml"); res.code != exitErr || !strings.Contains(res.stderr, "nope.yml: config file not found") { + t.Errorf("a missing config = %d, %q", res.code, res.stderr) + } +} diff --git a/internal/cli/interrupt_test.go b/internal/cli/interrupt_test.go new file mode 100644 index 0000000..a526a53 --- /dev/null +++ b/internal/cli/interrupt_test.go @@ -0,0 +1,52 @@ +//go:build unix + +package cli + +import ( + "context" + "io/fs" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + + "github.com/mohsensc/tend-cli/internal/core" +) + +// interrupting is a registry that is interrupted, once, while tend waits +// on it. +type interrupting struct{ once sync.Once } + +func (f *interrupting) Get(ctx context.Context, url string, _ ...core.FetchOpt) (*core.Response, error) { + f.once.Do(func() { _ = syscall.Kill(syscall.Getpid(), syscall.SIGINT) }) + <-ctx.Done() + return nil, ctx.Err() +} + +func (f *interrupting) Post(ctx context.Context, url string, _ []byte, o ...core.FetchOpt) (*core.Response, error) { + return f.Get(ctx, url, o...) +} + +// An interrupted check or run reports nothing it found so far, saves +// nothing, and exits 130, so a CI gate on --fail-on cannot pass by being +// cancelled. +func TestInterrupted(t *testing.T) { + for _, args := range [][]string{{"check", "--fail-on", "security"}, {"run", "--dry-run"}} { + t.Run(args[0], func(t *testing.T) { + dir := repo(t, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`}) + home := t.TempDir() + r := tend(t, dir, home, &interrupting{}, args...) + lines := strings.Split(strings.TrimSpace(r.stderr), "\n") + if r.code != exitInterrupted || lines[len(lines)-1] != "tend: interrupted" || strings.Count(r.stderr, "interrupt") != 1 || r.out != "" { + t.Errorf("exit %d\nstdout: %s\nstderr: %s", r.code, r.out, r.stderr) + } + _ = filepath.WalkDir(home, func(p string, d fs.DirEntry, err error) error { + if err == nil && d.Name() == "state.json" { + t.Errorf("an interrupted %s saved %s", args[0], p) + } + return nil + }) + }) + } +} diff --git a/internal/cli/main_test.go b/internal/cli/main_test.go new file mode 100644 index 0000000..4d00aab --- /dev/null +++ b/internal/cli/main_test.go @@ -0,0 +1,456 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "io/fs" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/plan" + "github.com/mohsensc/tend-cli/internal/state" + "github.com/mohsensc/tend-cli/internal/verify" +) + +// offline answers the URLs that end in one of its keys and 404 for the rest. +type offline map[string]string + +func (f offline) Get(_ context.Context, url string, _ ...core.FetchOpt) (*core.Response, error) { + for suffix, body := range f { + if strings.HasSuffix(url, suffix) { + return &core.Response{Status: 200, Body: []byte(body)}, nil + } + } + return &core.Response{Status: 404}, nil +} + +func (f offline) Post(context.Context, string, []byte, ...core.FetchOpt) (*core.Response, error) { + return &core.Response{Status: 404}, nil +} + +func gitIn(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", append([]string{"-c", "user.name=Ada", "-c", "user.email=ada@example.com", "-c", "commit.gpgsign=false"}, args...)...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) + } + return strings.TrimSpace(string(out)) +} + +// repo is a git repo on main with files in one commit, or none when files +// is nil. +func repo(t *testing.T, files map[string]string) string { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not found in PATH") + } + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + dir, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + gitIn(t, dir, "init", "--quiet", "--initial-branch=main") + if files == nil { + return dir + } + writeFiles(t, dir, files) + gitIn(t, dir, "add", "-A") + gitIn(t, dir, "commit", "--quiet", "-m", "Start") + return dir +} + +func writeFiles(t *testing.T, dir string, files map[string]string) { + t.Helper() + for name, body := range files { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } +} + +type tendRun struct { + code int + out, stderr string +} + +func tend(t *testing.T, dir, home string, f core.Fetcher, args ...string) tendRun { + t.Helper() + var out, errs bytes.Buffer + e := DefaultEnv() + e.Dir, e.Home, e.Stdout, e.Stderr, e.Stdin = dir, home, &out, &errs, strings.NewReader("") + e.Fetch, e.Getenv = f, func(string) string { return "" } + code := Main(args, e) + return tendRun{code, out.String(), errs.String()} +} + +// worktrees lists the worktrees tend made under home. +func worktrees(t *testing.T, home string) []string { + t.Helper() + var res []string + err := filepath.WalkDir(home, func(p string, d fs.DirEntry, err error) error { + if err == nil && d.IsDir() && d.Name() == "wt" { + ents, _ := os.ReadDir(p) + for _, e := range ents { + res = append(res, filepath.Join(p, e.Name())) + } + } + return err + }) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + return res +} + +// A base that names no branch stops run before it proves anything; it is +// never the checked-out branch in its place. +func TestRunBaseNotFound(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n", "tend.yml": "base: mian\n"}) + gitIn(t, dir, "checkout", "--quiet", "-b", "feature") + home := t.TempDir() + res := tend(t, dir, home, offline{}, "run", "--dry-run") + if res.code != exitErr || !strings.Contains(res.stderr, `base branch "mian" not found locally`) { + t.Errorf("run = %d, %q, %q", res.code, res.out, res.stderr) + } + if wts := worktrees(t, home); len(wts) > 0 { + t.Errorf("run made worktrees %q for a base it could not find", wts) + } + + writeFiles(t, dir, map[string]string{"tend.yml": "base: main\n"}) + res = tend(t, dir, home, offline{}, "run", "--json") + var got struct{ Action, Summary, Worktree string } + if err := json.Unmarshal([]byte(res.out), &got); err != nil || res.code != exitOK { + t.Fatalf("run --json = %d, %q, %q: %v", res.code, res.out, res.stderr, err) + } + if got.Action != "nothing" || !strings.HasPrefix(got.Summary, "nothing to watch: no manifests") || got.Worktree != "" { + t.Errorf("run --json = %+v", got) + } +} + +// check still lists what the checkout has when the base is nowhere, as in +// a CI checkout of a pull request, and says so. +func TestCheckBaseNotFound(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n", "tend.yml": "base: mian\n"}) + res := tend(t, dir, t.TempDir(), offline{}, "check", "--json") + var got struct{ Notes []string } + if err := json.Unmarshal([]byte(res.out), &got); err != nil || res.code != exitOK { + t.Fatalf("check --json = %d, %q, %q: %v", res.code, res.out, res.stderr, err) + } + if !slices.ContainsFunc(got.Notes, func(n string) bool { + return strings.HasPrefix(n, `base branch "mian" not found locally; showing the checkout at `) + }) { + t.Errorf("notes = %q", got.Notes) + } +} + +// check reads the checkout, and says so when run would work on another +// commit: a base branch only the remote has, or a checkout behind the base. +func TestCheckSaysWhereRunWorks(t *testing.T) { + origin := repo(t, map[string]string{"README.md": "hi\n"}) + old := strings.TrimSpace(gitIn(t, origin, "rev-parse", "HEAD")) + writeFiles(t, origin, map[string]string{"README.md": "hello\n"}) + gitIn(t, origin, "commit", "--quiet", "-am", "next") + dir := t.TempDir() + gitIn(t, dir, "clone", "--quiet", origin, ".") + gitIn(t, dir, "checkout", "--quiet", "--detach", old) + notes := func() []string { + res := tend(t, dir, t.TempDir(), offline{}, "check", "--json") + var got struct{ Notes []string } + if err := json.Unmarshal([]byte(res.out), &got); err != nil { + t.Fatalf("check --json = %d, %q, %q: %v", res.code, res.out, res.stderr, err) + } + return got.Notes + } + has := func(notes []string, part string) bool { + return slices.ContainsFunc(notes, func(n string) bool { return strings.Contains(n, part) }) + } + if got := notes(); !has(got, "showing the checkout at "+old[:7]+"; run works on origin/main at ") { + t.Errorf("behind the base: notes = %q", got) + } + gitIn(t, dir, "update-ref", "-d", "refs/remotes/origin/main") + gitIn(t, dir, "branch", "--quiet", "-D", "main") + if got := notes(); !has(got, `base branch "main" is not in this clone; showing the checkout at `+old[:7]+", but run fetches origin/main first") { + t.Errorf("no base here: notes = %q", got) + } + gitIn(t, dir, "checkout", "--quiet", "-b", "main") + gitIn(t, dir, "fetch", "--quiet", "origin") + gitIn(t, dir, "reset", "--quiet", "--hard", "origin/main") + writeFiles(t, dir, map[string]string{"NOTES.md": "x\n"}) + gitIn(t, dir, "add", "NOTES.md") + gitIn(t, dir, "commit", "--quiet", "-m", "on top") + if got := notes(); has(got, "showing the checkout") || has(got, "not in this clone") { + t.Errorf("a branch on the base: notes = %q", got) + } +} + +// Commit mode builds on deliver.branch once it exists, and on the base +// until then. +func TestRunCommitBranchNotYet(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n", "tend.yml": "deliver: {mode: commit, branch: release}\n"}) + res := tend(t, dir, t.TempDir(), offline{}, "run") + if res.code != exitOK || !strings.HasPrefix(res.out, "tend: nothing to watch: no manifests") { + t.Errorf("run = %d, %q, %q", res.code, res.out, res.stderr) + } +} + +func TestRunNoCommits(t *testing.T) { + dir := repo(t, nil) + for _, cfg := range []string{"", "base: main\n", "base: trunk\n"} { + writeFiles(t, dir, map[string]string{"tend.yml": cfg}) + res := tend(t, dir, t.TempDir(), offline{}, "run") + if res.code != exitOK || res.out != "tend: nothing to watch: the repository has no commits\n" { + t.Errorf("%q: run = %d, %q, %q", cfg, res.code, res.out, res.stderr) + } + } +} + +// --keep says where the worktree is, which the run would otherwise remove. +func TestRunKeep(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n"}) + home := t.TempDir() + res := tend(t, dir, home, offline{}, "run", "--keep") + wts := worktrees(t, home) + if res.code != exitOK || len(wts) != 1 || !strings.HasSuffix(strings.TrimSpace(res.out), "; the worktree is kept at "+wts[0]) { + t.Errorf("run --keep = %d, %q, worktrees %q", res.code, res.out, wts) + } +} + +// A first PR that only adds tend.yml is no work upstream, so it does not +// trip --fail-on any; one that removes an unused dependency does. +func TestCheckFailOn(t *testing.T) { + tests := []struct { + name string + files map[string]string + failOn string + code int + }{ + {"nothing but tend.yml to add", map[string]string{"go.mod": "module example.com/x\n\ngo 1.26\n"}, "any", exitOK}, + {"an unused dependency", map[string]string{ + "package.json": `{"dependencies": {"left-pad": "^1.0.0"}}`, + "package-lock.json": `{"lockfileVersion": 3, "packages": {"": {}, "node_modules/left-pad": {"version": "1.3.0"}}}`, + "index.js": "module.exports = 1\n", + }, "any", exitFound}, + {"an unused dependency is no security fix", map[string]string{ + "package.json": `{"dependencies": {"left-pad": "^1.0.0"}}`, + "package-lock.json": `{"lockfileVersion": 3, "packages": {"": {}, "node_modules/left-pad": {"version": "1.3.0"}}}`, + "index.js": "module.exports = 1\n", + }, "security", exitOK}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := repo(t, tt.files) + if res := tend(t, dir, t.TempDir(), offline{}, "check", "--fail-on", tt.failOn); res.code != tt.code { + t.Errorf("check --fail-on %s = %d, want %d: %q, %q", tt.failOn, res.code, tt.code, res.out, res.stderr) + } + }) + } +} + +func TestFails(t *testing.T) { + first := core.Change{Kind: core.First, Batch: &core.Batch{}} + removes := core.Change{Kind: core.First, Batch: &core.Batch{Unused: []core.Dep{{Name: "left-pad"}}}} + dep := core.Change{Kind: core.Deprecation} + now := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + gone := core.Change{Kind: core.Deprecation, Sunset: time.Date(2021, 2, 1, 0, 0, 0, 0, time.UTC)} + far := core.Change{Kind: core.Deprecation, Sunset: now.AddDate(1, 0, 0)} + for _, tt := range []struct { + ch core.Change + kind string + want bool + }{ + {first, "any", false}, + {core.Change{Kind: core.First}, "any", false}, + {removes, "any", true}, + {removes, "security", false}, + {dep, "any", true}, + {dep, "deprecation", true}, + {dep, "security", false}, + {dep, "breaking", false}, + {gone, "breaking", true}, + {gone, "deprecation", true}, + {far, "breaking", false}, + } { + if got := fails(tt.ch, tt.kind, now); got != tt.want { + t.Errorf("fails(%s, %d unused, %s) = %v", tt.ch.Kind, unused(tt.ch), tt.kind, got) + } + } +} + +func unused(ch core.Change) int { + if ch.Batch == nil { + return 0 + } + return len(ch.Batch.Unused) +} + +// check reads the checkout, so what it finds of the catch-up settles +// nothing: a stage it finds nothing for is not the end of it. +func TestCheckKeepsStage(t *testing.T) { + dir := repo(t, map[string]string{"go.mod": "module example.com/x\n\ngo 1.26\n"}) + home := t.TempDir() + key := state.Key("", dir) + st, _, err := state.Open(home, key) + if err != nil { + t.Fatal(err) + } + st.Onboard, st.Stage = "merged", plan.Fixes + if err := st.Save(); err != nil { + t.Fatal(err) + } + res := tend(t, dir, home, offline{}, "check") + if res.code != exitOK || strings.Contains(res.stderr, "catch-up") { + t.Errorf("check = %d, %q, %q", res.code, res.out, res.stderr) + } + if st, _, err = state.Open(home, key); err != nil { + t.Fatal(err) + } + if st.Onboard != "merged" || st.Stage != plan.Fixes { + t.Errorf("check left onboard %q, stage %d; want merged, %d", st.Onboard, st.Stage, plan.Fixes) + } +} + +// What run could not prove says why in --json too, and where the worktree +// is when it is kept. +func TestReportUnproven(t *testing.T) { + var out, errs bytes.Buffer + s := &session{e: Env{Stdout: &out, Stderr: &errs, Now: time.Now}, st: state.New(), o: opts{json: true, keep: true}} + r := &runner{s: s, wt: &verify.Worktree{Dir: "/wt/abc", Base: "abc"}} + detail := "npm test failed (exit 1)\nexpected 1 to equal 2" + if code := s.report(r.unproven(&core.Change{ID: "npm/a@2.0.0", Kind: core.Update}, detail)); code != exitUnproven { + t.Errorf("code = %d", code) + } + var got struct{ Action, Summary, Detail, Worktree string } + if err := json.Unmarshal(out.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Action != "unproven" || got.Summary != "could not prove npm/a@2.0.0: npm test failed (exit 1)" || got.Detail != detail || got.Worktree != "/wt/abc" { + t.Errorf("json = %+v", got) + } + out.Reset() + s.o.json = false + s.report(r.unproven(&core.Change{ID: "npm/a@2.0.0", Kind: core.Update}, detail)) + if want := "tend: could not prove npm/a@2.0.0: npm test failed (exit 1); the worktree is kept at /wt/abc\n"; out.String() != want { + t.Errorf("line = %q, want %q", out.String(), want) + } +} + +// The release notice comes with the check for a release, once a day, not +// on every run while a newer tag is known. +func TestNotice(t *testing.T) { + now := time.Now() + latest := offline{"/releases/latest": `{"tag_name": "v9.0.0", "html_url": "https://example.com"}`} + var errs bytes.Buffer + s := &session{e: Env{Stderr: &errs, Now: func() time.Time { return now }, Version: "1.0.0"}, st: state.New(), fetch: latest} + s.notice(context.Background()) + if errs.String() != "tend: v9.0.0 is available; run tend update\n" { + t.Errorf("first notice = %q", errs.String()) + } + errs.Reset() + now = now.Add(time.Hour) + s.notice(context.Background()) + if errs.Len() > 0 { + t.Errorf("noticed again within the day: %q", errs.String()) + } + now = now.Add(24 * time.Hour) + s.notice(context.Background()) + if errs.Len() == 0 { + t.Error("no notice a day later") + } +} + +// -C names a directory that must exist; tend never makes one for it. +func TestMainDir(t *testing.T) { + dir := t.TempDir() + res := tend(t, dir, t.TempDir(), offline{}, "-C", "missing", "init") + if res.code != exitUsage || !strings.Contains(res.stderr, "-C missing: no such directory") { + t.Errorf("init in a missing dir = %d, %q", res.code, res.stderr) + } + if _, err := os.Stat(filepath.Join(dir, "missing")); !os.IsNotExist(err) { + t.Errorf("init made the missing dir: %v", err) + } + writeFiles(t, dir, map[string]string{"file": "x"}) + if res := tend(t, dir, t.TempDir(), offline{}, "-C", "file", "check"); res.code != exitUsage || !strings.Contains(res.stderr, "-C file: not a directory") { + t.Errorf("-C on a file = %d, %q", res.code, res.stderr) + } + writeFiles(t, dir, map[string]string{"sub/README.md": "hi\n"}) + if res := tend(t, dir, t.TempDir(), offline{}, "--C", "sub", "check"); res.code != exitOK || !strings.Contains(res.out, "nothing to watch") { + t.Errorf("--C sub check = %d, %q, %q", res.code, res.out, res.stderr) + } +} + +// A relative home, from --home or TEND_HOME, is one place under the dir tend +// runs as if in, for the state and for the worktrees git makes alike. +func TestRelativeHome(t *testing.T) { + for _, flag := range []bool{true, false} { + dir := repo(t, map[string]string{"sub/README.md": "hi\n"}) + args := []string{"-C", "sub", "run", "--keep"} + home := "rel" + if flag { + args, home = append([]string{"--home", "rel"}, args...), filepath.Join(t.TempDir(), "unused") + } + res := tend(t, dir, home, offline{}, args...) + if res.code != exitOK { + t.Fatalf("exit %d: %s", res.code, res.stderr) + } + want := filepath.Join(dir, "sub", "rel") + if _, err := os.Stat(filepath.Join(want, "repos")); err != nil { + t.Errorf("no state under %s: %v", want, err) + } + list := gitIn(t, dir, "worktree", "list", "--porcelain") + for _, line := range strings.Split(list, "\n") { + if p, ok := strings.CutPrefix(line, "worktree "); ok && p != dir && !strings.HasPrefix(p, want+string(filepath.Separator)) { + t.Errorf("a worktree outside %s: %s", want, p) + } + } + if !strings.Contains(list, want) { + t.Errorf("no worktree under %s:\n%s", want, list) + } + } +} + +// --config is read as if tend started in -C's dir, as git -C does. +func TestConfigUnderDir(t *testing.T) { + dir := t.TempDir() + r2 := repo(t, map[string]string{"tend.yml": "bogus: 1\n"}) + if err := os.Rename(r2, filepath.Join(dir, "r2")); err != nil { + t.Fatal(err) + } + res := tend(t, dir, t.TempDir(), offline{}, "-C", "r2", "--config", "tend.yml", "check") + if res.code != exitErr || !strings.Contains(res.stderr, "unknown key") { + t.Errorf("exit %d: %s", res.code, res.stderr) + } +} + +// A repo with nothing to watch owes no first PR, in check's text, its JSON +// and its exit code alike. +func TestCheckNothing(t *testing.T) { + for _, files := range []map[string]string{nil, {"README.md": "hi\n"}} { + dir := repo(t, files) + if r := tend(t, dir, t.TempDir(), offline{}, "check", "--fail-on", "any"); r.code != exitOK || !strings.Contains(r.out, "nothing to watch") { + t.Errorf("check --fail-on any = %d, %q, %q", r.code, r.out, r.stderr) + } + r := tend(t, dir, t.TempDir(), offline{}, "check", "--json") + var got struct{ Queue []any } + if err := json.Unmarshal([]byte(r.out), &got); err != nil || len(got.Queue) != 0 { + t.Errorf("check --json = %v, %s", err, r.out) + } + } + dir := repo(t, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`, "tend.yml": "ecosystems: [docker]\n"}) + if r := tend(t, dir, t.TempDir(), offline{}, "check"); !strings.Contains(r.out, "tend.yml's ecosystems lists only docker") { + t.Errorf("check with ecosystems: [docker] = %q, %q", r.out, r.stderr) + } +} diff --git a/internal/cli/onboard.go b/internal/cli/onboard.go index 1dadbef..8a5ceae 100644 --- a/internal/cli/onboard.go +++ b/internal/cli/onboard.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "slices" "strconv" "strings" @@ -15,6 +16,7 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/deliver" "github.com/mohsensc/tend-cli/internal/gitx" + "github.com/mohsensc/tend-cli/internal/model" "github.com/mohsensc/tend-cli/internal/patch" "github.com/mohsensc/tend-cli/internal/plan" "github.com/mohsensc/tend-cli/internal/state" @@ -60,7 +62,6 @@ func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.P } commit := s.cfg.Deliver.Mode == "commit" if commit && st.Open != nil && st.Open.PR != 0 { - // The first PR was opened before tend.yml asked for commits. st.Onboard = "commit" return nil, nil } @@ -128,7 +129,7 @@ func (s *session) onboarding(ctx context.Context, inv *core.Inventory, p *plan.P // staged is the catch-up PR for the next stage once the first PR has // merged, nil when there is none: the catch-up is over, or tend had begun -// here before it had stages. A run that finds no stage left ends it. +// here before it had stages. Finding no stage left ends it; run says so. func (s *session) staged(p *plan.Plan) *core.Change { st := s.st if st.Stage == 0 || st.Stage >= plan.Last { @@ -137,7 +138,6 @@ func (s *session) staged(p *plan.Plan) *core.Change { ch := plan.Next(p, st.Stage) if ch == nil { st.Stage = plan.Last - s.logf("the catch-up is done; from here on tend works one change at a time") } return ch } @@ -252,6 +252,15 @@ func (r *runner) batch(ctx context.Context, ch *core.Change, preempt *core.PR) ( if !nothing { proof.Base = r.baseline(ctx, cmds) } + if proof.Base != nil && missing(proof.Base) { + st := proof.Base.Last() + detail := fmt.Sprintf("`%s` cannot run on the base (exit %d), so nothing can be proven here; install what it needs and run again", st.Cmd, st.Exit) + if l := lastLine(st.Tail); l != "" { + detail += "\n" + l + } + first, _, _ := strings.Cut(detail, "\n") + return &outcome{Action: "unproven", Change: ch, Worktree: wt.Dir, Summary: "could not prove " + ch.ID + ": " + first, Detail: detail, code: exitUnproven}, nil + } runs := max(proofMax, 2*(len(ch.Batch.Changes)+len(ch.Batch.Unused))) t := &trial{r: r, cmds: cmds, proof: proof, runs: map[string]*core.Run{}, left: runs, budget: runs} t.check = t.try @@ -265,6 +274,7 @@ func (r *runner) batch(ctx context.Context, ch *core.Change, preempt *core.PR) ( if x != nil { fixed, b.Baseline, r.floor = []*part{x}, x.base, x.code } + b.Thin = t.thin } nothing, r.cmds = proof.Nothing, t.cmds next := plan.After(ch.Batch) @@ -276,10 +286,14 @@ func (r *runner) batch(ctx context.Context, ch *core.Change, preempt *core.PR) ( // tracking issue, and comes back one change at a time. leave := func(c core.Change, why string) { s.logf("left %s out of %s: %s", name(&part{ch: &c}), where, why) - if next == 0 && c.Kind != core.Security { + at := next + if strings.HasPrefix(why, "No model is configured") { + at = ch.Batch.Stage + } + if at <= ch.Batch.Stage && c.Kind != core.Security { s.st.Fail(c.ID, why, wt.Base, s.e.Now()) } - b.Next = append(b.Next, core.Later{Change: c, Why: why, Stage: next}) + b.Next = append(b.Next, core.Later{Change: c, Why: why, Stage: at}) } var parts []*part for i := range ch.Batch.Changes { @@ -334,10 +348,18 @@ func (r *runner) batch(ctx context.Context, ch *core.Change, preempt *core.PR) ( return nil, err } if len(pt.Files) == 0 { - if ch.ID == core.FirstID { + settled := nothing || proof.Base != nil && proof.Base.Pass + if ch.ID == core.FirstID && settled { s.st.Onboard = "clean" } - return &outcome{Action: "nothing", line: "nothing to catch up on: no change or removal passed its proof, and tend.yml is there already"}, nil + why := "nothing to catch up on: no change or removal passed its proof" + switch { + case !settled: + why += ", and the base does not pass, so tend tries again on the next run" + case s.configured(wt.Dir): + why += ", and tend.yml is there already" + } + return &outcome{Action: "nothing", Summary: why}, nil } vt, err := r.vet(ctx, &out, pt, proof) if err != nil { @@ -394,13 +416,53 @@ func (r *runner) once(ctx context.Context, ch *core.Change, t *trial) (*part, st why = cmp.Or(stop, why) } c, pt, err := r.decide(ctx, ch, t.cmds, t.proof, &t.left) - if err != nil || c == nil { + if err != nil { return nil, why, err } + if c == nil { + if u := untestable(t.proof); u != "" { + return nil, cmp.Or(why, u), nil + } + if x != nil || len(ch.Steps) > 0 || !strings.HasPrefix(why, "No model is configured") { + return nil, why, nil + } + y, plain, err := r.plain(ctx, ch, t) + return y, cmp.Or(plain, why), err + } y, err := r.piece(ctx, c, pt, t) return y, "", err } +// plain makes ch as a plain bump, its call sites left as written, and keeps +// it when its proof passes on its own: what a catch-up does with a major +// bump that no model can move the code for, as a climb does with each of +// its steps. why names the step that failed when it does not pass. +func (r *runner) plain(ctx context.Context, ch *core.Change, t *trial) (*part, string, error) { + if r.model != nil || t.proof.Nothing || t.left <= 0 || ch.To == "" || ch.API != nil || ch.ToName != "" { + return nil, "", nil + } + if err := r.restart(ctx); err != nil { + return nil, "", err + } + proof := *t.proof + r.s.logf("trying %s as a plain bump, its call sites as written", name(&part{ch: ch})) + pt, err := r.attempt(ctx, ch, t.cmds, &proof) + switch { + case err != nil && ctx.Err() != nil: + return nil, "", ctx.Err() + case err != nil: + return nil, whyFailed(err), r.restart(ctx) + case pt.Decision || len(pt.Files) == 0: + return nil, "", r.restart(ctx) + } + t.left-- + if !plan.Proven(&proof) { + return nil, "on its own, " + broke(proof.Patched), r.restart(ctx) + } + y, err := r.piece(ctx, ch, pt, t) + return y, "", err +} + // made makes ch once, as once says, without proving it. func (r *runner) made(ctx context.Context, ch *core.Change, t *trial) (*part, string, error) { if err := r.restart(ctx); err != nil { @@ -408,6 +470,9 @@ func (r *runner) made(ctx context.Context, ch *core.Change, t *trial) (*part, st } o := r.options(ch, t.cmds, t.proof) o.Strict = true + if _, ok := r.model.(model.Agent); !ok { + o.Prove = nil + } bumped := "" o.Bumped = func(ctx context.Context) error { if bumped = r.tree(ctx); bumped == "" { @@ -421,8 +486,7 @@ func (r *runner) made(ctx context.Context, ch *core.Change, t *trial) (*part, st case err != nil && ctx.Err() != nil: return nil, "", ctx.Err() case err != nil: - why, _, _ := strings.Cut(err.Error(), "\n") - return nil, why, nil + return nil, whyFailed(err), nil case pt.Decision: return nil, pt.Note, nil case len(pt.Files) == 0: @@ -480,6 +544,8 @@ type trial struct { left int // proofs it may still run budget int // proofs it could run at the start check func(context.Context, []*part) (*drop, error) // try, or a test's stand-in + built bool // a set was built once, its steps logged + thin string // why the tests cannot prove the catch-up, when no baseline helps } // drop is a part the first PR leaves out: the run that failed with it, why @@ -579,12 +645,15 @@ func (t *trial) settle(ctx context.Context, set []*part) (*drop, error) { // try builds set and proves it. It returns how the set failed, or nil when // it passes. func (t *trial) try(ctx context.Context, set []*part) (*drop, error) { + quiet := t.built if _, x, err := t.build(ctx, set); err != nil { if ctx.Err() != nil { return nil, ctx.Err() } - first, _, _ := strings.Cut(err.Error(), "\n") - return &drop{x: x, build: first}, nil + return &drop{x: x, build: whyFailed(err)}, nil + } + if quiet { + t.r.s.logf("proving %d parts together", len(set)) } run, err := t.r.prove(ctx, t.cmds, "patched") if err != nil { @@ -608,11 +677,10 @@ func (t *trial) build(ctx context.Context, set []*part) (pt *core.Patch, x *part return nil, nil, err } o := r.options(nil, t.cmds, t.proof) - if t.runs[key(set)] != nil { - // A set already proven is built again only to stage it; its steps - // were logged the first time. + if t.built { o.Log = nil } + t.built = true p := &core.Patch{} var gone []*part var notes []string @@ -677,18 +745,21 @@ func (t *trial) final(ctx context.Context, set []*part, starter bool) (*core.Pat if err != nil { return nil, err } - if len(set) == 0 && starter { + for i := 0; i < 2; i++ { + if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil { + return nil, err + } + if pt.Diff, pt.Files, err = patch.Diff(ctx, wt.Dir, wt.Base); err != nil { + return nil, err + } + if len(pt.Files) > 0 || !starter || i > 0 { + break + } if err := os.WriteFile(filepath.Join(wt.Dir, "tend.yml"), config.Starter, 0o644); err != nil { return nil, err } pt.Applied = append(pt.Applied, "added tend.yml with every key commented out (tend.yml)") } - if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil { - return nil, err - } - if pt.Diff, pt.Files, err = patch.Diff(ctx, wt.Dir, wt.Base); err != nil { - return nil, err - } slices.Sort(pt.Edited) pt.Edited = slices.Compact(pt.Edited) if t.proof.Nothing || len(pt.Files) == 0 { @@ -715,7 +786,41 @@ func name(x *part) string { return x.ch.Deps[0].Name } +// telling picks the line of a tool's output that says why it failed. +var telling = regexp.MustCompile(`(?i)error|not found|failed|cannot|could not|unable|conflict`) + +// whyFailed is the first line of err, the command and how it exited, and the +// line of the tool's output after it that best says why. +func whyFailed(err error) string { + first, rest, _ := strings.Cut(err.Error(), "\n") + lines := strings.Split(rest, "\n") + pick := "" + for i := len(lines) - 1; i >= 0; i-- { + l := strings.TrimSpace(lines[i]) + if l == "" { + continue + } + if pick == "" { + pick = l + } + if telling.MatchString(l) { + pick = l + break + } + } + if pick == "" || strings.Contains(first, pick) { + return first + } + return first + ": " + core.Clip(pick, 200) +} + // broke says how a run failed, in a few words: "`npm test` fails (exit 1)". +// lastLine is the last line of s with text on it. +func lastLine(s string) string { + lines := strings.Split(strings.TrimSpace(s), "\n") + return strings.TrimSpace(lines[len(lines)-1]) +} + func broke(run *core.Run) string { st := run.Last() switch { diff --git a/internal/cli/onboard_test.go b/internal/cli/onboard_test.go index ac46a7a..e4fd7a9 100644 --- a/internal/cli/onboard_test.go +++ b/internal/cli/onboard_test.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "context" + "errors" "fmt" "os" "path/filepath" @@ -381,3 +382,35 @@ func TestUnwanted(t *testing.T) { }) } } + +func TestWhyFailed(t *testing.T) { + tests := []struct{ err, want string }{ + {"poetry update --lock certifi: exit status 1\nUpdating dependencies\nResolving dependencies...\n\nPackage codecov (2.1.8) not found.\n", "poetry update --lock certifi: exit status 1: Package codecov (2.1.8) not found."}, + {"npm install: exit status 1\nsomething odd\nlast words\n", "npm install: exit status 1: last words"}, + {"plain failure", "plain failure"}, + } + for _, tt := range tests { + if got := whyFailed(errors.New(tt.err)); got != tt.want { + t.Errorf("whyFailed(%q) = %q, want %q", tt.err, got, tt.want) + } + } +} + +func TestClimbGuards(t *testing.T) { + sec := &core.Change{Kind: core.Security, To: "10.1.4"} + if !shortOfFix(sec, []string{"8.0.7", "9.1.1"}) || shortOfFix(sec, []string{"9.1.1", "10.1.4"}) || shortOfFix(sec, nil) { + t.Error("shortOfFix") + } + if shortOfFix(&core.Change{Kind: core.Breaking, To: "10.1.4"}, []string{"9.1.1"}) { + t.Error("a plain major climb that stops short is short of nothing") + } + install := core.Step{Cmd: "yarn install --frozen-lockfile", Phase: core.PhaseInstall, Exit: 127} + dead := &core.Proof{Base: &core.Run{Steps: []core.Step{install, {Cmd: "yarn test", Phase: core.PhaseTest, Skipped: "previous step failed"}}}} + if got := untestable(dead); got != "the base fails at `yarn install --frozen-lockfile` before its tests run, so no step can be proven" { + t.Errorf("untestable = %q", got) + } + red := &core.Proof{Base: &core.Run{Steps: []core.Step{{Cmd: "yarn install", Phase: core.PhaseInstall}, {Cmd: "yarn test", Phase: core.PhaseTest, Exit: 1}}}} + if got := untestable(red); got != "" { + t.Errorf("a base whose tests fail can still prove a step: %q", got) + } +} diff --git a/internal/cli/output.go b/internal/cli/output.go index 83b52b2..8e88faf 100644 --- a/internal/cli/output.go +++ b/internal/cli/output.go @@ -12,26 +12,41 @@ import ( "unicode" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/deliver" "github.com/mohsensc/tend-cli/internal/plan" ) +// nothing is what a repo with nothing tend follows gets told, and what +// tend.yml left out of the search. +func (s *session) nothing() string { + msg := "nothing to watch: no manifests or API calls found in " + s.root + if s.cfg != nil && len(s.cfg.Ecosystems) > 0 { + msg += "; tend.yml's ecosystems lists only " + strings.Join(s.cfg.Ecosystems, ", ") + } + return msg +} + func writeCheck(w io.Writer, s *session, p *plan.Plan, empty bool) error { if empty { - _, err := fmt.Fprintf(w, "tend: nothing to watch: no manifests or API calls found in %s\n", s.root) + _, err := fmt.Fprintf(w, "tend: %s\n", s.nothing()) return err } var b bytes.Buffer - fmt.Fprintf(&b, "tend: %d queued, %d skipped, %s\n", len(p.Queue), len(p.Dropped), openSummary(p.Open, s.forge != nil)) + fmt.Fprintf(&b, "tend: %d queued, %d skipped, %s\n", len(p.Queue), len(p.Dropped), openSummary(p.Open, s.openWhy)) if s.o.quiet { _, err := w.Write(b.Bytes()) return err } openID := plan.OpenID(p.Open, s.st) + var now time.Time + if s.e.Now != nil { + now = s.e.Now() + } if len(p.Queue) > 0 { b.WriteString("\n") tw := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0) for i, ch := range p.Queue { - fmt.Fprintf(tw, " %d\t%s\t%s\t%s\t%s\n", i+1, ch.Kind, subject(&ch), target(&ch), detail(&ch, openID, p.Open)) + fmt.Fprintf(tw, " %d\t%s\t%s\t%s\t%s\n", i+1, ch.Kind, subject(&ch), target(&ch), detail(&ch, openID, p.Open, now)) } tw.Flush() } @@ -132,11 +147,13 @@ func trimLines(b []byte) []byte { // maxNotes keeps a long list of notes from burying the queue. const maxNotes = 10 -func openSummary(pr *core.PR, known bool) string { - if !known { - return "open PRs unknown" - } - if pr == nil { +// openSummary is the header's word on open PRs: unknown, and why, when +// unknown says why they could not be listed. +func openSummary(pr *core.PR, unknown string) string { + switch { + case unknown != "": + return "open PRs unknown (" + unknown + ")" + case pr == nil: return "no open PR" } return fmt.Sprintf("1 open PR (#%d)", pr.Number) @@ -170,8 +187,11 @@ func subject(ch *core.Change) string { if ch.Kind == core.First && ch.ID != core.FirstID { return plan.StageName(ch.Batch.Stage) } + if ch.Kind == core.First && ch.Batch != nil && len(deliver.Tally(ch.Batch)) == 0 { + return "set up tend" + } if ch.Kind == core.First { - return "first PR" + return "catch-up" } if ch.API != nil { return ch.API.Provider + " API" @@ -186,7 +206,13 @@ func subject(ch *core.Change) string { } d := ch.Deps[0] if d.Ecosystem == core.Docker || d.Min { - return strings.TrimPrefix(d.Name, "library/") + " (" + d.Manifest.Path + ")" + var files []string + for _, x := range ch.Deps { + if !slices.Contains(files, x.Manifest.Path) { + files = append(files, x.Manifest.Path) + } + } + return d.Display() + " (" + strings.Join(files, ", ") + ")" } return d.Name } @@ -210,7 +236,7 @@ func target(ch *core.Change) string { return from + " → " + ch.To } -func detail(ch *core.Change, openID string, open *core.PR) string { +func detail(ch *core.Change, openID string, open *core.PR, now time.Time) string { var parts []string if b := ch.Batch; b != nil { parts = append(parts, carries(b)) @@ -220,24 +246,26 @@ func detail(ch *core.Change, openID string, open *core.PR) string { return strings.Join(parts, " · ") } if ch.Kind == core.Security { - parts = append(parts, strings.TrimSpace(advisory(ch)+" "+ch.Severity)) + parts = append(parts, advisory(ch)) } if a := ch.API; a != nil { parts = append(parts, apiWhat(a)) } if !ch.Sunset.IsZero() { + eol := slices.ContainsFunc(ch.Evidence, func(ev core.Evidence) bool { return ev.Source == "eol" }) label := "sunset" - if slices.ContainsFunc(ch.Evidence, func(ev core.Evidence) bool { return ev.Source == "eol" }) { + switch { + case eol && ch.Sunset.Before(now): + label = "EOL since" + case eol: label = "EOL" + case ch.Sunset.Before(now): + label = "sunset passed" } parts = append(parts, label+" "+ch.Sunset.UTC().Format(time.DateOnly)) } if ch.To == "" && ch.API == nil { - if n := len(ch.Options); n > 0 { - parts = append(parts, fmt.Sprintf("%d options", n)) - } else { - parts = append(parts, "no known replacement") - } + parts = append(parts, ways(ch)) } parts = append(parts, sites(ch)) if open != nil && ch.ID == openID { @@ -246,36 +274,16 @@ func detail(ch *core.Change, openID string, open *core.PR) string { return strings.Join(slices.DeleteFunc(parts, func(s string) bool { return s == "" }), " · ") } -// carries sums up a catch-up PR: "fix 2 security · 1 API · move off 1 -// deprecated · remove 3 unused · 4 in later stages · 2 to look at", or that -// it only sets tend up. +// carries sums up a catch-up PR the way its title does, "2 end-of-life +// runtimes · 1 deprecated Action · 3 unused dependencies", then what waits +// for later PRs and what it keeps, or that it only sets tend up. func carries(b *core.Batch) string { - var sec, api, dep int - for _, ch := range b.Changes { - switch { - case ch.API != nil: - api++ - case ch.Kind == core.Security: - sec++ - default: - dep++ - } + parts := deliver.Tally(b) + if n := len(b.Next); n > 0 { + parts = append(parts, fmt.Sprintf("%d more in later PRs", n)) } - var parts []string - for _, x := range []struct { - n int - text string - }{ - {sec, "fix %d security"}, - {api, "%d API"}, - {dep, "move off %d deprecated"}, - {len(b.Unused), "remove %d unused"}, - {len(b.Next), "%d in later stages"}, - {len(b.Kept), "%d to look at"}, - } { - if x.n > 0 { - parts = append(parts, fmt.Sprintf(x.text, x.n)) - } + if n := len(b.Kept); n > 0 { + parts = append(parts, fmt.Sprintf("%d possibly unused, kept", n)) } if len(parts) == 0 { return "nothing to catch up on; adds tend.yml" @@ -283,30 +291,62 @@ func carries(b *core.Batch) string { return strings.Join(parts, " · ") } -// advisory is the first advisory id the evidence cites. -func advisory(ch *core.Change) string { - for _, ev := range ch.Evidence { - if ev.Source != "osv" { - continue +// ways says what a deprecation without a target can move to: the options +// that move it, not the one that stays. +func ways(ch *core.Change) string { + var moves []core.Option + for _, o := range ch.Options { + if !o.Stay { + moves = append(moves, o) } - if f := strings.Fields(ev.Title); len(f) > 0 { - return f[0] + } + switch len(moves) { + case 0: + for _, ev := range ch.Evidence { + if ev.Source == "registry" && strings.TrimSpace(ev.Text) != "" { + return "deprecated: " + core.Clip(strings.Join(strings.Fields(ev.Text), " "), 80) + } + } + return "no known replacement" + case 1: + if to := strings.TrimSpace(moves[0].ToName + " " + moves[0].To); to != "" { + return "1 option: → " + to } + return "1 option: " + moves[0].Title } - return "" + return fmt.Sprintf("%d options", len(moves)) } -// apiWhat turns "response field removed" and a field into "field total_cents removed". +// advisory is the first advisory the evidence cites and its severity, and +// how many more there are, as the PR's title counts them. +func advisory(ch *core.Change) string { + ids := deliver.Advisories(ch) + if len(ids) == 0 { + return ch.Severity + } + res := strings.TrimSpace(ids[0] + " " + ch.Severity) + if n := len(ids) - 1; n > 0 { + res += fmt.Sprintf(" +%d more", n) + } + return res +} + +// apiWhat turns "response field removed" and a field into "field +// total_cents removed", and a type change into "field total_cents changed +// type". func apiWhat(a *core.APIChange) string { words := strings.Fields(a.What) if a.Field == "" || len(words) < 2 { return a.What } + if strings.HasSuffix(a.What, "type changed") { + return "field " + a.Field + " changed type" + } return words[len(words)-2] + " " + a.Field + " " + words[len(words)-1] } func sites(ch *core.Change) string { - n := len(ch.Sites) + n := core.Lines(ch.Sites) switch { case n == 1 && ch.Sites[0].Chain == nil && len(ch.Deps) > 0: return fmt.Sprintf("%s:%d", ch.Sites[0].File, ch.Sites[0].Line) diff --git a/internal/cli/output_test.go b/internal/cli/output_test.go index 8d45548..86072e1 100644 --- a/internal/cli/output_test.go +++ b/internal/cli/output_test.go @@ -44,18 +44,55 @@ func TestFirstLine(t *testing.T) { want string }{ {core.Batch{Unused: []core.Dep{d, d, d}, Changes: []core.Change{{Kind: core.Security}, {Kind: core.Security}, {Kind: core.Deprecation, API: api}, {Kind: core.Deprecation}}, Kept: []core.Aside{{}}}, - nil, "fix 2 security · 1 API · move off 1 deprecated · remove 3 unused · 1 to look at"}, - {core.Batch{Next: []core.Later{{}, {}}}, open, "2 in later stages · open PR #1"}, - {core.Batch{}, nil, "nothing to catch up on; adds tend.yml"}, + nil, "catch-up||2 security fixes · 1 API change · 1 deprecation · 3 unused dependencies · 1 possibly unused, kept"}, + {core.Batch{Next: []core.Later{{}, {}}}, open, "set up tend||2 more in later PRs · open PR #1"}, + {core.Batch{}, nil, "set up tend||nothing to catch up on; adds tend.yml"}, } for _, tt := range tests { ch := core.Change{ID: core.FirstID, Kind: core.First, Deps: []core.Dep{d}, Batch: &tt.b} - if got := subject(&ch) + "|" + target(&ch) + "|" + detail(&ch, plan.OpenID(tt.open, nil), tt.open); got != "first PR||"+tt.want { + if got := subject(&ch) + "|" + target(&ch) + "|" + detail(&ch, plan.OpenID(tt.open, nil), tt.open, time.Time{}); got != tt.want { t.Errorf("line = %q, want %q", got, tt.want) } } } +func TestAPIWhat(t *testing.T) { + for what, want := range map[string]string{ + "response field removed": "field total_cents removed", + "response field type changed": "field total_cents changed type", + } { + if got := apiWhat(&core.APIChange{Field: "total_cents", What: what}); got != want { + t.Errorf("apiWhat(%q) = %q, want %q", what, got, want) + } + } +} + +func TestDetailWords(t *testing.T) { + stay := core.Option{Title: "Pin to 1.1.0 and ignore", Stay: true} + sec := func(n int) *core.Change { + ch := &core.Change{Kind: core.Security, Severity: "high", To: "4.18.1"} + for i := range n { + ch.Evidence = append(ch.Evidence, core.Evidence{Source: "osv", Title: fmt.Sprintf("GHSA-%d title", i)}) + } + return ch + } + tests := []struct { + ch *core.Change + want string + }{ + {&core.Change{Kind: core.Deprecation, Options: []core.Option{stay}}, "no known replacement"}, + {&core.Change{Kind: core.Deprecation, Options: []core.Option{{Title: "Move", ToName: "undici", To: "6.0.0"}, stay}}, "1 option: → undici 6.0.0"}, + {&core.Change{Kind: core.Deprecation, Options: []core.Option{{Title: "A"}, {Title: "B"}, stay}}, "2 options"}, + {sec(1), "GHSA-0 high"}, + {sec(6), "GHSA-0 high +5 more"}, + } + for _, tt := range tests { + if got := detail(tt.ch, "", nil, time.Time{}); got != tt.want { + t.Errorf("detail = %q, want %q", got, tt.want) + } + } +} + // target shows the version a dep is at the way the planner reads it: a // requirement without a lockfile shows its lowest version, not its range. func TestTargetReadsVersionsLikeThePlanner(t *testing.T) { @@ -200,7 +237,7 @@ func TestLoop(t *testing.T) { waits = append(waits, d) return ctx.Err() == nil } - loop(ctx, time.Hour, func(d time.Duration) time.Duration { return d / 10 }, wait, func(rc context.Context) { + loop(ctx, context.WithoutCancel(ctx), time.Hour, func(d time.Duration) time.Duration { return d / 10 }, wait, func(rc context.Context) { if runs.Add(1) == 3 { cancel() if rc.Err() != nil { @@ -217,3 +254,23 @@ func TestLoop(t *testing.T) { } } } + +func TestSitesByLine(t *testing.T) { + ch := &core.Change{Sites: []core.Site{ + {File: "src/bin/hexyl.rs", Line: 143, Col: 25, Chain: []string{"atty", "is"}}, + {File: "src/bin/hexyl.rs", Line: 143, Col: 34, Chain: []string{"Stream", "Stdout"}}, + }} + if got := sites(ch); got != "1 site" { + t.Errorf("sites = %q", got) + } +} + +func TestWaysUsesTheNotice(t *testing.T) { + ch := &core.Change{Kind: core.Deprecation, Evidence: []core.Evidence{{Source: "registry", Title: "left-pad 1.3.0 is deprecated", Text: "use String.prototype.padStart()"}}} + if got := ways(ch); got != "deprecated: use String.prototype.padStart()" { + t.Errorf("ways = %q", got) + } + if got := ways(&core.Change{}); got != "no known replacement" { + t.Errorf("ways = %q", got) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index 8c0a327..d7e2cdc 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -41,13 +41,16 @@ type outcome struct { Proof *core.Proof `json:"proof"` Vetting *core.Vetting `json:"vetting"` Notes []string `json:"notes"` + Summary string `json:"summary"` + Detail string `json:"detail,omitempty"` + + code int + parked bool // unproven, and the change waits in the tracking issue to be tried again - line string - code int } func run(ctx context.Context, e Env, o opts) int { - s, err := open(ctx, e, o) + s, err := open(ctx, e, o, false) if err != nil { return fail(e, err) } @@ -69,16 +72,44 @@ func (s *session) report(res *outcome) int { if !s.o.quiet && res.Body != "" && (res.Action == "dry-run" || res.Action == "branch") { fmt.Fprintf(s.e.Stdout, "%s\n\n%s\n", res.Title, strings.TrimRight(res.Body, "\n")) } - fmt.Fprintf(s.e.Stdout, "tend: %s\n", res.line) + line := res.Summary + if s.o.keep && res.Worktree != "" && res.Action != "dry-run" { + line += "; the worktree is kept at " + res.Worktree + } + fmt.Fprintf(s.e.Stdout, "tend: %s\n", line) + if s.listed(res) { + where := "the tracking issue" + if n := s.st.Issue.Number; n != 0 { + where = fmt.Sprintf("#%d", n) + } + fmt.Fprintf(s.e.Stdout, "::warning title=tend::%s; listed in %s\n", res.Summary, where) + return exitOK + } return res.code } +// listed says whether an unproven outcome is already in hand: the change +// waits in the tracking issue for its next try, and the run is a scheduled +// Action, where a failed job each time the base moves says nothing the +// issue does not, and buries the failures that do need someone. +// TEND_FAIL_ON_UNPROVEN=true keeps the failure. +func (s *session) listed(res *outcome) bool { + _, tracked := s.forge.(core.Tracker) + return res.parked && tracked && !s.o.dryRun && s.e.Getenv("GITHUB_ACTIONS") == "true" && s.e.Getenv("TEND_FAIL_ON_UNPROVEN") != "true" +} + // pass is one run: plan, pick, patch, prove, vet, deliver. func (s *session) pass(ctx context.Context) (*outcome, error) { if !s.git { return nil, fmt.Errorf("%s is not a git repository", s.root) } s.notice(ctx) + if err := s.reach(ctx); err != nil { + return nil, fmt.Errorf("forge: %w", err) + } + if s.noRepo && s.cfg.Deliver.Mode == "pr" && !s.o.dryRun { + return nil, errors.New(s.why) + } if s.forge == nil && s.cfg.Deliver.Mode == "pr" && !s.o.dryRun { s.logf("%s, so this run ends at a local branch", s.why) } @@ -99,32 +130,54 @@ func (s *session) pass(ctx context.Context) (*outcome, error) { if err != nil { return nil, fmt.Errorf("forge: %w", err) } - rev := s.baseRev(ctx, baseRef, true) + rev, err := s.baseRev(ctx, baseRef, true) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if !hasCommit(ctx, s.root, "HEAD") { + return noCommits(), nil + } + return nil, err + } // Commit mode builds on the branch it pushes to, so what lands is a - // fast-forward to the very tree that was proven. + // fast-forward to the very tree that was proven. A branch that does not + // exist yet starts from the base. if c := s.cfg.Deliver; c.Mode == "commit" && c.Branch != "" && c.Branch != baseRef { - if r := s.baseRev(ctx, c.Branch, true); r != "HEAD" { + if r, err := s.baseRev(ctx, c.Branch, true); err == nil { rev = r } } sha, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", rev+"^{commit}") if err != nil { - if _, herr := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", "HEAD"); herr != nil { - return &outcome{Action: "nothing", line: "nothing to watch: the repository has no commits"}, nil + if ctx.Err() != nil { + return nil, ctx.Err() + } + if !hasCommit(ctx, s.root, "HEAD") { + return noCommits(), nil } return nil, err } + if head, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", "HEAD^{commit}"); err == nil && head != sha { + s.logf("working on %s at %s, not the checkout at %s", rev, core.Short(sha), core.Short(head)) + } wt, err := verify.Checkout(ctx, s.root, filepath.Join(s.dir, "wt", dirName(sha)), sha) if err != nil { return nil, fmt.Errorf("cannot create the worktree: %w", err) } - if !s.o.keep && !s.o.dryRun { - defer func() { + for _, dir := range []string{"wt", "baseline"} { + if err := verify.Sweep(ctx, s.root, filepath.Join(s.dir, dir), wt.Dir); err != nil { + s.logf("cannot remove the worktrees earlier runs left: %v", err) + } + } + kept := s.o.keep + defer func() { + if !kept { if err := wt.Remove(context.WithoutCancel(ctx)); err != nil { s.logf("cannot remove the worktree %s: %v", wt.Dir, err) } - }() - } + } + }() r := &runner{s: s, wt: wt, baseRef: baseRef, ecos: ecosFor(s.cfg)} // The base commit's run comes first: what the runtimes say is deprecated @@ -150,16 +203,32 @@ func (s *session) pass(ctx context.Context) (*outcome, error) { } if len(inv.Manifests) == 0 && len(inv.Providers) == 0 && len(p.Untracked) == 0 { s.save() - return &outcome{Action: "nothing", line: "nothing to watch: no manifests or API calls found in " + s.root}, nil + res := &outcome{Action: "nothing", Summary: s.nothing()} + if kept { + res.Worktree = wt.Dir + } + return res, nil } + stage := s.st.Stage if err := s.onboard(ctx, inv, p, wt.Base); err != nil { return nil, err } + if s.st.Stage == plan.Last && stage != plan.Last { + s.logf("the catch-up is done; from here on tend works one change at a time") + } r.inv, r.p = inv, p res, err := r.work(ctx) + if err == nil { + err = ctx.Err() + } if err != nil { return nil, err } + kept = kept || s.o.dryRun && (res.Action == "dry-run" || res.Action == "unproven") + res.Worktree = "" + if kept { + res.Worktree = wt.Dir + } res.Notes = append(res.Notes, p.Notes...) // A dry run does not move the API baseline forward. if !s.o.dryRun { @@ -170,6 +239,10 @@ func (s *session) pass(ctx context.Context) (*outcome, error) { return res, nil } +func noCommits() *outcome { + return &outcome{Action: "nothing", Summary: "nothing to watch: the repository has no commits"} +} + // ecosFor is every ecosystem tend.yml turns on, by name. func ecosFor(cfg *config.Config) map[string]core.Ecosystem { res := map[string]core.Ecosystem{} @@ -277,14 +350,14 @@ func (r *runner) work(ctx context.Context) (*outcome, error) { if n := len(p.Queue); n > 0 { line += fmt.Sprintf("; %d queued behind it", n) } - return &outcome{Action: "waiting", PR: wait, line: line}, nil + return &outcome{Action: "waiting", PR: wait, Summary: line}, nil } if pick == nil { - return &outcome{Action: "nothing", line: "up to date"}, nil + return &outcome{Action: "nothing", Summary: "up to date"}, nil } if p.Open != nil && preempt == nil && deliver.Foreign(r.comments) { line := fmt.Sprintf("waiting on PR #%d (%s), whose branch has commits tend did not push", p.Open.Number, p.Open.Title) - return &outcome{Action: "waiting", PR: p.Open, line: line}, nil + return &outcome{Action: "waiting", PR: p.Open, Summary: line}, nil } if hasCmd && cmd.Verb == "apply" && !r.option(ctx, pick, cmd) { hasCmd = false @@ -293,7 +366,7 @@ func (r *runner) work(ctx context.Context) (*outcome, error) { r.cmdAt = cmd.At } if r.upToDate(pick, preempt, cmd, hasCmd) { - return &outcome{Action: "up-to-date", Change: pick, PR: p.Open, line: fmt.Sprintf("waiting on PR #%d (%s), which is up to date", p.Open.Number, p.Open.Title)}, nil + return &outcome{Action: "up-to-date", Change: pick, PR: p.Open, Summary: fmt.Sprintf("waiting on PR #%d (%s), which is up to date", p.Open.Number, p.Open.Title)}, nil } s.logf("working on %s (%s)", strings.TrimSpace(subject(pick)+" "+target(pick)), pick.Kind) @@ -336,6 +409,9 @@ func (r *runner) declined(ctx context.Context, pick *core.Change, preempt, wait if err != nil { return nil, nil, nil, fmt.Errorf("forge: %w", err) } + if pr != nil && !deliver.Carries(pr, pick) { + pr = nil + } no, err := deliver.Declined(ctx, s.forge, pr) if err != nil { return nil, nil, nil, fmt.Errorf("forge: %w", err) @@ -378,7 +454,7 @@ func (r *runner) upToDate(pick *core.Change, preempt *core.PR, cmd plan.Command, return false } id, base, _, ok := deliver.ParseMarker(open.Body) - if !ok || id != pick.ID || base != r.wt.Base || !holds(s.st.Open, open, pick) { + if !ok || id != pick.ID || base != r.wt.Base || r.baseRef != "" && open.Base != "" && open.Base != r.baseRef || !holds(s.st.Open, open, pick) { return false } return !hasCmd || s.st.Open == nil || !cmd.At.After(s.st.Open.At) @@ -498,10 +574,14 @@ func (r *runner) change(ctx context.Context, ch *core.Change, preempt *core.PR) func (r *runner) options(ch *core.Change, cmds core.Commands, proof *core.Proof) patch.Options { s := r.s o := patch.Options{Ecos: r.ecos, Index: r.inv.Index, Model: r.model, Attempts: s.cfg.Model.Attempts, Option: r.pick, Proven: !proof.Nothing, Log: s.logf} - if _, ok := r.model.(model.Agent); ok && !proof.Nothing { - o.Commands, o.Turns, o.Tokens = cmds, s.cfg.Model.Turns, s.cfg.Model.Tokens + if proof.Nothing { + return o + } + o.Commands = cmds + o.Prove = func(ctx context.Context, c core.Commands) (*core.Run, error) { return r.prove(ctx, c, "patched") } + if _, ok := r.model.(model.Agent); ok { + o.Turns, o.Tokens = s.cfg.Model.Turns, s.cfg.Model.Tokens o.Transcript = filepath.Join(s.dir, "logs", r.slug, "agent.jsonl") - o.Prove = func(ctx context.Context, c core.Commands) (*core.Run, error) { return r.prove(ctx, c, "patched") } scale(&o, shares(ch)) } return o @@ -586,7 +666,7 @@ func (r *runner) prove(ctx context.Context, cmds core.Commands, name string) (*c if s.o.verbose { o.Stream = s.e.Stderr } - s.logf("proving %s: %s", name, strings.Join(slices.Concat(cmds.Install, cmds.Build, cmds.Test), " && ")) + s.logf("proving %s: %s", name, showSteps(slices.Concat(cmds.Install, cmds.Build, cmds.Test))) run, err := verify.Run(ctx, r.wt, o) if err != nil { return nil, err @@ -596,7 +676,8 @@ func (r *runner) prove(ctx context.Context, cmds core.Commands, name string) (*c // discard puts the worktree back to what is staged: whatever the build and // tests wrote (a binary, a regenerated file) is not part of the patch. -// Ignored files such as installed dependencies stay. +// Ignored files stay, and so do installed dependencies such as +// node_modules, which tend's worktrees ignore whatever .gitignore says. func discard(ctx context.Context, wt *verify.Worktree) error { if _, err := gitx.Run(ctx, wt.Dir, "checkout", "--quiet", "--", "."); err != nil { return err @@ -608,7 +689,7 @@ func discard(ctx context.Context, wt *verify.Worktree) error { // baseline runs the commands on the base commit in a worktree of its own, // once per base: a base that already fails is shown next to the patch. A // failing base runs twice before it is kept, so one flaky install does not -// stand for the whole commit. +// stand for the whole commit, unless a command it needs is missing. func (r *runner) baseline(ctx context.Context, cmds core.Commands) *core.Run { s, sha := r.s, r.wt.Base if b := s.st.Baseline; b != nil && b.Sha == sha { @@ -616,7 +697,9 @@ func (r *runner) baseline(ctx context.Context, cmds core.Commands) *core.Run { } bwt, err := verify.Checkout(ctx, s.root, filepath.Join(s.dir, "baseline", dirName(sha)), sha) if err != nil { - s.logf("baseline: %v", err) + if ctx.Err() == nil { + s.logf("baseline: %v", err) + } return nil } defer func() { @@ -626,10 +709,13 @@ func (r *runner) baseline(ctx context.Context, cmds core.Commands) *core.Run { }() br := &runner{s: s, wt: bwt, listen: r.listen} run, err := br.prove(ctx, cmds, "base") - if err == nil && !run.Pass { + if err == nil && !run.Pass && ctx.Err() == nil && !missing(run) { s.logf("the base fails at %s; running it once more", run.Last().Cmd) run, err = br.prove(ctx, cmds, "base") } + if ctx.Err() != nil { + return nil + } if err != nil { s.logf("baseline: %v", err) return nil @@ -639,6 +725,56 @@ func (r *runner) baseline(ctx context.Context, cmds core.Commands) *core.Run { return run } +// runtimeOf is the command that says which version of a runtime the +// project's commands run on, by the ecosystem that needs it. +var runtimeOf = map[string][2]string{ + core.Npm: {"node", "node --version"}, + core.Pip: {"python", "python3 --version"}, + core.Go: {"go", "go env GOVERSION"}, +} + +// runtimes says what the proof ran on, one line per runtime the project's +// manifests need: a pin a change moves is proven only on what was there. +func (r *runner) runtimes(ctx context.Context) []string { + run := r.s.e.Runtime + if run == nil || r.inv == nil { + return nil + } + var res []string + seen := map[string]bool{} + for _, m := range r.inv.Manifests { + rt, ok := runtimeOf[m.Ecosystem] + if !ok || seen[rt[0]] { + continue + } + seen[rt[0]] = true + if f := strings.Fields(run(ctx, r.wt.Dir, rt[1])); len(f) > 0 { + res = append(res, rt[0]+" "+strings.TrimPrefix(f[len(f)-1], "go")) + } + } + return res +} + +// showSteps writes the proof's steps as one shell line that runs them the +// same way: a step that changes directory does so in a subshell of its own. +func showSteps(steps []string) string { + out := make([]string, len(steps)) + for i, st := range steps { + if strings.HasPrefix(st, "cd ") { + st = "(" + st + ")" + } + out[i] = st + } + return strings.Join(out, " && ") +} + +// missing says whether run stopped because a command it needs is not there, +// which running it again does not change. +func missing(run *core.Run) bool { + st := run.Last() + return st != nil && (st.Exit == 126 || st.Exit == 127) +} + func (r *runner) vet(ctx context.Context, ch *core.Change, pt *core.Patch, proof *core.Proof) (*core.Vetting, error) { s, wt := r.s, r.wt // Only the files the patch touched have changed since the plan read the tree. @@ -702,10 +838,13 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p if s.forge == nil && cfg.Mode == "pr" { in.Notes = append(in.Notes, "Prepared without a pull request: "+s.why+".") } + if proof != nil && !proof.Nothing && proof.Container == "" { + proof.Runtimes = r.runtimes(ctx) + } res := &outcome{Change: ch, Proof: proof, Vetting: vt, Title: deliver.Title(in, cfg.TitlePrefix), Worktree: wt.Dir, Branch: deliver.Branch(ch)} res.Body = deliver.Body(in) if s.o.dryRun { - res.Action, res.line = "dry-run", "dry run; the worktree is kept at "+wt.Dir + res.Action, res.Summary = "dry-run", "dry run; until the next run, the worktree is kept at "+wt.Dir return res, nil } // A commit goes in with nobody to read it first, so only a proven one does. @@ -744,14 +883,17 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p s.st.Open.Stage = ch.Batch.Stage } res.Action, res.Branch = "committed", branch - res.line = fmt.Sprintf("committed %s to %s: %s", core.Short(res.Commit), branch, res.Title) + res.Summary = fmt.Sprintf("committed %s to %s: %s", core.Short(res.Commit), branch, res.Title) case s.forge == nil || s.remote == "": if _, err := gitx.Run(ctx, wt.Dir, "branch", "--force", res.Branch, "HEAD"); err != nil { return nil, err } why := cmp.Or(s.why, "no remote to push to") res.Action = "branch" - res.line = fmt.Sprintf("branch %s has the change; %s, so no pull request was opened", res.Branch, why) + if s.cfg.Deliver.Mode == "pr" && s.remote != "" && s.noToken { + res.code = exitUndelivered + } + res.Summary = fmt.Sprintf("branch %s has the change; %s, so no pull request was opened", res.Branch, why) default: last := "" if o := s.st.Open; o != nil && o.ID == ch.ID && o.Branch == res.Branch { @@ -767,8 +909,11 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p if err != nil { return r.undelivered(ch, res, err) } - res.Action, res.PR = "opened", pr - if r.p.Open != nil && r.p.Open.Number == pr.Number { + res.Action, res.PR, res.Commit = "opened", pr, cmp.Or(pr.Head, sha) + switch o := r.p.Open; { + case o != nil && o.Number == pr.Number && o.Body == pr.Body && o.Title == pr.Title: + res.Action = "up-to-date" + case o != nil && o.Number == pr.Number: res.Action = "updated" } s.st.Open = &state.OpenPR{ID: ch.ID, PR: pr.Number, Branch: pr.Branch, Base: pr.Base, Commit: cmp.Or(pr.Head, sha), At: now} @@ -779,7 +924,10 @@ func (r *runner) deliver(ctx context.Context, ch *core.Change, pt *core.Patch, p delete(s.st.Parked, ch.ID) } res.Body = pr.Body - res.line = fmt.Sprintf("%s #%d %s %s", res.Action, pr.Number, pr.Title, pr.URL) + res.Summary = fmt.Sprintf("%s #%d %s %s", res.Action, pr.Number, pr.Title, pr.URL) + if res.Action == "up-to-date" { + res.Summary = fmt.Sprintf("#%d %s is up to date %s", pr.Number, pr.Title, pr.URL) + } if preempt != nil { if err := deliver.Replaced(ctx, s.forge, preempt.Number, pr.Number); err != nil { s.logf("cannot point #%d at #%d: %v", preempt.Number, pr.Number, err) @@ -795,11 +943,11 @@ func (r *runner) undelivered(ch *core.Change, res *outcome, err error) (*outcome s := r.s switch { case errors.Is(err, deliver.ErrMoved): - res.Action, res.line = "moved", err.Error()+"; the next run does the change again on the new tip" + res.Action, res.Summary, res.Detail = "moved", err.Error()+"; the next run does the change again on the new tip", err.Error() return res, nil case errors.Is(err, deliver.ErrForeign): res.Action, res.PR = "waiting", r.p.Open - res.line = err.Error() + "; tend leaves that PR alone" + res.Summary, res.Detail = err.Error()+"; tend leaves that PR alone", err.Error() return res, nil case errors.Is(err, deliver.ErrRefused): s.st.Fail(ch.ID, err.Error(), r.wt.Base, s.e.Now()) @@ -826,7 +974,7 @@ func (r *runner) unproven(ch *core.Change, detail string) *outcome { if !s.o.quiet && strings.Contains(detail, "\n") { fmt.Fprintf(s.e.Stderr, "%s\n", detail) } - return &outcome{Action: "unproven", Change: ch, line: fmt.Sprintf("could not prove %s: %s", ch.ID, first), code: exitUnproven} + return &outcome{Action: "unproven", Change: ch, Worktree: r.wt.Dir, Summary: fmt.Sprintf("could not prove %s: %s", ch.ID, first), Detail: detail, code: exitUnproven, parked: true} } func failure(run *core.Run) string { @@ -894,6 +1042,7 @@ func (s *session) skip(ctx context.Context, pr *core.PR, id string, c plan.Comma if err := s.forge.ClosePR(ctx, pr.Number); err != nil { return err } + s.dropBranch(ctx, pr) s.st.Parked[id] = state.Parked{PR: pr.Number, Reason: "rejected", To: core.TargetOf(id), At: s.e.Now()} s.st.See(id, "parked", fmt.Sprintf("#%d skipped by @%s", pr.Number, c.Author), s.e.Now()) s.st.Open = nil @@ -901,6 +1050,19 @@ func (s *session) skip(ctx context.Context, pr *core.PR, id string, c plan.Comma return nil } +// dropBranch deletes the branch of a PR tend just closed, as Dependabot +// does: only while it holds the commit tend last pushed, so work someone +// added to it stays. Failing to is logged, never fatal. +func (s *session) dropBranch(ctx context.Context, pr *core.PR) { + o := s.st.Open + if s.push == nil || s.cfg.Deliver.Mode != "pr" || o == nil || o.PR != pr.Number || o.Branch == "" { + return + } + if err := deliver.DeleteBranch(ctx, s.push, o.Branch, o.Commit); err != nil { + s.logf("kept the branch %s of #%d: %v", o.Branch, pr.Number, err) + } +} + // displace closes the PR a new one is about to replace: the same change at an // older target is superseded; the first PR folds any other in; anything else // gives way to security work and comes back. It goes first, so tend never @@ -918,6 +1080,7 @@ func (s *session) displace(ctx context.Context, old *core.PR, oldID string, ch * if err := deliver.Close(ctx, s.forge, old.Number, msg); err != nil { return err } + s.dropBranch(ctx, old) if !same && oldID != "" { s.st.Parked[oldID] = state.Parked{PR: old.Number, Reason: "preempted", To: core.TargetOf(oldID), At: s.e.Now()} } @@ -944,12 +1107,13 @@ func folded(b *core.Batch, id string) string { // notice prints one line a day at most when a newer release of tend exists. func (s *session) notice(ctx context.Context) { rel := &s.st.Release - if s.e.Now().Sub(rel.Checked) >= 24*time.Hour { - info, err := selfupdate.Latest(ctx, s.fetch, s.e.Version) - rel.Checked, rel.Tag = s.e.Now(), "" - if err == nil && info.Newer { - rel.Tag = info.Tag - } + if s.e.Now().Sub(rel.Checked) < 24*time.Hour { + return + } + info, err := selfupdate.Latest(ctx, s.fetch, s.e.Version) + rel.Checked, rel.Tag = s.e.Now(), "" + if err == nil && info.Newer { + rel.Tag = info.Tag } if rel.Tag != "" && !s.o.quiet && newer(rel.Tag, s.e.Version) { fmt.Fprintf(s.e.Stderr, "tend: %s is available; run tend update\n", rel.Tag) diff --git a/internal/cli/session.go b/internal/cli/session.go index f8187db..310d638 100644 --- a/internal/cli/session.go +++ b/internal/cli/session.go @@ -1,7 +1,9 @@ package cli import ( + "cmp" "context" + "errors" "fmt" "net/http" "path/filepath" @@ -38,37 +40,51 @@ type session struct { specs *api.Specs // the API specs the last plan read unlock func() picked *core.Model // the model, set once llm has run + + noToken bool // a GitHub origin, but no token to reach it with + noRepo bool // GitHub does not show the origin's repo to the token + readOnly bool // another run holds the lock: this one saves nothing + openWhy string // why the open PRs are not known, "" when they are + info *core.RepoInfo } // settings finds the repo's top level and reads its tend.yml. The top level // comes back even when the file is wrong. func settings(ctx context.Context, e Env, o opts) (*config.Config, string, bool, error) { - root, git := o.dir, false - if top, err := gitx.Run(ctx, o.dir, "rev-parse", "--show-toplevel"); err == nil { - root, git = top, true + root, git := top(ctx, o.dir) + cfg, used, err := config.Load(root, configPath(e, o, root)) + if err != nil { + return nil, root, git, err + } + if err := eco.Check(cfg); err != nil { + return nil, root, git, config.At(config.Shown(root, used), err) + } + return cfg, root, git, nil +} + +// top is the top level of the git repo dir is in, else dir itself. +func top(ctx context.Context, dir string) (string, bool) { + root, git := dir, false + if t, err := gitx.Run(ctx, dir, "rev-parse", "--show-toplevel"); err == nil { + root, git = t, true } if abs, err := filepath.Abs(root); err == nil { root = abs } - path := o.config + return root, git +} + +// configPath is the config file named by --config, read from the dir tend +// runs in, or by TEND_CONFIG, read from root; "" when neither names one. +func configPath(e Env, o opts, root string) string { + path, base := o.config, cmp.Or(o.dir, e.Dir) if path == "" { - path = e.Getenv("TEND_CONFIG") + path, base = e.Getenv("TEND_CONFIG"), root } if path != "" && !filepath.IsAbs(path) { - base := e.Dir - if o.config == "" { - base = root - } path = filepath.Join(base, path) } - cfg, used, err := config.Load(root, path) - if err != nil { - return nil, root, git, err - } - if err := eco.Check(cfg); err != nil { - return nil, root, git, fmt.Errorf("%s: %w", used, err) - } - return cfg, root, git, nil + return path } // llm is the configured model, nil without one. A model that cannot be set @@ -95,12 +111,15 @@ func (s *session) logf(format string, args ...any) { } // open sets up a session and takes the repo's lock. The caller runs close. -func open(ctx context.Context, e Env, o opts) (*session, error) { +// With shared set, a lock another run holds leaves the session reading the +// state that run last saved, and saving nothing. +func open(ctx context.Context, e Env, o opts, shared bool) (*session, error) { cfg, root, git, err := settings(ctx, e, o) if err != nil { return nil, err } s := &session{e: e, o: o, root: root, git: git, cfg: cfg} + core.Keep(cfg.Verify.Env) origin := "" if s.git { @@ -111,7 +130,11 @@ func open(ctx context.Context, e Env, o opts) (*session, error) { } key := state.Key(origin, s.root) s.dir = state.Dir(e.Home, key) - if s.unlock, err = state.Lock(s.dir); err != nil { + var held *state.Locked + if s.unlock, err = state.Lock(s.dir); errors.As(err, &held) && shared && !o.reset { + s.readOnly = true + s.logf("%v; this check saves nothing", err) + } else if err != nil { return nil, err } if o.reset { @@ -121,13 +144,16 @@ func open(ctx context.Context, e Env, o opts) (*session, error) { } } if s.st, _, err = state.Open(e.Home, key); err != nil { - s.unlock() + s.close() return nil, err } + if s.st.Discarded != "" { + s.logf("state.json could not be read (%s); started fresh: open PRs and rejections are read back from GitHub", s.st.Discarded) + } owner, name, ok := deliver.RepoFromRemote(origin) - if !ok { - owner, name, ok = deliver.RepoFromRemote(e.Getenv("GITHUB_REPOSITORY")) + if origin == "" { + owner, name, ok = deliver.RepoFromSlug(e.Getenv("GITHUB_REPOSITORY")) } s.repo = s.root if ok { @@ -158,17 +184,19 @@ func open(ctx context.Context, e Env, o opts) (*session, error) { owner, name = "", "" } if s.push, err = deliver.NewRemote(ctx, s.root, s.remote, token, owner, name); err != nil { - s.unlock() + s.close() return nil, err } } s.forge = e.Forge switch { case s.forge != nil: + case !ok && !s.git: + s.why = "not a git repository" case !ok: s.why = "no GitHub origin remote" case token == "": - s.why = "no GitHub token (set GITHUB_TOKEN or log in with gh)" + s.why, s.noToken = "no GitHub token: set GITHUB_TOKEN or log in with gh", true default: s.forge = deliver.NewGitHub(s.fetch, http.DefaultClient, token, owner, name) } @@ -181,9 +209,10 @@ func (s *session) close() { } } -// save writes the state. A dry run leaves no trace. +// save writes the state. A dry run leaves no trace, nor does a check that +// runs while another run holds the lock. func (s *session) save() { - if s.o.dryRun { + if s.o.dryRun || s.readOnly { return } s.st.Updated = s.e.Now() @@ -192,20 +221,36 @@ func (s *session) save() { } } +// reach asks the forge about the repo, once. A repo GitHub does not show +// the token leaves the session with no forge, for that reason. +func (s *session) reach(ctx context.Context) error { + if s.forge == nil || s.info != nil { + return nil + } + info, err := s.forge.Repo(ctx) + var missing *deliver.NoRepo + if errors.As(err, &missing) { + s.forge, s.why, s.noRepo = nil, err.Error(), true + return nil + } + if err != nil { + return err + } + s.info = &info + return nil +} + // baseName is the branch changes go to: tend.yml's base, else the forge's // default branch, else the remote's HEAD, else the current branch, else "". func (s *session) baseName(ctx context.Context) (string, error) { if s.cfg.Base != "" { return s.cfg.Base, nil } - if s.forge != nil { - info, err := s.forge.Repo(ctx) - if err != nil { - return "", err - } - if info.Default != "" { - return info.Default, nil - } + if err := s.reach(ctx); err != nil { + return "", err + } + if s.info != nil && s.info.Default != "" { + return s.info.Default, nil } if s.remote != "" { if ref, err := gitx.Run(ctx, s.root, "symbolic-ref", "--short", "refs/remotes/"+s.remote+"/HEAD"); err == nil { @@ -217,28 +262,48 @@ func (s *session) baseName(ctx context.Context) (string, error) { } // baseRev is where work on branch starts: the remote's copy when it has one, -// fetched first when fetch is set, else the local branch, else HEAD. -func (s *session) baseRev(ctx context.Context, branch string, fetch bool) string { +// fetched first when fetch is set, else the local branch. With no branch it +// is HEAD; a branch found nowhere is an error, never the checkout instead. +func (s *session) baseRev(ctx context.Context, branch string, fetch bool) (string, error) { if branch == "" { - return "HEAD" + return "HEAD", nil } + var ferr error if s.remote != "" { if fetch { - s.fetchBase(ctx, branch) + ferr = s.push.Fetch(ctx, branch) } remote := "refs/remotes/" + s.remote + "/" + branch - if _, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", remote+"^{commit}"); err == nil { - return remote + if hasCommit(ctx, s.root, remote) { + s.fetchFailed(branch, ferr) + return remote, nil } } - if _, err := gitx.Run(ctx, s.root, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch+"^{commit}"); err == nil { - return "refs/heads/" + branch + if local := "refs/heads/" + branch; hasCommit(ctx, s.root, local) { + s.fetchFailed(branch, ferr) + return local, nil + } + where := "locally" + if s.remote != "" { + where = "locally or on " + s.remote + } + msg := fmt.Sprintf("base branch %q not found %s", branch, where) + if ferr != nil { + msg += fmt.Sprintf(" (fetch: %v)", ferr) } - return "HEAD" + if s.remote != "" && strings.HasPrefix(branch, s.remote+"/") { + msg += fmt.Sprintf("; base names a branch, so write %q", strings.TrimPrefix(branch, s.remote+"/")) + } + return "", errors.New(msg) } -func (s *session) fetchBase(ctx context.Context, branch string) { - if err := s.push.Fetch(ctx, branch); err != nil { +func (s *session) fetchFailed(branch string, err error) { + if err != nil { s.logf("cannot fetch %s from %s: %v", branch, s.remote, err) } } + +func hasCommit(ctx context.Context, dir, rev string) bool { + _, err := gitx.Run(ctx, dir, "rev-parse", "--verify", "--quiet", rev+"^{commit}") + return err == nil +} diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go new file mode 100644 index 0000000..822368c --- /dev/null +++ b/internal/cli/session_test.go @@ -0,0 +1,174 @@ +package cli + +import ( + "bytes" + "os" + "strings" + "testing" + + "github.com/mohsensc/tend-cli/internal/deliver" + "github.com/mohsensc/tend-cli/internal/state" +) + +// A check while a run holds the lock still reports, from the state that run +// last saved, and saves nothing over it. +func TestCheckWhileLocked(t *testing.T) { + dir := repo(t, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`}) + home := t.TempDir() + if r := tend(t, dir, home, offline{}, "check"); r.code != exitOK { + t.Fatalf("first check = %d: %s", r.code, r.stderr) + } + sdir := state.Dir(home, state.Key("", dir)) + before, err := os.ReadFile(sdir + "/state.json") + if err != nil { + t.Fatal(err) + } + release, err := state.Lock(sdir) + if err != nil { + t.Fatal(err) + } + defer release() + r := tend(t, dir, home, offline{}, "check") + if r.code != exitOK || !strings.Contains(r.out, "queued") || !strings.Contains(r.stderr, "this check saves nothing") { + t.Errorf("check while locked = %d\nstdout: %s\nstderr: %s", r.code, r.out, r.stderr) + } + if after, _ := os.ReadFile(sdir + "/state.json"); !bytes.Equal(before, after) { + t.Error("a check while locked saved state") + } + if r := tend(t, dir, home, offline{}, "check", "--reset"); r.code != exitErr || !strings.Contains(r.stderr, "holds the lock") { + t.Errorf("check --reset while locked = %d: %s", r.code, r.stderr) + } + if r := tend(t, dir, home, offline{}, "run", "--dry-run"); r.code != exitErr || !strings.Contains(r.stderr, "holds the lock") { + t.Errorf("run while locked = %d: %s", r.code, r.stderr) + } +} + +// A repo GitHub does not show the token is said once, in words, not as +// three raw API errors; check goes on without the forge and run stops. +func TestNoRepo(t *testing.T) { + dir := repo(t, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`}) + missing := deliver.NewFake("acme", "shop", "main") + missing.Err = &deliver.NoRepo{Repo: "acme/shop"} + call := func(args ...string) tendRun { + var out, errs bytes.Buffer + e := DefaultEnv() + e.Dir, e.Home, e.Stdout, e.Stderr, e.Stdin = dir, t.TempDir(), &out, &errs, strings.NewReader("") + e.Fetch, e.Forge, e.Getenv = offline{}, missing, func(string) string { return "" } + return tendRun{Main(args, e), out.String(), errs.String()} + } + r := call("check") + head, _, _ := strings.Cut(r.out, "\n") + if r.code != exitOK || !strings.HasSuffix(head, "open PRs unknown (GitHub repo acme/shop not found, or the token cannot see it)") || strings.Contains(r.out, "/repos/") { + t.Errorf("check = %d\nstdout: %s\nstderr: %s", r.code, r.out, r.stderr) + } + r = call("run") + if r.code != exitErr || r.stderr != "tend: GitHub repo acme/shop not found, or the token cannot see it\n" { + t.Errorf("run = %d\nstdout: %s\nstderr: %s", r.code, r.out, r.stderr) + } +} + +// update on a build it cannot replace says so and fails; update --check, +// which was asked to change nothing, does not. +func TestUpdateDevBuild(t *testing.T) { + for _, tt := range []struct { + args []string + code int + }{{[]string{"update"}, exitErr}, {[]string{"update", "--check"}, exitOK}} { + var out, errs bytes.Buffer + e := DefaultEnv() + e.Dir, e.Home, e.Stdout, e.Stderr, e.Version = t.TempDir(), t.TempDir(), &out, &errs, "v1.0.0-2-gf5ba9bf" + e.Fetch, e.Getenv = offline{}, func(string) string { return "" } + if code := Main(tt.args, e); code != tt.code || !strings.Contains(out.String()+errs.String(), "development build") { + t.Errorf("%v = %d: %s%s", tt.args, code, out.String(), errs.String()) + } + } +} + +// A dry run that prepares nothing leaves no worktree, and a later run +// clears the one a dry run on an older base kept. +func TestWorktreesSwept(t *testing.T) { + dir := repo(t, map[string]string{"README.md": "hi\n"}) + home := t.TempDir() + if r := tend(t, dir, home, offline{}, "run", "--dry-run"); r.code != exitOK || len(worktrees(t, home)) != 0 { + t.Fatalf("dry run = %d %q, worktrees %q", r.code, r.out, worktrees(t, home)) + } + if r := tend(t, dir, home, offline{}, "run", "--keep"); r.code != exitOK || len(worktrees(t, home)) != 1 { + t.Fatalf("run --keep = %d %q", r.code, r.stderr) + } + old := worktrees(t, home)[0] + writeFiles(t, dir, map[string]string{"README.md": "hello\n"}) + gitIn(t, dir, "commit", "--quiet", "-am", "Next") + if r := tend(t, dir, home, offline{}, "run"); r.code != exitOK { + t.Fatalf("run = %d %q", r.code, r.stderr) + } + if wts := worktrees(t, home); len(wts) != 0 { + t.Errorf("worktrees left: %q", wts) + } + if list := gitIn(t, dir, "worktree", "list"); strings.Contains(list, old) { + t.Errorf("git still lists %s:\n%s", old, list) + } +} + +// An origin that is a local path is no GitHub repo, even with two path +// segments, and GITHUB_REPOSITORY does not stand in for it: only a repo +// with no origin reads that. +func TestCheckNotGit(t *testing.T) { + dir := t.TempDir() + writeFiles(t, dir, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`}) + var out, errs bytes.Buffer + e := DefaultEnv() + e.Dir, e.Home, e.Stdout, e.Stderr, e.Stdin = dir, t.TempDir(), &out, &errs, strings.NewReader("") + e.Fetch = offline{} + e.Getenv = func(string) string { return "" } + if code := Main([]string{"check"}, e); code != exitOK || !strings.Contains(out.String(), "open PRs unknown (not a git repository)") { + t.Errorf("check = %d\nstdout: %s\nstderr: %s", code, out.String(), errs.String()) + } +} + +func TestLocalOrigin(t *testing.T) { + dir := repo(t, map[string]string{"package.json": `{"dependencies": {"lodash": "4.17.0"}}`}) + gitIn(t, dir, "remote", "add", "origin", "/srv/repo") + var out, errs bytes.Buffer + e := DefaultEnv() + e.Dir, e.Home, e.Stdout, e.Stderr, e.Stdin = dir, t.TempDir(), &out, &errs, strings.NewReader("") + e.Fetch = offline{} + e.Getenv = func(k string) string { + if k == "GITHUB_REPOSITORY" { + return "acme/shop" + } + return "" + } + if code := Main([]string{"check"}, e); code != exitOK || !strings.Contains(out.String(), "open PRs unknown (no GitHub origin remote)") { + t.Errorf("check = %d\nstdout: %s\nstderr: %s", code, out.String(), errs.String()) + } +} + +func TestShowSteps(t *testing.T) { + got := showSteps([]string{"go build ./...", "cd ci && go build ./...", "go vet ./... && go test ./..."}) + if want := "go build ./... && (cd ci && go build ./...) && go vet ./... && go test ./..."; got != want { + t.Errorf("showSteps = %q, want %q", got, want) + } +} + +func TestListedUnproven(t *testing.T) { + env := map[string]string{"GITHUB_ACTIONS": "true"} + var out bytes.Buffer + s := &session{e: Env{Stdout: &out, Getenv: func(k string) string { return env[k] }}, st: state.New(), forge: deliver.NewFake("acme", "shop", "main")} + s.st.Issue.Number = 7 + res := &outcome{Action: "unproven", Summary: "could not prove npm/chalk@6.0.1: npm test failed (exit 1)", code: exitUnproven, parked: true} + if code := s.report(res); code != exitOK || !strings.Contains(out.String(), "::warning title=tend::could not prove npm/chalk@6.0.1: npm test failed (exit 1); listed in #7") { + t.Errorf("report = %d, %q", code, out.String()) + } + env["TEND_FAIL_ON_UNPROVEN"] = "true" + if code := s.report(res); code != exitUnproven { + t.Errorf("with fail-on-unproven, report = %d", code) + } + delete(env, "TEND_FAIL_ON_UNPROVEN") + if code := s.report(&outcome{Action: "unproven", code: exitUnproven}); code != exitUnproven { + t.Errorf("a CI revert failure, report = %d", code) + } + delete(env, "GITHUB_ACTIONS") + if code := s.report(res); code != exitUnproven { + t.Errorf("run by hand, report = %d", code) + } +} diff --git a/internal/cli/track.go b/internal/cli/track.go index e90c8d9..c5d77e0 100644 --- a/internal/cli/track.go +++ b/internal/cli/track.go @@ -2,13 +2,16 @@ package cli import ( "context" + "errors" "fmt" "maps" "slices" "strings" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/deliver" "github.com/mohsensc/tend-cli/internal/plan" + "github.com/mohsensc/tend-cli/internal/state" ) // trackMarker finds tend's tracking issue among the repository's issues. @@ -32,11 +35,22 @@ func (s *session) track(ctx context.Context, p *plan.Plan, base string) { if is.Number != 0 && is.Body == body && is.Open == open { return } + for range 2 { + if !s.trackOnce(ctx, tr, is, body, open) { + return + } + *is = state.Issue{} + } +} + +// trackOnce brings the tracking issue is to body and open. It reports +// whether the issue is gone, deleted or moved, so a fresh one is due. +func (s *session) trackOnce(ctx context.Context, tr core.Tracker, is *state.Issue, body string, open bool) bool { if is.Number == 0 { found, err := tr.FindIssue(ctx, trackMarker) if err != nil { s.logf("cannot look for the tracking issue: %v", err) - return + return false } if found != nil { is.Number, is.Body, is.Open = found.Number, found.Body, found.Open @@ -48,20 +62,24 @@ func (s *session) track(ctx context.Context, p *plan.Plan, base string) { made, err := tr.CreateIssue(ctx, trackTitle, body, s.cfg.Deliver.Labels) if err != nil { s.logf("cannot open the tracking issue: %v", err) - return + return false } is.Number, is.Body, is.Open = made.Number, body, true s.logf("opened #%d, which lists what tend could not do on its own", made.Number) case is.Body != body || is.Open != open: - if err := tr.EditIssue(ctx, is.Number, body, open); err != nil { + if err := tr.EditIssue(ctx, is.Number, body, open); errors.Is(err, deliver.ErrGone) { + s.logf("the tracking issue #%d is gone; tend looks for another", is.Number) + return true + } else if err != nil { s.logf("cannot update the tracking issue #%d: %v", is.Number, err) - return + return false } if is.Open && !open { s.logf("closed #%d: everything it listed is done", is.Number) } is.Body, is.Open = body, open } + return false } // undone lists, a line each with why, what tend tried on base and could @@ -69,10 +87,21 @@ func (s *session) track(ctx context.Context, p *plan.Plan, base string) { // deprecated packages it knows no replacement for. func (s *session) undone(p *plan.Plan, base string) []string { var res []string + queued := map[string]bool{} + if p != nil { + for _, ch := range p.Queue { + queued[ch.ID] = true + } + } for _, id := range slices.Sorted(maps.Keys(s.st.Seen)) { - if x := s.st.Seen[id]; x.Verdict == "unsupported" && base != "" && x.Base == base { + x := s.st.Seen[id] + switch { + case x.Verdict == "unsupported" && base != "" && x.Base == base: first, _, _ := strings.Cut(x.Detail, "\n") - res = append(res, fmt.Sprintf("- `%s`: could not be made or proven on %s: %s", id, core.Short(base), strings.TrimSuffix(first, "."))) + res = append(res, fmt.Sprintf("- `%s`: could not be made or proven on %s: %s", id, core.Short(base), deliver.Clause(first))) + case x.Verdict == "queued" && x.Failed != "" && queued[id]: + first, _, _ := strings.Cut(x.Failed, "\n") + res = append(res, fmt.Sprintf("- `%s`: could not be made or proven on %s (the base has moved on since; tend tries it again): %s", id, core.Short(x.FailedBase), deliver.Clause(first))) } } for _, id := range slices.Sorted(maps.Keys(s.st.Parked)) { @@ -91,7 +120,7 @@ func (s *session) undone(p *plan.Plan, base string) []string { if slices.ContainsFunc(gone, func(d core.Dep) bool { return len(ch.Deps) > 0 && d.Name == ch.Deps[0].Name }) { continue } - if ch.API == nil && ch.To == "" && ch.ToName == "" && len(ch.Options) == 0 && len(ch.Deps) > 0 { + if ch.Kind == core.Deprecation && ch.API == nil && ch.To == "" && ch.ToName == "" && len(ch.Options) == 0 && len(ch.Deps) > 0 { res = append(res, fmt.Sprintf("- `%s`: deprecated, and tend knows no replacement for it, so it stays", ch.Deps[0].Name)) } } diff --git a/internal/cli/update.go b/internal/cli/update.go index 4cc5ea2..1ef080f 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -17,13 +17,19 @@ func update(ctx context.Context, e Env, o opts) int { return fail(e, err) } switch { - case info.Tag == "dev": + case info.Tag == "dev" && o.check: fmt.Fprintf(e.Stdout, "tend: %s is a development build; self-update needs a release build\n", e.Version) + case info.Tag == "dev": + fmt.Fprintf(e.Stderr, "tend: %s is a development build; self-update needs a release build\n", e.Version) + return exitErr case !info.Newer: fmt.Fprintf(e.Stdout, "tend: %s is the latest release\n", e.Version) case o.check: fmt.Fprintf(e.Stdout, "tend: %s is available (this is %s); run tend update\n", info.Tag, e.Version) default: + if !o.quiet { + fmt.Fprintf(e.Stderr, "tend: downloading %s\n", info.Tag) + } if err := selfupdate.Apply(ctx, fetcher(e), info); err != nil { return fail(e, err) } diff --git a/internal/cli/watch.go b/internal/cli/watch.go index fdbe8d2..91205a0 100644 --- a/internal/cli/watch.go +++ b/internal/cli/watch.go @@ -8,34 +8,56 @@ import ( "os/signal" "syscall" "time" + + "github.com/mohsensc/tend-cli/internal/config" ) // watch runs again and again. The first interrupt lets the current run finish -// and stops; a second one ends it at once. +// and stops; a second one cuts the run short, and what it started with it. +// A tend.yml that does not load or a directory that is no git repository +// stops it at the start; a run that fails for anything else, a network down +// or a lock held, is said and tried again next time. func watch(ctx context.Context, e Env, o opts) int { + cfg, root, git, err := settings(ctx, e, o) + if err != nil { + return fail(e, err) + } + if !git { + return fail(e, fmt.Errorf("%s is not a git repository", root)) + } every := o.every if every <= 0 { - every = 24 * time.Hour - // A tend.yml that does not load is reported by the run itself. - if cfg, _, _, err := settings(ctx, e, o); err == nil { - every = time.Duration(cfg.Schedule) - } + every = time.Duration(cfg.Schedule) } + hard, cancel := context.WithCancel(context.WithoutCancel(ctx)) + defer cancel() + sig := make(chan os.Signal, 2) + signal.Notify(sig, os.Interrupt, syscall.SIGTERM) + defer signal.Stop(sig) go func() { - <-ctx.Done() - signal.Reset(os.Interrupt, syscall.SIGTERM) + for range 2 { + select { + case <-sig: + case <-hard.Done(): + return + } + } + cancel() }() - loop(ctx, every, jitter, sleep, func(ctx context.Context) { + loop(ctx, hard, every, jitter, sleep, func(ctx context.Context) { once(ctx, e, o) - if !o.quiet { - fmt.Fprintf(e.Stderr, "tend: next run in about %s (ctrl-c to stop)\n", every) + if !o.quiet && ctx.Err() == nil { + fmt.Fprintf(e.Stderr, "tend: next run in about %s (ctrl-c to stop)\n", config.Duration(every)) } }) + if hard.Err() != nil { + return exitInterrupted + } return exitOK } func once(ctx context.Context, e Env, o opts) { - s, err := open(ctx, e, o) + s, err := open(ctx, e, o, false) if err != nil { fail(e, err) return @@ -53,12 +75,12 @@ func once(ctx context.Context, e Env, o opts) { s.report(res) } -// loop calls once, then waits about every, until ctx is done. A run that has -// started is never cut short by ctx. -func loop(ctx context.Context, every time.Duration, jitter func(time.Duration) time.Duration, wait func(context.Context, time.Duration) bool, once func(context.Context)) { +// loop calls once with hard, then waits about every, until ctx is done. A +// run that has started is cut short only by hard, never by ctx. +func loop(ctx, hard context.Context, every time.Duration, jitter func(time.Duration) time.Duration, wait func(context.Context, time.Duration) bool, once func(context.Context)) { for { - once(context.WithoutCancel(ctx)) - if ctx.Err() != nil || !wait(ctx, every+jitter(every)) { + once(hard) + if ctx.Err() != nil || hard.Err() != nil || !wait(ctx, every+jitter(every)) { return } } diff --git a/internal/cli/watch_test.go b/internal/cli/watch_test.go new file mode 100644 index 0000000..3f8b26d --- /dev/null +++ b/internal/cli/watch_test.go @@ -0,0 +1,30 @@ +package cli + +import ( + "strings" + "testing" +) + +// What a later run cannot fix stops watch at once, so a broken setup does +// not look healthy for a day at a time. +func TestWatchStops(t *testing.T) { + plain := t.TempDir() + bad := repo(t, map[string]string{"tend.yml": "bogus: 1\n"}) + for _, c := range []struct { + name, dir string + args []string + code int + says string + }{ + {"no git", plain, []string{"watch", "--every", "1h"}, exitErr, "is not a git repository"}, + {"bad tend.yml", bad, []string{"watch"}, exitErr, "unknown key"}, + {"negative every", bad, []string{"watch", "--every=-1s"}, exitUsage, "--every wants a positive duration"}, + } { + t.Run(c.name, func(t *testing.T) { + r := tend(t, c.dir, t.TempDir(), offline{}, c.args...) + if r.code != c.code || !strings.Contains(r.stderr, c.says) || strings.Contains(r.stderr, "next run") { + t.Errorf("exit %d, stderr %q", r.code, r.stderr) + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index f5de22e..7cc615d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -7,8 +7,10 @@ import ( "errors" "fmt" "io" + "math" "net/url" "os" + "path" "path/filepath" "reflect" "regexp" @@ -93,9 +95,13 @@ type Model struct { // the model it serves: "groq/openai/gpt-oss-120b". func (m *Model) UnmarshalYAML(n *yaml.Node) error { if n.Kind == yaml.ScalarNode { + if n.Value == "none" { + m.Provider, m.Model = "none", "" + return nil + } provider, id, ok := strings.Cut(n.Value, "/") if !ok || provider == "" || id == "" { - return fmt.Errorf("line %d: model: want provider/model or a mapping, got %q", n.Line, n.Value) + return fmt.Errorf("line %d: model: want provider/model, none or a mapping, got %q", n.Line, n.Value) } m.Provider, m.Model = provider, id return nil @@ -185,7 +191,7 @@ func (d *Duration) UnmarshalYAML(n *yaml.Node) error { } v, err := ParseDuration(s) if err != nil { - return fmt.Errorf("line %d: %w", n.Line, err) + return fmt.Errorf("line %d: %w; want e.g. 20m, 1h30m or 3d", n.Line, err) } *d = Duration(v) return nil @@ -198,14 +204,21 @@ func (d Duration) String() string { if v > 0 && v%(24*time.Hour) == 0 { return strconv.Itoa(int(v/(24*time.Hour))) + "d" } - return v.String() + s := v.String() + if strings.HasSuffix(s, "m0s") { + s = strings.TrimSuffix(s, "0s") + } + if strings.HasSuffix(s, "h0m") { + s = strings.TrimSuffix(s, "0m") + } + return s } func ParseDuration(s string) (time.Duration, error) { s = strings.TrimSpace(s) if days, ok := strings.CutSuffix(s, "d"); ok { n, err := strconv.Atoi(days) - if err != nil || n < 0 { + if err != nil || n < 0 || int64(n) > math.MaxInt64/int64(24*time.Hour) { return 0, fmt.Errorf("bad duration %q", s) } return time.Duration(n) * 24 * time.Hour, nil @@ -254,16 +267,19 @@ func Load(root, path string) (*Config, string, error) { path = filepath.Join(root, path) } b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, "", fmt.Errorf("%s: config file not found", Shown(root, path)) + } if err != nil { return nil, "", err } cfg, err := Parse(b) if err != nil { - return nil, "", at(shown(root, path), err) + return nil, "", At(Shown(root, path), err) } return cfg, path, nil } - for _, name := range []string{"tend.yml", filepath.Join(".github", "tend.yml")} { + for _, name := range Files { p := filepath.Join(root, name) b, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { @@ -274,20 +290,24 @@ func Load(root, path string) (*Config, string, error) { } cfg, err := Parse(b) if err != nil { - return nil, "", at(name, err) + return nil, "", At(name, err) } return cfg, p, nil } return Default(), "", nil } -// at puts the file's name in front of each line of err. -func at(name string, err error) error { +// Files are where tend looks for its config under the repo's top level, in +// order; the first that exists is the one it reads. +var Files = []string{"tend.yml", filepath.Join(".github", "tend.yml")} + +// At puts the file's name in front of each line of err. +func At(name string, err error) error { return errors.New(name + ": " + strings.ReplaceAll(err.Error(), "\n", "\n"+name+": ")) } -// shown is p as a person would type it: relative to root when it is inside. -func shown(root, p string) string { +// Shown is p as a person would type it: relative to root when it is inside. +func Shown(root, p string) string { if rel, err := filepath.Rel(root, p); err == nil && !strings.HasPrefix(rel, "..") { return rel } @@ -301,7 +321,15 @@ func Parse(b []byte) (*Config, error) { dec := yaml.NewDecoder(bytes.NewReader(b)) dec.KnownFields(true) if err := dec.Decode(cfg); err != nil && !errors.Is(err, io.EOF) { + return nil, keyed(b, plain(err)) + } + var extra yaml.Node + switch err := dec.Decode(&extra); { + case errors.Is(err, io.EOF): + case err != nil: return nil, plain(err) + case len(extra.Content) > 0 && extra.Content[0].Tag != "!!null": + return nil, fmt.Errorf("line %d: only one YAML document is allowed", extra.Content[0].Line) } if err := cfg.Validate(); err != nil { return nil, err @@ -342,6 +370,12 @@ func (c *Config) Validate() error { bad("schedule: want 1h, 2h, 3h, 4h, 6h, 8h, 12h, 1d or 7d, got %s", c.Schedule) } oneOf("onboarding", c.Onboarding, onboardings) + if c.Base != "" && !branchName(c.Base) { + bad("base: %q is not a branch name", c.Base) + } + if c.Deliver.Branch != "" && !branchName(c.Deliver.Branch) { + bad("deliver.branch: %q is not a branch name", c.Deliver.Branch) + } for i, ig := range c.Ignore { if ig.Name == "" { bad("ignore[%d]: name is required", i) @@ -370,19 +404,39 @@ func (c *Config) Validate() error { if re, err := regexp.Compile(d.Match); err != nil || re.SubexpIndex("v") < 0 { bad("deps[%d]: match must be a regexp with a group (?P...) around the version", i) } + if _, err := path.Match(d.File, ""); err != nil { + bad("deps[%d]: file %q is not a glob", i, d.File) + } if scheme, rest, _ := strings.Cut(d.Source, ":"); scheme == "" || rest == "" { bad("deps[%d]: source wants github:, npm:, pypi:, url: or another ecosystem's name, got %q", i, d.Source) } } oneOf("model.provider", c.Model.Provider, providers) - if c.Model.Provider == "command" && c.Model.Command == "" { - bad("model.command: required when model.provider is command") + switch c.Model.Provider { + case "command": + if c.Model.Command == "" { + bad("model.command: required when model.provider is command") + } + case "none": + default: + if c.Model.Model == "" && slices.Contains(providers, c.Model.Provider) { + bad("model.model: required for model.provider %s; name the model it serves", c.Model.Provider) + } } - if k := c.Model.KeyEnv; k == "GITHUB_TOKEN" || k == "GH_TOKEN" || strings.HasPrefix(k, "TEND_") && k != "TEND_MODEL_KEY" { + switch k := c.Model.KeyEnv; { + case k == "": + case !envName.MatchString(k): + bad("model.key_env: %q is not a variable name", k) + case k == "GITHUB_TOKEN" || k == "GH_TOKEN" || strings.HasPrefix(k, "TEND_") && k != "TEND_MODEL_KEY": bad("model.key_env: %s is not a model key; name the variable that holds one", k) } - if u := c.Model.BaseURL; u != "" && c.Model.sendsKey() && !private(u) { - bad("model.base_url: http is only allowed for a local server") + if u := c.Model.BaseURL; u != "" { + switch p, err := url.Parse(u); { + case err != nil || p.Scheme != "http" && p.Scheme != "https" || p.Host == "": + bad("model.base_url: want an http or https URL, got %q", u) + case c.Model.sendsKey() && !private(u): + bad("model.base_url: http is only allowed for a local server") + } } if c.Model.Attempts < 1 { bad("model.attempts: want at least 1, got %d", c.Model.Attempts) @@ -412,6 +466,26 @@ func (c *Config) Validate() error { var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) +// branchName reports whether name is a branch name git accepts, as +// git check-ref-format --branch does for a plain name. +func branchName(name string) bool { + if name == "" || name == "@" || strings.HasPrefix(name, "-") || strings.HasSuffix(name, "/") || strings.HasSuffix(name, ".") || + strings.Contains(name, "..") || strings.Contains(name, "@{") || strings.Contains(name, "//") { + return false + } + for _, r := range name { + if r < 0x20 || r == 0x7f || strings.ContainsRune(" ~^:?*[\\", r) { + return false + } + } + for part := range strings.SplitSeq(name, "/") { + if strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") { + return false + } + } + return true +} + // Off reports whether tend.yml turns an ecosystem off: ecosystems lists // others but not it, or an ignore entry with the name "*" names it. func (c *Config) Off(eco string) bool { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 2f83a02..5febe6d 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -29,6 +29,9 @@ func TestDuration(t *testing.T) { {"3", 0, true}, {"d", 0, true}, {"-1d", 0, true}, + {"106751d", 106751 * 24 * time.Hour, false}, + {"106752d", 0, true}, + {"300000d", 0, true}, {"1.5d", 0, true}, {"soon", 0, true}, {"[1d]", 0, true}, @@ -59,6 +62,11 @@ func TestDurationRoundTrip(t *testing.T) { t.Errorf("%s -> %q -> %s, %v", d, b, time.Duration(got), err) } } + for d, want := range map[time.Duration]string{6 * time.Hour: "6h", 90 * time.Minute: "1h30m", 20 * time.Minute: "20m", 45 * time.Second: "45s", 36 * time.Hour: "36h"} { + if s := Duration(d).String(); s != want { + t.Errorf("Duration(%s) = %q, want %q", d, s, want) + } + } if s := Duration(72 * time.Hour).String(); s != "3d" { t.Errorf("String = %q, want 3d", s) } @@ -248,6 +256,8 @@ func TestParseErrors(t *testing.T) { {"verify: {test: go test}\n", `line 1: want a list, such as [go test]`}, {"updates: true\n", `line 1: want a map with the keys security, deprecations, major, minor, patch`}, {"zzz: 1\n", `line 1: unknown key "zzz"`}, + {"base: main\n---\nbogus: 1\n", "line 3: only one YAML document is allowed"}, + {"cooldown: 200000d\n", `line 1: cooldown: bad duration "200000d"; want e.g. 20m, 1h30m or 3d`}, } for _, tt := range tests { _, err := Parse([]byte(tt.in)) @@ -257,6 +267,15 @@ func TestParseErrors(t *testing.T) { } } +// A file may end with a bare document marker or a comment after one. +func TestParseOneDocument(t *testing.T) { + for _, in := range []string{"base: main\n---\n", "base: main\n---\n# later\n", "---\nbase: main\n"} { + if cfg, err := Parse([]byte(in)); err != nil || cfg.Base != "main" { + t.Errorf("Parse(%q) = %+v, %v", in, cfg, err) + } + } +} + func TestValidate(t *testing.T) { tests := []struct { name string @@ -300,11 +319,32 @@ func TestValidate(t *testing.T) { {"key from the repo token", func(c *Config) { c.Model.Provider, c.Model.KeyEnv = "openai", "GITHUB_TOKEN" }, "model.key_env: GITHUB_TOKEN"}, {"key from gh", func(c *Config) { c.Model.KeyEnv = "GH_TOKEN" }, "model.key_env"}, {"key from tend's own", func(c *Config) { c.Model.KeyEnv = "TEND_SIGNING_KEY" }, "model.key_env"}, - {"key from the usual place", func(c *Config) { c.Model.Provider, c.Model.KeyEnv = "openai", "TEND_MODEL_KEY" }, ""}, + {"key from the usual place", func(c *Config) { c.Model.Provider, c.Model.Model, c.Model.KeyEnv = "openai", "m", "TEND_MODEL_KEY" }, ""}, + {"key not a name", func(c *Config) { c.Model.Provider, c.Model.Model, c.Model.KeyEnv = "openai", "m", "a b" }, `model.key_env: "a b" is not a variable name`}, {"key in the clear", func(c *Config) { c.Model.Provider, c.Model.BaseURL = "openai", "http://example.net/v1" }, "model.base_url: http is only allowed for a local server"}, - {"key to this machine", func(c *Config) { c.Model.Provider, c.Model.BaseURL = "openai", "http://127.0.0.1:8080/v1" }, ""}, - {"key over https", func(c *Config) { c.Model.Provider, c.Model.BaseURL = "openai", "https://llm.internal/v1" }, ""}, - {"no key on the lan", func(c *Config) { c.Model.Provider, c.Model.BaseURL = "ollama", "http://gpu-box:11434/v1" }, ""}, + {"key to this machine", func(c *Config) { + c.Model.Provider, c.Model.Model, c.Model.BaseURL = "openai", "m", "http://127.0.0.1:8080/v1" + }, ""}, + {"key over https", func(c *Config) { + c.Model.Provider, c.Model.Model, c.Model.BaseURL = "openai", "m", "https://llm.internal/v1" + }, ""}, + {"no key on the lan", func(c *Config) { + c.Model.Provider, c.Model.Model, c.Model.BaseURL = "ollama", "qwen3", "http://gpu-box:11434/v1" + }, ""}, + {"base url not http", func(c *Config) { + c.Model.Provider, c.Model.Model, c.Model.BaseURL = "openai", "m", "ftp://localhost/v1" + }, `model.base_url: want an http or https URL, got "ftp://localhost/v1"`}, + {"base url without a host", func(c *Config) { c.Model.Provider, c.Model.Model, c.Model.BaseURL = "ollama", "m", "localhost:11434" }, "model.base_url: want an http or https URL"}, + {"model id missing", func(c *Config) { c.Model.Provider = "anthropic" }, "model.model: required for model.provider anthropic"}, + {"model id not needed for a command", func(c *Config) { c.Model.Provider, c.Model.Command = "command", "llm" }, ""}, + {"base", func(c *Config) { c.Base = "release/2.x" }, ""}, + {"base not a branch", func(c *Config) { c.Base = "main..dev" }, `base: "main..dev" is not a branch name`}, + {"base with a space", func(c *Config) { c.Base = "my branch" }, "base: "}, + {"base a ref", func(c *Config) { c.Base = "refs/heads/main^" }, "base: "}, + {"deliver branch not a branch", func(c *Config) { c.Deliver.Branch = "-x" }, `deliver.branch: "-x" is not a branch name`}, + {"dep glob", func(c *Config) { + c.Deps = []Dep{{Name: "x", File: "[abc", Match: `v(?P\S+)`, Source: "github:a/b"}} + }, `deps[0]: file "[abc" is not a glob`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -513,6 +553,7 @@ func TestModelLine(t *testing.T) { {"model: ollama/qwen3\n", "ollama", "qwen3", ""}, {"model: {provider: openai, model: m, base_url: http://localhost:8080/v1}\n", "openai", "m", ""}, {"model: groq\n", "", "", "want provider/model"}, + {"model: none\n", "none", "", ""}, {"model: {provider: groq, name: openai/gpt-oss-120b}\n", "groq", "openai/gpt-oss-120b", ""}, {"model: {provider: openai, model: m, name: n}\n", "", "", "the same key"}, {"model: {provider: openai, model: m, temperature: 0}\n", "", "", `unknown key "temperature"`}, @@ -535,3 +576,16 @@ func TestModelLine(t *testing.T) { } } } + +// A bad duration names its key, as every other config error does. +func TestDurationKey(t *testing.T) { + for in, want := range map[string]string{ + "cooldown: 3x\n": `line 1: cooldown: bad duration "3x"; want e.g. 20m, 1h30m or 3d`, + "verify:\n timeout: soon\n": `line 2: verify.timeout: bad duration "soon"`, + } { + _, err := Parse([]byte(in)) + if err == nil || !strings.HasPrefix(err.Error(), want) { + t.Errorf("Parse(%q) = %v, want %s", in, err, want) + } + } +} diff --git a/internal/config/errors.go b/internal/config/errors.go index 312dbc7..dfa7b1d 100644 --- a/internal/config/errors.go +++ b/internal/config/errors.go @@ -6,6 +6,7 @@ import ( "reflect" "regexp" "slices" + "strconv" "strings" "gopkg.in/yaml.v3" @@ -128,3 +129,51 @@ func distance(a, b string) int { } return prev[len(b)] } + +var badDuration = regexp.MustCompile(`^line (\d+): bad duration `) + +// keyed names the key in an error a value's own decoder gave, which knows +// its line but not its key: "line 3: cooldown: bad duration". +func keyed(b []byte, err error) error { + m := badDuration.FindStringSubmatch(err.Error()) + if m == nil || strings.Contains(err.Error(), "\n") { + return err + } + var doc yaml.Node + if yaml.Unmarshal(b, &doc) != nil { + return err + } + line, _ := strconv.Atoi(m[1]) + key := keyAt(&doc, line, "") + if key == "" { + return err + } + return fmt.Errorf("line %d: %s: %s", line, key, strings.TrimPrefix(err.Error(), fmt.Sprintf("line %d: ", line))) +} + +// keyAt is the dotted path of the key whose scalar value sits on line. +func keyAt(n *yaml.Node, line int, at string) string { + switch n.Kind { + case yaml.DocumentNode, yaml.SequenceNode: + for _, c := range n.Content { + if k := keyAt(c, line, at); k != "" { + return k + } + } + case yaml.MappingNode: + for i := 0; i+1 < len(n.Content); i += 2 { + k, v := n.Content[i], n.Content[i+1] + path := k.Value + if at != "" { + path = at + "." + k.Value + } + if v.Kind == yaml.ScalarNode && v.Line == line { + return path + } + if r := keyAt(v, line, path); r != "" { + return r + } + } + } + return "" +} diff --git a/internal/core/change.go b/internal/core/change.go index 7327c2a..3df7caf 100644 --- a/internal/core/change.go +++ b/internal/core/change.go @@ -54,6 +54,7 @@ type Batch struct { Kept []Aside // they look unused, but tend cannot prove it, or removing them failed Next []Later // queued changes left for a later stage Baseline *Baseline `json:",omitempty"` // tests the PR adds first, when the project's own are weak + Thin string `json:",omitempty"` // why the project's tests cannot prove the batch, when tend could add no baseline } // Baseline is what a catch-up PR adds so that its proof, and every later @@ -89,8 +90,8 @@ type APIChange struct { Path string // template as in the spec: "/v1/orders/{id}" Field string // for field/parameter changes, "" otherwise // What is one of: operation removed | operation deprecated | response field removed | - // response field deprecated | parameter removed | parameter deprecated | - // required parameter added | request field removed + // response field deprecated | response field type changed | parameter removed | + // parameter deprecated | required parameter added | request field removed What string } @@ -119,6 +120,20 @@ type Codemod struct { Text map[string]string // literal line substitutions (actions `::set-output` -> $GITHUB_OUTPUT) } +// Lines counts the lines sites sit on: two chains on one line of code are +// one place to change. +func Lines(sites []Site) int { + type at struct { + file string + line int + } + seen := map[at]bool{} + for _, s := range sites { + seen[at{s.File, s.Line}] = true + } + return len(seen) +} + // Calls are the sites of ch in code, leaving out the manifest lines that name // what it moves. func Calls(ch *Change) []Site { diff --git a/internal/core/core.go b/internal/core/core.go index 3197a85..67fddd4 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -3,6 +3,7 @@ package core import ( "context" + "strings" "time" ) @@ -49,6 +50,10 @@ type Dep struct { Min bool `json:",omitempty"` // toolchain: the oldest runtime the project supports, not one it runs } +// Display is the name a person knows d by: node, not the registry's +// library/node. +func (d Dep) Display() string { return strings.TrimPrefix(d.Name, "library/") } + type Release struct { Version string Time time.Time // zero when the registry has no timestamp @@ -121,11 +126,21 @@ type Remover interface { Remove(ctx context.Context, root string, deps []Dep) (*Bump, error) } +// Settler is an ecosystem some of whose deps are read in full only once +// their registry metadata is in, such as an Action pinned to a bare commit, +// whose version is the tag on that commit. +type Settler interface { + // Settle is d with what m tells about it filled in, or an error saying + // why d cannot be followed. + Settle(d Dep, m *Meta) (Dep, error) +} + // Traits are what stages outside an adapter need to know about its ecosystem. type Traits struct { OSV string // the ecosystem's name in OSV, "" when OSV does not cover it Page func(name string) string // where a person reads about a package, nil for nowhere KeepShape bool // a tag keeps its shape across a bump: node:16-alpine moves to another -alpine tag + KeepSuffix bool // a version keeps its qualifier across a bump: guava's -jre moves to another -jre Transitive bool // the native tool can move a locked transitive dep by itself Tooling bool // it pins what the project runs or builds on, not code it calls: runtimes, base images, CI } @@ -168,6 +183,7 @@ type FetchOpts struct { NoCache bool // Idempotent lets a Post be retried on 429 and 5xx. A Get always may be. Idempotent bool + Timeout time.Duration // how long one request may take, its body read too; 0 means the client's own } type Response struct { diff --git a/internal/core/env.go b/internal/core/env.go index 29be4c5..9685c82 100644 --- a/internal/core/env.go +++ b/internal/core/env.go @@ -1,14 +1,17 @@ package core import ( + "os" "regexp" "slices" "strings" + "sync" ) // secretName catches GITHUB_TOKEN, GH_TOKEN, a model provider's API key and -// the rest of their kind by name. -var secretName = regexp.MustCompile(`(?i)(token|secret|password|passwd|api[_-]?key|private|credential)`) +// the rest of their kind by name, and credentials by the shape of their +// name: STRIPE_KEY, GH_PAT, VAULT_ROOT_TOKEN. +var secretName = regexp.MustCompile(`(?i)(token|secret|password|passwd|api[_-]?key|private|credential)|(_KEY|_PAT)$`) // Scrub returns env without anything that looks like a secret and without // tend's own TEND_ variables, except the names in keep. It is the @@ -28,3 +31,24 @@ func Scrub(env, keep []string) []string { func secret(name string) bool { return strings.HasPrefix(name, "TEND_") || secretName.MatchString(name) } + +var kept struct { + sync.RWMutex + names []string +} + +// Keep names the variables Environ passes on although they look like +// secrets, such as a private registry's token in verify.env. +func Keep(names []string) { + kept.Lock() + defer kept.Unlock() + kept.names = slices.Clone(names) +} + +// Environ is the environment the tools tend runs itself see, a lock tool or +// go doc: tend's own, scrubbed, with the names Keep listed, plus extra. +func Environ(extra ...string) []string { + kept.RLock() + defer kept.RUnlock() + return append(Scrub(os.Environ(), kept.names), extra...) +} diff --git a/internal/core/env_test.go b/internal/core/env_test.go new file mode 100644 index 0000000..38fd8a1 --- /dev/null +++ b/internal/core/env_test.go @@ -0,0 +1,41 @@ +package core + +import ( + "slices" + "strings" + "testing" +) + +func TestScrub(t *testing.T) { + env := []string{ + "GITHUB_TOKEN=a", "GH_PAT=b", "GITHUB_PAT=c", "STRIPE_KEY=d", "VAULT_ROOT_TOKEN=e", + "DB_PASSWORD=f", "OPENAI_API_KEY=g", "TEND_MODEL_KEY=h", "NPM_TOKEN=i", + "PATH=/bin", "HOME=/home/a", "KEYBOARD=us", "SSH_AUTH_SOCK=/tmp/s", "PATCH_LEVEL=1", + } + var got []string + for _, kv := range Scrub(env, []string{"NPM_TOKEN"}) { + name, _, _ := strings.Cut(kv, "=") + got = append(got, name) + } + want := []string{"NPM_TOKEN", "PATH", "HOME", "KEYBOARD", "SSH_AUTH_SOCK", "PATCH_LEVEL"} + if !slices.Equal(got, want) { + t.Errorf("Scrub kept %v, want %v", got, want) + } +} + +func TestEnviron(t *testing.T) { + t.Setenv("GITHUB_TOKEN", "secret") + t.Setenv("TEND_MODEL_KEY", "secret") + t.Setenv("NPM_TOKEN", "registry") + defer Keep(nil) + Keep([]string{"NPM_TOKEN"}) + env := Environ("GOFLAGS=-mod=readonly") + for _, kv := range env { + if strings.HasPrefix(kv, "GITHUB_TOKEN=") || strings.HasPrefix(kv, "TEND_MODEL_KEY=") { + t.Errorf("Environ passed on %s", kv) + } + } + if !slices.Contains(env, "NPM_TOKEN=registry") || env[len(env)-1] != "GOFLAGS=-mod=readonly" { + t.Errorf("Environ = %v", env) + } +} diff --git a/internal/core/id.go b/internal/core/id.go index b469d13..f73b8ca 100644 --- a/internal/core/id.go +++ b/internal/core/id.go @@ -1,6 +1,8 @@ package core import ( + "crypto/sha256" + "encoding/hex" "slices" "strconv" "strings" @@ -103,6 +105,8 @@ func groupName(c *Change) string { } // Slug makes a branch-safe lowercase token: [a-z0-9.-]+, at most 60 chars. +// A longer one is cut and ends in a hash of s, so two that share their +// first 60 chars stay apart. func Slug(s string) string { var b strings.Builder var prev byte @@ -119,12 +123,22 @@ func Slug(s string) string { prev = c } res := strings.Trim(b.String(), "-.") - if len(res) > 60 { - res = strings.TrimRight(res[:60], "-.") + if len(res) > slugMax { + res = Cut(res, slugMax, s) } return res } +const slugMax = 60 + +// Cut shortens slug to at most n bytes, the last nine a dash and a hash of +// whole, which tells apart what the cut would make the same. +func Cut(slug string, n int, whole string) string { + sum := sha256.Sum256([]byte(whole)) + tag := "-" + hex.EncodeToString(sum[:])[:8] + return strings.TrimRight(slug[:max(n-len(tag), 1)], "-.") + tag +} + // Subject is a change id without its target: the same thing at another // version has the same subject. func Subject(id string) string { diff --git a/internal/core/id_test.go b/internal/core/id_test.go index bcf9017..242afe1 100644 --- a/internal/core/id_test.go +++ b/internal/core/id_test.go @@ -47,8 +47,8 @@ func TestSlug(t *testing.T) { {"GET /v1/orders/{id}/legacy", "get-v1-orders-id-legacy"}, {"", ""}, {"日本", ""}, - {"0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmn"}, - {"01234567890123456789012345678901234567890123456789012345678-xyz", "01234567890123456789012345678901234567890123456789012345678"}, + {"0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcde-b6034a6a"}, + {"01234567890123456789012345678901234567890123456789012345678-xyz", "012345678901234567890123456789012345678901234567890-6c86414c"}, } for _, tt := range tests { if got := Slug(tt.in); got != tt.want { diff --git a/internal/core/scan.go b/internal/core/scan.go index 6e9a552..d3ea08e 100644 --- a/internal/core/scan.go +++ b/internal/core/scan.go @@ -1,5 +1,10 @@ package core +import ( + "os" + "path/filepath" +) + type Site struct { File string Line int @@ -23,6 +28,7 @@ type URLUse struct { Method string // GET|POST|... when inferable, "" otherwise URL string // literal as written: full URL or path such as "/v1/orders" Host string // from the literal, else a host literal elsewhere in the file; "" if unknown + Text string `json:",omitempty"` // the source line, trimmed } // ScanIndex is what internal/scan.Index implements. @@ -41,3 +47,25 @@ type ScanIndex interface { Imports(pkg string) []Import Files() []string } + +// TestReacher is a ScanIndex that can say which files a test covers, as +// internal/scan.Index does. +type TestReacher interface { + // Reaches reports whether the test file test reaches the file p. + Reaches(test, p string) bool +} + +// Reaches reports whether x knows the test file test to reach p, false +// when x cannot tell. +func Reaches(x ScanIndex, test, p string) bool { + r, ok := x.(TestReacher) + return ok && r.Reaches(test, p) +} + +// NestedRepo reports whether dir is a git repository of its own, a clone, a +// submodule or a worktree, whose files are another project's, as git +// ls-files sees them. +func NestedRepo(dir string) bool { + _, err := os.Lstat(filepath.Join(dir, ".git")) + return err == nil +} diff --git a/internal/core/stages.go b/internal/core/stages.go index bf16098..0c1eef3 100644 --- a/internal/core/stages.go +++ b/internal/core/stages.go @@ -1,6 +1,9 @@ package core -import "time" +import ( + "strings" + "time" +) type Patch struct { Files []string @@ -15,8 +18,16 @@ type Patch struct { Landed map[string]string `json:",omitempty"` } +// The phases a step belongs to. +const ( + PhaseInstall = "install" + PhaseBuild = "build" + PhaseTest = "test" +) + type Step struct { Cmd string + Phase string `json:",omitempty"` // install|build|test; "" in runs recorded before phases were Exit int Took time.Duration Tail string // first failure and last 40 lines of combined output @@ -59,7 +70,8 @@ type Proof struct { Base *Run // nil when the baseline could not run Patched *Run Container string - Nothing bool // no build or test command exists for this project + Nothing bool // no build or test command exists for this project + Runtimes []string `json:",omitempty"` // what the commands ran on: "node v22.23.4", "go1.26.0" } type Finding struct { @@ -76,3 +88,60 @@ type Vetting struct { Changed bool // vet modified the worktree; proof must be re-run Verdict string // pass|draft|reject } + +// Proven says whether the patched tree did its part: it passes, or the base +// already fails and the patch stops at the very step the base stops at, after +// the base reached its tests, and with no new way of failing there. The PR +// for the second goes out as a draft. A base that dies before any test runs +// proves nothing about a change. +func (p *Proof) Proven() bool { + if p.Patched != nil && p.Patched.Pass { + return true + } + if p.Base == nil || p.Base.Pass || p.Patched == nil || !p.Base.Tested() { + return false + } + fp, fb := p.Patched.Last(), p.Base.Last() + return fp != nil && fb != nil && fp.Cmd == fb.Cmd && p.Patched.reached() == p.Base.reached() && !newFailure(fb.Tail, fp.Tail) +} + +// Tested says whether a test step of r ran, passing or not. A run recorded +// before steps had phases counts as tested. +func (r *Run) Tested() bool { + if r == nil { + return false + } + phased := false + for _, st := range r.Steps { + phased = phased || st.Phase != "" + if st.Phase == PhaseTest && st.Skipped == "" { + return true + } + } + return !phased && len(r.Steps) > 0 +} + +// reached is how many steps of a run passed before the first that failed. +func (r *Run) reached() int { + for i, st := range r.Steps { + if st.Skipped != "" || st.Exit != 0 { + return i + } + } + return len(r.Steps) +} + +// resolveFailures are what a dependency resolver prints when the set it was +// given cannot be installed together. +var resolveFailures = []string{"ResolutionImpossible", "Cannot install", "ERESOLVE", "version solving failed", "Could not find a version that satisfies", "conflicting dependencies"} + +// newFailure says whether the patched run's output shows a resolver failure +// the base's does not: the patch broke the install in a way of its own. +func newFailure(base, patched string) bool { + for _, m := range resolveFailures { + if strings.Contains(patched, m) && !strings.Contains(base, m) { + return true + } + } + return false +} diff --git a/internal/core/stages_test.go b/internal/core/stages_test.go new file mode 100644 index 0000000..48b63f2 --- /dev/null +++ b/internal/core/stages_test.go @@ -0,0 +1,43 @@ +package core + +import "testing" + +func TestProven(t *testing.T) { + run := func(pass bool, steps ...Step) *Run { return &Run{Pass: pass, Steps: steps} } + install := Step{Cmd: "yarn install", Phase: PhaseInstall} + failed := func(s Step, tail string) Step { s.Exit, s.Tail = 1, tail; return s } + skipped := func(s Step) Step { s.Skipped = "previous step failed"; return s } + test := Step{Cmd: "yarn test", Phase: PhaseTest} + tests := []struct { + name string + proof Proof + want bool + }{ + {"passes", Proof{Patched: run(true, install, test)}, true}, + {"base fails before its tests", Proof{ + Base: run(false, failed(install, "sh: yarn: command not found"), skipped(test)), + Patched: run(false, failed(install, "sh: yarn: command not found"), skipped(test)), + }, false}, + {"base fails at its tests", Proof{ + Base: run(false, install, failed(test, "1 failing")), + Patched: run(false, install, failed(test, "1 failing")), + }, true}, + {"patch fails earlier", Proof{ + Base: run(false, install, failed(test, "1 failing")), + Patched: run(false, failed(install, "boom"), skipped(test)), + }, false}, + {"patch cannot resolve", Proof{ + Base: run(false, install, failed(test, "ImportError")), + Patched: run(false, install, failed(test, "ERROR: ResolutionImpossible")), + }, false}, + {"recorded before phases", Proof{ + Base: run(false, Step{Cmd: "make test", Exit: 2}), + Patched: run(false, Step{Cmd: "make test", Exit: 2}), + }, true}, + } + for _, tt := range tests { + if got := tt.proof.Proven(); got != tt.want { + t.Errorf("%s: Proven() = %v, want %v", tt.name, got, tt.want) + } + } +} diff --git a/internal/deliver/body.go b/internal/deliver/body.go index 5dba2bd..66c80cd 100644 --- a/internal/deliver/body.go +++ b/internal/deliver/body.go @@ -5,6 +5,7 @@ import ( _ "embed" "fmt" "html" + "net/url" "regexp" "slices" "strconv" @@ -12,6 +13,7 @@ import ( "text/template" "time" + "github.com/mohsensc/tend-cli/internal/api" "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/ver" "github.com/mohsensc/tend-cli/internal/vet" @@ -73,9 +75,12 @@ func Body(in BodyInput) string { p.Due = "due" } if ch.Kind == core.First && ch.Batch != nil { - p.Welcome, p.Batch = welcome(ch.Batch), batched(in) + c := *ch + c.Batch = reached(ch.Batch, in.Patch) + in.Change = &c + p.Welcome, p.Batch = welcome(c.Batch), batched(in) if ch.ID != core.FirstID { - p.Welcome = intro(ch.Batch) + p.Welcome = intro(c.Batch) } if k := ch.Batch.Stage; k > 0 { p.Stage = strconv.Itoa(k) @@ -128,21 +133,30 @@ func render(p page) string { return b.String() } +var fenceRe = regexp.MustCompile("(?m)^( *)```") + // cut shortens a section to at most n bytes at a line break, closing what // the cut leaves open, and says where the rest is. func cut(s string, n int) string { const more = "\n\n_Cut to fit GitHub's limit on a PR body._" - n -= len(more) + len("\n```\n") + pad := 0 + for _, m := range fenceRe.FindAllStringSubmatch(s, -1) { + pad = max(pad, len(m[1])) + } + n -= len(more) + len("\n") + 1 + pad + len(ticks(s, 3)) if n <= 0 { return strings.TrimPrefix(more, "\n\n") } if i := strings.LastIndexByte(s[:min(n, len(s))], '\n'); i > 0 { s = s[:i] } else { - s = s[:min(n, len(s))] + s = core.Clip(s, n) + if i := strings.LastIndexByte(s, '&'); i >= 0 && !strings.Contains(s[i:], ";") { + s = s[:i] + } } - if strings.Count(s, "```")%2 == 1 { - s += "\n```" + if fence := unclosed(s); fence != "" { + s += "\n" + fence } if strings.Count(s, "
") > strings.Count(s, "
") { s += "\n" @@ -150,6 +164,27 @@ func cut(s string, n int) string { return s + more } +// unclosed is the line that closes the code fence s ends inside, indented +// as the fence that opened it so it closes in the same list item, "" when s +// ends outside any fence. +func unclosed(s string) string { + open, pad := "", "" + for _, l := range strings.Split(s, "\n") { + t := strings.TrimLeft(l, " ") + run := t[:len(t)-len(strings.TrimLeft(t, "`"))] + switch { + case open == "" && len(run) >= 3: + open, pad = run, l[:len(l)-len(t)] + case open != "" && len(run) >= len(open) && strings.TrimSpace(t) == run: + open = "" + } + } + if open == "" { + return "" + } + return pad + open +} + // tail keeps the end of a step's output, where the failure is. func tail(s string, n int) string { if len(s) <= n { @@ -202,7 +237,7 @@ func ParseMarker(body string) (id, base string, rev int, ok bool) { func heading(ch *core.Change) string { if a := ch.API; a != nil { - return strings.TrimSpace(a.Provider + " " + strings.TrimSpace(strings.ToUpper(a.Method)+" "+a.Path)) + return strings.TrimSpace(api.Title(a.Provider) + " " + strings.TrimSpace(strings.ToUpper(a.Method)+" "+a.Path)) } if len(ch.Deps) == 0 { return ch.ID @@ -287,30 +322,122 @@ func reason(in BodyInput) string { if a := ch.API; a != nil { s := a.What if a.Field != "" { - s += " (" + a.Field + ")" + s += " (" + prose(oneLine(a.Field, 120)) + ")" } return s } if m := in.Meta; m != nil && len(ch.Deps) > 0 { if m.Deprecated != "" { - return oneLine(m.Deprecated, 120) + return prose(oneLine(m.Deprecated, 120)) } for _, r := range m.Releases { if r.Version == ch.Deps[0].Version && r.Deprecated != "" { - return oneLine(r.Deprecated, 120) + return prose(oneLine(r.Deprecated, 120)) } } } if len(ch.Evidence) > 0 && ch.Evidence[0].Title != "" { - return oneLine(ch.Evidence[0].Title, 120) + return prose(oneLine(ch.Evidence[0].Title, 120)) } return "deprecated" } +var ( + closingRe = regexp.MustCompile(`(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b|\bgh-\d`) + proseEscape = map[rune]string{ + '<': "<", '>': ">", '&': "&", '"': """, '\'': "'", + '\\': `\\`, '`': "\\`", '*': `\*`, '_': `\_`, '[': `\[`, ']': `\]`, + '~': `\~`, '|': `\|`, + } +) + +const zeroWidth = "​" + +// prose makes text from upstream safe to show as Markdown outside a fence: +// it renders as written, but cannot open a tag, an image or a link, mention +// anyone, point at an issue, or close one when the PR merges. A code span +// stays one, since nothing in it does any of that. +func prose(s string) string { + s = strings.ReplaceAll(s, "\x00", "") + var b strings.Builder + for s != "" { + i := strings.IndexByte(s, '`') + if i < 0 { + b.WriteString(plain(s)) + break + } + b.WriteString(plain(s[:i])) + s = s[i:] + run := s[:len(s)-len(strings.TrimLeft(s, "`"))] + if end := closer(s[len(run):], run); end >= 0 { + n := len(run) + end + len(run) + b.WriteString(s[:n]) + s = s[n:] + continue + } + b.WriteString(strings.Repeat("\\`", len(run))) + s = s[len(run):] + } + return b.String() +} + +// closer is where the backtick run that closes a code span opened by run +// starts in s, -1 when nothing closes it. +func closer(s, run string) int { + for at := 0; at < len(s); { + i := strings.IndexByte(s[at:], '`') + if i < 0 { + return -1 + } + i += at + n := len(s[i:]) - len(strings.TrimLeft(s[i:], "`")) + if n == len(run) { + return i + } + at = i + n + } + return -1 +} + +func plain(s string) string { + s = closingRe.ReplaceAllStringFunc(s, func(m string) string { + return m[:1] + "\x00" + m[1:] + }) + var b strings.Builder + for i, c := range s { + switch { + case c == 0: + b.WriteString(zeroWidth) + case proseEscape[c] != "": + b.WriteString(proseEscape[c]) + case c == '@': + b.WriteString("@" + zeroWidth) + case c == '#' && i+1 < len(s) && s[i+1] >= '0' && s[i+1] <= '9': + b.WriteString("#" + zeroWidth) + default: + b.WriteRune(c) + } + } + return b.String() +} + +// link is u as the target of a Markdown link, "" for anything but a web URL. +func link(u string) string { + p, err := url.Parse(strings.TrimSpace(u)) + if err != nil || p.Scheme != "http" && p.Scheme != "https" || p.Host == "" { + return "" + } + return strings.NewReplacer(" ", "%20", "(", "%28", ")", "%29", "<", "%3C", ">", "%3E").Replace(p.String()) +} + func oneLine(s string, n int) string { s = strings.Join(strings.Fields(s), " ") if len(s) > n { - s = strings.TrimSpace(core.Clip(s, n)) + "…" + c := core.Clip(s, n) + if i := strings.LastIndexByte(c, ' '); i > 0 && len(c)-i <= 20 { + c = c[:i] + } + s = strings.TrimSpace(c) + "…" } return s } @@ -325,7 +452,7 @@ func level(in BodyInput) string { to, ok2 := ver.Parse(ch.To) if ok1 && ok2 { if ch.Level == "major" { - res = fmt.Sprintf("major (%d → %d)", from.Major(), to.Major()) + res = fmt.Sprintf("major (%s → %s)", from.Line(), to.Line()) } else { res = fmt.Sprintf("%s (%s → %s)", ch.Level, ch.Deps[0].Version, ch.To) } @@ -391,13 +518,13 @@ func evidence(e core.Evidence) string { if name == "" { name = e.Source } - b.WriteString("- **" + name + "**") - if e.URL != "" { + b.WriteString("- **" + prose(oneLine(name, 200)) + "**") + if u := link(e.URL); u != "" { label := "source" if isNotes(e) { label = "full notes" } - b.WriteString(" · [" + label + "](" + e.URL + ")") + b.WriteString(" · [" + label + "](" + u + ")") } lines := textLines(e.Text) if len(lines) == 0 { @@ -433,7 +560,8 @@ func ticks(s string, n int) string { } // fenced wraps s in a code fence longer than any backtick run inside it, so -// upstream text cannot close the block, link, or mention anyone. +// upstream text cannot close the block, link, or mention anyone. Text from +// upstream outside a fence goes through prose. func fenced(s string) string { fence := ticks(s, 3) return fence + "\n" + s + "\n" + fence @@ -570,25 +698,41 @@ func goMoved(ch *core.Change, diff string) string { if len(ch.Deps) == 0 || ch.Deps[0].Ecosystem != core.Go { return "" } - var file, old, now string + file, old, now := goLineMoved(diff) + if file == "" { + return "" + } + return fmt.Sprintf("The go line in %s moved from %s to %s, as %s %s requires, so building this module now takes Go %s or later.", code(file), old, now, ch.Deps[0].Name, ch.To, now) +} + +// goLineMoved finds a go.mod whose go line the diff moves, and from what to +// what; file is "" when none does. +func goLineMoved(diff string) (file, old, now string) { + at := "" for _, l := range strings.Split(diff, "\n") { if rest, ok := strings.CutPrefix(l, "diff --git a/"); ok { - file, _, _ = strings.Cut(rest, " b/") + if old != "" && now != "" && old != now { + return file, old, now + } + at, _, _ = strings.Cut(rest, " b/") continue } - if file != "go.mod" && !strings.HasSuffix(file, "/go.mod") { + if at != "go.mod" && !strings.HasSuffix(at, "/go.mod") { continue } - if m := goDirective.FindStringSubmatch(l); m != nil && m[1] == "-" { - old = m[2] - } else if m != nil { - now = m[2] + if m := goDirective.FindStringSubmatch(l); m != nil { + file = at + if m[1] == "-" { + old = m[2] + } else { + now = m[2] + } } } if old == "" || now == "" || old == now { - return "" + return "", "", "" } - return fmt.Sprintf("The go line in %s moved from %s to %s, as %s %s requires, so building this module now takes Go %s or later.", code(file), old, now, ch.Deps[0].Name, ch.To, now) + return file, old, now } func siteLine(s core.Site, after []string) string { @@ -710,11 +854,30 @@ func proof(in BodyInput) string { if s := verdictLine(in); s != "" { b.WriteString("\n\n" + s) } + if s := stale(in.Patch); s != "" { + b.WriteString("\n\n" + s) + } + if in.Change != nil && in.Change.Batch != nil && in.Change.Batch.Thin != "" && in.Change.Batch.Baseline == nil { + bt := in.Change.Batch + b.WriteString("\n\nThe project's tests are thin (" + Clause(bt.Thin) + "), and tend could not add a baseline, so this proof shows that the change builds and the existing tests pass, not that the changed code behaves the same.") + } if s := pr.Container; s != "" { b.WriteString("\n\nRan in container " + code(s) + ".") } - if st := tailStep(pr.Patched); st != nil { - fmt.Fprintf(&b, "\n\n
%s (patched), end of its output\n\n%s\n
", html.EscapeString(st.Cmd), fenced(tail(clean(st.Tail), tailMax))) + if len(pr.Runtimes) > 0 { + b.WriteString("\n\nRan on " + and(pr.Runtimes) + ".") + if s := offPin(in.Change, pr.Runtimes); s != "" { + b.WriteString(" " + s) + } + } + st, which := tailStep(pr.Patched), "patched" + if pr.Patched != nil && pr.Patched.Pass && pr.Base != nil && !pr.Base.Pass { + if f := failedStep(pr.Base); f != nil && strings.TrimSpace(f.Tail) != "" { + st, which = f, "base" + } + } + if st != nil { + fmt.Fprintf(&b, "\n\n
%s (%s), end of its output\n\n%s\n
", html.EscapeString(st.Cmd), which, fenced(tail(clean(st.Tail), tailMax))) } return b.String() } @@ -787,7 +950,14 @@ func verdictLine(in BodyInput) string { decision := in.Patch != nil && in.Patch.Decision switch { case pr.Base != nil && !pr.Base.Pass: - return "Tests already fail on " + at + ", so this PR is a draft." + what := "Tests already fail" + if f := failedStep(pr.Base); f != nil { + what = code(f.Cmd) + " already fails" + if pr.Patched != nil && pr.Patched.Pass { + return code(f.Cmd) + " fails on " + at + " and passes with this change, so this PR is a draft until a person confirms it." + } + } + return what + " on " + at + ", so this PR is a draft." case decision && pr.Patched != nil && !pr.Patched.Pass: return "The patched column is what tend tried before deciding to ask; its failing output is below." case pr.Patched != nil && !pr.Patched.Pass: @@ -798,6 +968,63 @@ func verdictLine(in BodyInput) string { return "" } +// runtimeNames are the runtimes a proof reports, by the toolchain dep that +// pins them. +var runtimeNames = map[string]string{"nodejs": "node", "node": "node", "python": "python", "go": "go"} + +// offPin warns when a change moves a runtime pin to a major the proof did +// not run on: .nvmrc moves to 26, and the runner has node 22. +func offPin(ch *core.Change, ran []string) string { + if ch == nil || len(ch.Deps) == 0 || ch.Deps[0].Ecosystem != core.Toolchain || ch.To == "" { + return "" + } + name := runtimeNames[ch.Deps[0].Name] + want, ok := ver.Parse(ch.To) + if name == "" || !ok { + return "" + } + for _, r := range ran { + v, found := strings.CutPrefix(r, name+" ") + got, ok := ver.Parse(strings.TrimPrefix(v, "v")) + if !found || !ok || got.Major() == want.Major() && (got.Major() > 0 || got.Line() == want.Line()) { + continue + } + return fmt.Sprintf("The pin moves to %s, but the proof ran on %s; set `verify.container`, or a setup step in CI, to prove it on %s.", ch.To, r, ch.To) + } + return "" +} + +// stale says which lockfiles the patch could not regenerate, from the notes +// its bumps left: the manifest moved, its lockfile did not. +func stale(p *core.Patch) string { + if p == nil { + return "" + } + var notes []string + for _, l := range p.Applied { + if n, ok := strings.CutPrefix(l, "lockfile not regenerated, "); ok && n != "no lockfile" { + notes = append(notes, n) + } + } + if len(notes) == 0 { + return "" + } + return "The lockfile was not regenerated (" + strings.Join(notes, "; ") + "), so it may not match the manifest; an install that insists on the lockfile can fail until it is." +} + +// failedStep is the step r failed at, nil when none did. +func failedStep(r *core.Run) *core.Step { + if r == nil { + return nil + } + for i := range r.Steps { + if s := &r.Steps[i]; s.Skipped == "" && s.Exit != 0 { + return s + } + } + return nil +} + func tailStep(r *core.Run) *core.Step { if r == nil { return nil diff --git a/internal/deliver/body_test.go b/internal/deliver/body_test.go index 03f22e3..11f6cbf 100644 --- a/internal/deliver/body_test.go +++ b/internal/deliver/body_test.go @@ -157,6 +157,25 @@ func TestBodyGoldens(t *testing.T) { Base: "abc1234", BaseRef: "main", Rev: 1, }, }, + { + name: "deprecation_hostile", + in: BodyInput{ + Change: &core.Change{ + ID: "npm/stripe@16.0.1", Kind: core.Deprecation, + Deps: []core.Dep{dep("npm", "stripe", "16.0.0")}, To: "16.0.1", + Evidence: []core.Evidence{ + {Source: "releases", Title: "v16.0.1 cc @octocat fixes #1 ![x](https://evil.example/p.png)", URL: "https://x/y", Text: "Closes #9, thanks @someone"}, + {Source: "releases", Title: "", "<!-- a & b -->"}, + {"![x](https://e.x/p.png)", `!\[x\](https://e.x/p.png)`}, + {"*a* _b_ ~c~ a|b \\", `\*a\* \_b\_ \~c\~ a\|b \\`}, + {"run `npm test` @here", "run `npm test` @​here"}, + {"a ``x ` @y`` b", "a ``x ` @y`` b"}, + {"open ` @x", "open \\` @​x"}, + {"nul\x00l", "null"}, + } + for _, tc := range tests { + if got := prose(tc.in); got != tc.want { + t.Errorf("prose(%q) = %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestLink(t *testing.T) { + tests := map[string]string{ + "https://github.com/a/b/releases/tag/v1": "https://github.com/a/b/releases/tag/v1", + "http://example.test/notes (v2)": "http://example.test/notes%20%28v2%29", + "javascript:alert(1)": "", + "/relative/path": "", + "https://": "", + "ftp://example.test/x": "", + } + for in, want := range tests { + if got := link(in); got != want { + t.Errorf("link(%q) = %q, want %q", in, got, want) + } + } +} + +// fenceOpen reports whether s ends inside a code fence, by the rules GitHub +// renders with: a fence closes on a run at least as long, in the same list +// item. +func fenceOpen(s string) bool { + open, pad := "", -1 + for _, l := range strings.Split(s, "\n") { + t := strings.TrimLeft(l, " ") + run := t[:len(t)-len(strings.TrimLeft(t, "`"))] + switch { + case open == "" && len(run) >= 3: + open, pad = run, len(l)-len(t) + case open != "" && len(run) >= len(open) && strings.TrimSpace(t) == run && len(l)-len(t) >= pad: + open = "" + case open != "" && pad > 0 && strings.TrimSpace(l) != "" && len(l)-len(t) < pad: + return true + } + } + return open != "" +} + +func TestBodyCutClosesFences(t *testing.T) { + for _, text := range []string{"run ```go test``` first", "plain notes, nothing fenced"} { + t.Run(text, func(t *testing.T) { + ch := &core.Change{ID: "npm/a@2.0.0", Kind: core.Update, Level: "major", To: "2.0.0", Deps: []core.Dep{dep("npm", "a", "1.0.0")}} + for i := range 40 { + var notes []string + for j := range 6 { + notes = append(notes, fmt.Sprintf("%d.%d %s %s", i, j, text, strings.Repeat("z", 1000))) + } + ch.Evidence = append(ch.Evidence, core.Evidence{Source: "releases", Title: fmt.Sprintf("v1.%d.0", i), Text: strings.Join(notes, "\n")}) + } + body := Body(BodyInput{Change: ch, Patch: &core.Patch{Files: []string{"package.json"}}, Base: "abc1234", Rev: 1}) + if len(body) > bodyMax || !strings.Contains(body, "Cut to fit") { + t.Fatalf("body is %d bytes, cut: %v", len(body), strings.Contains(body, "Cut to fit")) + } + upto, _, _ := strings.Cut(body, "_Cut to fit") + if fenceOpen(upto) { + t.Errorf("the cut leaves a fence open:\n%s", upto[max(0, len(upto)-300):]) + } + if fenceOpen(body) { + t.Error("the footer and marker render as code") + } + }) + } +} + +func TestCutKeepsEntitiesWhole(t *testing.T) { + s := strings.Repeat("a", 200) + "​" + strings.Repeat("b", 200) + for n := 150; n < 300; n++ { + got, _, _ := strings.Cut(cut(s, n), "\n\n_Cut") + if i := strings.LastIndexByte(got, '&'); i >= 0 && !strings.Contains(got[i:], ";") { + t.Fatalf("cut(%d) splits an entity: %q", n, got[i:]) + } + } +} + func TestBodyFits(t *testing.T) { var out strings.Builder for i := range 40 { @@ -698,3 +838,39 @@ func TestOneLineKeepsRunesWhole(t *testing.T) { t.Errorf("oneLine = %q", got) } } + +func TestOneLineCutsAtAWord(t *testing.T) { + if got := oneLine("the newest release its ranges allow", 26); got != "the newest release its…" { + t.Errorf("oneLine = %q", got) + } +} + +func TestStaleLockfile(t *testing.T) { + pt := &core.Patch{Applied: []string{"bumped joi 17.0.0 -> 17.13.0 (package.json)", "lockfile not regenerated, yarn not found"}} + got := proof(BodyInput{Patch: pt, Proof: &core.Proof{Base: &core.Run{Pass: true}, Patched: &core.Run{Pass: true}}}) + if !strings.Contains(got, "The lockfile was not regenerated (yarn not found)") { + t.Errorf("proof = %s", got) + } + if stale(&core.Patch{Applied: []string{"bumped x"}}) != "" { + t.Error("a regenerated lockfile is called stale") + } +} + +func TestThinTestsSaid(t *testing.T) { + ch := &core.Change{ID: core.FirstID, Kind: core.First, Batch: &core.Batch{Stage: 1, Thin: "no test reaches `app.go`, which the catch-up changes"}} + got := proof(BodyInput{Change: ch, Proof: &core.Proof{Base: &core.Run{Pass: true}, Patched: &core.Run{Pass: true}}}) + if !strings.Contains(got, "The project's tests are thin (no test reaches `app.go`, which the catch-up changes), and tend could not add a baseline") { + t.Errorf("proof = %s", got) + } +} + +func TestOffPin(t *testing.T) { + ch := &core.Change{Kind: core.Deprecation, To: "26", Deps: []core.Dep{{Ecosystem: core.Toolchain, Name: "nodejs", Version: "18", Manifest: core.Manifest{Path: ".nvmrc"}}}} + got := proof(BodyInput{Change: ch, Proof: &core.Proof{Base: &core.Run{Pass: true}, Patched: &core.Run{Pass: true}, Runtimes: []string{"node v22.23.4"}}}) + if !strings.Contains(got, "Ran on node v22.23.4. The pin moves to 26, but the proof ran on node v22.23.4") { + t.Errorf("proof = %s", got) + } + if s := offPin(ch, []string{"node v26.9.0"}); s != "" { + t.Errorf("on the pinned major: %q", s) + } +} diff --git a/internal/deliver/close.go b/internal/deliver/close.go index b6e3df0..264e1c8 100644 --- a/internal/deliver/close.go +++ b/internal/deliver/close.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strings" + "time" "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/plan" @@ -13,10 +14,11 @@ import ( // one without state, tells tend's own closing from a maintainer's. const closedByTend = "" -// Closer is a forge that can say who closed a PR. +// Closer is a forge that can say who closed a PR, and when. type Closer interface { - // ClosedBy is the login that closed PR number, "" when the forge does not say. - ClosedBy(ctx context.Context, number int) (string, error) + // ClosedBy is the login that closed PR number and when, "" and the zero + // time for what the forge does not say. + ClosedBy(ctx context.Context, number int) (string, time.Time, error) } // Close comments msg on the PR and closes it on tend's own account: to keep @@ -37,7 +39,9 @@ func Replaced(ctx context.Context, forge core.Forge, number, by int) error { // Declined reports whether pr was closed unmerged as a maintainer's no, which // outlives tend's own state: someone with write access commented `tend -// skip`, or a person, neither tend nor a bot, closed it. +// skip`, or a person, neither tend nor a bot, closed it. tend may run with a +// person's token, so the close is tend's when it came right after tend's +// closing comment, from the account that posted it. func Declined(ctx context.Context, forge core.Forge, pr *core.PR) (bool, error) { if pr == nil || pr.State != "closed" { return false, nil @@ -49,30 +53,34 @@ func Declined(ctx context.Context, forge core.Forge, pr *core.PR) (bool, error) if c, ok := plan.ParseCommand(cs); ok && c.Verb == "skip" { return true, nil } - if tendClosed(cs) { - return false, nil - } cl, ok := forge.(Closer) if !ok { - return true, nil + return !tendClosed(cs, "", time.Time{}), nil } - who, err := cl.ClosedBy(ctx, pr.Number) + who, at, err := cl.ClosedBy(ctx, pr.Number) if err != nil { return false, err } + if tendClosed(cs, who, at) { + return false, nil + } return who != "" && !plan.Bot(who), nil } -// tendClosed reports whether tend's closing comment is the last word on the -// PR. What bots say after it, a CI report say, does not change that. -func tendClosed(cs []core.Comment) bool { +// closeWindow is how long after its closing comment tend's close may land. +const closeWindow = 2 * time.Minute + +// tendClosed reports whether the close by who at at is tend's own: the last +// closing comment tend posted by then is who's, and came just before it. +// Who or at left unsaid matches any. What anyone says after the close does +// not change whose it was; a reopen and a later close does. +func tendClosed(cs []core.Comment, who string, at time.Time) bool { for i := len(cs) - 1; i >= 0; i-- { - if strings.Contains(cs[i].Body, closedByTend) { - return true - } - if !plan.Bot(cs[i].Author) { - return false + c := cs[i] + if !strings.Contains(c.Body, closedByTend) || !at.IsZero() && c.At.After(at) { + continue } + return (who == "" || strings.EqualFold(c.Author, who)) && (at.IsZero() || at.Sub(c.At) <= closeWindow) } return false } diff --git a/internal/deliver/close_test.go b/internal/deliver/close_test.go index 5745fa3..74deeb2 100644 --- a/internal/deliver/close_test.go +++ b/internal/deliver/close_test.go @@ -1,6 +1,9 @@ package deliver -import "testing" +import ( + "testing" + "time" +) func TestDeclined(t *testing.T) { tests := []struct { @@ -65,3 +68,49 @@ func TestDeclined(t *testing.T) { }) } } + +// tend running on a person's token closes as that person; a later comment, +// from anyone, does not make the close a maintainer's no. A maintainer who +// reopens and closes again, minutes on and without a word, does say no. +func TestDeclinedByTime(t *testing.T) { + tests := []struct { + name string + after func(f *FakeForge, tick func(time.Duration)) + want bool + }{ + {"tend's close, then a contributor's thanks", func(f *FakeForge, tick func(time.Duration)) { + tick(time.Hour) + noErr(t, f.Say(1, "contrib", "CONTRIBUTOR", "thanks")) + }, false}, + {"tend's close, then the token's own person comments", func(f *FakeForge, tick func(time.Duration)) { + tick(time.Hour) + noErr(t, f.Say(1, "alice", "OWNER", "ok")) + }, false}, + {"reopened and closed again without a word", func(f *FakeForge, tick func(time.Duration)) { + tick(time.Hour) + noErr(t, f.Reopen(1)) + tick(time.Hour) + noErr(t, f.CloseAs(1, "maintainer")) + }, true}, + {"reopened and closed again by the token's own person", func(f *FakeForge, tick func(time.Duration)) { + tick(time.Hour) + noErr(t, f.Reopen(1)) + tick(time.Hour) + noErr(t, f.CloseAs(1, "alice")) + }, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + now := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + f := NewFake("acme", "shop", "main") + f.Login, f.Now = "alice", func() time.Time { return now } + tendPR(t, f, "tend/npm-a-2.0.0", "npm/a@2.0.0") + noErr(t, Close(bg, f, 1, "Closing to make room for a security fix.")) + tt.after(f, func(d time.Duration) { now = now.Add(d) }) + got, err := Declined(bg, f, f.PR(1)) + if err != nil || got != tt.want { + t.Errorf("Declined = %v, %v; want %v", got, err, tt.want) + } + }) + } +} diff --git a/internal/deliver/fake.go b/internal/deliver/fake.go index 84a2220..92f358a 100644 --- a/internal/deliver/fake.go +++ b/internal/deliver/fake.go @@ -23,13 +23,15 @@ type FakeForge struct { CreateErr error // returned by the next CreatePR, once Peak int // the most PRs open at once CI map[string]core.CI // what CI made of a commit, by sha; none when missing + Login string // the account tend writes as, tend[bot] when empty mu sync.Mutex prs []*core.PR comments map[int][]core.Comment - closer map[int]string + closer map[int]closing nextID int64 issues []*core.Issue + made int } var ( @@ -50,10 +52,29 @@ func NewFake(owner, name, base string) *FakeForge { Merges: map[int]string{}, CI: map[string]core.CI{}, comments: map[int][]core.Comment{}, - closer: map[int]string{}, + closer: map[int]closing{}, } } +type closing struct { + login string + at time.Time +} + +func (f *FakeForge) login() string { + if f.Login != "" { + return f.Login + } + return tendLogin +} + +func (f *FakeForge) now() time.Time { + if f.Now != nil { + return f.Now() + } + return time.Time{} +} + func (f *FakeForge) Repo(ctx context.Context) (core.RepoInfo, error) { f.mu.Lock() defer f.mu.Unlock() @@ -147,6 +168,9 @@ func (f *FakeForge) CreatePR(ctx context.Context, in core.PRInput) (*core.PR, er func (f *FakeForge) UpdatePR(ctx context.Context, number int, in core.PRInput) error { return f.edit(number, func(pr *core.PR) error { pr.Title, pr.Body, pr.Draft = in.Title, in.Body, in.Draft + if in.Base != "" { + pr.Base = in.Base + } return nil }) } @@ -154,18 +178,18 @@ func (f *FakeForge) UpdatePR(ctx context.Context, number int, in core.PRInput) e func (f *FakeForge) ClosePR(ctx context.Context, number int) error { return f.edit(number, func(pr *core.PR) error { pr.State = "closed" - f.closer[number] = tendLogin + f.closer[number] = closing{f.login(), f.now()} return nil }) } -func (f *FakeForge) ClosedBy(ctx context.Context, number int) (string, error) { - var res string +func (f *FakeForge) ClosedBy(ctx context.Context, number int) (string, time.Time, error) { + var res closing err := f.edit(number, func(*core.PR) error { res = f.closer[number] return nil }) - return res, err + return res.login, res.at, err } func (f *FakeForge) Comments(ctx context.Context, number int) ([]core.Comment, error) { @@ -181,7 +205,7 @@ func (f *FakeForge) Comments(ctx context.Context, number int) ([]core.Comment, e } func (f *FakeForge) Comment(ctx context.Context, number int, body string) error { - return f.Say(number, tendLogin, "NONE", body) + return f.Say(number, f.login(), "NONE", body) } func (f *FakeForge) AutoMerge(ctx context.Context, pr *core.PR, method string) error { @@ -235,7 +259,7 @@ func (f *FakeForge) CloseAs(n int, login string) error { return fmt.Errorf("fake forge: #%d is %s", n, pr.State) } pr.State = "closed" - f.closer[n] = login + f.closer[n] = closing{login, f.now()} return nil }) } @@ -263,10 +287,7 @@ func (f *FakeForge) Say(n int, author, role, body string) error { return fmt.Errorf("fake forge: no PR #%d", n) } f.nextID++ - var at time.Time - if f.Now != nil { - at = f.Now() - } + at := f.now() f.comments[n] = append(f.comments[n], core.Comment{ID: f.nextID, Author: author, Role: role, Body: body, At: at}) return nil } @@ -324,7 +345,8 @@ func (f *FakeForge) CreateIssue(ctx context.Context, title, body string, labels if f.Err != nil { return nil, f.Err } - is := &core.Issue{Number: 1000 + len(f.issues), Title: title, Body: body, Open: true} + is := &core.Issue{Number: 1000 + f.made, Title: title, Body: body, Open: true} + f.made++ f.issues = append(f.issues, is) res := *is return &res, nil @@ -342,7 +364,14 @@ func (f *FakeForge) EditIssue(ctx context.Context, number int, body string, open return nil } } - return fmt.Errorf("fake forge: no issue #%d", number) + return fmt.Errorf("%w: fake forge: no issue #%d", ErrGone, number) +} + +// DeleteIssue removes issue n, as a maintainer who deletes or moves it would. +func (f *FakeForge) DeleteIssue(n int) { + f.mu.Lock() + defer f.mu.Unlock() + f.issues = slices.DeleteFunc(f.issues, func(is *core.Issue) bool { return is.Number == n }) } // Issues returns copies of every issue in creation order. Their numbers diff --git a/internal/deliver/first.go b/internal/deliver/first.go index 42e3912..35a6626 100644 --- a/internal/deliver/first.go +++ b/internal/deliver/first.go @@ -11,6 +11,7 @@ import ( "github.com/mohsensc/tend-cli/internal/api" "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/plan" + "github.com/mohsensc/tend-cli/internal/ver" ) // FirstBranch is where tend's first PR on a repo lives, whatever it carries. @@ -50,6 +51,10 @@ var sections = []string{"Security", "API", "Deprecated", "Runtimes and tooling", // tally counts the changes a batch makes by what they are, in the order the // body lists them, then the dependencies it removes and the baseline it // adds. short counts every deprecation as one kind. +// Tally counts what a catch-up PR does as its title does: "2 end-of-life +// runtimes", "1 deprecated Action", "3 unused dependencies". +func Tally(b *core.Batch) []string { return tally(b, true) } + func tally(b *core.Batch, short bool) []string { var order []string n := map[string]int{} @@ -111,11 +116,18 @@ func noun(ch *core.Change) (string, string) { case ch.Deps[0].Min: return "runtime minimum", "runtime minimums" } - switch ch.Deps[0].Ecosystem { - case core.Toolchain, core.Docker: - return "end-of-life runtime", "end-of-life runtimes" - case core.Actions: + bump := ch.Kind == core.Breaking || ch.Kind == core.Update + switch e := ch.Deps[0].Ecosystem; { + case e == core.Actions && bump && ch.Level == "major": + return "major Action upgrade", "major Action upgrades" + case e == core.Actions && bump: + return "Action upgrade", "Action upgrades" + case e == core.Actions: return "deprecated Action", "deprecated Actions" + case (e == core.Toolchain || e == core.Docker) && bump: + return "runtime upgrade", "runtime upgrades" + case e == core.Toolchain || e == core.Docker: + return "end-of-life runtime", "end-of-life runtimes" } switch { case group(ch) == "Runtimes and tooling": @@ -164,6 +176,9 @@ func welcome(b *core.Batch) string { "The rest comes in "+count(more, "more pull request", "more pull requests")+", one stage at a time, listed under Next stages and each proven the same way.") case len(did) > 0: s = append(s, "This first pull request catches up in one go: "+and(did)+".") + case more > 0 && len(tried(b)) > 0: + s = append(s, "Its first look found "+and(tried(b))+", but none could be made and proven yet; each is listed below with why, so this pull request only adds a `tend.yml` with every key commented out.", + "The catch-up comes in "+count(more, "more pull request", "more pull requests")+", one stage at a time, listed under Next stages.") case more > 0: s = append(s, "Its first look found nothing to fix right away, so this pull request only adds a `tend.yml` with every key commented out.", "The catch-up comes in "+count(more, "more pull request", "more pull requests")+", one stage at a time, listed under Next stages.") @@ -185,6 +200,30 @@ func welcome(b *core.Batch) string { return strings.Join(s, " ") } +// tried counts what this stage tried to make and left out, by what it is. +func tried(b *core.Batch) []string { + var order []string + n := map[string]int{} + many := map[string]string{} + for i := range b.Next { + l := &b.Next[i] + if l.Why == "" || plan.Tier(&l.Change) > b.Stage { + continue + } + one, more := noun(&l.Change) + if n[one] == 0 { + order = append(order, one) + } + n[one]++ + many[one] = more + } + var res []string + for _, one := range order { + res = append(res, count(n[one], one, many[one])) + } + return res +} + // intro opens a catch-up PR after the first: which stage it is, what it // does and what is left. func intro(b *core.Batch) string { @@ -261,6 +300,11 @@ func batched(in BodyInput) string { parts = append(parts, "### "+s+"\n\n"+strings.Join(lines, "\n")) } } + if p != nil { + if file, old, now := goLineMoved(p.Diff); file != "" { + parts = append(parts, fmt.Sprintf("The go line in %s moved from %s to %s, as the Go bumps above require, so building this module now takes Go %s or later.", code(file), old, now, now)) + } + } if s := unused(b); s != "" { parts = append(parts, "### Unused\n\n"+s) } @@ -273,6 +317,28 @@ func batched(in BodyInput) string { return strings.Join(parts, "\n\n") } +// reached is b without the later changes its patch already made on the way: +// a go line a bump raised past the go change a later stage would make. +func reached(b *core.Batch, p *core.Patch) *core.Batch { + if p == nil { + return b + } + file, _, now := goLineMoved(p.Diff) + if file == "" { + return b + } + res := *b + res.Next = slices.DeleteFunc(slices.Clone(b.Next), func(l core.Later) bool { + ch := &l.Change + if len(ch.Deps) != 1 || ch.To == "" { + return false + } + d := ch.Deps[0] + return d.Ecosystem == core.Toolchain && d.Name == "go" && d.Manifest.Path == file && !ver.Less(now, ch.To) + }) + return &res +} + // baseline says why the PR adds tests first and what they are. func baseline(in BodyInput) string { bl := in.Change.Batch.Baseline @@ -381,7 +447,7 @@ func moved(ch *core.Change) string { s := named(ch, ch.To) switch ch.Deps[0].Ecosystem { case core.Toolchain, core.Docker, core.Actions: - s += " in " + code(ch.Deps[0].Manifest.Path) + s += where(ch) } if len(ch.Via) > 0 { s += ", by way of " + and(ch.Via) + ", each proven" @@ -403,12 +469,12 @@ func moved(ch *core.Change) string { func because(ch *core.Change) string { for _, ev := range ch.Evidence { if (ev.Source == "registry" || ev.Source == "archived") && ev.Text != "" { - return ": " + oneLine(ev.Text, 160) + return ": " + prose(oneLine(ev.Text, 160)) } } for _, ev := range ch.Evidence { if ev.Title != "" { - return ": " + oneLine(ev.Title, 160) + return ": " + prose(oneLine(ev.Title, 160)) } } return "" @@ -479,15 +545,118 @@ func stages(b *core.Batch) string { lines := []string{"Each comes as a pull request of its own once this one is merged, proven the same way.", ""} for _, k := range ks { lines = append(lines, strconv.Itoa(k)+". "+upper(plan.StageName(k))) + var carried, own []core.Later for _, l := range b.Next { - if l.Stage == k { - lines = append(lines, " - "+later(l)) + switch { + case l.Stage != k: + case l.Why != "" && plan.Tier(&l.Change) < k: + carried = append(carried, l) + default: + own = append(own, l) } } + if len(carried) > 0 { + lines = append(lines, " - Carried over from an earlier stage, where they could not be made or proven, and tried again here:") + for _, l := range laters(carried) { + lines = append(lines, " - "+l) + } + } + for _, l := range laters(own) { + lines = append(lines, " - "+l) + } } return strings.Join(lines, "\n") } +// laterMax is how many packages one line of left-out changes names that +// failed for the same reason. +const laterMax = 8 + +// laters lists left-out changes: those of one package together, and three +// or more that failed for one reason, the package's name aside, as one line. +func laters(ls []core.Later) []string { + ls = samePackage(ls) + type bunch struct { + why string + items []core.Later + } + var bunches []*bunch + at := map[string]*bunch{} + for _, l := range ls { + k := reasonOf(l) + if k == "" { + bunches = append(bunches, &bunch{items: []core.Later{l}}) + continue + } + if at[k] == nil { + at[k] = &bunch{why: k} + bunches = append(bunches, at[k]) + } + at[k].items = append(at[k].items, l) + } + var res []string + for _, g := range bunches { + if len(g.items) < 3 { + for _, l := range g.items { + res = append(res, later(l)) + } + continue + } + var names []string + for _, l := range g.items[:min(len(g.items), laterMax)] { + names = append(names, named(&l.Change, l.Change.To)) + } + line := upper(strings.ReplaceAll(g.why, pkgMark, "each")) + fmt.Sprintf(" (%d packages): ", len(g.items)) + strings.Join(names, ", ") + if n := len(g.items) - laterMax; n > 0 { + line += fmt.Sprintf(" and %d more", n) + } + res = append(res, line+".") + } + return res +} + +const pkgMark = "\x00" + +// reasonOf is why l was left out with its own package's name taken out, so +// reasons that differ only by it match; "" when l has no reason. +func reasonOf(l core.Later) string { + why := prose(oneLine(Clause(l.Why), 200)) + if why == "" || len(l.Change.Deps) == 0 { + return "" + } + for _, n := range core.Names(&l.Change) { + why = strings.ReplaceAll(why, n, pkgMark) + } + return strings.TrimSuffix(why, ".") +} + +// samePackage folds left-out changes that move one package of one manifest +// to different releases into the first of them, which names both targets. +func samePackage(ls []core.Later) []core.Later { + var res []core.Later + at := map[string]int{} + for _, l := range ls { + names := core.Names(&l.Change) + if l.Change.API != nil || len(names) != 1 || l.Change.To == "" { + res = append(res, l) + continue + } + d := l.Change.Deps[0] + k := fmt.Sprintf("%s/%s %s %v", d.Ecosystem, names[0], d.Manifest.Path, d.Min) + i, ok := at[k] + if !ok { + at[k] = len(res) + res = append(res, l) + continue + } + first := &res[i] + if ver.Less(first.Change.To, l.Change.To) { + first.Why = strings.TrimSuffix(cmp.Or(first.Why, what(&first.Change)), ".") + "; " + l.Change.To + " after it: " + strings.TrimSuffix(cmp.Or(l.Why, what(&l.Change)), ".") + } + } + return res +} + // undone lists what a batch left out with nowhere left to go: the catch-up // ends without it, and it comes back one change at a time. func undone(b *core.Batch) string { @@ -516,11 +685,15 @@ func later(l core.Later) string { s = code(ch.ID) default: s = named(ch, ch.To) - if m := ch.Deps[0].Manifest.Path; m != "" && len(core.Names(ch)) == 1 { - s += " in " + code(m) + switch d := ch.Deps[0]; { + case len(core.Names(ch)) != 1: + case !d.Direct && d.Manifest.Lock != "": + s += " (transitive, in " + code(d.Manifest.Lock) + ")" + default: + s += where(ch) } } - why := oneLine(Clause(l.Why), 200) + why := prose(oneLine(Clause(l.Why), 200)) if why == "" { why = strings.TrimSuffix(what(ch), ".") } @@ -538,6 +711,28 @@ func later(l core.Later) string { return line } +// where names the files a change moves its deps in: " in `a`", " in `a` +// and `b`", or for many " in 5 files". +func where(ch *core.Change) string { + var files []string + for _, d := range ch.Deps { + if p := d.Manifest.Path; p != "" && !slices.Contains(files, p) { + files = append(files, p) + } + } + switch { + case len(files) == 0: + return "" + case len(files) > 3: + return fmt.Sprintf(" in %d files", len(files)) + } + var named []string + for _, f := range files { + named = append(named, code(f)) + } + return " in " + and(named) +} + // what says what a change waiting for a later stage is. func what(ch *core.Change) string { switch { @@ -548,8 +743,8 @@ func what(ch *core.Change) string { return "a new " + ch.Level + " release" } return "a new release" - case len(core.Calls(ch)) > plan.Spread: - return fmt.Sprintf("a migration of %d call sites", len(core.Calls(ch))) + case plan.MovesCode(ch) && core.Lines(core.Calls(ch)) > plan.Spread: + return fmt.Sprintf("a migration of %d call sites", core.Lines(core.Calls(ch))) case len(ch.Deps) > 0 && ch.Deps[0].Min: return "the oldest " + ch.Deps[0].Name + " the project supports, past its end of life" case ch.To == "" && ch.ToName == "" && len(ch.Options) == 0: @@ -604,9 +799,10 @@ func Clause(s string) string { // Displaced reports whether pr was closed by tend to make room, for a // security fix, for the first PR or to keep one PR open, rather than -// declined: it comes back. It reads a close the way Declined does, so a word -// someone leaves on the PR after tend closed it does not turn the close into -// theirs. +// declined: it comes back. It reads a close the way Declined does: by who +// closed it and when, so a word someone leaves after tend closed it does +// not turn the close into theirs, even when tend runs with a person's +// token, while a maintainer who reopens and closes it again declines it. func Displaced(ctx context.Context, forge core.Forge, pr *core.PR) (bool, error) { if pr == nil || pr.State != "closed" { return false, nil diff --git a/internal/deliver/first_test.go b/internal/deliver/first_test.go index 6b27147..ff9ee6c 100644 --- a/internal/deliver/first_test.go +++ b/internal/deliver/first_test.go @@ -107,3 +107,83 @@ func TestHadPR(t *testing.T) { t.Errorf("a fork's PR: HadPR = %v, %v", had, err) } } + +func TestFirstTitleActionUpgrade(t *testing.T) { + checkout := core.Change{Kind: core.Breaking, Level: "major", To: "v7", Deps: []core.Dep{{Ecosystem: core.Actions, Name: "actions/checkout", Version: "v1", Direct: true, Manifest: core.Manifest{Path: ".github/workflows/ci.yml"}}}} + if got := firstTitle(&core.Batch{Stage: 2, Changes: []core.Change{checkout}}); got != "Catch up: 1 major Action upgrade" { + t.Errorf("title = %q", got) + } +} + +// Security fixes an earlier stage could not make are listed apart from the +// stage's own changes, those that failed alike on one line, with the +// lockfile a transitive one sits in. +func TestStagesCarried(t *testing.T) { + m := core.Manifest{Ecosystem: core.Npm, Path: "package.json", Lock: "yarn.lock"} + b := &core.Batch{Stage: 1} + for i := range 40 { + name := fmt.Sprintf("pkg%02d", i) + ch := core.Change{Kind: core.Security, To: "1.0.1", Deps: []core.Dep{{Ecosystem: core.Npm, Name: name, Version: "1.0.0", Manifest: m}}} + b.Next = append(b.Next, core.Later{Change: ch, Stage: 2, Why: "making it next to the rest fails: yarn v1 cannot update " + name + " alone"}) + } + mongoose := core.Dep{Ecosystem: core.Npm, Name: "mongoose", Version: "5.13.20", Direct: true, Manifest: m} + b.Next = append(b.Next, + core.Later{Change: core.Change{Kind: core.Breaking, Level: "major", To: "6.13.10", Deps: []core.Dep{mongoose}}, Stage: 3}, + core.Later{Change: core.Change{Kind: core.Breaking, Level: "major", To: "9.11.4", Deps: []core.Dep{mongoose}}, Stage: 3}, + core.Later{Change: core.Change{Kind: core.Deprecation, To: "22", Deps: []core.Dep{{Ecosystem: core.Toolchain, Name: "nodejs", Version: "16", Direct: true, Manifest: core.Manifest{Path: ".nvmrc"}}}}, Stage: 2}, + ) + got := stages(b) + carried := " - Carried over from an earlier stage, where they could not be made or proven, and tried again here:\n - Making it next to the rest fails: yarn v1 cannot update each alone (40 packages): `pkg00` 1.0.0 → 1.0.1" + if !strings.Contains(got, carried) || !strings.Contains(got, "and 32 more.") { + t.Errorf("stages:\n%s", got) + } + if strings.Index(got, "Carried over") > strings.Index(got, "`nodejs`") { + t.Errorf("carried fixes come after the stage's own:\n%s", got) + } + if strings.Count(got, "`mongoose`") != 1 || !strings.Contains(got, "; 9.11.4 after it: a new major release") { + t.Errorf("mongoose rows:\n%s", got) + } + one := later(core.Later{Change: b.Next[0].Change, Why: "x"}) + if !strings.Contains(one, "(transitive, in `yarn.lock`)") { + t.Errorf("later = %q", one) + } +} + +func TestWelcomeTriedAll(t *testing.T) { + ch := core.Change{Kind: core.Security, To: "6.0.1", Deps: []core.Dep{{Ecosystem: core.Pip, Name: "pyyaml", Version: "5.3", Direct: true}}} + b := &core.Batch{Stage: 1, Next: []core.Later{ + {Change: ch, Stage: 3, Why: "`poetry lock` fails (exit 1)"}, + {Change: core.Change{Kind: core.Breaking, Level: "major", To: "8.0.0", Deps: []core.Dep{{Ecosystem: core.Pip, Name: "pytest", Version: "6.0", Direct: true}}}, Stage: 3}, + }} + got := welcome(b) + if strings.Contains(got, "nothing to fix") || !strings.Contains(got, "found 1 security fix, but none could be made and proven yet") { + t.Errorf("welcome = %s", got) + } +} + +func TestWhere(t *testing.T) { + dep := func(p string) core.Dep { + return core.Dep{Ecosystem: core.Actions, Name: "actions/checkout", Manifest: core.Manifest{Path: p}} + } + ch := &core.Change{Deps: []core.Dep{dep(".github/workflows/a.yml"), dep(".github/workflows/b.yml"), dep(".github/workflows/a.yml")}} + if got := where(ch); got != " in `.github/workflows/a.yml` and `.github/workflows/b.yml`" { + t.Errorf("where = %q", got) + } +} + +// A security bump that raised the go line says so, and the later stage that +// would have raised it is gone. +func TestBatchGoLineMoved(t *testing.T) { + crypto := core.Change{Kind: core.Security, To: "v0.56.0", Deps: []core.Dep{{Ecosystem: core.Go, Name: "golang.org/x/crypto", Version: "v0.31.0", Direct: true, Manifest: core.Manifest{Path: "go.mod"}}}} + goline := core.Change{Kind: core.Deprecation, To: "1.26", Deps: []core.Dep{{Ecosystem: core.Toolchain, Name: "go", Version: "1.22", Min: true, Manifest: core.Manifest{Path: "go.mod"}}}} + teams := core.Change{Kind: core.Deprecation, API: &core.APIChange{Provider: "github", Method: "GET", Path: "/teams/{team_id}"}} + b := &core.Batch{Stage: 1, Changes: []core.Change{crypto}, Next: []core.Later{{Change: goline, Stage: 2}, {Change: teams, Stage: 2}}} + diff := "diff --git a/go.mod b/go.mod\n--- a/go.mod\n+++ b/go.mod\n@@ -1,3 +1,3 @@\n module x\n-go 1.22\n+go 1.26.0\n" + got := Body(BodyInput{Change: &core.Change{ID: core.FirstID, Kind: core.First, Batch: b}, Patch: &core.Patch{Diff: diff}, Base: "abc"}) + if !strings.Contains(got, "The go line in `go.mod` moved from 1.22 to 1.26.0") { + t.Errorf("no go line note:\n%s", got) + } + if strings.Contains(got, "`go` 1.22 → 1.26") || !strings.Contains(got, "/teams/{team_id}") { + t.Errorf("next stages:\n%s", got) + } +} diff --git a/internal/deliver/git.go b/internal/deliver/git.go index 42c264c..bcb81f3 100644 --- a/internal/deliver/git.go +++ b/internal/deliver/git.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/mohsensc/tend-cli/internal/gitx" "github.com/mohsensc/tend-cli/internal/verify" @@ -68,7 +69,7 @@ func (r *Remote) git(ctx context.Context, args ...string) (string, error) { if now != r.config { return "", errors.New("git: the repository's git settings changed while the project's commands ran, so tend will not reach the remote with them") } - out, err := (gitx.Cmd{Dir: r.repo, Env: r.auth()}).Run(ctx, args...) + out, err := (gitx.Cmd{Dir: r.repo, Env: r.auth(), Terminal: r.token == ""}).Run(ctx, args...) return strings.TrimSpace(out), err } @@ -99,6 +100,28 @@ func (r *Remote) Fetch(ctx context.Context, branch string) error { return err } +// Deepen makes sure a shallow clone, such as the one actions/checkout makes +// by default, has sha and the commit before it on branch's history. It first +// fetches what landed from a while before since, and when that is not +// enough, the whole history. A clone that is not shallow is left alone. +func (r *Remote) Deepen(ctx context.Context, branch, sha string, since time.Time) error { + if out, err := gitx.Run(ctx, r.repo, "rev-parse", "--is-shallow-repository"); err != nil || out != "true" { + return err + } + spec := "+refs/heads/" + branch + ":" + r.tracking(branch) + after := since.Add(-48 * time.Hour).UTC().Format("2006-01-02 15:04:05 +0000") + if _, err := r.git(ctx, "fetch", "--quiet", "--no-tags", "--shallow-since="+after, r.URL, spec); err == nil && r.has(ctx, sha+"^") { + return nil + } + _, err := r.git(ctx, "fetch", "--quiet", "--no-tags", "--unshallow", r.URL, spec) + return err +} + +func (r *Remote) has(ctx context.Context, rev string) bool { + _, err := gitx.Run(ctx, r.repo, "rev-parse", "--verify", "--quiet", rev+"^{commit}") + return err == nil +} + func (r *Remote) tracking(branch string) string { return "refs/remotes/" + r.Name + "/" + branch } // Push pushes HEAD of the worktree to refs/heads/. With force it @@ -161,6 +184,21 @@ func (r *Remote) expected(ctx context.Context, branch, last string) (string, err return have, nil } +// DeleteBranch removes branch from the remote while it still points at +// last, the commit tend pushed there: a branch someone pushed to since, or +// one tend does not know the tip of, stays. +func DeleteBranch(ctx context.Context, r *Remote, branch, last string) error { + if last == "" { + return errors.New("tend does not know the commit it last pushed there") + } + ref := "refs/heads/" + branch + if _, err := r.git(ctx, "push", "--force-with-lease="+ref+":"+last, r.URL, ":"+ref); err != nil { + return err + } + _, err := gitx.Run(ctx, r.repo, "update-ref", "-d", r.tracking(branch)) + return err +} + // BranchExists reports whether the remote has the branch. func BranchExists(ctx context.Context, r *Remote, branch string) (bool, error) { tip, err := r.tip(ctx, branch) diff --git a/internal/deliver/git_test.go b/internal/deliver/git_test.go index 9d8fa5a..bfc91e0 100644 --- a/internal/deliver/git_test.go +++ b/internal/deliver/git_test.go @@ -391,3 +391,23 @@ func TestRemoteAuth(t *testing.T) { t.Errorf("without a token: %+v", r.push) } } + +// A closed PR's branch goes while it holds what tend pushed, and stays once +// someone else moved it. +func TestDeleteBranch(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + head := commit(t, wt.Dir, "package.json", `{"v":2}`, "bump") + if err := Push(bg, wt, r.push, "tend/a", false); err != nil { + t.Fatal(err) + } + if err := DeleteBranch(bg, r.push, "tend/a", "0000000000000000000000000000000000000000"); err == nil || r.tip(t, "tend/a") != head { + t.Errorf("deleted a branch that moved: %v", err) + } + if err := DeleteBranch(bg, r.push, "tend/a", head); err != nil || r.tip(t, "tend/a") != "" { + t.Errorf("delete = %v, tip %q", err, r.tip(t, "tend/a")) + } + if err := DeleteBranch(bg, r.push, "tend/a", ""); err == nil { + t.Error("deleted with no known commit") + } +} diff --git a/internal/deliver/github.go b/internal/deliver/github.go index 6479a1c..6f43847 100644 --- a/internal/deliver/github.go +++ b/internal/deliver/github.go @@ -50,15 +50,33 @@ var ( ) func NewGitHub(f core.Fetcher, hc *http.Client, token, owner, name string) core.Forge { - if hc == nil { - hc = &http.Client{} + c := &http.Client{} + if hc != nil { + *c = *hc } + if c.CheckRedirect == nil { + c.CheckRedirect = writesStay + } + hc = c return &GitHub{ fetch: f, http: hc, token: token, owner: owner, name: name, api: apiBase, warn: os.Stderr, sleep: sleep, now: time.Now, } } +// writesStay follows a redirect for a read only. Go would follow a write's +// as a GET without its body, and report a PATCH to an issue that moved as +// done when nothing was written. +func writesStay(req *http.Request, via []*http.Request) error { + if via[0].Method != http.MethodGet { + return http.ErrUseLastResponse + } + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + return nil +} + type pull struct { Number int `json:"number"` NodeID string `json:"node_id"` @@ -100,11 +118,27 @@ func (g *GitHub) Repo(ctx context.Context) (core.RepoInfo, error) { Default string `json:"default_branch"` } if err := g.do(ctx, "GET", g.repoPath(""), nil, &res); err != nil { + if isStatus(err, http.StatusNotFound) { + err = &NoRepo{Repo: g.owner + "/" + g.name, err: err} + } return core.RepoInfo{}, err } return core.RepoInfo{Owner: g.owner, Name: g.name, Default: res.Default}, nil } +// NoRepo is a repo GitHub says is not there: it does not exist, or the +// token cannot see it, which GitHub does not tell apart. +type NoRepo struct { + Repo string + err error +} + +func (e *NoRepo) Error() string { + return "GitHub repo " + e.Repo + " not found, or the token cannot see it" +} + +func (e *NoRepo) Unwrap() error { return e.err } + // FindPR returns the open PR for branch, else the newest one. Sorting by // update would let a comment on an old closed PR hide the open one. func (g *GitHub) FindPR(ctx context.Context, branch string) (*core.PR, error) { @@ -185,9 +219,12 @@ func (g *GitHub) CreatePR(ctx context.Context, in core.PRInput) (*core.PR, error } pr := p.pr() if err := g.label(ctx, pr.Number, in.Labels); err != nil { - return &pr, err + fmt.Fprintf(g.warn, "tend: could not label #%d: %v\n", pr.Number, err) } - return &pr, g.review(ctx, pr.Number, in.Reviewers) + if err := g.review(ctx, pr.Number, in.Reviewers); err != nil { + fmt.Fprintf(g.warn, "tend: could not request reviewers on #%d: %v\n", pr.Number, err) + } + return &pr, nil } func (g *GitHub) label(ctx context.Context, number int, names []string) error { @@ -219,8 +256,6 @@ func isStatus(err error, status int) bool { return errors.As(err, &ae) && ae.Status == status } -// review requests reviewers. GitHub answers 422 for a login that cannot -// review, such as the PR's own author; that is worth a line, not a failure. func (g *GitHub) review(ctx context.Context, number int, names []string) error { if len(names) == 0 { return nil @@ -233,12 +268,7 @@ func (g *GitHub) review(ctx context.Context, number int, names []string) error { } body["reviewers"] = append(body["reviewers"], n) } - err := g.do(ctx, "POST", g.repoPath("/pulls/"+strconv.Itoa(number)+"/requested_reviewers"), body, nil) - if isStatus(err, http.StatusUnprocessableEntity) { - fmt.Fprintf(g.warn, "tend: could not request reviewers on #%d: %v\n", number, err) - return nil - } - return err + return g.do(ctx, "POST", g.repoPath("/pulls/"+strconv.Itoa(number)+"/requested_reviewers"), body, nil) } func (g *GitHub) UpdatePR(ctx context.Context, number int, in core.PRInput) error { @@ -248,6 +278,9 @@ func (g *GitHub) UpdatePR(ctx context.Context, number int, in core.PRInput) erro return err } body := map[string]string{"title": in.Title, "body": in.Body} + if in.Base != "" && in.Base != cur.Base.Ref { + body["base"] = in.Base + } if err := g.do(ctx, "PATCH", path, body, nil); err != nil { return err } @@ -285,25 +318,27 @@ func (g *GitHub) Comments(ctx context.Context, number int) ([]core.Comment, erro return res, nil } -// ClosedBy asks the issue behind the PR who closed it; the pulls endpoint does not say. -func (g *GitHub) ClosedBy(ctx context.Context, number int) (string, error) { +// ClosedBy asks the issue behind the PR who closed it and when; the pulls +// endpoint does not say who. +func (g *GitHub) ClosedBy(ctx context.Context, number int) (string, time.Time, error) { var res struct { ClosedBy *struct { Login string `json:"login"` Type string `json:"type"` } `json:"closed_by"` + ClosedAt time.Time `json:"closed_at"` } if err := g.do(ctx, "GET", g.repoPath("/issues/"+strconv.Itoa(number)), nil, &res); err != nil { - return "", err + return "", time.Time{}, err } c := res.ClosedBy if c == nil { - return "", nil + return "", res.ClosedAt, nil } if strings.EqualFold(c.Type, "Bot") && !strings.HasSuffix(strings.ToLower(c.Login), "[bot]") { - return c.Login + "[bot]", nil + return c.Login + "[bot]", res.ClosedAt, nil } - return c.Login, nil + return c.Login, res.ClosedAt, nil } func role(s string) string { @@ -500,11 +535,17 @@ func limit(res *reply, now time.Time) (time.Duration, bool) { return max(time.Unix(n, 0).Sub(now), 0) + time.Second, true } +const detailMax = 300 + func message(b []byte) string { var m struct { - Message string `json:"message"` + Message string `json:"message"` + Errors []json.RawMessage `json:"errors"` } if json.Unmarshal(b, &m) == nil && m.Message != "" { + if d := details(m.Errors); d != "" { + return m.Message + ": " + d + } return m.Message } s := strings.TrimSpace(string(b)) @@ -514,6 +555,33 @@ func message(b []byte) string { return s } +// details is what GitHub says in errors[] about a failed request, which it +// sends as plain strings on some endpoints and as objects on others. +func details(raw []json.RawMessage) string { + var parts []string + for _, r := range raw { + var s string + if json.Unmarshal(r, &s) != nil { + var e struct{ Message, Code, Field, Resource string } + if json.Unmarshal(r, &e) != nil { + continue + } + s = e.Message + if s == "" { + s = strings.Join(strings.Fields(e.Resource+" "+e.Field+" "+e.Code), " ") + } + } + if s = strings.TrimSpace(s); s != "" { + parts = append(parts, s) + } + } + res := strings.Join(parts, "; ") + if len(res) > detailMax { + res = strings.ToValidUTF8(res[:detailMax], "") + "…" + } + return res +} + func sleep(ctx context.Context, d time.Duration) error { t := time.NewTimer(d) defer t.Stop() @@ -525,30 +593,50 @@ func sleep(ctx context.Context, d time.Duration) error { } } -// RepoFromRemote reads owner and name from a github.com remote URL, or from a -// bare "owner/name" such as GITHUB_REPOSITORY. +// RepoFromRemote reads owner and name from a github.com remote URL: a URL +// with a scheme, or git's scp-like host:owner/name. A local path such as +// /srv/repo, or a bare owner/name, is no GitHub remote. func RepoFromRemote(raw string) (owner, name string, ok bool) { raw = strings.TrimSpace(raw) - path := "" - switch { - case strings.Contains(raw, "://"): + if strings.Contains(raw, "://") { u, err := url.Parse(raw) if err != nil || !isGitHub(u.Hostname()) { return "", "", false } - path = u.Path - case strings.Contains(raw, "@"): - host, p, found := strings.Cut(raw[strings.LastIndexByte(raw, '@')+1:], ":") - if !found || !isGitHub(host) { - return "", "", false - } - path = p - default: - path = raw + return repoPath(u.Path) + } + colon, slash := strings.IndexByte(raw, ':'), strings.IndexByte(raw, '/') + if colon < 0 || slash >= 0 && slash < colon || strings.HasPrefix(raw, ".") { + return "", "", false + } + host := raw[:colon] + if i := strings.LastIndexByte(host, '@'); i >= 0 { + host = host[i+1:] } - path = strings.TrimSuffix(strings.Trim(path, "/"), ".git") - parts := strings.Split(path, "/") - if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + if len(host) < 2 || !isGitHub(host) { + return "", "", false + } + return repoPath(raw[colon+1:]) +} + +// RepoFromSlug reads owner and name from a bare "owner/name", as +// GITHUB_REPOSITORY gives them. +func RepoFromSlug(raw string) (owner, name string, ok bool) { + raw = strings.TrimSpace(raw) + if strings.Contains(raw, ":") || strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, ".") { + return "", "", false + } + parts := strings.Split(raw, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" || parts[1] == ".." { + return "", "", false + } + return parts[0], parts[1], true +} + +func repoPath(p string) (owner, name string, ok bool) { + p = strings.TrimSuffix(strings.Trim(p, "/"), ".git") + parts := strings.Split(p, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" || parts[0] == ".." || parts[1] == ".." { return "", "", false } return parts[0], parts[1], true diff --git a/internal/deliver/github_test.go b/internal/deliver/github_test.go index 882a954..739f684 100644 --- a/internal/deliver/github_test.go +++ b/internal/deliver/github_test.go @@ -317,8 +317,21 @@ func TestCreatePRErrors(t *testing.T) { {req: "GET /repos/acme/shop/labels/tend", status: 401, resp: `{"message": "Bad credentials"}`}, }) pr, err := a.g.CreatePR(context.Background(), in) - if err == nil || pr == nil || pr.Number != 12 { - t.Fatalf("a failed label call must still return the created PR: %+v, %v", pr, err) + if err != nil || pr == nil || pr.Number != 12 { + t.Fatalf("a failed label call must not fail the created PR: %+v, %v", pr, err) + } + if !strings.Contains(a.warn.String(), "could not label #12: github: GET /repos/acme/shop/labels/tend: 401 Bad credentials") { + t.Errorf("warning = %q", a.warn) + } + + a = newAPI(t, []step{ + {req: "POST " + pulls, body: `{"title": "t", "head": "b", "base": "main", "body": "", "draft": false}`, status: 201, resp: "pull_draft.json"}, + {req: "GET /repos/acme/shop/labels/tend", resp: "label.json"}, + {req: "POST /repos/acme/shop/issues/12/labels", body: `{"labels": ["tend"]}`, status: 502, resp: `{"message": "Server Error"}`}, + }) + pr, err = a.g.CreatePR(context.Background(), in) + if err != nil || pr == nil || pr.Number != 12 || !strings.Contains(a.warn.String(), "could not label #12") { + t.Fatalf("pr = %+v, err = %v, warning = %q", pr, err, a.warn) } } @@ -329,9 +342,32 @@ func TestCreatePRReviewerErrors(t *testing.T) { {req: "POST /repos/acme/shop/pulls/12/requested_reviewers", body: "*", status: 404, resp: `{"message": "Not Found"}`}, }) pr, err := a.g.CreatePR(context.Background(), in) - if err == nil || pr == nil || pr.Number != 12 || !strings.Contains(err.Error(), "404") { + if err != nil || pr == nil || pr.Number != 12 { t.Fatalf("pr = %+v, err = %v", pr, err) } + if !strings.Contains(a.warn.String(), "could not request reviewers on #12: github: POST /repos/acme/shop/pulls/12/requested_reviewers: 404 Not Found") { + t.Errorf("warning = %q", a.warn) + } +} + +func TestAPIMessage(t *testing.T) { + long := strings.Repeat("x", 400) + tests := []struct{ name, body, want string }{ + {"plain", `{"message": "Not Found"}`, "Not Found"}, + {"object errors", `{"message": "Validation Failed", "errors": [{"resource": "PullRequest", "code": "custom", "message": "A pull request already exists for acme:tend/x."}]}`, "Validation Failed: A pull request already exists for acme:tend/x."}, + {"string errors", `{"message": "Validation Failed", "errors": ["No commits between main and tend/x", ""]}`, "Validation Failed: No commits between main and tend/x"}, + {"code only", `{"message": "Validation Failed", "errors": [{"resource": "Label", "code": "already_exists", "field": "name"}]}`, "Validation Failed: Label name already_exists"}, + {"mixed", `{"message": "Validation Failed", "errors": [{"field": "base", "code": "invalid"}, "Reviews may only be requested from collaborators.", 7]}`, "Validation Failed: base invalid; Reviews may only be requested from collaborators."}, + {"capped", `{"message": "Validation Failed", "errors": ["` + long + `"]}`, "Validation Failed: " + long[:detailMax] + "…"}, + {"no message", `oops`, "oops"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := message([]byte(tc.body)); got != tc.want { + t.Errorf("message = %q, want %q", got, tc.want) + } + }) + } } func TestWritesTimeOut(t *testing.T) { @@ -380,6 +416,24 @@ func TestUpdatePR(t *testing.T) { }) } + t.Run("a new base retargets the PR", func(t *testing.T) { + a := newAPI(t, []step{get("pull_open.json"), {req: "PATCH " + pulls + "/12", body: `{"title": "New title", "body": "New body", "base": "develop"}`}}) + in := in + in.Base = "develop" + if err := a.g.UpdatePR(context.Background(), 12, in); err != nil { + t.Fatal(err) + } + }) + + t.Run("the same base is left alone", func(t *testing.T) { + a := newAPI(t, []step{get("pull_open.json"), patch}) + in := in + in.Base = "main" + if err := a.g.UpdatePR(context.Background(), 12, in); err != nil { + t.Fatal(err) + } + }) + t.Run("graphql errors surface", func(t *testing.T) { a := newAPI(t, []step{get("pull_open.json"), patch, {req: "POST /graphql", body: "*", resp: `{"errors": [{"message": "Could not resolve"}]}`}}) in := in @@ -410,7 +464,7 @@ func TestClosedBy(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { a := newAPI(t, []step{{req: "GET /repos/acme/shop/issues/12", resp: tt.resp}}) - got, err := a.g.ClosedBy(context.Background(), 12) + got, _, err := a.g.ClosedBy(context.Background(), 12) if err != nil || got != tt.want { t.Errorf("ClosedBy = %q, %v; want %q", got, err, tt.want) } @@ -418,6 +472,14 @@ func TestClosedBy(t *testing.T) { } } +func TestClosedAt(t *testing.T) { + a := newAPI(t, []step{{req: "GET /repos/acme/shop/issues/12", resp: `{"number": 12, "closed_by": {"login": "ada", "type": "User"}, "closed_at": "2026-10-21T12:00:00Z"}`}}) + who, at, err := a.g.ClosedBy(context.Background(), 12) + if err != nil || who != "ada" || !at.Equal(time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC)) { + t.Errorf("ClosedBy = %q, %v, %v", who, at, err) + } +} + func TestComments(t *testing.T) { a := newAPI(t, []step{{req: "GET /repos/acme/shop/issues/12/comments?per_page=100", resp: "comments.json"}}) got, err := a.g.Comments(context.Background(), 12) @@ -584,9 +646,17 @@ func TestRepoFromRemote(t *testing.T) { {"https://x-access-token:abc@github.com/acme/shop.git", "acme", "shop", true}, {"HTTPS://GitHub.com/Acme/Shop.git", "Acme", "Shop", true}, {"git://github.com/acme/shop.git", "acme", "shop", true}, - {"acme/shop", "acme", "shop", true}, - {" acme/shop\n", "acme", "shop", true}, - {"my.repo/with.dots", "my.repo", "with.dots", true}, + {"github.com:acme/shop", "acme", "shop", true}, + {" git@github.com:acme/shop.git\n", "acme", "shop", true}, + {"acme/shop", "", "", false}, + {"/srv/repo", "", "", false}, + {"/tmp/project.git", "", "", false}, + {"backup/shop", "", "", false}, + {"../shop", "", "", false}, + {"./a:b/c", "", "", false}, + {"C:/repos/acme/shop", "", "", false}, + {"github-work:acme/shop", "", "", false}, + {"git@github.com:../shop", "", "", false}, {"git@gitlab.com:acme/shop.git", "", "", false}, {"https://gitlab.com/acme/shop", "", "", false}, {"https://github.com/acme", "", "", false}, @@ -608,6 +678,29 @@ func TestRepoFromRemote(t *testing.T) { } } +func TestRepoFromSlug(t *testing.T) { + tests := []struct { + in, owner, name string + ok bool + }{ + {"acme/shop", "acme", "shop", true}, + {" acme/shop\n", "acme", "shop", true}, + {"my.repo/with.dots", "my.repo", "with.dots", true}, + {"/srv/repo", "", "", false}, + {"../shop", "", "", false}, + {"acme/..", "", "", false}, + {"github.com:acme/shop", "", "", false}, + {"a/b/c", "", "", false}, + {"acme/", "", "", false}, + {"", "", "", false}, + } + for _, tc := range tests { + if owner, name, ok := RepoFromSlug(tc.in); owner != tc.owner || name != tc.name || ok != tc.ok { + t.Errorf("RepoFromSlug(%q) = %q %q %v", tc.in, owner, name, ok) + } + } +} + func TestTokenFrom(t *testing.T) { env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } gh := func(out string, err error) func(string, ...string) (string, error) { diff --git a/internal/deliver/send.go b/internal/deliver/send.go index 77ca354..8202a72 100644 --- a/internal/deliver/send.go +++ b/internal/deliver/send.go @@ -55,6 +55,9 @@ func Send(ctx context.Context, forge core.Forge, wt *verify.Worktree, in SendInp if remote == nil { return nil, errors.New("deliver: no remote to push to") } + if err := sign(ctx, wt); err != nil { + return nil, err + } if in.BaseRef == "" { info, err := forge.Repo(ctx) if err != nil { @@ -67,17 +70,28 @@ func Send(ctx context.Context, forge core.Forge, wt *verify.Worktree, in SendInp return nil, err } if pr != nil && pr.State == "open" { + if !Carries(pr, in.Change) { + id, _, _, _ := ParseMarker(pr.Body) + return nil, fmt.Errorf("deliver: #%d on %s is tend's PR for %s, not %s", pr.Number, branch, id, in.Change.ID) + } return updatePR(ctx, forge, wt, in, pr, remote, title, draft) } return openPR(ctx, forge, wt, in, remote, branch, title, draft) } +// Carries reports whether pr is tend's PR for ch, or for ch at another +// target: what its marker names, when it has one. +func Carries(pr *core.PR, ch *core.Change) bool { + id, _, _, ok := ParseMarker(pr.Body) + return !ok || ch == nil || id == "" || core.Subject(id) == core.Subject(ch.ID) +} + func openPR(ctx context.Context, forge core.Forge, wt *verify.Worktree, in SendInput, remote *Remote, branch, title string, draft bool) (*core.PR, error) { - exists, err := BranchExists(ctx, remote, branch) + left, err := remote.tip(ctx, branch) if err != nil { return nil, err } - if err := Push(ctx, wt, remote, branch, exists); err != nil { + if err := push(ctx, wt, remote, branch, left != "", left); err != nil { return nil, err } tip, err := head(ctx, wt, "HEAD") @@ -101,7 +115,7 @@ func updatePR(ctx context.Context, forge core.Forge, wt *verify.Worktree, in Sen branch := pr.Branch same, tip, err := SameTree(ctx, wt, remote, branch) if err != nil { - same, tip = false, "" + return nil, err } _, base, rev, ok := ParseMarker(pr.Body) if !ok { @@ -109,18 +123,14 @@ func updatePR(ctx context.Context, forge core.Forge, wt *verify.Worktree, in Sen } res := *pr res.Head = tip - if same && ok && base == in.Base && pr.Title == title && pr.Draft == draft { + if same && ok && base == in.Base && pr.Base == in.BaseRef && pr.Title == title && pr.Draft == draft { return &res, nil } if !same { - last := in.Last - if tip != "" { - if !ours(ctx, remote, wt, pr, tip, in.Last) { - return nil, foreign(ctx, forge, pr) - } - last = tip + if !ours(ctx, remote, wt, pr, tip, in.Last) { + return nil, foreign(ctx, forge, pr) } - err := push(ctx, wt, remote, branch, true, last) + err := push(ctx, wt, remote, branch, true, tip) if errors.Is(err, ErrRejected) { return nil, foreign(ctx, forge, pr) } @@ -133,21 +143,23 @@ func updatePR(ctx context.Context, forge core.Forge, wt *verify.Worktree, in Sen } in.Rev = rev + 1 body := Body(in.BodyInput) - err = forge.UpdatePR(ctx, pr.Number, core.PRInput{Title: title, Body: body, Branch: branch, Base: pr.Base, Draft: draft}) + err = forge.UpdatePR(ctx, pr.Number, core.PRInput{Title: title, Body: body, Branch: branch, Base: in.BaseRef, Draft: draft}) if err != nil { return nil, err } - res.Title, res.Body, res.Draft = title, body, draft + res.Title, res.Body, res.Draft, res.Base = title, body, draft, in.BaseRef return merge(ctx, forge, in, &res, title, draft) } // ours reports whether tip, the commit the PR's branch is at, holds nothing // but tend's own work. The forge decides, not state, which may be stale or // lost: the PR is tend's when its branch is under tend/ and its body carries -// the marker, and tip is then tend's when it is the one commit tend makes, -// straight on the base the marker names, or adds nothing to the base tend -// builds on. A commit pushed on top, or a merge of the base branch, is -// someone else's. The last push state knows of counts as well. +// the marker, and tip is then tend's when it adds nothing to the base tend +// builds on, or is the one commit tend makes, straight on the base the +// marker names, with the files tend signed it for. A commit pushed on top, a +// merge of the base branch or an amend that changes files is someone else's. +// The last push state knows of counts as well, and a commit from before tend +// signed its work is taken as tend's only when state knows of no other. func ours(ctx context.Context, r *Remote, wt *verify.Worktree, pr *core.PR, tip, last string) bool { if tip == last { return true @@ -163,8 +175,83 @@ func ours(ctx context.Context, r *Remote, wt *verify.Worktree, pr *core.PR, tip, if err != nil { return false } + if f := strings.Fields(out); len(f) != 2 || base == "" || f[1] != base { + return false + } + tree, err := gitx.Run(ctx, r.repo, "rev-parse", "--verify", tip+"^{tree}") + if err != nil { + return false + } + msg, err := gitx.Raw(ctx, r.repo, "log", "-1", "--format=%B", tip) + if err != nil { + return false + } + if signed := stamp(msg); signed != "" { + return signed == tree + } + return last == "" +} + +const treeKey = "Tend-Tree" + +// stamp is the tree a commit message says tend built the commit with, "" for none. +func stamp(msg string) string { + res := "" + for _, l := range strings.Split(msg, "\n") { + if v, ok := strings.CutPrefix(strings.TrimSpace(l), treeKey+":"); ok { + res = strings.TrimSpace(v) + } + } + return res +} + +// sign makes HEAD of the worktree carry the tree it holds in a Tend-Tree +// trailer, so a later run tells tend's commit from one a maintainer amended: +// an amend keeps the message but not the files. Who made the commit, and +// when, stay as they were. +func sign(ctx context.Context, wt *verify.Worktree) error { + tree, err := gitx.Run(ctx, wt.Dir, "rev-parse", "--verify", "HEAD^{tree}") + if err != nil { + return err + } + msg, err := gitx.Raw(ctx, wt.Dir, "log", "-1", "--format=%B", "HEAD") + if err != nil { + return err + } + if stamp(msg) == tree { + return nil + } + signed, err := gitx.Cmd{Dir: wt.Dir, Stdin: msg}.Run(ctx, "interpret-trailers", "--if-exists", "replace", "--trailer", treeKey+": "+tree) + if err != nil { + return err + } + who, err := gitx.Run(ctx, wt.Dir, "log", "-1", "--date=raw", "--format=%an%x00%ae%x00%ad%x00%cn%x00%ce%x00%cd", "HEAD") + if err != nil { + return err + } + w := strings.Split(who, "\x00") + if len(w) != 6 { + return errors.New("deliver: cannot read who made the commit") + } + env := []string{ + "GIT_AUTHOR_NAME=" + w[0], "GIT_AUTHOR_EMAIL=" + w[1], "GIT_AUTHOR_DATE=" + w[2], + "GIT_COMMITTER_NAME=" + w[3], "GIT_COMMITTER_EMAIL=" + w[4], "GIT_COMMITTER_DATE=" + w[5], + } + out, err := gitx.Run(ctx, wt.Dir, "rev-list", "--parents", "-n", "1", "HEAD") + if err != nil { + return err + } f := strings.Fields(out) - return len(f) == 2 && base != "" && f[1] == base + args := []string{"commit-tree", "--no-gpg-sign", tree} + for _, p := range f[1:] { + args = append(args, "-p", p) + } + sha, err := gitx.Cmd{Dir: wt.Dir, Env: env, Stdin: signed}.Run(ctx, args...) + if err != nil { + return err + } + _, err = gitx.Run(ctx, wt.Dir, "update-ref", "HEAD", strings.TrimSpace(sha), f[0]) + return err } // foreign says once on the PR that its branch has someone else's commits, diff --git a/internal/deliver/send_test.go b/internal/deliver/send_test.go index d3ca254..130c1c5 100644 --- a/internal/deliver/send_test.go +++ b/internal/deliver/send_test.go @@ -3,6 +3,9 @@ package deliver import ( "context" "errors" + "os" + "path/filepath" + "runtime" "strings" "testing" @@ -40,13 +43,14 @@ const stripeBranch = "tend/npm-stripe-16.0.1" func TestSendCreates(t *testing.T) { r := newRemote(t) wt := r.worktree(t) - head := commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") f := NewFake("acme", "shop", "trunk") pr, err := Send(bg, f, wt, sendInput(r, wt)) if err != nil { t.Fatal(err) } + head := must(t, wt.Dir, "rev-parse", "HEAD") if pr.Number != 1 || pr.Branch != stripeBranch || pr.Base != "trunk" || pr.Draft { t.Errorf("pr = %+v", pr) } @@ -101,13 +105,14 @@ func TestSendUpdatesTheOpenPR(t *testing.T) { } must(t, wt.Dir, "reset", "--hard", r.base) - next := commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") + commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") in := sendInput(r, wt) in.Notes = []string{"lockfile not regenerated: npm not found"} pr, err := Send(bg, f, wt, in) if err != nil { t.Fatal(err) } + next := must(t, wt.Dir, "rev-parse", "HEAD") if pr.Number != first.Number || len(f.All()) != 1 { t.Fatalf("a second PR was opened: %+v", f.All()) } @@ -227,11 +232,12 @@ func TestSendAfterAClosedPR(t *testing.T) { noErr(t, f.CloseByHuman(1)) must(t, wt.Dir, "reset", "--hard", r.base) - again := commit(t, wt.Dir, "package.json", `{"v":4}`, "Bump stripe, retried") + commit(t, wt.Dir, "package.json", `{"v":4}`, "Bump stripe, retried") pr, err := Send(bg, f, wt, sendInput(r, wt)) if err != nil { t.Fatal(err) } + again := must(t, wt.Dir, "rev-parse", "HEAD") if pr.Number != 2 { t.Errorf("pr = %+v, want a new PR", pr) } @@ -275,11 +281,12 @@ func TestSendPushRejected(t *testing.T) { func TestSendRefusesToOverwriteWhatItDidNotPush(t *testing.T) { r := newRemote(t) wt := r.worktree(t) - pushed := commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") f := NewFake("acme", "shop", "main") if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { t.Fatal(err) } + pushed := must(t, wt.Dir, "rev-parse", "HEAD") other := r.elsewhere(t) must(t, other, "checkout", "-q", stripeBranch) theirs := commit(t, other, "notes.txt", "mine\n", "human fix") @@ -434,11 +441,12 @@ func TestSendForgeErrors(t *testing.T) { func TestSendStaleStateIsNotForeign(t *testing.T) { r := newRemote(t) wt := r.worktree(t) - first := commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") f := NewFake("acme", "shop", "main") if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { t.Fatal(err) } + first := must(t, wt.Dir, "rev-parse", "HEAD") must(t, wt.Dir, "reset", "--hard", r.base) commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") in := sendInput(r, wt) @@ -448,7 +456,7 @@ func TestSendStaleStateIsNotForeign(t *testing.T) { } must(t, wt.Dir, "reset", "--hard", r.base) - next := commit(t, wt.Dir, "package.json", `{"v":4}`, "Bump stripe, a third time") + commit(t, wt.Dir, "package.json", `{"v":4}`, "Bump stripe, a third time") must(t, wt.Dir, "update-ref", "-d", "refs/remotes/origin/"+stripeBranch) in = sendInput(r, wt) in.Last = first @@ -456,6 +464,7 @@ func TestSendStaleStateIsNotForeign(t *testing.T) { if err != nil { t.Fatalf("err = %v, want the PR updated", err) } + next := must(t, wt.Dir, "rev-parse", "HEAD") if r.tip(t, stripeBranch) != next || pr.Head != next { t.Errorf("branch at %q, pr head %q, want %q", r.tip(t, stripeBranch), pr.Head, next) } @@ -482,3 +491,230 @@ func TestSendLeavesAHandMadePR(t *testing.T) { t.Error("the hand-made branch was overwritten") } } + +func TestSendSignsItsCommit(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + tip := r.tip(t, stripeBranch) + tree := must(t, r.bare, "rev-parse", tip+"^{tree}") + if msg := must(t, r.bare, "log", "-1", "--format=%B", tip); msg != "Bump stripe\n\nTend-Tree: "+tree { + t.Errorf("message = %q", msg) + } + if who := must(t, r.bare, "log", "-1", "--format=%an <%ae> %cn", tip); who != "Ada Ada" { + t.Errorf("made by %q", who) + } + if err := sign(bg, wt); err != nil || must(t, wt.Dir, "rev-parse", "HEAD") != tip { + t.Errorf("signing a signed commit changed it: %v", err) + } +} + +func TestSignKeepsATrailerBlock(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe\n\nSigned-off-by: Ada \nTend-Tree: 0000") + if err := sign(bg, wt); err != nil { + t.Fatal(err) + } + tree := must(t, wt.Dir, "rev-parse", "HEAD^{tree}") + want := "Bump stripe\n\nSigned-off-by: Ada \nTend-Tree: " + tree + if msg := must(t, wt.Dir, "log", "-1", "--format=%B"); msg != want { + t.Errorf("message = %q, want %q", msg, want) + } + if must(t, wt.Dir, "rev-parse", "HEAD^") != r.base { + t.Error("the signed commit is not on the base") + } +} + +// amend rewrites the commit at the tip of the PR's branch from another +// clone, as a maintainer fixing up tend's PR would, and force-pushes it. +func amend(t *testing.T, r *remote, file, body string, args ...string) string { + t.Helper() + other := r.elsewhere(t) + must(t, other, "checkout", "-q", stripeBranch) + if file != "" { + write(t, other, file, body) + must(t, other, "add", "-A") + } + must(t, other, append([]string{"commit", "--amend"}, args...)...) + must(t, other, "push", "-q", "-f", "origin", stripeBranch) + return must(t, other, "rev-parse", "HEAD") +} + +func TestSendLeavesAnAmendedBranch(t *testing.T) { + for _, known := range []bool{true, false} { + t.Run(map[bool]string{true: "state knows the last push", false: "state lost"}[known], func(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + pushed := must(t, wt.Dir, "rev-parse", "HEAD") + theirs := amend(t, r, "app.txt", "fixed by hand\n", "--no-edit") + + must(t, wt.Dir, "reset", "--hard", r.base) + commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") + in := sendInput(r, wt) + if known { + in.Last = pushed + } + if _, err := Send(bg, f, wt, in); !errors.Is(err, ErrForeign) { + t.Fatalf("err = %v, want ErrForeign", err) + } + if r.tip(t, stripeBranch) != theirs { + t.Error("the maintainer's amend was overwritten") + } + }) + } +} + +func TestSendTakesARewordedCommitAsItsOwn(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + pushed := must(t, wt.Dir, "rev-parse", "HEAD") + msg := must(t, wt.Dir, "log", "-1", "--format=%B") + amend(t, r, "", "", "-m", strings.Replace(msg, "Bump stripe", "Bump stripe (reworded)", 1)) + + must(t, wt.Dir, "reset", "--hard", r.base) + commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") + in := sendInput(r, wt) + in.Last = pushed + if _, err := Send(bg, f, wt, in); err != nil { + t.Fatalf("err = %v, want the PR updated", err) + } + if r.tip(t, stripeBranch) != must(t, wt.Dir, "rev-parse", "HEAD") { + t.Error("the branch was not updated") + } +} + +// A commit tend pushed before it signed its work is still its own, unless +// state knows tend pushed something else. +func TestSendUnsignedCommit(t *testing.T) { + for _, known := range []bool{false, true} { + t.Run(map[bool]string{false: "state lost", true: "state knows another push"}[known], func(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + pushed := must(t, wt.Dir, "rev-parse", "HEAD") + old := amend(t, r, "", "", "-m", "Bump stripe") + + must(t, wt.Dir, "reset", "--hard", r.base) + commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") + in := sendInput(r, wt) + if known { + in.Last = pushed + } + _, err := Send(bg, f, wt, in) + if known { + if !errors.Is(err, ErrForeign) || r.tip(t, stripeBranch) != old { + t.Fatalf("err = %v, want ErrForeign and the branch left alone", err) + } + return + } + if err != nil || r.tip(t, stripeBranch) != must(t, wt.Dir, "rev-parse", "HEAD") { + t.Fatalf("err = %v, want the branch updated", err) + } + }) + } +} + +// A remote-tracking ref left from a push long ago does not stop tend from +// replacing the branch of a closed PR. +func TestSendAfterAClosedPRWithAStaleTrackingRef(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + amend(t, r, "package.json", `{"v":9}`, "-m", "pushed by another run") + noErr(t, f.ClosePR(bg, 1)) + + must(t, wt.Dir, "reset", "--hard", r.base) + commit(t, wt.Dir, "package.json", `{"v":4}`, "Bump stripe, retried") + pr, err := Send(bg, f, wt, sendInput(r, wt)) + if err != nil { + t.Fatal(err) + } + if pr.Number != 2 || r.tip(t, stripeBranch) != must(t, wt.Dir, "rev-parse", "HEAD") { + t.Errorf("pr #%d, branch at %s", pr.Number, r.tip(t, stripeBranch)) + } +} + +// A fetch that fails while tend checks the branch stops the run; it does not +// push over whatever the branch holds. +func TestSendStopsWhenItCannotReadTheBranch(t *testing.T) { + r := newRemote(t) + if runtime.GOOS == "windows" { + t.Skip("needs sh") + } + arm := filepath.Join(t.TempDir(), "arm") + script := filepath.Join(t.TempDir(), "upload-pack") + write(t, filepath.Dir(script), filepath.Base(script), "#!/bin/sh\nif [ -e '"+arm+"' ]; then rm -f '"+arm+"'; echo flaky >&2; exit 1; fi\nexec git-upload-pack \"$@\"\n") + noErr(t, os.Chmod(script, 0o755)) + must(t, r.clone, "config", "remote.origin.uploadpack", script) + r.push = r.remote(t, "origin") + + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + other := r.elsewhere(t) + must(t, other, "checkout", "-q", stripeBranch) + theirs := commit(t, other, "notes.txt", "mine\n", "human fix") + must(t, other, "push", "-q", "origin", stripeBranch) + + must(t, wt.Dir, "reset", "--hard", r.base) + commit(t, wt.Dir, "package.json", `{"v":3}`, "Bump stripe, again") + must(t, wt.Dir, "update-ref", "-d", "refs/remotes/origin/"+stripeBranch) + write(t, filepath.Dir(arm), filepath.Base(arm), "") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err == nil || !strings.Contains(err.Error(), "flaky") { + t.Fatalf("err = %v, want the fetch error", err) + } + if r.tip(t, stripeBranch) != theirs { + t.Error("the human's commit was overwritten") + } +} + +func TestSendRetargetsANewBase(t *testing.T) { + r := newRemote(t) + wt := r.worktree(t) + commit(t, wt.Dir, "package.json", `{"v":2}`, "Bump stripe") + f := NewFake("acme", "shop", "main") + if _, err := Send(bg, f, wt, sendInput(r, wt)); err != nil { + t.Fatal(err) + } + in := sendInput(r, wt) + in.BaseRef = "develop" + pr, err := Send(bg, f, wt, in) + if err != nil { + t.Fatal(err) + } + if pr.Base != "develop" || f.PR(1).Base != "develop" { + t.Errorf("base = %q, stored %q", pr.Base, f.PR(1).Base) + } + if _, err := Send(bg, f, wt, in); err != nil { + t.Fatal(err) + } + if _, _, rev, _ := ParseMarker(f.PR(1).Body); rev != 2 { + t.Errorf("rev = %d, want 2: a re-run on the new base changes nothing", rev) + } +} diff --git a/internal/deliver/testdata/api_field_removed.golden.md b/internal/deliver/testdata/api_field_removed.golden.md index 6977e85..1585d61 100644 --- a/internal/deliver/testdata/api_field_removed.golden.md +++ b/internal/deliver/testdata/api_field_removed.golden.md @@ -1,6 +1,6 @@ ## fixture GET /v1/orders -**Why**: breaking · response field removed (total_cents) +**Why**: breaking · response field removed (total\_cents) ### What changed upstream diff --git a/internal/deliver/testdata/broken_install_fixed.golden.md b/internal/deliver/testdata/broken_install_fixed.golden.md new file mode 100644 index 0000000..294a65c --- /dev/null +++ b/internal/deliver/testdata/broken_install_fixed.golden.md @@ -0,0 +1,33 @@ +## requests 2.19.0 → 2.32.3 + +**Why**: update · minor release +**Level**: minor (2.19.0 → 2.32.3) + +### Touched in this repo + +- `requirements.txt` + +### Proof + +| step | base (main@feaaca8) | patched | +|---|---|---| +| `python3 -m venv .venv && .venv/bin/pip install -r requirements.txt` | failed (exit 1) · 4s | ok · 6s | +| `.venv/bin/python -m unittest` | skipped (after failure) | ok · 1s | + +`python3 -m venv .venv && .venv/bin/pip install -r requirements.txt` fails on `main@feaaca8` and passes with this change, so this PR is a draft until a person confirms it. + +
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt (base), end of its output + +``` +ERROR: Cannot install urllib3==1.24 and requests==2.19.0 because these package versions have conflicting dependencies. +``` +
+ +### Vetting + +- scope: every changed file is explained by this change + +Verdict: draft. + +tend · comment `tend skip` or `tend retry` + diff --git a/internal/deliver/testdata/deprecation_hostile.golden.md b/internal/deliver/testdata/deprecation_hostile.golden.md new file mode 100644 index 0000000..2516dbb --- /dev/null +++ b/internal/deliver/testdata/deprecation_hostile.golden.md @@ -0,0 +1,29 @@ +## stripe 16.0.0 → 16.0.1 + +**Why**: deprecation · Use @​acme/evil instead, c​loses #​2 ping @​org/team <img src=x> & f​ixes https://github.com/acme/shop/issues/4 + +### What changed upstream + +- **v16.0.1 cc @​octocat f​ixes #​1 !\[x\](https://evil.example/p.png)** · [full notes](https://x/y) + ``` + Closes #9, thanks @someone + ``` +- **<!-- v16.0.0 G​H-7 r​esolved acme/shop#​3 `ok @code`** +- **v15.9.0 \| \*bold\* \_it\_ \~gone\~ \[link\](https://evil.example)** · [full notes](https://example.test/notes%20%28v15%29) + +### Touched in this repo + +- `package.json` + +### Proof + +| step | base (main@abc1234) | patched | +|---|---|---| +| `npm test` | ok · 4s | ok · 5s | + +### Vetting + +- scope: every changed file is explained by this change + +tend · comment `tend skip` or `tend retry` + diff --git a/internal/deliver/testdata/failing_baseline_draft.golden.md b/internal/deliver/testdata/failing_baseline_draft.golden.md index 0b7f73b..c8d945e 100644 --- a/internal/deliver/testdata/failing_baseline_draft.golden.md +++ b/internal/deliver/testdata/failing_baseline_draft.golden.md @@ -16,7 +16,7 @@ | `npm test` | failed (exit 1) · 2s | failed (exit 1) · 1m15s | | `npm run build` | not run | skipped (after failure) | -Tests already fail on `main@abc1234`, so this PR is a draft. +`npm test` already fails on `main@abc1234`, so this PR is a draft.
npm test (patched), end of its output diff --git a/internal/deliver/testdata/tidy.golden.md b/internal/deliver/testdata/tidy.golden.md index e8ab03d..fd31202 100644 --- a/internal/deliver/testdata/tidy.golden.md +++ b/internal/deliver/testdata/tidy.golden.md @@ -29,7 +29,7 @@ go: ### Deprecated -- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.* was replaced by paymentIntents.* +- `stripe` 14.2.0 → 16.0.0: 14.x is deprecated: charges.\* was replaced by paymentIntents.\* - `src/billing.js:42` `const c = await stripe.charges.create({ amount: order.total })` → `const c = await stripe.paymentIntents.create({ amount: order.total })` - `src/billing.js:88` `return stripe.charges.retrieve(id)` → `return stripe.paymentIntents.retrieve(id)` @@ -50,8 +50,9 @@ Possibly unused, kept: these look unused, but tend cannot prove it, so they are Each comes as a pull request of its own once this one is merged, proven the same way. 2. Runtimes and build tooling + - Carried over from an earlier stage, where they could not be made or proven, and tried again here: + - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1). - `nodejs` 18.20.4 → 22.20.0 in `.nvmrc`: Node.js 18 reached end of life on 2025-04-30. - - `axios` 0.27.2 → 1.12.0: with it in the batch, `npm test` fails (exit 1). 3. Major upgrades - `vitest` 1.6.0 → 3.2.4: a new major release. 4. Migrations and replacements diff --git a/internal/deliver/title.go b/internal/deliver/title.go index 798ca0f..8c6695b 100644 --- a/internal/deliver/title.go +++ b/internal/deliver/title.go @@ -43,7 +43,7 @@ func decide(ch *core.Change) string { } d := ch.Deps[0] if v, ok := ver.Parse(d.Version); ok && len(v.Nums) > 0 && ch.To != "" { - return fmt.Sprintf("Decide: migrate off %s %d.x", depName(d), v.Major()) + return fmt.Sprintf("Decide: migrate off %s %s.x", depName(d), v.Line()) } return "Decide: migrate off " + depName(d) } @@ -98,7 +98,7 @@ func title(ch *core.Change) string { return "Bump " + name + " to " + ch.To case ch.Kind == core.Deprecation: if v, ok := ver.Parse(d.Version); ok && len(v.Nums) > 0 { - return fmt.Sprintf("Migrate off deprecated %s %d.x", name, v.Major()) + return fmt.Sprintf("Migrate off deprecated %s %s.x", name, v.Line()) } return "Migrate off deprecated " + name } @@ -111,6 +111,9 @@ func apiTitle(a *core.APIChange) string { if strings.Contains(a.What, "parameter") { noun = "parameter" } + if op != "" { + op = api.Title(a.Provider) + " " + op + } subject := op switch { case a.Field != "" && op == "": @@ -126,6 +129,8 @@ func apiTitle(a *core.APIChange) string { return "Handle new required parameter on " + op } return "Handle new required " + subject + case strings.HasSuffix(a.What, "type changed"): + return "Handle changed type of " + subject } return "Handle removed " + subject } @@ -142,6 +147,9 @@ func fixes(ch *core.Change) string { return res + ")" } +// Advisories are the advisory ids ch's evidence cites, each once. +func Advisories(ch *core.Change) []string { return advisories(ch) } + func advisories(ch *core.Change) []string { var res []string seen := map[string]bool{} @@ -159,15 +167,13 @@ func advisories(ch *core.Change) []string { return res } -func depName(d core.Dep) string { - return strings.TrimPrefix(d.Name, "library/") -} +func depName(d core.Dep) string { return d.Display() } func groupName(ch *core.Change) string { id := core.ChangeID(ch) _, rest, ok := strings.Cut(id, "/group:") if !ok { - return ch.Deps[0].Name + return ch.Deps[0].Display() } if i := strings.LastIndexByte(rest, '@'); i > 0 { rest = rest[:i] @@ -211,10 +217,13 @@ func Branch(ch *core.Change) string { return fit("tend/"+eco+"-", core.Slug(ch.Deps[0].Name), to) } +// fit is head+mid+tail, with mid cut to keep the branch within branchMax +// and a hash of the whole name in its place, so the cut never makes two +// changes share a branch. func fit(head, mid, tail string) string { room := branchMax - len(head) - len(tail) if len(mid) > room { - mid = strings.TrimRight(mid[:max(room, 1)], "-.") + mid = core.Cut(mid, max(room, 10), head+mid+tail) } return head + mid + tail } diff --git a/internal/deliver/title_test.go b/internal/deliver/title_test.go index 78fae19..4554641 100644 --- a/internal/deliver/title_test.go +++ b/internal/deliver/title_test.go @@ -175,37 +175,43 @@ func TestTitleAndBranch(t *testing.T) { { name: "api deprecation", ch: core.Change{Kind: core.Deprecation, API: &core.APIChange{Provider: "fixture", Method: "GET", Path: "/v1/orders/{id}/legacy", What: "operation deprecated"}}, - title: "Migrate off deprecated GET /v1/orders/{id}/legacy", + title: "Migrate off deprecated fixture GET /v1/orders/{id}/legacy", branch: "tend/api-fixture-get-v1-orders-id-legacy", }, { name: "api deprecated field", ch: core.Change{Kind: core.Deprecation, API: &core.APIChange{Provider: "fixture", Method: "get", Path: "/v1/orders", Field: "total", What: "response field deprecated"}}, - title: "Migrate off deprecated field total on GET /v1/orders", + title: "Migrate off deprecated field total on fixture GET /v1/orders", branch: "tend/api-fixture-get-v1-orders-total", }, { name: "api field removed", ch: core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "fixture", Method: "GET", Path: "/v1/orders", Field: "total_cents", What: "response field removed"}}, - title: "Handle removed field total_cents on GET /v1/orders", + title: "Handle removed field total_cents on fixture GET /v1/orders", + branch: "tend/api-fixture-get-v1-orders-total-cents", + }, + { + name: "api field type changed", + ch: core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "fixture", Method: "GET", Path: "/v1/orders", Field: "total_cents", What: "response field type changed"}}, + title: "Handle changed type of field total_cents on fixture GET /v1/orders", branch: "tend/api-fixture-get-v1-orders-total-cents", }, { name: "api operation removed", ch: core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "fixture", Method: "DELETE", Path: "/v1/orders/{id}", What: "operation removed"}}, - title: "Handle removed DELETE /v1/orders/{id}", + title: "Handle removed fixture DELETE /v1/orders/{id}", branch: "tend/api-fixture-delete-v1-orders-id", }, { name: "api parameter removed", ch: core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "fixture", Method: "GET", Path: "/v1/orders", Field: "expand", What: "parameter removed"}}, - title: "Handle removed parameter expand on GET /v1/orders", + title: "Handle removed parameter expand on fixture GET /v1/orders", branch: "tend/api-fixture-get-v1-orders-expand", }, { name: "api required parameter added", ch: core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "fixture", Method: "POST", Path: "/v1/orders", Field: "currency", What: "required parameter added"}}, - title: "Handle new required parameter currency on POST /v1/orders", + title: "Handle new required parameter currency on fixture POST /v1/orders", branch: "tend/api-fixture-post-v1-orders-currency", }, { @@ -279,6 +285,30 @@ func TestBranchLength(t *testing.T) { } } +// Changes whose names share a long start get branches of their own. +func TestBranchesStayApart(t *testing.T) { + op := func(field string) core.Change { + return core.Change{API: &core.APIChange{Provider: "stripe", Method: "POST", Path: "/v1/test_helpers/issuing/authorizations/{authorization}/finalize_amount", Field: field}} + } + azure := "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/" + pairs := [][2]core.Change{ + {op("fleet.cardholder_prompt_data"), op("fuel.unit_cost_decimal")}, + { + {Deps: []core.Dep{dep("go", azure+"armcontainerservice/v4", "1.0.0")}, To: "1.2.0"}, + {Deps: []core.Dep{dep("go", azure+"armcontainerservicefleet", "1.0.0")}, To: "1.2.0"}, + }, + } + for _, p := range pairs { + a, b := Branch(&p[0]), Branch(&p[1]) + if a == b || len(a) > 100 || len(b) > 100 { + t.Errorf("branches %q and %q", a, b) + } + if a != Branch(&p[0]) { + t.Errorf("branch %q is not stable", a) + } + } +} + func TestMessage(t *testing.T) { ch := core.Change{Deps: []core.Dep{dep("npm", "stripe", "14.2.0")}, To: "16.1.0"} p := &core.Patch{Applied: []string{"bumped stripe 14.2.0 -> 16.1.0 (package.json)", "renamed 2 call sites"}} @@ -312,7 +342,7 @@ func TestTitleOfWhatThePRCarries(t *testing.T) { {BodyInput{Change: &ch, Patch: &core.Patch{}, Option: 1}, "Migrate off deprecated @fixture/pay 1.x"}, {BodyInput{Change: &ch, Patch: &core.Patch{}, Option: 2}, "Pin @fixture/pay to 1.4.0"}, {BodyInput{Change: &core.Change{Kind: core.Deprecation, API: &core.APIChange{Provider: "fixture", Method: "GET", Path: "/v1/orders/{id}/legacy", What: "operation deprecated"}}, Patch: decision}, - "Migrate off deprecated GET /v1/orders/{id}/legacy"}, + "Migrate off deprecated fixture GET /v1/orders/{id}/legacy"}, } for _, tt := range tests { if got := Title(tt.in, ""); got != tt.want { diff --git a/internal/deliver/track.go b/internal/deliver/track.go index 56d97ba..e01d91c 100644 --- a/internal/deliver/track.go +++ b/internal/deliver/track.go @@ -2,6 +2,9 @@ package deliver import ( "context" + "errors" + "fmt" + "net/http" "slices" "strconv" "strings" @@ -87,25 +90,36 @@ type issue struct { Title string `json:"title"` Body string `json:"body"` State string `json:"state"` - Pull *struct { + Role string `json:"author_association"` + User struct { + Type string `json:"type"` + } `json:"user"` + Pull *struct { URL string `json:"url"` } `json:"pull_request"` } +// trusted reports whether i was opened by an app, as tend in Actions is, +// or by someone with write access, whose token tend may run with. Anyone +// else can open an issue with tend's marker in it. +func (i issue) trusted() bool { + return strings.EqualFold(i.User.Type, "Bot") || i.Role == "OWNER" || i.Role == "MEMBER" || i.Role == "COLLABORATOR" +} + func (i issue) issue() *core.Issue { return &core.Issue{Number: i.Number, Title: i.Title, Body: i.Body, Open: i.State == "open"} } -// FindIssue looks through the issues tend's account opened for the one -// whose body holds marker, newest first. Pull requests, which the issues -// API lists too, never count. +// FindIssue looks for the issue whose body holds marker, newest first, +// among those an app or someone with write access opened. Pull requests, +// which the issues API lists too, never count. func (g *GitHub) FindIssue(ctx context.Context, marker string) (*core.Issue, error) { all, err := getAll[issue](ctx, g, g.repoPath("/issues?state=all&sort=created&direction=desc")) if err != nil { return nil, err } for _, i := range all { - if i.Pull == nil && strings.Contains(i.Body, marker) { + if i.Pull == nil && i.trusted() && strings.Contains(i.Body, marker) { return i.issue(), nil } } @@ -134,5 +148,12 @@ func (g *GitHub) EditIssue(ctx context.Context, number int, body string, open bo if open { state = "open" } - return g.do(ctx, "PATCH", g.repoPath("/issues/"+strconv.Itoa(number)), map[string]any{"body": body, "state": state}, nil) + err := g.do(ctx, "PATCH", g.repoPath("/issues/"+strconv.Itoa(number)), map[string]any{"body": body, "state": state}, nil) + if isStatus(err, http.StatusNotFound) || isStatus(err, http.StatusGone) || isStatus(err, http.StatusMovedPermanently) { + return fmt.Errorf("%w: %w", ErrGone, err) + } + return err } + +// ErrGone is an issue that was deleted, or moved to another repo. +var ErrGone = errors.New("the issue is gone") diff --git a/internal/deliver/track_test.go b/internal/deliver/track_test.go index 9b06cfc..cb3f8bb 100644 --- a/internal/deliver/track_test.go +++ b/internal/deliver/track_test.go @@ -2,6 +2,7 @@ package deliver import ( "context" + "errors" "reflect" "testing" @@ -47,8 +48,9 @@ func TestChecks(t *testing.T) { func TestTrackingIssue(t *testing.T) { api := newAPI(t, []step{ {req: "GET /repos/acme/shop/issues?state=all&sort=created&direction=desc&per_page=100", resp: `[ - {"number": 9, "title": "a PR", "body": "", "state": "open", "pull_request": {"url": "x"}}, - {"number": 7, "title": "tend: what it could not do on its own", "body": "list\n", "state": "closed"} + {"number": 9, "title": "a PR", "body": "", "state": "open", "author_association": "OWNER", "pull_request": {"url": "x"}}, + {"number": 8, "title": "looks like tend's", "body": "", "state": "open", "author_association": "NONE", "user": {"type": "User"}}, + {"number": 7, "title": "tend: what it could not do on its own", "body": "list\n", "state": "closed", "author_association": "NONE", "user": {"type": "Bot"}} ]`}, {req: "GET /repos/acme/shop/labels/tend", resp: `{"name": "tend"}`}, {req: "POST /repos/acme/shop/issues", body: `{"body":"b","labels":["tend"],"title":"t"}`, status: 201, resp: `{"number": 12, "title": "t", "body": "b", "state": "open"}`}, @@ -67,3 +69,18 @@ func TestTrackingIssue(t *testing.T) { t.Fatal(err) } } + +// An issue deleted, or moved to another repo, which GitHub answers with a +// redirect, is gone: never an edit that went through. +func TestEditIssueGone(t *testing.T) { + for _, status := range []int{410, 404, 301} { + st := step{req: "PATCH /repos/acme/shop/issues/7", body: `{"body":"c","state":"open"}`, status: status, resp: `{"message": "gone"}`} + if status == 301 { + st.header = map[string]string{"Location": "/repos/acme/other/issues/3"} + } + api := newAPI(t, []step{st}) + if err := api.g.EditIssue(context.Background(), 7, "c", true); !errors.Is(err, ErrGone) { + t.Errorf("%d: EditIssue = %v, want ErrGone", status, err) + } + } +} diff --git a/internal/e2e/catchup_test.go b/internal/e2e/catchup_test.go index abb282d..d6a06f1 100644 --- a/internal/e2e/catchup_test.go +++ b/internal/e2e/catchup_test.go @@ -114,6 +114,9 @@ func TestCatchUpLegacy(t *testing.T) { w.golden("4-body.md", pr.Body) w.golden("4-diff.patch", w.diff(pr.Branch)+"\n") w.merge(4) + if res := w.tend("check").want(t, 0); strings.Contains(res.stdout, " first ") { + t.Errorf("check after the last stage merged still lists a stage:\n%s", res.stdout) + } w.pull() w.model = replies(t) diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go index 0615afd..ba9eff1 100644 --- a/internal/e2e/e2e_test.go +++ b/internal/e2e/e2e_test.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "slices" "strings" "testing" @@ -14,8 +15,13 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/deliver" "github.com/mohsensc/tend-cli/internal/model" + "github.com/mohsensc/tend-cli/internal/state" ) +// treeTrailer is the one trailer tend's commits carry: the tree they were +// proven on. +var treeTrailer = regexp.MustCompile(`^Tend-Tree: [0-9a-f]{40}$`) + // script is a model that writes the migration in replies/.diff and finds // nothing to say when vetting asks about it. func script(t *testing.T, name string) *model.Script { @@ -106,7 +112,7 @@ func TestNodeDeprecation(t *testing.T) { t.Fatalf("%d commits on the branch, want 1", len(cs)) } c := cs[0] - if c.subject != "Migrate off deprecated @fixture/pay 1.x" || c.author != maintainer.Name+" <"+maintainer.Email+">" || c.trailers != "" { + if c.subject != "Migrate off deprecated @fixture/pay 1.x" || c.author != maintainer.Name+" <"+maintainer.Email+">" || !treeTrailer.MatchString(c.trailers) { t.Errorf("commit = %+v", c) } if !slices.Equal(c.files, []string{"package-lock.json", "package.json", "src/billing.js"}) { @@ -251,7 +257,7 @@ test('charges go to the charges endpoint', async () => { if d := w.diff(pr.Branch); d != "" { t.Errorf("a decision PR changed files:\n%s", d) } - if cs := w.commits(pr.Branch); len(cs) != 1 || cs[0].files != nil || cs[0].body != "" { + if cs := w.commits(pr.Branch); len(cs) != 1 || cs[0].files != nil || !treeTrailer.MatchString(cs[0].body) { t.Errorf("want one empty commit, got %+v", cs) } if pr.Draft { @@ -374,7 +380,7 @@ func TestFormat(t *testing.T) { if !pr.Draft { t.Error("not a draft") } - for _, want := range []string{"Tests already fail on `main@BASE`", "| `go vet ./... && go test ./...` | failed (exit 1)"} { + for _, want := range []string{"`go vet ./... && go test ./...` fails on `main@BASE` and passes with this change", "| `go vet ./... && go test ./...` | failed (exit 1)"} { if !strings.Contains(w.stable(pr.Body), want) { t.Errorf("body lacks %q:\n%s", want, pr.Body) } @@ -392,7 +398,7 @@ func TestAPIDeprecationThenRemoval(t *testing.T) { w.tend("run").want(t, 0) pr := onlyPR(t, w) - if pr.Title != "Migrate off deprecated GET /v1/orders/{id}/legacy" { + if pr.Title != "Migrate off deprecated fixture GET /v1/orders/{id}/legacy" { t.Errorf("title %q", pr.Title) } w.golden("decision-body.md", pr.Body) @@ -413,7 +419,7 @@ func TestAPIDeprecationThenRemoval(t *testing.T) { w.closeByHuman(1) w.model = script(t, "py-api") res := w.tend("run").want(t, 0) - if !strings.HasPrefix(res.stdout, "tend: opened #2 Handle removed field total_cents on GET /v1/orders ") { + if !strings.HasPrefix(res.stdout, "tend: opened #2 Handle removed field total_cents on fixture GET /v1/orders ") { t.Fatalf("run said %q", res.stdout) } if p := w.state().Parked["api/fixture/GET /v1/orders/{id}/legacy"]; p.Reason != "rejected" || p.PR != 1 { @@ -759,7 +765,8 @@ func TestCommentSkip(t *testing.T) { } } -// `tend retry` redoes the work even when nothing moved. +// `tend retry` redoes the work even when nothing moved, and says the PR it +// came to the same answer for is up to date. func TestCommentRetry(t *testing.T) { need(t, "node", "npm") w := setup(t, "node-sdk") @@ -769,8 +776,8 @@ func TestCommentRetry(t *testing.T) { w.forge.Now = func() time.Time { return now.Add(time.Hour) } w.say(1, "maintainer", "OWNER", "tend retry") w.model = script(t, "node-sdk") - if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: updated #1 ") { - t.Errorf("retry: %q", res.stdout) + if res := w.tend("run").want(t, 0); !strings.HasPrefix(res.stdout, "tend: #1 ") || !strings.Contains(res.stdout, " is up to date ") || !strings.Contains(res.stderr, "proving patched") { + t.Errorf("retry: %q\n%s", res.stdout, res.stderr) } } @@ -902,11 +909,13 @@ func TestLockHeld(t *testing.T) { w := setup(t, "empty") w.tend("check").want(t, 0) dir := filepath.Dir(w.statePath()) - if err := os.WriteFile(filepath.Join(dir, "lock"), []byte(fmt.Sprintf("4242 %d\n", time.Now().Unix())), 0o644); err != nil { + release, err := state.Lock(dir) + if err != nil { t.Fatal(err) } + defer release() res := w.tend("run").want(t, 1) - if !strings.Contains(res.stderr, "pid 4242") { + if !strings.Contains(res.stderr, fmt.Sprintf("pid %d", os.Getpid())) { t.Errorf("stderr %q does not name the holder", res.stderr) } } diff --git a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/body.md b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/body.md index b2f01a9..64a289f 100644 --- a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/body.md +++ b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/body.md @@ -1,6 +1,6 @@ ## fixture GET /v1/orders -**Why**: breaking · response field removed (total_cents) · published 2026-10-21 +**Why**: breaking · response field removed (total\_cents) · published 2026-10-21 ### What changed upstream @@ -12,7 +12,7 @@ ### Touched in this repo -- `app/orders.py:9` `/v1/orders` +- `app/orders.py:9` `with urllib.request.urlopen(BASE + "/v1/orders") as res:` - `app/orders.py:17` `cents += order["total_cents"]` → `cents += order["total"]["amount"]` Part of this change was written by a model. The vetting section below covers it. diff --git a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v1.json b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v1.json index 19006b7..30822d5 100644 --- a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v1.json +++ b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v1.json @@ -27,12 +27,12 @@ "col": 0, "file": "app/orders.py", "line": 25, - "text": "/v1/orders/%s/legacy" + "text": "with urllib.request.urlopen(BASE + \"/v1/orders/%s/legacy\" % order_id) as res:" } ], "sunset": "2027-03-01T00:00:00Z" } ], - "repo": "acme/py-api", + "repo": "$TMP/work", "untracked": [] } diff --git a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v2.json b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v2.json index 22872cf..7f35af1 100644 --- a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v2.json +++ b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/check-v2.json @@ -4,13 +4,13 @@ "notes": [], "open": { "base": "main", - "body": "## fixture GET /v1/orders/{id}/legacy\n\n**Why**: deprecation · operation deprecated · sunset 2027-03-01\n\n### What changed upstream\n\n- **fixture spec 2025-01-01** · [source](https://api.fixture.dev/openapi.json)\n ```\n Fetch an order in the legacy shape\n Use GET /v1/orders/{id} instead; it returns the total as an amount and a currency.\n ```\n\n### Touched in this repo\n\nNothing was changed in the code. No model is configured to move the call site, and there is nothing to bump.\n\nWhere the code uses it:\n\n- `app/orders.py:25` `/v1/orders/%s/legacy`\n\n### Proof\n\n| step | base (main@BASE) | patched |\n|---|---|---|\n| `python3 -m unittest` | ok · 0s | not run |\n\ntend · comment `tend skip` or `tend retry`\n\n", + "body": "## fixture GET /v1/orders/{id}/legacy\n\n**Why**: deprecation · operation deprecated · sunset 2027-03-01\n\n### What changed upstream\n\n- **fixture spec 2025-01-01** · [source](https://api.fixture.dev/openapi.json)\n ```\n Fetch an order in the legacy shape\n Use GET /v1/orders/{id} instead; it returns the total as an amount and a currency.\n ```\n\n### Touched in this repo\n\nNothing was changed in the code. No model is configured to move the call site, and there is nothing to bump.\n\nWhere the code uses it:\n\n- `app/orders.py:25` `with urllib.request.urlopen(BASE + \"/v1/orders/%s/legacy\" % order_id) as res:`\n\n### Proof\n\n| step | base (main@BASE) | patched |\n|---|---|---|\n| `python3 -m unittest` | ok · 0s | not run |\n\ntend · comment `tend skip` or `tend retry`\n\n", "branch": "tend/api-fixture-get-v1-orders-id-legacy", "draft": false, "nodeID": "PR_1", "number": 1, "state": "open", - "title": "Migrate off deprecated GET /v1/orders/{id}/legacy", + "title": "Migrate off deprecated fixture GET /v1/orders/{id}/legacy", "url": "https://github.com/acme/py-api/pull/1" }, "queue": [ @@ -39,7 +39,7 @@ "col": 0, "file": "app/orders.py", "line": 9, - "text": "/v1/orders" + "text": "with urllib.request.urlopen(BASE + \"/v1/orders\") as res:" }, { "call": false, @@ -76,12 +76,12 @@ "col": 0, "file": "app/orders.py", "line": 25, - "text": "/v1/orders/%s/legacy" + "text": "with urllib.request.urlopen(BASE + \"/v1/orders/%s/legacy\" % order_id) as res:" } ], "sunset": "2027-03-01T00:00:00Z" } ], - "repo": "acme/py-api", + "repo": "$TMP/work", "untracked": [] } diff --git a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/decision-body.md b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/decision-body.md index bb94389..2468646 100644 --- a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/decision-body.md +++ b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/decision-body.md @@ -16,7 +16,7 @@ Nothing was changed in the code. No model is configured to move the call site, a Where the code uses it: -- `app/orders.py:25` `/v1/orders/%s/legacy` +- `app/orders.py:25` `with urllib.request.urlopen(BASE + "/v1/orders/%s/legacy" % order_id) as res:` ### Proof diff --git a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/title.txt b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/title.txt index 3f7dd67..27e49f1 100644 --- a/internal/e2e/testdata/TestAPIDeprecationThenRemoval/title.txt +++ b/internal/e2e/testdata/TestAPIDeprecationThenRemoval/title.txt @@ -1 +1 @@ -Handle removed field total_cents on GET /v1/orders +Handle removed field total_cents on fixture GET /v1/orders diff --git a/internal/e2e/testdata/TestCIImages/check.json b/internal/e2e/testdata/TestCIImages/check.json index 2db2c49..2e72b17 100644 --- a/internal/e2e/testdata/TestCIImages/check.json +++ b/internal/e2e/testdata/TestCIImages/check.json @@ -180,6 +180,30 @@ "text": "## What's Changed\r\n* Port v6 cleanup to v5 by @ericsciple in https://github.com/actions/checkout/pull/2301\r\n\r\n\r\n**Full Changelog**: https://github.com/actions/checkout/compare/v5...v5.0.1", "title": "v5.0.1", "url": "https://github.com/actions/checkout/releases/tag/v5.0.1" + }, + { + "source": "releases", + "text": "## What's Changed\r\n* Update actions checkout to use node 24 by @salmanmkc in https://github.com/actions/checkout/pull/2226\r\n* Prepare v5.0.0 release by @salmanmkc in https://github.com/actions/checkout/pull/2238\r\n\r\n## ⚠️ Minimum Compatible Runner Version\r\n\r\n**v2.327.1** \r\n[Release Notes](https://github.com/actions/runner/releases/tag/v2.327.1)\r\n\r\nMake sure your runner is updated to this version or newer to use this release.\r\n\r\n**Full Changelog**: https://github.com/actions/checkout/compare/v4...v5.0.0", + "title": "v5.0.0", + "url": "https://github.com/actions/checkout/releases/tag/v5.0.0" + }, + { + "source": "releases", + "text": "## What's Changed\r\n* Update default runtime to node20 by @takost in https://github.com/actions/checkout/pull/1436\r\n* Support fetching without the --progress option by @simonbaird in https://github.com/actions/checkout/pull/1067\r\n* Release 4.0.0 by @takost in https://github.com/actions/checkout/pull/1447\r\n\r\n## New Contributors\r\n* @takost made their first contribution in https://github.com/actions/checkout/pull/1436\r\n* @simonbaird made their first contribution in https://github.com/actions/checkout/pull/1067\r\n\r\n**Full Changelog**: https://github.com/actions/checkout/compare/v3...v4.0.0", + "title": "v4.0.0", + "url": "https://github.com/actions/checkout/releases/tag/v4.0.0" + }, + { + "source": "releases", + "text": "- Updated to the node16 runtime by default\r\n - This requires a minimum [Actions Runner](https://github.com/actions/runner/releases/tag/v2.285.0) version of v2.285.0 to run, which is by default available in GHES 3.4 or later.", + "title": "v3.0.0", + "url": "https://github.com/actions/checkout/releases/tag/v3.0.0" + }, + { + "source": "releases", + "text": "- [Group output](https://github.com/actions/checkout/pull/191)\r\n- [Changes to support GHES alpha release](https://github.com/actions/checkout/pull/199)\r\n- [Persist core.sshCommand for submodules](https://github.com/actions/checkout/pull/184)\r\n- [Add support ssh](https://github.com/actions/checkout/pull/163)\r\n- [Convert submodule SSH URL to HTTPS, when not using SSH](https://github.com/actions/checkout/pull/179)\r\n- [Add submodule support](https://github.com/actions/checkout/pull/157)\r\n- [Follow proxy settings](https://github.com/actions/checkout/pull/144)\r\n- [Fix ref for pr closed event when a pr is merged](https://github.com/actions/checkout/pull/141)\r\n- [Fix issue checking detached when git less than 2.22](https://github.com/actions/checkout/pull/128)", + "title": "v2.1.0", + "url": "https://github.com/actions/checkout/releases/tag/v2.1.0" } ], "id": "actions/actions/checkout@v7", @@ -269,6 +293,6 @@ "to": "26-alpine" } ], - "repo": "acme/ci-images", + "repo": "$TMP/work", "untracked": [] } diff --git a/internal/e2e/testdata/TestCIImages/checkout-body.md b/internal/e2e/testdata/TestCIImages/checkout-body.md index 3ce3169..beaa50d 100644 --- a/internal/e2e/testdata/TestCIImages/checkout-body.md +++ b/internal/e2e/testdata/TestCIImages/checkout-body.md @@ -1,7 +1,7 @@ ## actions/checkout v2 → v7 **Why**: deprecation · runs on node12, removed from GitHub runners -**Level**: major (2 → 7); release notes below mention breaking changes in 2 of 8 releases +**Level**: major (2 → 7); release notes below mention breaking changes in 2 of 12 releases ### What changed upstream @@ -46,7 +46,7 @@ https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/ for more details about this breaking change **Full Changelog**: https://github.com/actions/checkout/compare/v5.0.1...v5.1.0 ``` -- 4 more releases, not quoted +- 8 more releases, not quoted ### Touched in this repo diff --git a/internal/e2e/testdata/TestGoSecurity/check.json b/internal/e2e/testdata/TestGoSecurity/check.json index 8c0daac..3d246d6 100644 --- a/internal/e2e/testdata/TestGoSecurity/check.json +++ b/internal/e2e/testdata/TestGoSecurity/check.json @@ -115,6 +115,6 @@ "to": "v1.0.1" } ], - "repo": "acme/go-vuln", + "repo": "$TMP/work", "untracked": [] } diff --git a/internal/e2e/testdata/TestInit/workflow.yml b/internal/e2e/testdata/TestInit/workflow.yml index 1437ccf..2fac1de 100644 --- a/internal/e2e/testdata/TestInit/workflow.yml +++ b/internal/e2e/testdata/TestInit/workflow.yml @@ -12,6 +12,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - with: {persist-credentials: false} + with: {persist-credentials: false, fetch-depth: 0} - uses: mohsensc/tend-cli@v1 with: {model-key: "${{ secrets.TEND_MODEL_KEY }}"} diff --git a/internal/e2e/testdata/TestNodeChoice/body.md b/internal/e2e/testdata/TestNodeChoice/body.md index 57bc976..166f34c 100644 --- a/internal/e2e/testdata/TestNodeChoice/body.md +++ b/internal/e2e/testdata/TestNodeChoice/body.md @@ -1,11 +1,11 @@ ## @fixture/pay 1.4.0 → 2.0.0 -**Why**: deprecation · 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +**Why**: deprecation · 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* **Level**: major (1 → 2) ### What changed upstream -- **@fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) +- **@​fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) ``` 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* ``` diff --git a/internal/e2e/testdata/TestNodeDecision/applied-body.md b/internal/e2e/testdata/TestNodeDecision/applied-body.md index 2bd6fca..181d663 100644 --- a/internal/e2e/testdata/TestNodeDecision/applied-body.md +++ b/internal/e2e/testdata/TestNodeDecision/applied-body.md @@ -1,11 +1,11 @@ ## @fixture/pay 1.4.0 → 2.0.0 -**Why**: deprecation · 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +**Why**: deprecation · 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* **Level**: major (1 → 2) ### What changed upstream -- **@fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) +- **@​fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) ``` 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* ``` diff --git a/internal/e2e/testdata/TestNodeDecision/body.md b/internal/e2e/testdata/TestNodeDecision/body.md index 938aa3a..843ee6c 100644 --- a/internal/e2e/testdata/TestNodeDecision/body.md +++ b/internal/e2e/testdata/TestNodeDecision/body.md @@ -1,11 +1,11 @@ ## @fixture/pay 1.4.0 → 2.0.0 -**Why**: deprecation · 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +**Why**: deprecation · 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* **Level**: major (1 → 2) ### What changed upstream -- **@fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) +- **@​fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) ``` 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* ``` diff --git a/internal/e2e/testdata/TestNodeDeprecation/body.md b/internal/e2e/testdata/TestNodeDeprecation/body.md index 7b90a6c..00f5a90 100644 --- a/internal/e2e/testdata/TestNodeDeprecation/body.md +++ b/internal/e2e/testdata/TestNodeDeprecation/body.md @@ -1,11 +1,11 @@ ## @fixture/pay 1.4.0 → 2.0.0 -**Why**: deprecation · 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +**Why**: deprecation · 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* **Level**: major (1 → 2) ### What changed upstream -- **@fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) +- **@​fixture/pay 1.4.0 is deprecated** · [source](https://www.npmjs.com/package/@fixture/pay) ``` 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* ``` diff --git a/internal/e2e/testdata/TestNodeDeprecation/check.json b/internal/e2e/testdata/TestNodeDeprecation/check.json index 11c69e9..ffc46ab 100644 --- a/internal/e2e/testdata/TestNodeDeprecation/check.json +++ b/internal/e2e/testdata/TestNodeDeprecation/check.json @@ -112,6 +112,6 @@ "to": "2.0.0" } ], - "repo": "acme/node-sdk", + "repo": "$TMP/work", "untracked": [] } diff --git a/internal/e2e/testdata/TestOnboardCatchUp/body.md b/internal/e2e/testdata/TestOnboardCatchUp/body.md index 234b583..113d728 100644 --- a/internal/e2e/testdata/TestOnboardCatchUp/body.md +++ b/internal/e2e/testdata/TestOnboardCatchUp/body.md @@ -11,7 +11,7 @@ npm: ### Deprecated -- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* - `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })` - `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)` diff --git a/internal/e2e/testdata/TestOnboardNode/body.md b/internal/e2e/testdata/TestOnboardNode/body.md index a94e89b..427e472 100644 --- a/internal/e2e/testdata/TestOnboardNode/body.md +++ b/internal/e2e/testdata/TestOnboardNode/body.md @@ -4,7 +4,7 @@ Part of this pull request was written by a model. The vetting section below cove ### Deprecated -- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.* was replaced by paymentIntents.* +- `@fixture/pay` 1.4.0 → 2.0.0: 1.x is deprecated, use 2.x: charges.\* was replaced by paymentIntents.\* - `src/billing.js:12` `return pay.charges.create({ amount, currency: 'usd', customer })` → `return pay.paymentIntents.create({ amount, currency: 'usd', customer })` - `src/billing.js:20` `return pay.charges.retrieve(id)` → `return pay.paymentIntents.retrieve(id)` diff --git a/internal/e2e/testdata/TestOnboardNode/check.txt b/internal/e2e/testdata/TestOnboardNode/check.txt index a53f4f9..8ddc460 100644 --- a/internal/e2e/testdata/TestOnboardNode/check.txt +++ b/internal/e2e/testdata/TestOnboardNode/check.txt @@ -1,4 +1,4 @@ tend: 2 queued, 0 skipped, no open PR - 1 first first PR move off 1 deprecated · remove 3 unused + 1 first catch-up 1 deprecation · 3 unused dependencies 2 deprecation @fixture/pay 1.4.0 → 2.0.0 2 sites diff --git a/internal/e2e/testdata/TestPinnedInScript/body.md b/internal/e2e/testdata/TestPinnedInScript/body.md index 5f20e47..fb455c6 100644 --- a/internal/e2e/testdata/TestPinnedInScript/body.md +++ b/internal/e2e/testdata/TestPinnedInScript/body.md @@ -1,7 +1,7 @@ ## protoc 25.1 → 36.2 **Why**: breaking · major release · released 2026-09-17 -**Level**: major (25 → 36); release notes below mention breaking changes in 3 of 8 releases +**Level**: major (25 → 36); release notes below mention breaking changes in 4 of 12 releases ### What changed upstream @@ -85,6 +85,44 @@ * [Python] Raise errors in OSS when assign bool to int/enum field in Python Proto. (https://github.com/protocolbuffers/protobuf/commit/5b116fe2f14f49dd0cc3b76089983717f211025c) … ``` +- **v28.0 Protocol Buffers v28.0** · [full notes](https://github.com/protocolbuffers/protobuf/releases/tag/v28.0) + ``` + # Announcements + * [Protobuf News](https://protobuf.dev/news/) may include additional announcements or pre-announcements for upcoming changes. + # Compiler + * UPB text encoder without using reflection for Rust (used for a message's Debug trait) that will print out field number to value entries instead of field name to value entries of a message like how it's expected for the usual text format using reflection. (https://github.com/protocolbuffers/protobuf/commit/f9dd9ce66e05d034378b4b37b82307f41fc3395c) + * Enable MessageLite::DebugString to use Message::DebugString where possible. (https://github.com/protocolbuffers/protobuf/commit/f810cc5b668d78cb982f44b34f188160d55c27d6) + * Always report plugin support errors from protoc. (https://github.com/protocolbuffers/protobuf/commit/986ef8d80bb9432ec7c3a83f0988e2cc589d5cee) + … + ``` +- **v27.0 Protocol Buffers v27.0** · [full notes](https://github.com/protocolbuffers/protobuf/releases/tag/v27.0) + ``` + # Announcements + * [Protobuf News](https://protobuf.dev/news/) may include additional announcements or pre-announcements for upcoming changes. + # Compiler + * Future-proof edition 2023 against feature value support windows. (https://github.com/protocolbuffers/protobuf/commit/fea6847e408d58e40a2f10ab124ae795afd703d4) + * Mark deleted fields in `descriptor.proto` reserved (https://github.com/protocolbuffers/protobuf/commit/d2da4636c06ccad04371434dabbf24ca1c6ee83e) + * Add extension declarations for known features. (https://github.com/protocolbuffers/protobuf/commit/f8d0a5b1dd6f5655be3c0d1a8aa1fec88e80c13a) + … + ``` +- **v26.0 Protocol Buffers v26.0** · [full notes](https://github.com/protocolbuffers/protobuf/releases/tag/v26.0) + ``` + # Announcements + * **This version includes breaking changes to: Java, PHP, C++, Ruby, Python.** + * [Java] Remove the deprecated always_print_primitive_fields option from Java, Python and C++ JSON parsers. (https://github.com/protocolbuffers/protobuf/commit/06e7caba58ede0220b110b89d08f329e5f8a7537) + * [Java] Remove unused helper methods for creating new mutable arraylists. (https://github.com/protocolbuffers/protobuf/commit/787447430fc9a69c071393e85a380b664d261ab4) + * [Java] Use Editions features in Java full runtimes. (https://github.com/protocolbuffers/protobuf/commit/65c65c2d04b293225db150029d005056a9f078b8) + * [Java] Stop generating the "newInstance" method. This is not used anymore. (https://github.com/protocolbuffers/protobuf/commit/c0d08bdcade9d44698015b85c9c23343ca1319b7) + … + ``` +- **v25.2 Protocol Buffers v25.2** · [full notes](https://github.com/protocolbuffers/protobuf/releases/tag/v25.2) + ``` + # Announcements + * [Protobuf News](https://protobuf.dev/news/) may include additional announcements or pre-announcements for upcoming changes. + # C++ + * Only substitute prefixes during installation setup. (https://github.com/protocolbuffers/protobuf/commit/05ad6525c3aae2ae5b6e1987227445a420caada7) + * Register a shutdown delete for C++ feature defaults (https://github.com/protocolbuffers/protobuf/commit/3d5c709ebe01f1f9f3d3345cd4239e239081f8fd) + ``` ### Touched in this repo diff --git a/internal/e2e/testdata/TestRuntimeMinimum/check.txt b/internal/e2e/testdata/TestRuntimeMinimum/check.txt index 0f4dffc..0909a12 100644 --- a/internal/e2e/testdata/TestRuntimeMinimum/check.txt +++ b/internal/e2e/testdata/TestRuntimeMinimum/check.txt @@ -1,3 +1,3 @@ tend: 1 queued, 0 skipped, no open PR - 1 deprecation go (go.mod) 1.24 → 1.26 EOL 2026-02-10 · go.mod:3 + 1 deprecation go (go.mod) 1.24 → 1.26 EOL since 2026-02-10 · go.mod:3 diff --git a/internal/e2e/testdata/TestToolchainEndOfLife/check.txt b/internal/e2e/testdata/TestToolchainEndOfLife/check.txt index 6c09bf1..708f63a 100644 --- a/internal/e2e/testdata/TestToolchainEndOfLife/check.txt +++ b/internal/e2e/testdata/TestToolchainEndOfLife/check.txt @@ -1,3 +1,3 @@ tend: 1 queued, 0 skipped, no open PR - 1 deprecation nodejs 16.20.2 → 24.22.0 EOL 2023-09-11 · .nvmrc:1 + 1 deprecation nodejs 16.20.2 → 24.22.0 EOL since 2023-09-11 · .nvmrc:1 diff --git a/internal/e2e/testdata/TestUnknownAPIs/body.md b/internal/e2e/testdata/TestUnknownAPIs/body.md index 7180661..d100b3a 100644 --- a/internal/e2e/testdata/TestUnknownAPIs/body.md +++ b/internal/e2e/testdata/TestUnknownAPIs/body.md @@ -16,7 +16,7 @@ Nothing was changed in the code. No model is configured to move the call site, a Where the code uses it: -- `src/inventory.js:4` `GET https://api.example-unknown.com/v2/items` +- `src/inventory.js:4` `const res = await fetch('https://api.example-unknown.com/v2/items')` ### Proof diff --git a/internal/e2e/testdata/TestUnknownAPIs/title.txt b/internal/e2e/testdata/TestUnknownAPIs/title.txt index 02200fd..76611eb 100644 --- a/internal/e2e/testdata/TestUnknownAPIs/title.txt +++ b/internal/e2e/testdata/TestUnknownAPIs/title.txt @@ -1 +1 @@ -Migrate off deprecated GET /v2/items +Migrate off deprecated api.example-unknown.com GET /v2/items diff --git a/internal/eco/actions.go b/internal/eco/actions.go index c21924e..a7c52fc 100644 --- a/internal/eco/actions.go +++ b/internal/eco/actions.go @@ -318,6 +318,27 @@ func (actions) Bump(ctx context.Context, root string, d core.Dep, to, toName str return res, nil } +// Settle reads a ref pinned to a bare commit, with no "# v4.2.2" comment to +// say which release it is, as the most specific tag on that commit. +func (actions) Settle(d core.Dep, m *core.Meta) (core.Dep, error) { + if d.Pin == "" || d.Version != d.Pin { + return d, nil + } + v, _ := actionsShas.Load(d.Name) + tags, _ := v.(map[string]string) + name, best := "", 0 + for t, sha := range tags { + if pv, ok := ver.Parse(t); ok && sha == d.Pin && (len(pv.Nums) > best || len(pv.Nums) == best && t < name) { + name, best = t, len(pv.Nums) + } + } + if name == "" { + return d, fmt.Errorf("pinned to untagged commit %s, not tracked", core.Short(d.Pin)) + } + d.Version = name + return d, nil +} + func withTagComment(line, tag string) string { if m := trailingVer.FindStringSubmatchIndex(line); m != nil { return line[:m[2]] + tag + line[m[3]:] diff --git a/internal/eco/actions_test.go b/internal/eco/actions_test.go index 1fb1546..a610a67 100644 --- a/internal/eco/actions_test.go +++ b/internal/eco/actions_test.go @@ -408,3 +408,25 @@ func TestActionsBumpKeepsOtherLines(t *testing.T) { t.Errorf("file changed beyond the one line:\n%s", after) } } + +// A step pinned to a bare commit, with no comment naming its release, is at +// the most specific tag on that commit; one no tag points at is said, not +// read as a version. +func TestActionsSettle(t *testing.T) { + sha := "11bd71901bbe5b1630ceea73d27597364c9af683" + actionsShas.Store("acme/settle", map[string]string{"v4": sha, "v4.2": sha, "v4.2.2": sha, "v4.2.1": "aaaa71901bbe5b1630ceea73d27597364c9af683"}) + d := core.Dep{Ecosystem: core.Actions, Name: "acme/settle", Version: sha, Req: sha, Pin: sha} + got, err := actions{}.Settle(d, &core.Meta{}) + if err != nil || got.Version != "v4.2.2" || got.Pin != sha { + t.Errorf("Settle = %+v, %v", got, err) + } + commented := d + commented.Version = "v4.2.1" + if got, err := (actions{}).Settle(commented, &core.Meta{}); err != nil || got.Version != "v4.2.1" { + t.Errorf("a commented pin = %+v, %v", got, err) + } + d.Version, d.Pin = "cdca7365b2dadb8aad0a33bc7601856ffabcc48e", "cdca7365b2dadb8aad0a33bc7601856ffabcc48e" + if _, err := (actions{}).Settle(d, &core.Meta{}); err == nil || !strings.Contains(err.Error(), "untagged commit cdca736") { + t.Errorf("an untagged pin = %v", err) + } +} diff --git a/internal/eco/cargo.go b/internal/eco/cargo.go index 73e8b97..7d98dfb 100644 --- a/internal/eco/cargo.go +++ b/internal/eco/cargo.go @@ -361,7 +361,7 @@ func pickVersion(req string, vs []string) string { top = v } pv, ok := ver.Parse(v) - if ok && admits(req, pv, true) && (best == "" || ver.Less(best, v)) { + if ok && admits(req, pv, cargoDialect) && (best == "" || ver.Less(best, v)) { best = v } } @@ -413,7 +413,7 @@ func (cargo) Bump(ctx context.Context, root string, d core.Dep, to, toName strin if toName != "" { return cargoSwap(ctx, root, d, e, to, toName) } - next, err := fixReq(d.Req, to, true) + next, err := fixReq(d.Req, to, cargoDialect) if err != nil { return nil, fmt.Errorf("cargo: %s: %w", d.Name, err) } diff --git a/internal/eco/cargo_test.go b/internal/eco/cargo_test.go index ae6ff60..128aed6 100644 --- a/internal/eco/cargo_test.go +++ b/internal/eco/cargo_test.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "sort" "strings" "testing" @@ -134,6 +135,20 @@ func hideTools(t *testing.T) { t.Cleanup(func() { have = old }) } +// stubTools puts lock tools on PATH that change nothing, so a bump with a +// lockfile shows what it edits by hand. +func stubTools(t *testing.T, names ...string) { + t.Helper() + dir := t.TempDir() + for _, n := range names { + if err := os.WriteFile(filepath.Join(dir, n), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + have = func(n string) bool { return slices.Contains(names, n) } +} + type canned struct { url string status int @@ -238,6 +253,9 @@ type bumpCase struct { func bumpGolden(t *testing.T, e core.Ecosystem, fixture string, tests []bumpCase) { t.Helper() hideTools(t) + if e.Name() == core.Npm { + stubTools(t, "npm", "yarn", "pnpm") + } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { root := copyTestdata(t, fixture) @@ -618,10 +636,16 @@ func TestRequirements(t *testing.T) { {"gem", "1.2.3", "1.2.4", "1.2.4"}, {"gem", "!= 1.2.3", "1.2.3", "!= 1.2.3"}, {"gem", "~> 2.0.0.rc1", "2.0.0.rc2", "~> 2.0.0.rc1"}, + {"helm", "~1.2", "1.5.0", "~1.5"}, + {"helm", "~>1.2", "1.5.0", "~>1.5"}, + {"helm", "~1.2", "1.2.9", "~1.2"}, + {"helm", "~1", "1.5.0", "~1"}, + {"helm", "~1.2.3", "1.3.0", "~1.3.0"}, + {"composer", "~1.2", "1.5.0", "~1.2"}, } for _, tt := range tests { t.Run(tt.dialect+" "+tt.req+" to "+tt.to, func(t *testing.T) { - got, err := fixReq(tt.req, tt.to, tt.dialect == "cargo") + got, err := fixReq(tt.req, tt.to, map[string]dialect{"cargo": cargoDialect, "helm": helmDialect}[tt.dialect]) if tt.want == "" { if err == nil { t.Fatalf("got %q, want an error", got) @@ -638,29 +662,34 @@ func TestRequirements(t *testing.T) { func TestRequirementsAdmit(t *testing.T) { tests := []struct { req, v string - cargo bool + d dialect want bool }{ - {"1.2", "1.9.0", true, true}, - {"1.2", "2.0.0", true, false}, - {"0.2.3", "0.2.9", true, true}, - {"0.2.3", "0.3.0", true, false}, - {"~1.2", "1.2.9", true, true}, - {"~1.2", "1.3.0", true, false}, - {"~1.2", "1.3.0", false, true}, - {"=1.2", "1.2.7", true, true}, - {"1.2", "1.2.7", false, false}, - {"1.2.0", "1.2", false, true}, - {"^1.2", "2.0.0-rc.1", true, false}, - {"^2.0.0-rc.1", "2.0.0-rc.2", true, true}, - {"*", "0.0.1", true, true}, - {">=1, <3 || ^5", "5.1.0", false, true}, - {"garbage", "1.0.0", true, false}, + {"1.2", "1.9.0", cargoDialect, true}, + {"1.2", "2.0.0", cargoDialect, false}, + {"0.2.3", "0.2.9", cargoDialect, true}, + {"0.2.3", "0.3.0", cargoDialect, false}, + {"~1.2", "1.2.9", cargoDialect, true}, + {"~1.2", "1.3.0", cargoDialect, false}, + {"~1.2", "1.3.0", anyDialect, true}, + {"~1.2", "1.5.0", helmDialect, false}, + {"~>1.2", "1.5.0", helmDialect, false}, + {"~1.2", "1.2.9", helmDialect, true}, + {"~1", "1.5.0", helmDialect, true}, + {"~1", "2.0.0", helmDialect, false}, + {"=1.2", "1.2.7", cargoDialect, true}, + {"1.2", "1.2.7", anyDialect, false}, + {"1.2.0", "1.2", anyDialect, true}, + {"^1.2", "2.0.0-rc.1", cargoDialect, false}, + {"^2.0.0-rc.1", "2.0.0-rc.2", cargoDialect, true}, + {"*", "0.0.1", cargoDialect, true}, + {">=1, <3 || ^5", "5.1.0", anyDialect, true}, + {"garbage", "1.0.0", cargoDialect, false}, } for _, tt := range tests { v, _ := ver.Parse(tt.v) - if got := admits(tt.req, v, tt.cargo); got != tt.want { - t.Errorf("admits(%q, %s, cargo=%v) = %v, want %v", tt.req, tt.v, tt.cargo, got, tt.want) + if got := admits(tt.req, v, tt.d); got != tt.want { + t.Errorf("admits(%q, %s, dialect %d) = %v, want %v", tt.req, tt.v, tt.d, got, tt.want) } } } diff --git a/internal/eco/composer.go b/internal/eco/composer.go index 857adf3..2a14fb4 100644 --- a/internal/eco/composer.go +++ b/internal/eco/composer.go @@ -349,7 +349,7 @@ func composerEdit(root string, d core.Dep, to, toName string) (bool, error) { return false, err } next = "^" + shape(to, 2) - } else if next, err = fixReq(d.Req, to, false); err != nil { + } else if next, err = fixReq(d.Req, to, anyDialect); err != nil { return false, fmt.Errorf("composer: %s: %w", d.Name, err) } if next == d.Req { diff --git a/internal/eco/custom.go b/internal/eco/custom.go index 555abfe..f67958b 100644 --- a/internal/eco/custom.go +++ b/internal/eco/custom.go @@ -29,10 +29,13 @@ func (c custom) Detect(root string) ([]core.Manifest, error) { seen := map[string]bool{} var res []core.Manifest for _, d := range c.deps { - files, err := walk(root, d.File) + files, err := walkNamed(root, d.File) if err != nil { return nil, err } + if len(files) == 0 { + files = []string{d.File} + } for _, f := range files { if !seen[f] { seen[f] = true @@ -46,6 +49,15 @@ func (c custom) Detect(root string) ([]core.Manifest, error) { func (c custom) Deps(root string, m core.Manifest) ([]core.Dep, error) { src, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(m.Path))) + if err != nil && !onDisk(root, m.Path) { + var names []string + for _, d := range c.deps { + if d.File == m.Path { + names = append(names, d.Name) + } + } + return nil, fmt.Errorf("no file matches %q, named by tend.yml deps entry %s", m.Path, strings.Join(names, ", ")) + } if err != nil { return nil, err } diff --git a/internal/eco/custom_test.go b/internal/eco/custom_test.go index 76e49da..3b2ba67 100644 --- a/internal/eco/custom_test.go +++ b/internal/eco/custom_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "os/exec" "path/filepath" "slices" "strings" @@ -176,3 +177,38 @@ func TestCheck(t *testing.T) { t.Errorf("err = %v", err) } } + +func TestCustomDetectNamed(t *testing.T) { + for _, git := range []bool{true, false} { + root := t.TempDir() + write(t, root, map[string]string{"bin/install.sh": "VERSION=1.2.3\n"}) + if git { + if _, err := exec.LookPath("git"); err != nil { + continue + } + for _, args := range [][]string{{"init", "-q"}, {"add", "."}} { + if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + } + e := Custom([]config.Dep{ + {Name: "tool", File: "bin/install.sh", Match: `VERSION=(?P\S+)`, Source: "github:a/b"}, + {Name: "gone", File: "scripts/missing.sh", Match: `V=(?P\S+)`, Source: "github:a/c"}, + }) + ms, err := e.Detect(root) + if err != nil { + t.Fatal(err) + } + if len(ms) != 2 || ms[0].Path != "bin/install.sh" || ms[1].Path != "scripts/missing.sh" { + t.Fatalf("git %v: manifests = %+v", git, ms) + } + if deps, err := e.Deps(root, ms[0]); err != nil || len(deps) != 1 || deps[0].Version != "1.2.3" { + t.Errorf("git %v: deps = %+v, %v", git, deps, err) + } + _, err = e.Deps(root, ms[1]) + if err == nil || !strings.Contains(err.Error(), `no file matches "scripts/missing.sh"`) || !strings.Contains(err.Error(), "gone") || strings.Contains(err.Error(), root) { + t.Errorf("git %v: missing file err = %v", git, err) + } + } +} diff --git a/internal/eco/docker.go b/internal/eco/docker.go index cd085f5..29eba99 100644 --- a/internal/eco/docker.go +++ b/internal/eco/docker.go @@ -35,36 +35,52 @@ var dockerTags learned[string] const dockerTagCap = 500 func (docker) Detect(root string) ([]core.Manifest, error) { - files, err := walk(root, "Dockerfile", "Dockerfile.*", "*.dockerfile", - "compose.yml", "compose.yaml", "docker-compose*.yml", "docker-compose*.yaml") + files, err := walkFunc(root, func(rel string) bool { return isDockerfile(rel) || composeFile.MatchString(path.Base(rel)) }) if err != nil { return nil, err } var res []core.Manifest for _, f := range files { - if !strings.HasSuffix(f, ".dockerignore") { - res = append(res, core.Manifest{Ecosystem: core.Docker, Path: f, Tool: "docker"}) - } + res = append(res, core.Manifest{Ecosystem: core.Docker, Path: f, Tool: "docker"}) } return res, nil } +var composeFile = regexp.MustCompile(`^(?:docker-)?compose[^/]*\.ya?ml$`) + +func isDockerfile(rel string) bool { + base := strings.ToLower(path.Base(rel)) + if strings.HasSuffix(base, ".dockerignore") || strings.HasSuffix(base, ".containerignore") { + return false + } + for _, n := range []string{"dockerfile", "containerfile"} { + if base == n || strings.HasPrefix(base, n+".") || strings.HasSuffix(base, "."+n) { + return true + } + } + return false +} + func dockerIsCompose(p string) bool { e := path.Ext(p) return e == ".yml" || e == ".yaml" } type dockerRef struct { - line int - raw string // as written, variables and all - name string // canonical - rawName string - rawTag string - tag string // resolved; "" when absent or not resolvable - digest string - note string - arg string // ARG that holds the tag - argLine int + line int + raw string // as written, variables and all + name string // canonical + rawName string + rawTag string + tag string // resolved; "" when absent or not resolvable + digest string + note string + arg string // ARG that holds the tag, or with argWhole the whole reference + argLine int + argPrefix string // what the tag carries around the ARG, as in v${V}-alpine + argSuffix string + argWhole string // the name the ARG holds when it holds the whole reference + inName bool // the variables in rawName carry a tag or digest } const dockerUnknown = "\x00" @@ -143,7 +159,8 @@ func dockerCanon(name string) string { } var ( - dockerArgRef = regexp.MustCompile(`^\$\{(\w+)\}$|^\$(\w+)$`) + dockerArgRef = regexp.MustCompile(`^([^$]*)\$(?:\{(\w+)\}|(\w+))([^$]*)$`) + dockerArgWhole = regexp.MustCompile(`^\$\{(\w+)\}$|^\$(\w+)$`) dockerArgDefault = regexp.MustCompile(`^\$\{(\w+):?-([^}]*)\}$`) ) @@ -161,10 +178,19 @@ func dockerNewRef(line int, raw string, args map[string]*string, argLines map[st r.tag, r.digest = "", "" r.note = "unresolved ARG " + strings.Join(missing, ", ") } - if m := dockerArgRef.FindStringSubmatch(r.rawTag); m != nil && args[m[1]+m[2]] != nil { - r.arg = m[1] + m[2] + if m := dockerArgRef.FindStringSubmatch(r.rawTag); m != nil && args[m[2]+m[3]] != nil { + r.arg, r.argPrefix, r.argSuffix = m[2]+m[3], m[1], m[4] r.argLine = argLines[r.arg] } + nameExp, _ := dockerExpand(r.rawName, args) + _, nameTag, nameDigest := dockerSplit(nameExp) + r.inName = nameTag+nameDigest != "" + if m := dockerArgWhole.FindStringSubmatch(r.rawName); m != nil && r.rawTag == "" && args[m[1]+m[2]] != nil { + if whole, tag, digest := dockerSplit(*args[m[1]+m[2]]); tag != "" && digest == "" && !strings.Contains(whole, "$") { + r.arg, r.argWhole = m[1]+m[2], whole + r.argLine = argLines[r.arg] + } + } return r, true } @@ -251,7 +277,7 @@ func composeRefs(src []byte) ([]dockerRef, error) { } for i := 1; i < len(svc.Content); i += 2 { img := yamlGet(svc.Content[i], "image") - if img == nil || img.Kind != yaml.ScalarNode { + if img == nil || img.Kind != yaml.ScalarNode || yamlGet(svc.Content[i], "build") != nil { continue } if r, ok := dockerNewRef(img.Line, img.Value, nil, nil); ok { @@ -591,10 +617,22 @@ func (docker) Bump(ctx context.Context, root string, d core.Dep, to, toName stri name = strings.TrimPrefix(toName, "library/") } p := filepath.Join(root, filepath.FromSlash(d.Manifest.Path)) - next, argEdit := name+":"+to, false + if r.argWhole != "" { + return dockerBumpWhole(ctx, p, d, r, cmp.Or(strings.TrimPrefix(toName, "library/"), r.argWhole), to) + } + if r.inName && toName == "" { + return nil, fmt.Errorf("docker: %s: %q holds the whole reference and is not settable: %w", d.Name, r.rawName, core.ErrNotSupported) + } + next, argVal := name+":"+to, "" switch m := dockerArgDefault.FindStringSubmatch(r.rawTag); { case r.arg != "": - next, argEdit = name+":"+r.rawTag, true + val, ok := strings.CutPrefix(to, r.argPrefix) + val, ok2 := strings.CutSuffix(val, r.argSuffix) + if !ok || !ok2 || val == "" { + return nil, fmt.Errorf("docker: %s: target tag %s does not fit %q, which only ARG %s can move: %w", + d.Name, to, r.rawTag, r.arg, core.ErrNotSupported) + } + next, argVal = name+":"+r.rawTag, val case m != nil: next = name + ":${" + m[1] + ":-" + to + "}" case strings.Contains(r.rawTag, "$"): @@ -607,8 +645,8 @@ func (docker) Bump(ctx context.Context, root string, d core.Dep, to, toName stri next += pin res := &core.Bump{Note: "no lockfile"} changed := false - if argEdit { - if changed, err = dockerSetArg(p, r, to); err != nil { + if argVal != "" { + if changed, err = dockerSetArg(p, d, r, argVal); err != nil { return nil, err } } @@ -655,15 +693,18 @@ func dockerCanonOf(name string) string { // dockerSetArg points the ARG behind a ${TAG} reference at a new default. It // reports whether the file changed: another stage may have done it already. -func dockerSetArg(p string, r dockerRef, to string) (bool, error) { +func dockerSetArg(p string, d core.Dep, r dockerRef, to string) (bool, error) { lines, err := readLines(p) if err != nil { return false, err } - re := regexp.MustCompile(`(\bARG\s+` + regexp.QuoteMeta(r.arg) + `\s*=\s*)(["']?)([^"'\s]*)(["']?)`) - m := re.FindStringSubmatch(lines[r.argLine-1]) + re := regexp.MustCompile(`((?i:\bARG\b)(?:\s+\S+)*?\s+` + regexp.QuoteMeta(r.arg) + `=)(["']?)([^"'\s]*)(["']?)`) + var m []string + if r.argLine >= 1 && r.argLine <= len(lines) { + m = re.FindStringSubmatch(lines[r.argLine-1]) + } if m == nil { - return false, fmt.Errorf("%s:%d: ARG %s has no default", p, r.argLine, r.arg) + return false, fmt.Errorf("docker: %s: %s:%d: ARG %s default not found", d.Name, d.Manifest.Path, r.argLine, r.arg) } if m[3] == to { return false, nil @@ -671,6 +712,28 @@ func dockerSetArg(p string, r dockerRef, to string) (bool, error) { return true, rewriteLine(p, r.argLine, m[0], m[1]+m[2]+to+m[4]) } +func dockerBumpWhole(ctx context.Context, p string, d core.Dep, r dockerRef, name, to string) (*core.Bump, error) { + pin, err := dockerRepin(ctx, d, r, dockerCanon(name), to) + if err != nil { + return nil, err + } + changed, err := dockerSetArg(p, d, r, name+":"+to) + if err != nil { + return nil, err + } + if _, _, digest := dockerSplit(r.raw); digest != "" && "@"+digest != pin { + if err := rewriteLine(p, r.line, r.raw, strings.TrimSuffix(r.raw, "@"+digest)+pin); err != nil { + return nil, fmt.Errorf("docker: %s: %w", d.Name, err) + } + changed = true + } + res := &core.Bump{Note: "no lockfile"} + if changed { + res.Files = []string{d.Manifest.Path} + } + return res, nil +} + func (docker) Commands(root string, m core.Manifest) core.Commands { return core.Commands{} } func (docker) Traits() core.Traits { diff --git a/internal/eco/docker_test.go b/internal/eco/docker_test.go index 004d6f5..02bfdde 100644 --- a/internal/eco/docker_test.go +++ b/internal/eco/docker_test.go @@ -539,3 +539,90 @@ func TestDockerNothingToRun(t *testing.T) { t.Errorf("Imports = %v", got) } } + +func TestDockerBumpVariables(t *testing.T) { + tests := []struct { + name, file, to, want, err string + }{ + {"whole reference from an ARG", "ARG IMAGE=node:20\nFROM ${IMAGE}\n", "22", "ARG IMAGE=node:22\nFROM ${IMAGE}\n", ""}, + {"bare whole reference with alias", "ARG IMAGE=node:20\nFROM $IMAGE AS b\n", "22", "ARG IMAGE=node:22\nFROM $IMAGE AS b\n", ""}, + {"whole reference with a digest", "ARG IMAGE=node:20@" + digestOf("a") + "\nFROM ${IMAGE}\n", "22", "", "holds the whole reference"}, + {"whole reference pinned on the line", "ARG IMAGE=node:20\nFROM ${IMAGE}@" + digestOf("a") + "\n", "22", "", "no registry to ask"}, + {"whole reference inline default", "FROM ${IMAGE:-node:20}\n", "22", "", "holds the whole reference"}, + {"name only from an ARG", "ARG IMAGE=node\nFROM ${IMAGE}\n", "22", "ARG IMAGE=node\nFROM ${IMAGE}:22\n", ""}, + {"registry from an ARG", "ARG REGISTRY=docker.io\nFROM ${REGISTRY}/node:20\n", "22", "ARG REGISTRY=docker.io\nFROM ${REGISTRY}/node:22\n", ""}, + {"name from an ARG with a tag", "ARG IMAGE=node\nFROM ${IMAGE}:20\n", "22", "ARG IMAGE=node\nFROM ${IMAGE}:22\n", ""}, + {"ARG with a suffix", "ARG NODE_VERSION=20\nFROM node:${NODE_VERSION}-alpine\n", "22-alpine", "ARG NODE_VERSION=22\nFROM node:${NODE_VERSION}-alpine\n", ""}, + {"ARG with a prefix", "ARG V=1.2.0\nFROM acme/tool:v${V}\n", "v1.3.0", "ARG V=1.3.0\nFROM acme/tool:v${V}\n", ""}, + {"target drops the suffix", "ARG NODE_VERSION=20\nFROM node:${NODE_VERSION}-alpine\n", "22-bookworm", "", "does not fit"}, + {"lowercase arg and from", "arg NODE=20\nfrom node:${NODE}\n", "22", "arg NODE=22\nfrom node:${NODE}\n", ""}, + {"two variables", "ARG A=1\nARG B=x\nFROM acme/tool:${A}-${B}\n", "2-x", "", "not settable"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + withRegistry(t, nil) + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": tt.file}) + deps := depsIn(t, docker{}, root, "Dockerfile") + if len(deps) != 1 { + t.Fatalf("deps = %+v", deps) + } + res, err := (docker{}).Bump(context.Background(), root, deps[0], tt.to, "") + got := treeSnapshot(t, root)["Dockerfile"] + if tt.err != "" { + if !errors.Is(err, core.ErrNotSupported) || !strings.Contains(err.Error(), tt.err) { + t.Errorf("err = %v, want %q and not supported", err, tt.err) + } + if got != tt.file { + t.Errorf("Dockerfile changed:\n%s", got) + } + return + } + if err != nil { + t.Fatal(err) + } + if got != tt.want { + t.Errorf("Dockerfile =\n%s\nwant\n%s", got, tt.want) + } + if !reflect.DeepEqual(res.Files, []string{"Dockerfile"}) { + t.Errorf("Files = %v", res.Files) + } + }) + } +} + +func TestDockerSetArgMissing(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "RUN true\nFROM node:${NODE}\n"}) + d := core.Dep{Name: "library/node", Manifest: core.Manifest{Path: "Dockerfile"}} + _, err := dockerSetArg(filepath.Join(root, "Dockerfile"), d, dockerRef{arg: "NODE", argLine: 1}, "22") + if err == nil || strings.Contains(err.Error(), root) || !strings.Contains(err.Error(), "Dockerfile:1: ARG NODE default not found") { + t.Errorf("err = %v", err) + } +} + +func TestDockerBumpArgAmongOthers(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "ARG BASE=x NODE=20 OTHER=1\nFROM node:${NODE}\n"}) + d := depIn(t, docker{}, root, "Dockerfile", "library/node", true) + if _, err := (docker{}).Bump(context.Background(), root, d, "22", ""); err != nil { + t.Fatal(err) + } + if got, want := treeSnapshot(t, root)["Dockerfile"], "ARG BASE=x NODE=22 OTHER=1\nFROM node:${NODE}\n"; got != want { + t.Errorf("Dockerfile =\n%s\nwant\n%s", got, want) + } +} + +func TestDockerBumpWholePinned(t *testing.T) { + withRegistry(t, replayCanned(t, manifest("library/node", "22", digestOf("b")))) + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "ARG IMAGE=node:20\nFROM ${IMAGE}@" + digestOf("a") + " AS web\n"}) + d := depIn(t, docker{}, root, "Dockerfile", "library/node", true) + if _, err := (docker{}).Bump(context.Background(), root, d, "22", ""); err != nil { + t.Fatal(err) + } + want := "ARG IMAGE=node:22\nFROM ${IMAGE}@" + digestOf("b") + " AS web\n" + if got := treeSnapshot(t, root)["Dockerfile"]; got != want { + t.Errorf("Dockerfile =\n%s\nwant\n%s", got, want) + } +} diff --git a/internal/eco/eco.go b/internal/eco/eco.go index 4f528cc..51e4c5d 100644 --- a/internal/eco/eco.go +++ b/internal/eco/eco.go @@ -26,6 +26,7 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/gitx" + "github.com/mohsensc/tend-cli/internal/proc" "github.com/mohsensc/tend-cli/internal/ver" ) @@ -63,25 +64,39 @@ func ByName(name string) core.Ecosystem { return nil } -// skipDirs hold other people's code, build output, or, like the go tool's -// testdata, fixtures that are not the project's own manifests. -var skipDirs = map[string]bool{ - "node_modules": true, "vendor": true, ".git": true, "target": true, "dist": true, - "build": true, ".venv": true, "venv": true, "__pycache__": true, "bin": true, "obj": true, - "testdata": true, +// thirdParty holds other people's code or, like the go tool's testdata, +// fixtures that are not the project's own manifests, tracked or not. +var thirdParty = map[string]bool{ + "node_modules": true, "vendor": true, ".git": true, ".venv": true, "venv": true, + "__pycache__": true, "testdata": true, } +var buildOutput = map[string]bool{"build": true, "bin": true, "dist": true, "obj": true, "target": true} + // walk returns the repo-relative, slash-separated paths of files under root that // match one of the glob patterns, sorted. A pattern with a slash matches the whole -// path, one without matches the base name. Git-ignored files are left out. +// path, one without matches the base name. Git-ignored files, other people's +// code and untracked build output are left out. func walk(root string, names ...string) ([]string, error) { - files, err := Files(root) + return walkFunc(root, func(rel string) bool { return matches(rel, names) }) +} + +func walkFunc(root string, match func(rel string) bool) ([]string, error) { + return walkFiles(root, true, match, nil) +} + +func walkNamed(root string, names ...string) ([]string, error) { + return walkFiles(root, false, func(rel string) bool { return matches(rel, names) }, names) +} + +func walkFiles(root string, skip bool, match func(rel string) bool, names []string) ([]string, error) { + t, err := listTree(root) if err != nil { return nil, err } var res []string - for _, f := range files { - if skipped(f) || !matches(f, names) { + for _, f := range t.files { + if skip && t.skipped(f) || !match(f) { continue } if fi, err := os.Lstat(filepath.Join(root, f)); err != nil || !fi.Mode().IsRegular() { @@ -89,44 +104,89 @@ func walk(root string, names ...string) ([]string, error) { } res = append(res, f) } + if !skip && !t.git { + for _, n := range names { + if !strings.ContainsAny(n, `*?[\`) && onDisk(root, n) { + res = append(res, path.Clean(n)) + } + } + } slices.Sort(res) return slices.Compact(res), nil } +type fileTree struct { + files []string + untracked map[string]bool + git bool +} + +func (t *fileTree) skipped(rel string) bool { + for _, part := range strings.Split(path.Dir(rel), "/") { + if thirdParty[part] || buildOutput[part] && (!t.git || t.untracked[rel]) { + return true + } + } + return false +} + var listed struct { sync.Mutex - m map[string][]string + m map[string]*fileTree } // Files lists the files under root: what git tracks or would track, or every // file when git is not there. Within Keep it lists each root once. func Files(root string) ([]string, error) { + t, err := listTree(root) + if err != nil { + return nil, err + } + return t.files, nil +} + +func listTree(root string) (*fileTree, error) { listed.Lock() - files, ok := listed.m[root] + t, ok := listed.m[root] listed.Unlock() if ok { - return files, nil + return t, nil } - files, err := gitx.Files(context.Background(), root) + ctx := context.Background() + files, err := gitx.Files(ctx, root) if err != nil { - return dirFiles(root) + files, err := dirFiles(root) + if err != nil { + return nil, err + } + return &fileTree{files: files}, nil } - return files, nil + t = &fileTree{files: files, untracked: map[string]bool{}, git: true} + out, err := gitx.Raw(ctx, root, "ls-files", "-z", "--others", "--exclude-standard") + if err != nil { + return nil, err + } + for _, f := range strings.Split(out, "\x00") { + if f != "" { + t.untracked[f] = true + } + } + return t, nil } // Keep has Files list root once until the returned func is called: one // inventory reads one tree, and every ecosystem looks at the same list. func Keep(root string) (done func(), err error) { - files, err := Files(root) + t, err := listTree(root) if err != nil { return nil, err } listed.Lock() defer listed.Unlock() if listed.m == nil { - listed.m = map[string][]string{} + listed.m = map[string]*fileTree{} } - listed.m[root] = files + listed.m[root] = t return func() { listed.Lock() delete(listed.m, root) @@ -141,7 +201,7 @@ func dirFiles(root string) ([]string, error) { return err } if d.IsDir() { - if p != root && skipDirs[d.Name()] { + if p != root && (thirdParty[d.Name()] || buildOutput[d.Name()] || core.NestedRepo(p)) { return filepath.SkipDir } return nil @@ -156,15 +216,6 @@ func dirFiles(root string) ([]string, error) { return res, err } -func skipped(rel string) bool { - for _, part := range strings.Split(path.Dir(rel), "/") { - if skipDirs[part] { - return true - } - } - return false -} - func matches(rel string, names []string) bool { if len(names) == 0 { return true @@ -192,13 +243,21 @@ var runTimeout = 10 * time.Minute // run executes line with sh -c in root and returns its combined output. env is // added to the process environment. +// Run runs line with sh in dir, as the lock and bump tools run: with tend's +// environment scrubbed of its tokens, in a process group of its own, and +// for no longer than a lock tool needs. +func Run(ctx context.Context, dir, line string) (string, error) { + return run(ctx, dir, []string{"CI=1"}, line) +} + func run(ctx context.Context, root string, env []string, line string) (string, error) { ctx, cancel := context.WithTimeout(ctx, runTimeout) defer cancel() cmd := exec.CommandContext(ctx, "sh", "-c", line) cmd.Dir = root - cmd.Env = append(os.Environ(), env...) + cmd.Env = core.Environ(env...) cmd.WaitDelay = time.Second + proc.Group(cmd) out, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { return string(out), fmt.Errorf("%s: timed out after %s", line, runTimeout) @@ -251,12 +310,18 @@ func readJSON(p string, v any) error { if err != nil { return err } - if err := json.Unmarshal(b, v); err != nil { + if err := json.Unmarshal(stripBOM(b), v); err != nil { return fmt.Errorf("%s: %w", p, err) } return nil } +var utf8BOM = []byte("\xef\xbb\xbf") + +// stripBOM drops the byte order mark Windows editors put before JSON, which +// npm and Node skip but encoding/json refuses. +func stripBOM(b []byte) []byte { return bytes.TrimPrefix(b, utf8BOM) } + func readYAML(p string, v any) error { b, err := os.ReadFile(p) if err != nil { diff --git a/internal/eco/eco_test.go b/internal/eco/eco_test.go index c6a2be2..8a0300a 100644 --- a/internal/eco/eco_test.go +++ b/internal/eco/eco_test.go @@ -238,3 +238,95 @@ func TestTraits(t *testing.T) { t.Errorf("docker page = %s", p) } } + +func TestWalkTracked(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not found") + } + root := t.TempDir() + write(t, root, map[string]string{ + "build/package/Dockerfile": "FROM node:22", + "bin/install.sh": "curl x", + "testdata/Dockerfile": "FROM node:22", + "vendor/x/Dockerfile": "FROM node:22", + "node_modules/a/Dockerfile": "FROM node:22", + "api.Dockerfile": "FROM node:22", + "Containerfile": "FROM node:22", + "compose.prod.yaml": "services: {}", + "compose.override.yml": "services: {}", + ".dockerignore": "x", + "Dockerfile.dockerignore": "x", + "docs/compose-notes.txt": "x", + }) + for _, args := range [][]string{{"init", "-q"}, {"add", "."}} { + if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + write(t, root, map[string]string{"build/package.json": "{}", "build/out/Dockerfile": "FROM node:22"}) + got, err := (docker{}).Detect(root) + if err != nil { + t.Fatal(err) + } + var paths []string + for _, m := range got { + paths = append(paths, m.Path) + } + want := []string{"Containerfile", "api.Dockerfile", "build/package/Dockerfile", "compose.override.yml", "compose.prod.yaml"} + if !reflect.DeepEqual(paths, want) { + t.Errorf("docker Detect = %v\nwant %v", paths, want) + } + if got, _ := walk(root, "package.json"); len(got) != 0 { + t.Errorf("untracked build output = %v", got) + } + if got, _ := walk(root, "install.sh"); !reflect.DeepEqual(got, []string{"bin/install.sh"}) { + t.Errorf("tracked bin script = %v", got) + } +} + +func TestIsDockerfile(t *testing.T) { + for name, want := range map[string]bool{ + "Dockerfile": true, "dockerfile": true, "Containerfile": true, "Dockerfile.dev": true, + "api.Dockerfile": true, "web.dockerfile": true, "app.containerfile": true, "a/b/Dockerfile.prod": true, + ".dockerignore": false, "Dockerfile.dockerignore": false, "Dockerfiles": false, "README.md": false, + } { + if got := isDockerfile(name); got != want { + t.Errorf("isDockerfile(%q) = %v, want %v", name, got, want) + } + } +} + +// The tools tend runs to bump and lock never see its token or model key. +func TestRunScrubsEnv(t *testing.T) { + t.Setenv("GITHUB_TOKEN", "ghs_secret") + t.Setenv("TEND_MODEL_KEY", "sk_secret") + out, err := Run(context.Background(), t.TempDir(), "env") + if err != nil { + t.Fatal(err) + } + if strings.Contains(out, "ghs_secret") || strings.Contains(out, "sk_secret") { + t.Errorf("the environment reached the tool:\n%s", out) + } +} + +// Outside git, a directory that is a repository of its own is another +// project, as git ls-files would see it, and is not listed. +func TestDirFilesNestedRepo(t *testing.T) { + root := t.TempDir() + for _, f := range []string{"package.json", "a/index.js", "inner/requirements.txt", "inner/.git/HEAD", "wt/go.mod", "wt/.git"} { + p := filepath.Join(root, filepath.FromSlash(f)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + } + got, err := dirFiles(root) + if err != nil { + t.Fatal(err) + } + if want := []string{"a/index.js", "package.json"}; !reflect.DeepEqual(got, want) { + t.Errorf("dirFiles = %q, want %q", got, want) + } +} diff --git a/internal/eco/git.go b/internal/eco/git.go index 532e31e..5365518 100644 --- a/internal/eco/git.go +++ b/internal/eco/git.go @@ -3,10 +3,12 @@ package eco import ( "context" "fmt" + "net/url" "os" "path" "path/filepath" "regexp" + "slices" "strings" "sync" @@ -52,9 +54,10 @@ var ( var gitShas sync.Map func (gitRefs) Detect(root string) ([]core.Manifest, error) { - files, err := walk(root, ".pre-commit-config.yaml", "*.tf", "package.json", "Dockerfile", "Dockerfile.*", "*.dockerfile", + names := []string{".pre-commit-config.yaml", "*.tf", "package.json", "Makefile", "*.mk", "*.sh", ".github/workflows/*.yml", ".github/workflows/*.yaml", - "requirements*.txt", "pyproject.toml", "setup.cfg", "Pipfile", "Cargo.toml", "Gemfile") + "requirements*.txt", "pyproject.toml", "setup.cfg", "Pipfile", "Cargo.toml", "Gemfile"} + files, err := walkFunc(root, func(rel string) bool { return isDockerfile(rel) || matches(rel, names) }) if err != nil { return nil, err } @@ -155,6 +158,7 @@ func preCommitPins(b []byte, pin func(owner, repo, ref string, line int) core.De } func (gitRefs) Meta(ctx context.Context, f core.Fetcher, name string) (*core.Meta, error) { + gitClient.set(f) m, tags, err := githubMeta(ctx, f, name) if err != nil { return nil, fmt.Errorf("git: %w", err) @@ -178,8 +182,8 @@ func (gitRefs) Bump(ctx context.Context, root string, d core.Dep, to, toName str return nil, fmt.Errorf("git: %s: no line %d in %s", d.Name, d.Line, d.Manifest.Path) } line := strings.TrimRight(lines[d.Line-1], "\r") - next, ok := releaseURLs(line, d.Name, d.Req, to) - if !ok { + next, release := releaseURLs(line, d.Name, d.Req, to) + if !release { next = strings.Replace(line, d.Req, to, 1) } if d.Pin != "" { @@ -199,7 +203,15 @@ func (gitRefs) Bump(ctx context.Context, root string, d core.Dep, to, toName str if next == line { return &core.Bump{Note: "no lockfile"}, nil } - if err := rewriteLine(p, d.Line, line, next); err != nil { + if release && d.Pin == "" { + lines[d.Line-1] = next + strings.TrimPrefix(lines[d.Line-1], line) + if err := releaseSums(ctx, d, lines, line, next, to); err != nil { + return nil, err + } + if err := writeKeepMode(p, []byte(strings.Join(lines, "\n"))); err != nil { + return nil, err + } + } else if err := rewriteLine(p, d.Line, line, next); err != nil { return nil, err } res := &core.Bump{Files: []string{d.Manifest.Path}, Note: "no lockfile"} @@ -266,6 +278,195 @@ func releaseURLs(line, repo, from, to string) (string, bool) { return b.String(), ok } +var gitClient fetcherBox + +var ( + sumHex = regexp.MustCompile(`[0-9A-Fa-f]{64,}`) + sumVarRef = regexp.MustCompile(`\$\{?([A-Za-z_]\w*)`) + sumVarRe = regexp.MustCompile(`(?i)sha|checksum|digest`) +) + +type sumAt struct { + line int + hex string +} + +func releaseSums(ctx context.Context, d core.Dep, lines []string, was, now, to string) error { + at := d.Line - 1 + first, last := at, at + for first > 0 && strings.HasSuffix(strings.TrimRight(lines[first-1], "\r"), `\`) { + first-- + } + for last+1 < len(lines) && strings.HasSuffix(strings.TrimRight(lines[last], "\r"), `\`) { + last++ + } + first, last = max(first-3, 0), min(last+3, len(lines)-1) + var sums []sumAt + vars := map[string]bool{} + for i := first; i <= last; i++ { + sums = append(sums, sumsIn(i, lines[i])...) + for _, m := range sumVarRef.FindAllStringSubmatch(lines[i], -1) { + if sumVarRe.MatchString(m[1]) { + vars[m[1]] = true + } + } + } + for name := range vars { + set := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\s*(?:[:?]?=|:)\s*["']?[0-9A-Fa-f]{64}\b`) + for i, l := range lines { + if (i < first || i > last) && set.MatchString(l) { + sums = append(sums, sumsIn(i, l)...) + } + } + } + if len(sums) == 0 { + return nil + } + where := fmt.Sprintf("%s:%d", d.Manifest.Path, sums[0].line+1) + refuse := func(why string) error { + return fmt.Errorf("git: %s: %s pins a sha256 of the asset; %s: %w", d.Name, where, why, core.ErrNotSupported) + } + oldAsset, newAsset := releaseAsset(was, d.Name, d.Req), releaseAsset(now, d.Name, to) + if newAsset == "" || strings.ContainsAny(newAsset, "$`(){}*") { + return refuse("tend cannot tell which asset " + now + " downloads") + } + f := gitClient.get() + if f == nil { + return refuse("tend has no GitHub client to read the new asset's digest") + } + before, err := releaseDigests(ctx, f, d.Name, d.Req, oldAsset) + if err != nil { + return refuse(err.Error()) + } + after, err := releaseDigests(ctx, f, d.Name, to, newAsset) + if err != nil { + return refuse(err.Error()) + } + known := map[string]bool{} + for name, dg := range before { + if name != oldAsset { + known[dg] = true + } + } + for _, dg := range after { + known[dg] = true + } + old := before[oldAsset] + var left []string + for _, s := range sums { + if h := strings.ToLower(s.hex); !known[h] && !slices.Contains(left, h) { + left = append(left, h) + } + } + switch { + case old != "" && !slices.Contains(left, old): + return nil + case old == "" && len(left) == 0: + return nil + case old == "" && len(left) > 1: + return refuse(fmt.Sprintf("tend cannot tell which of %d checksums is %s's", len(left), oldAsset)) + case old == "": + old = left[0] + } + next := after[newAsset] + if next == "" { + return refuse("tend cannot find the digest of " + newAsset + " in release " + to) + } + n := 0 + for _, s := range sums { + if strings.EqualFold(s.hex, old) { + n++ + } + } + if n != 1 { + return refuse(fmt.Sprintf("its checksum appears %d times", n)) + } + for _, s := range sums { + if strings.EqualFold(s.hex, old) { + if strings.ToUpper(s.hex) == s.hex { + next = strings.ToUpper(next) + } + lines[s.line] = strings.Replace(lines[s.line], s.hex, next, 1) + } + } + return nil +} + +func sumsIn(i int, l string) []sumAt { + var res []sumAt + for _, m := range sumHex.FindAllStringIndex(l, -1) { + if m[1]-m[0] == 64 && !strings.HasSuffix(l[:m[0]], "@sha256:") { + res = append(res, sumAt{i, l[m[0]:m[1]]}) + } + } + return res +} + +func releaseAsset(line, repo, tag string) string { + for _, m := range releaseDL.FindAllStringSubmatchIndex(line, -1) { + if strings.EqualFold(line[m[2]:m[3]]+"/"+line[m[4]:m[5]], repo) && line[m[6]:m[7]] == tag { + end := m[1] + strings.IndexAny(line[m[1]:]+" ", " \t\"'`)>") + return line[m[1]:end] + } + } + return "" +} + +type githubAsset struct { + Name string `json:"name"` + Digest string `json:"digest"` + URL string `json:"browser_download_url"` +} + +func releaseDigests(ctx context.Context, f core.Fetcher, repo, tag, want string) (map[string]string, error) { + var rel struct { + Assets []githubAsset `json:"assets"` + } + u := "https://api.github.com/repos/" + repo + "/releases/tags/" + url.PathEscape(tag) + ok, err := getDoc(ctx, f, u, &rel) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("no GitHub release %s of %s", tag, repo) + } + res := map[string]string{} + var sumFiles []githubAsset + for _, a := range rel.Assets { + if dg, ok := strings.CutPrefix(a.Digest, "sha256:"); ok && len(dg) == 64 { + res[a.Name] = strings.ToLower(dg) + } + lower := strings.ToLower(a.Name) + if strings.Contains(lower, "checksums") || strings.Contains(lower, "sha256sums") || strings.HasSuffix(lower, ".sha256") || strings.HasSuffix(lower, ".sha256sum") { + sumFiles = append(sumFiles, a) + } + } + for _, a := range sumFiles { + if res[want] != "" { + break + } + got, err := f.Get(ctx, a.URL) + if err != nil || got.Status != 200 { + continue + } + own := strings.TrimSuffix(strings.TrimSuffix(a.Name, ".sha256sum"), ".sha256") + for _, l := range strings.Split(string(got.Body), "\n") { + fields := strings.Fields(l) + if len(fields) == 0 || len(fields[0]) != 64 || !sumHex.MatchString(fields[0]) { + continue + } + name := own + if len(fields) > 1 { + name = path.Base(strings.TrimPrefix(fields[len(fields)-1], "*")) + } + if res[name] == "" { + res[name] = strings.ToLower(fields[0]) + } + } + } + return res, nil +} + // replaceVersion replaces each copy of version from in s that stands alone: // 1.2.0 in tool_1.2.0.tar.gz or tool-v1.2.0, not in 11.2.0 or 1.2.0.1. func replaceVersion(s, from, to string) string { diff --git a/internal/eco/git_test.go b/internal/eco/git_test.go index a7bc35b..76f014d 100644 --- a/internal/eco/git_test.go +++ b/internal/eco/git_test.go @@ -2,12 +2,15 @@ package eco import ( "context" + "errors" "fmt" "os" "path/filepath" "slices" "strings" "testing" + + "github.com/mohsensc/tend-cli/internal/core" ) func TestGitDeps(t *testing.T) { @@ -239,3 +242,84 @@ func TestGitMeta(t *testing.T) { t.Errorf("meta = %+v", m) } } + +func TestGitBumpChecksums(t *testing.T) { + oldSum, newSum, otherSum := strings.Repeat("a", 64), strings.Repeat("b", 64), strings.Repeat("c", 64) + image := "sha256:" + strings.Repeat("d", 64) + release := func(tag, asset, digest string) canned { + body := `{"assets": [{"name": "` + asset + `", "digest": "` + digest + `", "browser_download_url": "https://github.com/krallin/tini/releases/download/` + tag + `/` + asset + `"}]}` + return canned{url: "https://api.github.com/repos/krallin/tini/releases/tags/" + tag, body: body} + } + withSums := replayCanned(t, + release("v0.19.0", "tini", "sha256:"+oldSum), + release("v0.19.1", "tini", "sha256:"+newSum), + ) + sumsFile := replayCanned(t, + canned{url: "https://api.github.com/repos/krallin/tini/releases/tags/v0.19.0", body: `{"assets": [{"name": "tini"}]}`}, + canned{url: "https://api.github.com/repos/krallin/tini/releases/tags/v0.19.1", body: `{"assets": [{"name": "tini"}, {"name": "checksums.txt", "browser_download_url": "https://github.com/krallin/tini/releases/download/v0.19.1/checksums.txt"}]}`}, + canned{url: "https://github.com/krallin/tini/releases/download/v0.19.1/checksums.txt", body: newSum + " tini\n" + otherSum + " tini-arm64\n"}, + ) + noDigest := replayCanned(t, + release("v0.19.0", "tini", ""), + release("v0.19.1", "tini", ""), + ) + url0, url1 := "https://github.com/krallin/tini/releases/download/v0.19.0/tini", "https://github.com/krallin/tini/releases/download/v0.19.1/tini" + tests := []struct { + name string + f core.Fetcher + file string + line int + want string + refuse string + }{ + {"ADD --checksum on the line", withSums, + "FROM alpine@" + image + "\nADD --checksum=sha256:" + oldSum + " " + url0 + " /tini\n", 2, + "FROM alpine@" + image + "\nADD --checksum=sha256:" + newSum + " " + url1 + " /tini\n", ""}, + {"sha256sum -c on the next line", sumsFile, + "RUN curl -fsSLo /tini " + url0 + " && \\\n echo \"" + oldSum + " /tini\" | sha256sum -c\n", 1, + "RUN curl -fsSLo /tini " + url1 + " && \\\n echo \"" + newSum + " /tini\" | sha256sum -c\n", ""}, + {"ARG a few lines above", noDigest, + "FROM alpine\nARG TINI_SHA256=" + oldSum + "\nRUN apk add curl\nRUN apk add bash\nRUN curl -fsSLo /tini " + url0 + "\n", 5, + "FROM alpine\nARG TINI_SHA256=" + oldSum + "\nRUN apk add curl\nRUN apk add bash\nRUN curl -fsSLo /tini " + url1 + "\n", "cannot find the digest"}, + {"ARG a few lines above, with a digest", withSums, + "FROM alpine\nARG TINI_SHA256=" + oldSum + "\nRUN apk add curl\nRUN curl -fsSLo /tini " + url0 + "\n", 4, + "FROM alpine\nARG TINI_SHA256=" + newSum + "\nRUN apk add curl\nRUN curl -fsSLo /tini " + url1 + "\n", ""}, + {"checksum variable far above", withSums, + "TINI_SHA256=" + oldSum + "\n\n\n\n\n\ncurl -fsSLo /tini " + url0 + "\necho \"${TINI_SHA256} /tini\" | sha256sum -c\n", 7, + "TINI_SHA256=" + newSum + "\n\n\n\n\n\ncurl -fsSLo /tini " + url1 + "\necho \"${TINI_SHA256} /tini\" | sha256sum -c\n", ""}, + {"no client", nil, + "ADD --checksum=sha256:" + oldSum + " " + url0 + " /tini\n", 1, "", "no GitHub client"}, + {"asset named by a variable", withSums, + "ADD --checksum=sha256:" + oldSum + " https://github.com/krallin/tini/releases/download/v0.19.0/tini-${ARCH} /tini\n", 1, "", "cannot tell which asset"}, + {"no checksum, image digest only", nil, + "FROM alpine@" + image + "\nADD " + url0 + " /tini\n", 2, + "FROM alpine@" + image + "\nADD " + url1 + " /tini\n", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + old := gitClient.get() + gitClient.set(tt.f) + t.Cleanup(func() { gitClient.set(old) }) + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": tt.file}) + d := core.Dep{Ecosystem: core.Git, Name: "krallin/tini", Version: "v0.19.0", Req: "v0.19.0", Line: tt.line, Manifest: core.Manifest{Path: "Dockerfile"}} + res, err := (gitRefs{}).Bump(context.Background(), root, d, "v0.19.1", "") + got := treeSnapshot(t, root)["Dockerfile"] + if tt.refuse != "" { + if !errors.Is(err, core.ErrNotSupported) || !strings.Contains(err.Error(), tt.refuse) { + t.Errorf("err = %v, want %q", err, tt.refuse) + } + if got != tt.file { + t.Errorf("Dockerfile changed:\n%s", got) + } + return + } + if err != nil { + t.Fatal(err) + } + if got != tt.want || !slices.Equal(res.Files, []string{"Dockerfile"}) { + t.Errorf("Dockerfile =\n%s\nwant\n%s\nfiles %v", got, tt.want, res.Files) + } + }) + } +} diff --git a/internal/eco/github.go b/internal/eco/github.go index b7137ec..268029b 100644 --- a/internal/eco/github.go +++ b/internal/eco/github.go @@ -61,7 +61,7 @@ func githubMeta(ctx context.Context, f core.Fetcher, repo string) (*core.Meta, m if _, ok := ver.Parse(tag); !ok { continue } - r := core.Release{Version: tag, Pre: isPre(tag)} + r := core.Release{Version: tag, Pre: isPre(tag) || semverPre(tag)} if i, ok := released[tag]; ok { r.Time, r.Pre = rels[i].Published, r.Pre || rels[i].Pre } diff --git a/internal/eco/github_test.go b/internal/eco/github_test.go index 524874d..92f8c7b 100644 --- a/internal/eco/github_test.go +++ b/internal/eco/github_test.go @@ -113,3 +113,24 @@ func TestGithubReleasesPaging(t *testing.T) { }) } } + +// A bare tag with a hyphen label is a SemVer pre-release, whatever the +// label says, and never the latest over the release it leads up to. +func TestGithubMetaHyphenPre(t *testing.T) { + const api = "https://api.github.com/repos/acme/tags" + m, _, err := githubMeta(context.Background(), replayCanned(t, + canned{url: api + "/tags?per_page=100", body: `[{"name": "v3.0.0-test.1", "commit": {"sha": "b"}}, {"name": "v3.0.0", "commit": {"sha": "c"}}, {"name": "v2.9.0", "commit": {"sha": "a"}}]`}, + canned{url: api + "/releases?per_page=100", body: `[]`}, + canned{url: api, body: `{}`}), "acme/tags") + if err != nil { + t.Fatal(err) + } + for _, r := range m.Releases { + if r.Pre != (r.Version == "v3.0.0-test.1") { + t.Errorf("%s: pre = %v", r.Version, r.Pre) + } + } + if m.Latest != "v3.0.0" { + t.Errorf("latest = %s", m.Latest) + } +} diff --git a/internal/eco/gomod.go b/internal/eco/gomod.go index 0db50cf..aa27b2a 100644 --- a/internal/eco/gomod.go +++ b/internal/eco/gomod.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "go/build" "go/parser" "go/token" "io/fs" @@ -107,14 +108,50 @@ func goParse(root, rel string) (*modfile.File, error) { return modfile.Parse(rel, data, nil) } +var goEnvFile = sync.OnceValue(func() map[string]string { + p := os.Getenv("GOENV") + if p == "off" { + return nil + } + if p == "" { + dir, err := os.UserConfigDir() + if err != nil { + return nil + } + p = filepath.Join(dir, "go", "env") + } + return readGoEnvFile(p) +}) + +func readGoEnvFile(p string) map[string]string { + b, err := os.ReadFile(p) + if err != nil { + return nil + } + res := map[string]string{} + for _, l := range strings.Split(string(b), "\n") { + if k, v, ok := strings.Cut(strings.TrimSpace(l), "="); ok && k != "" { + res[k] = v + } + } + return res +} + +func goSetting(key string) string { + if v := os.Getenv(key); v != "" { + return v + } + return goEnvFile()[key] +} + // goProxy is the module proxy Meta reads, from GOPROXY the way the go command // would pick it. "direct" has no proxy protocol, so it reads the public one. func goProxy(mod string) (string, error) { - private := cmp.Or(os.Getenv("GONOPROXY"), os.Getenv("GOPRIVATE")) + private := cmp.Or(goSetting("GONOPROXY"), goSetting("GOPRIVATE")) if private != "" && module.MatchPrefixPatterns(private, mod) { return "", fmt.Errorf("%s is private (GOPRIVATE/GONOPROXY): %w", mod, core.ErrNotSupported) } - first := os.Getenv("GOPROXY") + first := goSetting("GOPROXY") if i := strings.IndexAny(first, ",|"); i >= 0 { first = first[:i] } @@ -302,21 +339,15 @@ func (gomod) Meta(ctx context.Context, f core.Fetcher, name string) (*core.Meta, meta := &core.Meta{Name: name} paths := map[string][]string{name: vs} order := []string{name} - top := goHighestMajor(name, vs) - for n, tries := top+1, 0; goMayMove(name) && tries < 20; n, tries = n+1, tries+1 { - p := goPathAt(name, n) - if p == "" { - break - } - more, found, err := c.list(p) + if goMayMove(name) { + majors, err := c.majors(name, goHighestMajor(name, vs)) if err != nil { return nil, err } - if !found || len(more) == 0 { - break + for _, m := range majors { + paths[m.path] = m.vs + order = append(order, m.path) } - paths[p] = more - order = append(order, p) } for _, p := range order { rel, err := c.releases(p, paths[p], meta, p == name) @@ -336,6 +367,74 @@ func (gomod) Meta(ctx context.Context, f core.Fetcher, name string) (*core.Meta, return meta, nil } +// goMajorMax caps how far above the major in use the proxy is asked about. +const goMajorMax = 1000 + +type goMajor struct { + path string + vs []string +} + +// majors finds the major versions above top that a module has under /vN +// paths: the next one, the one to move a major at a time to, and the +// highest, the latest. It gallops, +1, +2, +4 and on until a path is +// missing, then halves the gap, so go-github's v28 to v90 takes a dozen +// requests and not sixty. +func (c goProxyClient) majors(name string, top int) ([]goMajor, error) { + seen := map[int][]string{} + at := func(n int) (bool, error) { + if _, ok := seen[n]; ok { + return true, nil + } + p := goPathAt(name, n) + if p == "" { + return false, nil + } + vs, found, err := c.list(p) + if err != nil || !found || len(vs) == 0 { + return false, err + } + seen[n] = vs + return true, nil + } + hit, miss := top, 0 + for step := 1; ; step *= 2 { + n := top + step + if n > top+goMajorMax { + miss = n + break + } + ok, err := at(n) + if err != nil { + return nil, err + } + if !ok { + miss = n + break + } + hit = n + } + for miss-hit > 1 { + mid := hit + (miss-hit)/2 + ok, err := at(mid) + if err != nil { + return nil, err + } + if ok { + hit = mid + } else { + miss = mid + } + } + var res []goMajor + for _, n := range []int{top + 1, hit} { + if vs, ok := seen[n]; ok && n > top && !slices.ContainsFunc(res, func(m goMajor) bool { return m.path == goPathAt(name, n) }) { + res = append(res, goMajor{goPathAt(name, n), vs}) + } + } + return res, nil +} + // releases lists one module path's versions with its retractions applied, // and fills Latest (the newest path wins) and, for the required path, // Deprecated. A proxy that does not serve @latest gets the newest listed @@ -598,10 +697,23 @@ func goKeep(root string, m core.Manifest, snap fileSnap, skip ...string) error { } } lines = slices.DeleteFunc(lines, func(l string) bool { return l == "" }) - slices.Sort(lines) + slices.SortFunc(lines, goSumCompare) return writeKeepMode(p, []byte(strings.Join(lines, "\n")+"\n")) } +func goSumCompare(a, b string) int { + fa, fb := strings.Fields(a), strings.Fields(b) + if len(fa) != 3 || len(fb) != 3 { + return strings.Compare(a, b) + } + if c := strings.Compare(fa[0], fb[0]); c != 0 { + return c + } + va, sa, _ := strings.Cut(fa[1], "/") + vb, sb, _ := strings.Cut(fb[1], "/") + return cmp.Or(semver.Compare(va, vb), strings.Compare(va, vb), strings.Compare(sa, sb), strings.Compare(fa[2], fb[2])) +} + // goEnv forces module mode for go get and tidy, and keeps a go.work above the // module from deciding what gets edited. The proxy and checksum settings the // caller runs with are left alone. @@ -729,10 +841,36 @@ func goMajorSuffix(rest string) bool { func (gomod) Commands(root string, m core.Manifest) core.Commands { dir := path.Dir(m.Path) - return core.Commands{ - Build: []string{inDir(dir, "go build ./...")}, - Test: []string{inDir(dir, "go vet ./... && go test ./...")}, + c := core.Commands{Build: []string{inDir(dir, "go build ./...")}} + if goHasPackages(filepath.Join(root, filepath.FromSlash(dir))) { + c.Test = []string{inDir(dir, "go vet ./... && go test ./...")} } + return c +} + +// goHasPackages says whether a file of the module at dir builds under the +// default build context, leaving out the modules nested in it. +func goHasPackages(dir string) bool { + found := false + _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil || found { + return filepath.SkipDir + } + n := d.Name() + if d.IsDir() { + if p != dir && (n == "testdata" || n == "vendor" || strings.HasPrefix(n, ".") || strings.HasPrefix(n, "_") || onDisk(p, "go.mod")) { + return filepath.SkipDir + } + return nil + } + if strings.HasSuffix(n, ".go") { + if ok, err := build.Default.MatchFile(filepath.Dir(p), n); err == nil && ok { + found = true + } + } + return nil + }) + return found } // Imports is the module path; scan matches the module's packages by prefix. diff --git a/internal/eco/gomod_test.go b/internal/eco/gomod_test.go index f0e023b..f1c9817 100644 --- a/internal/eco/gomod_test.go +++ b/internal/eco/gomod_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "strings" "sync" "testing" @@ -52,6 +53,7 @@ func goPublic(t *testing.T) { for _, k := range []string{"GOPROXY", "GOPRIVATE", "GONOPROXY"} { t.Setenv(k, "") } + withGoEnvFile(t, nil) } func TestGoMeta(t *testing.T) { @@ -234,6 +236,7 @@ func TestGoProxy(t *testing.T) { {"", "corp.example/*,github.com/corp", "github.com/corp/lib", "", true}, {"", "corp.example/*", "github.com/x/y", "https://proxy.golang.org", false}, } + withGoEnvFile(t, nil) for _, tt := range tests { t.Setenv("GOPROXY", tt.proxy) t.Setenv("GOPRIVATE", tt.private) @@ -303,11 +306,25 @@ func TestGoBumpRefused(t *testing.T) { } func TestGoCommands(t *testing.T) { - got := gomod{}.Commands("", core.Manifest{Path: "tools/go.mod"}) + root := t.TempDir() + write(t, root, map[string]string{ + "tools/go.mod": "module example.com/tools\n", + "tools/main.go": "package main\n", + "ci/go.mod": "module example.com/ci\n", + "ci/magefile.go": "//go:build mage\n\npackage main\n", + "ci/mage.go": "// +build ignore\n\npackage main\n", + "ci/sub/go.mod": "module example.com/ci/sub\n", + "ci/sub/x.go": "package sub\n", + "ci/testdata/t/one.go": "package t\n", + }) + got := gomod{}.Commands(root, core.Manifest{Path: "tools/go.mod"}) want := core.Commands{Build: []string{"cd tools && go build ./..."}, Test: []string{"cd tools && go vet ./... && go test ./..."}} if !reflect.DeepEqual(got, want) { t.Errorf("Commands = %+v", got) } + if got := (gomod{}).Commands(root, core.Manifest{Path: "ci/go.mod"}); !reflect.DeepEqual(got, core.Commands{Build: []string{"cd ci && go build ./..."}}) { + t.Errorf("a module of tagged files: Commands = %+v", got) + } if got := (gomod{}).Imports(core.Dep{Name: "github.com/x/y/v2"}); !reflect.DeepEqual(got, []string{"github.com/x/y/v2"}) { t.Errorf("Imports = %v", got) } @@ -499,3 +516,117 @@ func TestGoBumpKeepsUnusedRequires(t *testing.T) { t.Errorf("the kept requires do not verify: %v\n%s", err, out) } } + +func withGoEnvFile(t *testing.T, m map[string]string) { + t.Helper() + old := goEnvFile + goEnvFile = func() map[string]string { return m } + t.Cleanup(func() { goEnvFile = old }) +} + +func TestGoProxyEnvFile(t *testing.T) { + p := filepath.Join(t.TempDir(), "env") + if err := os.WriteFile(p, []byte("GOPRIVATE=github.com/corp/*\nGOPROXY=https://goproxy.corp.example,direct\nbroken line\n"), 0o644); err != nil { + t.Fatal(err) + } + withGoEnvFile(t, readGoEnvFile(p)) + t.Setenv("GOPROXY", "") + t.Setenv("GOPRIVATE", "") + t.Setenv("GONOPROXY", "") + if _, err := goProxy("github.com/corp/lib"); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("private module from the env file: %v", err) + } + if got, err := goProxy("github.com/x/y"); err != nil || got != "https://goproxy.corp.example" { + t.Errorf("proxy from the env file = %q, %v", got, err) + } + t.Setenv("GOPROXY", "https://other.example") + t.Setenv("GONOPROXY", "none.example") + if got, err := goProxy("github.com/corp/lib"); err != nil || got != "https://other.example" { + t.Errorf("the environment wins = %q, %v", got, err) + } +} + +func TestGoSumOrder(t *testing.T) { + lines := []string{ + "example.com/a v0.10.0/go.mod h1:b=", + "example.com/b v1.0.0 h1:e=", + "example.com/a v0.9.0 h1:c=", + "example.com/a v0.10.0 h1:a=", + "example.com/a v1.0.0-rc.1 h1:f=", + "example.com/a v0.9.0/go.mod h1:d=", + "example.com/a v1.0.0 h1:g=", + } + slices.SortFunc(lines, goSumCompare) + want := []string{ + "example.com/a v0.9.0 h1:c=", + "example.com/a v0.9.0/go.mod h1:d=", + "example.com/a v0.10.0 h1:a=", + "example.com/a v0.10.0/go.mod h1:b=", + "example.com/a v1.0.0-rc.1 h1:f=", + "example.com/a v1.0.0 h1:g=", + "example.com/b v1.0.0 h1:e=", + } + if !slices.Equal(lines, want) { + t.Errorf("order =\n%s\nwant\n%s", strings.Join(lines, "\n"), strings.Join(want, "\n")) + } +} + +// A module far behind its newest major finds it in a few requests: majors +// v2 through v90 of github.com/acme/far exist, and the latest is v90. +func TestGoMetaFarMajors(t *testing.T) { + goPublic(t) + var mu sync.Mutex + lists := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rest, ok := strings.CutPrefix(r.URL.Path, "/github.com/acme/far") + if !ok { + http.NotFound(w, r) + return + } + major, file := 1, strings.TrimPrefix(rest, "/@") + if m, f, ok := strings.Cut(strings.TrimPrefix(rest, "/v"), "/@"); ok && strings.HasPrefix(rest, "/v") { + if _, err := fmt.Sscanf(m, "%d", &major); err != nil || major > 90 { + http.NotFound(w, r) + return + } + file = f + } + v := fmt.Sprintf("v%d.0.0", major) + mod := "github.com/acme/far" + if major > 1 { + mod += fmt.Sprintf("/v%d", major) + } + switch { + case file == "v/list": + mu.Lock() + lists++ + mu.Unlock() + fmt.Fprintln(w, v) + case file == "latest" || strings.HasSuffix(file, ".info"): + fmt.Fprintf(w, `{"Version": %q, "Time": "2026-01-01T00:00:00Z"}`, v) + case strings.HasSuffix(file, ".mod"): + fmt.Fprintf(w, "module %s\n", mod) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + t.Setenv("GOPROXY", srv.URL) + meta, err := (gomod{}).Meta(context.Background(), fetch.New("", "test"), "github.com/acme/far/v28") + if err != nil { + t.Fatal(err) + } + if meta.Latest != "v90.0.0" { + t.Errorf("latest = %q, want v90.0.0", meta.Latest) + } + var vs []string + for _, r := range meta.Releases { + vs = append(vs, r.Version) + } + if !slices.Equal(vs, []string{"v28.0.0", "v29.0.0", "v90.0.0"}) { + t.Errorf("releases = %v", vs) + } + if lists > 20 { + t.Errorf("%d list requests, want a few", lists) + } +} diff --git a/internal/eco/gradle.go b/internal/eco/gradle.go index 0221fd4..432fd3b 100644 --- a/internal/eco/gradle.go +++ b/internal/eco/gradle.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/ver" ) type gradle struct{} @@ -56,6 +57,7 @@ type gradleEntry struct { at int // its line there pre, suf string // text around the version on that line notation bool // written as "group:artifact:version" in the manifest + dynamic bool // a version Gradle resolves: 4.+, latest.release, [1.0,2.0) } func (e gradleEntry) name() string { return e.group + ":" + e.artifact } @@ -65,6 +67,12 @@ func (gradle) Deps(root string, m core.Manifest) ([]core.Dep, error) { if err != nil { return nil, err } + var locked map[string]string + if slices.ContainsFunc(entries, func(e gradleEntry) bool { return e.dynamic }) { + if locked, err = gradleLocked(root, gradleRoot(root, m)); err != nil { + return nil, err + } + } var res []core.Dep seen := map[string]bool{} for _, e := range entries { @@ -72,11 +80,17 @@ func (gradle) Deps(root string, m core.Manifest) ([]core.Dep, error) { continue } seen[e.name()] = true + version, req := e.version, e.req + if e.dynamic { + if version, req = locked[e.name()], e.version; version == "" { + continue + } + } res = append(res, core.Dep{ Ecosystem: core.Gradle, Name: e.name(), - Version: e.version, - Req: e.req, + Version: version, + Req: req, Manifest: m, Line: e.line, Dev: e.dev, @@ -103,12 +117,14 @@ var ( gradleVarRef = regexp.MustCompile(`^\$\{?([A-Za-z_][\w.]*)\}?$`) ) +var gradleNotDeps = map[string]bool{"module": true, "project": true, "println": true, "print": true, "uri": true, "file": true, "files": true} + // buildEntries reads "g:a:v" strings and group/name/version maps given to a -// configuration (implementation, api, testImplementation, ...). Catalog -// references (libs.x) are reported by the catalog itself, plugins blocks are -// not dependencies, and $var versions resolve through gradleVars. +// configuration (implementation, api, testImplementation, ...) inside a +// dependencies block. Catalog references (libs.x) are reported by the +// catalog itself, and $var versions resolve through gradleVars. func buildEntries(root string, m core.Manifest, src []byte) []gradleEntry { - clean := gradleNoPlugins(gradleClean(src)) + clean := gradleOnlyDeps(gradleClean(src)) vars := gradleVars(root, m) var res []gradleEntry for _, re := range []*regexp.Regexp{gradleNotation, gradleMapForm} { @@ -121,12 +137,16 @@ func buildEntries(root string, m core.Manifest, src []byte) []gradleEntry { } return string(src[x[2*i]:x[2*i+1]]) } + if gradleNotDeps[g("conf")] { + continue + } e := gradleEntry{group: g("group"), artifact: g("artifact"), req: g("version"), line: lineOf(src, at("version")), dev: gradleTestConf(g("conf"))} e.version, e.file, e.at, e.pre, e.suf = e.req, m.Path, e.line, g("pre"), g("q") if re == gradleNotation { e.notation, e.pre, e.suf = true, e.group+":"+e.artifact+":", g("rest")+g("q") } if gradleUseVar(&e, vars, g("q")) { + e.dynamic = gradleDynamic(e.version) res = append(res, e) } } @@ -265,7 +285,98 @@ func gradleClean(src []byte) []byte { return res } -var gradlePlugins = regexp.MustCompile(`\bplugins\s*\{`) +var ( + gradlePlugins = regexp.MustCompile(`\bplugins\s*\{`) + gradleDepsRe = regexp.MustCompile(`\bdependencies\s*\{`) +) + +func gradleOnlyDeps(src []byte) []byte { + keep := make([]bool, len(src)) + for _, x := range gradleDepsRe.FindAllIndex(src, -1) { + depth := 0 + for i := x[1] - 1; i < len(src); i++ { + switch src[i] { + case '{': + depth++ + case '}': + depth-- + } + keep[i] = true + if depth == 0 { + break + } + } + } + res := bytes.Clone(src) + for i, k := range keep { + if !k && res[i] != '\n' { + res[i] = ' ' + } + } + return res +} + +func gradleDynamic(v string) bool { + return strings.HasSuffix(v, "+") || strings.HasPrefix(v, "latest.") || strings.HasPrefix(v, "[") || strings.HasPrefix(v, "(") || strings.HasPrefix(v, "]") +} + +func gradleAdmits(spec, v string) bool { + switch { + case strings.HasPrefix(spec, "latest."), spec == "+": + return true + case strings.HasSuffix(spec, "+"): + return strings.HasPrefix(v, strings.TrimSuffix(spec, "+")) + } + if len(spec) < 2 { + return false + } + lo, hi, ok := strings.Cut(spec[1:len(spec)-1], ",") + if !ok { + return spec[0] == '[' && strings.TrimSpace(lo) == v + } + lo, hi = strings.TrimSpace(lo), strings.TrimSpace(hi) + if lo != "" && (ver.Less(v, lo) || spec[0] != '[' && !ver.Less(lo, v)) { + return false + } + end := spec[len(spec)-1] + return hi == "" || ver.Less(v, hi) || end == ']' && !ver.Less(hi, v) +} + +func gradleMove(spec, to string) (string, bool) { + if !strings.HasSuffix(spec, ".+") { + return "", false + } + n := strings.Count(strings.TrimSuffix(spec, ".+"), ".") + 1 + next := shape(to, n) + ".+" + return next, gradleAdmits(next, to) +} + +var gradleLockLine = regexp.MustCompile(`^([^:#=\s]+):([^:=\s]+):([^:=\s]+)=`) + +func gradleLocked(root, top string) (map[string]string, error) { + locks, err := gradleLocks(root, top) + if err != nil { + return nil, err + } + res := map[string]string{} + for _, l := range locks { + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(l))) + if err != nil { + continue + } + for _, line := range strings.Split(string(b), "\n") { + m := gradleLockLine.FindStringSubmatch(strings.TrimSpace(line)) + if m == nil { + continue + } + name := m[1] + ":" + m[2] + if cur := res[name]; cur == "" || ver.Less(cur, m[3]) { + res[name] = m[3] + } + } + } + return res, nil +} func gradleNoPlugins(src []byte) []byte { for _, x := range gradlePlugins.FindAllIndex(src, -1) { @@ -337,6 +448,7 @@ func catalogEntry(lines []tomlLine, i int, v any, versions map[string]any) (grad e.notation = true e.req, e.version = parts[2], parts[2] e.pre = module + ":" + e.dynamic = gradleDynamic(e.version) return catalogModule(e, module) } case map[string]any: @@ -360,6 +472,7 @@ func catalogEntry(lines []tomlLine, i int, v any, versions map[string]any) (grad e.version = catalogVersion(ver) e.req = e.version } + e.dynamic = gradleDynamic(e.version) if e.version != "" { q := `"` if strings.Contains(lines[e.at-1].text, `'`+e.version+`'`) { @@ -451,6 +564,9 @@ func (gradle) Bump(ctx context.Context, root string, d core.Dep, to, toName stri if err != nil { return nil, err } + if e.dynamic { + return gradleBumpDynamic(ctx, root, top, locks, *e, d, to, toName) + } snap := snapFiles(root, append([]string{e.file}, locks...)...) p := filepath.Join(root, filepath.FromSlash(e.file)) switch { @@ -483,6 +599,36 @@ func (gradle) Bump(ctx context.Context, root string, d core.Dep, to, toName stri return &core.Bump{Files: snap.changed(root), Locked: true}, nil } +func gradleBumpDynamic(ctx context.Context, root, top string, locks []string, e gradleEntry, d core.Dep, to, toName string) (*core.Bump, error) { + m := d.Manifest + if toName != "" || len(locks) == 0 { + return nil, fmt.Errorf("%s: %s is at %s, which Gradle resolves: %w", m.Path, d.Name, e.version, core.ErrNotSupported) + } + next := e.version + if !gradleAdmits(next, to) { + moved, ok := gradleMove(next, to) + if !ok { + return nil, fmt.Errorf("%s: %s is at %s, which does not admit %s and cannot be moved: %w", m.Path, d.Name, e.version, to, core.ErrNotSupported) + } + next = moved + } + tool := gradleTool(root, top) + if tool == "gradle" && !have(tool) { + return nil, core.ToolMissing{Tool: tool} + } + snap := snapFiles(root, append([]string{e.file}, locks...)...) + if next != e.version { + if err := rewriteLine(filepath.Join(root, filepath.FromSlash(e.file)), e.at, e.pre+e.version+e.suf, e.pre+next+e.suf); err != nil { + return nil, err + } + } + if err := runIn(ctx, root, top, nil, tool+" "+gradleLockTasks(top, locks)+" --update-locks "+shArg(d.Name)); err != nil { + _ = snap.restore(root) + return nil, err + } + return &core.Bump{Files: snap.changed(root), Locked: true}, nil +} + func gradleLocks(root, top string) ([]string, error) { files, err := walk(root, "gradle.lockfile", "buildscript-gradle.lockfile", "*/gradle/dependency-locks/*.lockfile", "gradle/dependency-locks/*.lockfile") if err != nil { @@ -550,7 +696,7 @@ func (gradle) Commands(root string, m core.Manifest) core.Commands { } func (gradle) Traits() core.Traits { - return core.Traits{OSV: "Maven", Page: centralPage} + return core.Traits{OSV: "Maven", Page: centralPage, KeepSuffix: true} } func (gradle) Imports(d core.Dep) []string { return mavenImports(d.Name) } diff --git a/internal/eco/gradle_test.go b/internal/eco/gradle_test.go index 26c0d08..75b486e 100644 --- a/internal/eco/gradle_test.go +++ b/internal/eco/gradle_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "strings" "testing" @@ -237,3 +238,111 @@ func TestGradleBumpReal(t *testing.T) { t.Errorf("gradle.lockfile:\n%s", b) } } + +func TestGradleDynamic(t *testing.T) { + build := "dependencies {\n" + + " implementation(\"com.squareup.okhttp3:okhttp:4.+\")\n" + + " implementation(\"com.example:floating:latest.release\")\n" + + " implementation(\"com.example:ranged:[1.0,2.0)\")\n" + + " implementation(\"com.example:unlocked:1.+\")\n" + + " implementation(\"com.example:fixed:1.0.0\")\n" + + " implementation(module(\"old:lib:1.0\"))\n" + + " println(\"not:a:dependency\")\n" + + "}\n" + + "configurations.all { resolutionStrategy { force(\"com.example:forced:1.0\") } }\n" + + "println(\"not:a:dependency\")\n" + lock := "com.squareup.okhttp3:okhttp:4.11.0=compileClasspath\ncom.example:floating:3.2.0=compileClasspath\ncom.example:ranged:1.4.0=compileClasspath\ncom.example:fixed:1.0.0=compileClasspath\nempty=\n" + setup := func(t *testing.T) (string, string) { + root := t.TempDir() + log := filepath.Join(t.TempDir(), "log") + write(t, root, map[string]string{"settings.gradle.kts": "", "build.gradle.kts": build, "gradle.lockfile": lock}) + if err := os.WriteFile(filepath.Join(root, "gradlew"), []byte("#!/bin/sh\necho \"$*\" >> "+log+"\necho changed >> gradle.lockfile\n"), 0o755); err != nil { + t.Fatal(err) + } + return root, log + } + root, _ := setup(t) + var got []string + for _, d := range depsIn(t, gradle{}, root, "build.gradle.kts") { + got = append(got, d.Name+" "+d.Version+" "+d.Req) + } + want := []string{ + "com.squareup.okhttp3:okhttp 4.11.0 4.+", + "com.example:floating 3.2.0 latest.release", + "com.example:ranged 1.4.0 [1.0,2.0)", + "com.example:fixed 1.0.0 1.0.0", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("deps = %q\nwant %q", got, want) + } + + tests := []struct { + name, dep, to, line, err string + }{ + {"inside the prefix moves the lock alone", "com.squareup.okhttp3:okhttp", "4.12.0", `implementation("com.squareup.okhttp3:okhttp:4.+")`, ""}, + {"a major keeps the prefix", "com.squareup.okhttp3:okhttp", "5.0.1", `implementation("com.squareup.okhttp3:okhttp:5.+")`, ""}, + {"latest moves the lock alone", "com.example:floating", "4.0.0", `implementation("com.example:floating:latest.release")`, ""}, + {"inside the range", "com.example:ranged", "1.9.0", `implementation("com.example:ranged:[1.0,2.0)")`, ""}, + {"outside the range", "com.example:ranged", "2.0.0", "", "cannot be moved"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root, log := setup(t) + d := depIn(t, gradle{}, root, "build.gradle.kts", tt.dep, true) + before := treeSnapshot(t, root) + res, err := (gradle{}).Bump(context.Background(), root, d, tt.to, "") + if tt.err != "" { + if !errors.Is(err, core.ErrNotSupported) || !strings.Contains(err.Error(), tt.err) { + t.Errorf("err = %v", err) + } + if !reflect.DeepEqual(before, treeSnapshot(t, root)) { + t.Error("a refused bump changed files") + } + return + } + if err != nil { + t.Fatal(err) + } + if !res.Locked || !slices.Contains(res.Files, "gradle.lockfile") { + t.Errorf("bump = %+v", res) + } + if b := treeSnapshot(t, root)["build.gradle.kts"]; !strings.Contains(b, tt.line) { + t.Errorf("build.gradle.kts =\n%s", b) + } + if b, _ := os.ReadFile(log); string(b) != "dependencies --update-locks "+tt.dep+"\n" { + t.Errorf("gradlew ran with %q", b) + } + }) + } +} + +func TestGradleAdmits(t *testing.T) { + tests := []struct { + spec, v string + want bool + }{ + {"4.+", "4.12.0", true}, + {"4.+", "5.0.0", false}, + {"4.1.+", "4.1.9", true}, + {"4.1.+", "4.2.0", false}, + {"+", "9.0.0", true}, + {"latest.integration", "1.0.0", true}, + {"[1.0,2.0)", "1.0", true}, + {"[1.0,2.0)", "2.0.0", false}, + {"[1.0,2.0]", "2.0", true}, + {"(1.0,2.0)", "1.0", false}, + {"]1.0,2.0[", "1.5", true}, + {"[1.0,)", "9.0", true}, + {"[1.5]", "1.5", true}, + } + for _, tt := range tests { + if got := gradleAdmits(tt.spec, tt.v); got != tt.want { + t.Errorf("gradleAdmits(%q, %q) = %v, want %v", tt.spec, tt.v, got, tt.want) + } + } + for spec, want := range map[string]string{"4.+": "5.+", "4.1.+": "5.0.+"} { + if got, ok := gradleMove(spec, "5.0.1"); !ok || got != want { + t.Errorf("gradleMove(%q) = %q, %v; want %q", spec, got, ok, want) + } + } +} diff --git a/internal/eco/helm.go b/internal/eco/helm.go index 1436641..daec3fe 100644 --- a/internal/eco/helm.go +++ b/internal/eco/helm.go @@ -223,10 +223,10 @@ func (helm) Bump(ctx context.Context, root string, d core.Dep, to, toName string // helmReq is the version range req written for to. One that already admits // to stays, and one tend cannot read becomes to itself. func helmReq(req, to string) string { - if v, ok := ver.Parse(to); ok && admits(req, v, false) { + if v, ok := ver.Parse(to); ok && admits(req, v, helmDialect) { return req } - next, err := fixReq(req, to, false) + next, err := fixReq(req, to, helmDialect) if err != nil { return to } diff --git a/internal/eco/lock.go b/internal/eco/lock.go index 71f9843..0e0ef7c 100644 --- a/internal/eco/lock.go +++ b/internal/eco/lock.go @@ -66,7 +66,7 @@ func ReadLock(file string, src []byte) ([]Locked, error) { } case "composer.lock": var lock composerLock - if err := json.Unmarshal(src, &lock); err != nil { + if err := json.Unmarshal(stripBOM(src), &lock); err != nil { return nil, err } for _, p := range append(lock.Packages, lock.PackagesDev...) { @@ -84,7 +84,7 @@ func ReadLock(file string, src []byte) ([]Locked, error) { } case "packages.lock.json": var lock nugetLockFile - if err := json.Unmarshal(src, &lock); err != nil { + if err := json.Unmarshal(stripBOM(src), &lock); err != nil { return nil, err } for _, fw := range lock.Dependencies { @@ -208,7 +208,9 @@ func lockedVersions(root, lock, ecosystem, name string) (map[string]bool, error) // what it actually locked. The tool moves such a dep to the newest release // its ranges allow, so to is a floor: every version of name the update // brought in must be to or later on to's major, and one of them must be -// locked. It returns the newest one when that is past to, else "". +// locked. A copy on another release line that the update only moved up +// within its line is another fix's business. It returns the newest one when +// that is past to, else "". func lockedTo(root, lock, ecosystem, name, to string, before map[string]bool) (string, error) { after, err := lockedVersions(root, lock, ecosystem, name) if err != nil { @@ -222,12 +224,26 @@ func lockedTo(root, lock, ecosystem, name, to string, before map[string]bool) (s } return ver.Compare(x, floor) >= 0 && x.Major() == floor.Major() } + raised := func(v string) bool { + x, okX := ver.Parse(v) + if !okX { + return false + } + for b := range before { + y, okY := ver.Parse(b) + if okY && y.Line() == x.Line() && ver.Compare(y, x) < 0 && y.Line() != floor.Line() { + return true + } + } + return false + } var other, in []string for _, v := range keys(after) { switch { case before[v] && !fits(v): case fits(v): in = append(in, v) + case raised(v): default: other = append(other, v) } diff --git a/internal/eco/lock_test.go b/internal/eco/lock_test.go index 5db0f6a..d62e571 100644 --- a/internal/eco/lock_test.go +++ b/internal/eco/lock_test.go @@ -2,7 +2,11 @@ package eco import ( "errors" + "fmt" + "os" + "path/filepath" "slices" + "strings" "testing" "github.com/mohsensc/tend-cli/internal/core" @@ -155,3 +159,40 @@ func TestCanon(t *testing.T) { } } } + +func TestLockedToOtherLines(t *testing.T) { + lock := func(vs ...string) string { + var b strings.Builder + b.WriteString(`{"lockfileVersion": 3, "packages": {"": {"name": "app"}`) + for i, v := range vs { + fmt.Fprintf(&b, `, "node_modules/%sansi-regex": {"version": %q}`, strings.Repeat("x/node_modules/", i), v) + } + b.WriteString("}}") + return b.String() + } + tests := []struct { + to string + after []string + landed string + err string + }{ + {"5.0.1", []string{"4.1.1", "5.0.1"}, "", ""}, + {"4.1.1", []string{"4.1.1", "5.0.1"}, "", ""}, + {"5.0.1", []string{"3.0.0", "5.0.1"}, "", "locked ansi-regex at 3.0.0"}, + {"5.0.1", []string{"4.1.0", "5.0.2"}, "5.0.2", ""}, + } + for _, tt := range tests { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "package-lock.json"), []byte(lock(tt.after...)), 0o644); err != nil { + t.Fatal(err) + } + before := map[string]bool{"4.1.0": true, "5.0.0": true} + got, err := lockedTo(root, "package-lock.json", core.Npm, "ansi-regex", tt.to, before) + if tt.err == "" && (err != nil || got != tt.landed) { + t.Errorf("lockedTo(%s, %v) = %q, %v; want %q", tt.to, tt.after, got, err, tt.landed) + } + if tt.err != "" && (err == nil || !strings.Contains(err.Error(), tt.err)) { + t.Errorf("lockedTo(%s, %v) err = %v, want %q", tt.to, tt.after, err, tt.err) + } + } +} diff --git a/internal/eco/maven.go b/internal/eco/maven.go index 4d53506..d36a838 100644 --- a/internal/eco/maven.go +++ b/internal/eco/maven.go @@ -677,7 +677,7 @@ func mavenReactor(root, dir string) string { // Traits says Maven cannot move a transitive dependency by itself: it has // no lockfile, and only a direct declaration overrides what a parent brings. func (maven) Traits() core.Traits { - return core.Traits{OSV: "Maven", Page: centralPage} + return core.Traits{OSV: "Maven", Page: centralPage, KeepSuffix: true} } func centralPage(name string) string { diff --git a/internal/eco/npm.go b/internal/eco/npm.go index 9542628..f8d9854 100644 --- a/internal/eco/npm.go +++ b/internal/eco/npm.go @@ -39,6 +39,8 @@ var npmLocks = []struct{ file, tool string }{ {"package-lock.json", "npm"}, {"pnpm-lock.yaml", "pnpm"}, {"yarn.lock", "yarn"}, + {"bun.lock", "bun"}, + {"bun.lockb", "bun"}, } const npmDefaultRegistry = "https://registry.npmjs.org" @@ -112,6 +114,12 @@ func npmMember(root, dir, member string) bool { if json.Unmarshal(raw, &pats) != nil && json.Unmarshal(raw, &ws) == nil { pats = append(pats, ws.Packages...) } + return globsMatch(pats, member) +} + +// globsMatch reports whether a workspace's member patterns take the dir +// member, relative to the workspace root; a trailing ** takes any depth. +func globsMatch(pats []string, member string) bool { for _, p := range pats { p = strings.TrimSuffix(strings.TrimPrefix(p, "./"), "/") if ok, _ := path.Match(p, member); ok { @@ -127,7 +135,7 @@ func npmMember(root, dir, member string) bool { func npmManager(info npmInfo) string { name, _, _ := strings.Cut(info.PackageManager, "@") switch name { - case "npm", "pnpm", "yarn": + case "npm", "pnpm", "yarn", "bun": return name } return "" @@ -152,7 +160,9 @@ type npmBlock struct { // npmParse reads the dependency blocks of package.json in file order. It walks // tokens instead of unmarshaling so that order and offsets survive. func npmParse(src []byte) ([]npmBlock, error) { - dec := json.NewDecoder(bytes.NewReader(src)) + body := stripBOM(src) + off := len(src) - len(body) + dec := json.NewDecoder(bytes.NewReader(body)) if t, err := dec.Token(); err != nil || t != json.Delim('{') { return nil, errors.New("package.json is not a JSON object") } @@ -170,7 +180,7 @@ func npmParse(src []byte) ([]npmBlock, error) { if !npmBlocks[key] || len(raw) == 0 || raw[0] != '{' { continue } - start := int(dec.InputOffset()) - len(raw) + start := off + int(dec.InputOffset()) - len(raw) b, err := npmParseBlock(src, start, key) if err != nil { return nil, err @@ -542,6 +552,9 @@ func npmValid(v string) bool { func (n npm) Bump(ctx context.Context, root string, d core.Dep, to, toName string) (*core.Bump, error) { m := d.Manifest + if err := lockUnsupported(m); err != nil { + return nil, err + } if toName != "" && !d.Direct { return nil, fmt.Errorf("%s: replacing %s, which only the lockfile names: %w", m.Path, d.Name, core.ErrNotSupported) } @@ -568,17 +581,20 @@ func (n npm) Bump(ctx context.Context, root string, d core.Dep, to, toName strin return nil, err } if !have(m.Tool) { - if !edited { - return nil, core.ToolMissing{Tool: m.Tool} - } - return &core.Bump{Files: snap.changed(root), Note: m.Tool + " not found"}, nil + return nil, errors.Join(core.ToolMissing{Tool: m.Tool}, snap.restore(root)) } var before map[string]bool if targeted { if before, err = lockedVersions(root, m.Lock, core.Npm, d.Name); err != nil { return nil, err } + if m.Tool == "yarn" && !yarnBerry(root, m) { + if err := yarnDrop(root, m.Lock, d.Name); err != nil { + return nil, errors.Join(err, snap.restore(root)) + } + } } + format := npmLockVersion(root, m) if exact { if err := n.lockAt(ctx, root, []core.Dep{d}, to, line); err != nil { return nil, err @@ -587,6 +603,9 @@ func (n npm) Bump(ctx context.Context, root string, d core.Dep, to, toName strin if err := runIn(ctx, root, path.Dir(m.Lock), nil, line); err != nil { return nil, err } + if err := n.keepFormat(ctx, root, m, line, format); err != nil { + return nil, errors.Join(err, snap.restore(root)) + } landed := "" if targeted { if landed, err = lockedTo(root, m.Lock, core.Npm, d.Name, to, before); err != nil { @@ -596,6 +615,35 @@ func (n npm) Bump(ctx context.Context, root string, d core.Dep, to, toName strin return &core.Bump{Files: snap.changed(root), Locked: true, Landed: landed}, nil } +// npmLockVersion is package-lock.json's lockfileVersion, 0 for none or +// another lockfile. +func npmLockVersion(root string, m core.Manifest) int { + if path.Base(m.Lock) != "package-lock.json" { + return 0 + } + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(m.Lock))) + if err != nil { + return 0 + } + var doc struct { + LockfileVersion int `json:"lockfileVersion"` + } + if json.Unmarshal(b, &doc) != nil { + return 0 + } + return doc.LockfileVersion +} + +// keepFormat runs line again with the lockfile's old format when the npm on +// PATH rewrote it in its own, as npm 7 and later do with a version 1 lock: +// thousands of changed lines, and an npm 7 floor for every contributor. +func (npm) keepFormat(ctx context.Context, root string, m core.Manifest, line string, was int) error { + if was == 0 || npmLockVersion(root, m) == was { + return nil + } + return runIn(ctx, root, path.Dir(m.Lock), nil, line+" --lockfile-version="+strconv.Itoa(was)) +} + // lockAt locks deps, all of one manifest, at exactly to. Left to itself the // lock tool takes the newest release the range allows, which may be past the // release tend chose; so each requirement reads to alone for one pass, and @@ -636,6 +684,18 @@ func (npm) lockAt(ctx context.Context, root string, deps []core.Dep, to, line st return err } err = runIn(ctx, root, path.Dir(m.Lock), nil, line) + if err == nil && m.Tool == "yarn" && !yarnBerry(root, m) { + for _, e := range es { + req := to + if strings.HasPrefix(e.req, "npm:") { + name, _ := npmRegistryName(e.key, e.req) + req = "npm:" + name + "@" + to + } + if _, err = yarnAlias(root, m.Lock, e.key+"@"+req, e.key+"@"+e.req); err != nil { + break + } + } + } if werr := writeKeepMode(p, src); err == nil { err = werr } @@ -647,6 +707,9 @@ func (npm) lockAt(ctx context.Context, root string, deps []core.Dep, to, line st // move at once. func (n npm) BumpGroup(ctx context.Context, root string, deps []core.Dep, to string) (*core.Bump, error) { m := deps[0].Manifest + if err := lockUnsupported(m); err != nil { + return nil, err + } snap := snapFiles(root, m.Path, m.Lock) for _, d := range deps { if !d.Direct || d.Manifest.Path != m.Path { @@ -660,18 +723,22 @@ func (n npm) BumpGroup(ctx context.Context, root string, deps []core.Dep, to str case m.Lock == "": return &core.Bump{Files: snap.changed(root), Note: "no lockfile"}, nil case !have(m.Tool): - return &core.Bump{Files: snap.changed(root), Note: m.Tool + " not found"}, nil + return nil, errors.Join(core.ToolMissing{Tool: m.Tool}, snap.restore(root)) } line, err := npmLockLine(root, m, "", false) if err != nil { return nil, err } + format := npmLockVersion(root, m) if err := n.lockAt(ctx, root, deps, to, line); err != nil { return nil, err } if err := runIn(ctx, root, path.Dir(m.Lock), nil, line); err != nil { return nil, err } + if err := n.keepFormat(ctx, root, m, line, format); err != nil { + return nil, errors.Join(err, snap.restore(root)) + } return &core.Bump{Files: snap.changed(root), Locked: true}, nil } @@ -910,9 +977,6 @@ func npmLockLine(root string, m core.Manifest, name string, targeted bool) (stri } return "yarn install --mode=update-lockfile", nil } - if targeted { - return "", fmt.Errorf("yarn v1 cannot update %s alone: %w", name, core.ErrNotSupported) - } return "yarn install --ignore-scripts --non-interactive", nil } if targeted { @@ -938,6 +1002,8 @@ func (npm) Commands(root string, m core.Manifest) core.Commands { tool := cmp.Or(m.Tool, "npm") var install string switch { + case tool == "bun": + install = "bun install --frozen-lockfile" case tool == "pnpm": install = "pnpm install --frozen-lockfile" case tool == "yarn" && yarnBerry(root, m): @@ -956,7 +1022,11 @@ func (npm) Commands(root string, m core.Manifest) core.Commands { c.Build = []string{inDir(dir, tool+" run build")} } if s, _ := scripts["test"].(string); s != "" && !strings.Contains(s, "no test specified") { - c.Test = []string{inDir(dir, tool+" test")} + test := tool + " test" + if tool == "bun" { + test = "bun run test" + } + c.Test = []string{inDir(dir, test)} } return c } diff --git a/internal/eco/npm_lock.go b/internal/eco/npm_lock.go index addf042..26e661b 100644 --- a/internal/eco/npm_lock.go +++ b/internal/eco/npm_lock.go @@ -46,6 +46,7 @@ func npmReadLock(root string, m core.Manifest) (npmLock, error) { lk, err = pnpmLock(src, member) case "yarn.lock": lk = yarnLock(src) + err = yarnWorkspaces(root, path.Dir(m.Lock), member, &lk) default: return none, nil } @@ -61,6 +62,66 @@ func npmReadLock(root string, m core.Manifest) (npmLock, error) { return lk, nil } +// yarnWorkspaces marks the workspace packages under lockDir as links. A +// classic lockfile has no entry for them and a member may require a sibling +// by a plain range, so only their package.json files name them. For the +// root it also records what the members require directly. +func yarnWorkspaces(root, lockDir, member string, lk *npmLock) error { + files, err := walk(root, "package.json") + if err != nil { + return err + } + var members []string + for _, f := range files { + dir := path.Dir(f) + if dir == lockDir || lockDir != "." && !strings.HasPrefix(dir, lockDir+"/") || !npmMember(root, lockDir, memberDir(lockDir, dir)) { + continue + } + members = append(members, f) + var info struct { + Name string `json:"name"` + } + if readJSON(filepath.Join(root, filepath.FromSlash(f)), &info) == nil && info.Name != "" { + lk.links[info.Name] = true + } + } + if member != "" { + return nil + } + lk.members = map[string]bool{} + for _, f := range members { + src, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(f))) + if err != nil { + continue + } + blocks, err := npmParse(src) + if err != nil { + continue + } + for _, e := range npmDirect(blocks) { + name, ok := npmRegistryName(e.key, e.req) + if !ok || lk.links[e.key] { + continue + } + if v := lk.resolve(e.key, e.req); v != "" { + lk.members[name+"@"+v] = true + } + } + } + return nil +} + +// unreadLocks are lockfiles tend finds but cannot read or bring in line, so +// it changes nothing their projects lock rather than leave them stale. +var unreadLocks = map[string]bool{"bun.lock": true, "bun.lockb": true, "pdm.lock": true} + +func lockUnsupported(m core.Manifest) error { + if base := path.Base(m.Lock); m.Lock != "" && unreadLocks[base] { + return fmt.Errorf("%s: %s lockfiles are not supported: %w", m.Path, base, core.ErrNotSupported) + } + return nil +} + // memberDir is dir relative to the lockfile's dir, "" when they are the same. func memberDir(lockDir, dir string) string { switch { @@ -103,6 +164,7 @@ func packageLock(src []byte, member string) (npmLock, error) { Version string `json:"version"` Dev bool `json:"dev"` Link bool `json:"link"` + Resolved string `json:"resolved"` Dependencies map[string]string `json:"dependencies"` DevDependencies map[string]string `json:"devDependencies"` OptionalDependencies map[string]string `json:"optionalDependencies"` @@ -110,7 +172,7 @@ func packageLock(src []byte, member string) (npmLock, error) { } `json:"packages"` Dependencies map[string]packageLockV1 `json:"dependencies"` } - if err := json.Unmarshal(src, &lf); err != nil { + if err := json.Unmarshal(stripBOM(src), &lf); err != nil { return npmLock{}, err } lk := npmLock{links: map[string]bool{}, members: map[string]bool{}} @@ -125,7 +187,7 @@ func packageLock(src []byte, member string) (npmLock, error) { if p.Link { lk.links[key] = true } - if p.Link || !npmValid(p.Version) { + if p.Link || !npmValid(p.Version) || !npmRegistryTarball(p.Resolved) { continue } byPath[k] = p.Version @@ -173,6 +235,18 @@ func packageLock(src []byte, member string) (npmLock, error) { return lk, nil } +// npmRegistryTarball reports whether a package-lock resolved URL is a +// registry's, //-/-.tgz, or is not recorded. +// Git, file and other tarball URLs install packages no registry has. +func npmRegistryTarball(resolved string) bool { + if resolved == "" { + return true + } + u, _, _ := strings.Cut(resolved, "?") + u, _, _ = strings.Cut(u, "#") + return (strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://")) && strings.Contains(u, "/-/") && strings.HasSuffix(u, ".tgz") +} + // pnpmRef is an importer entry: a bare version in lockfile v5, a // {specifier, version} mapping from v6 on. type pnpmRef string @@ -191,16 +265,23 @@ func (r *pnpmRef) UnmarshalYAML(n *yaml.Node) error { } // version drops the peer suffix pnpm appends: 1.2.3(react@18.2.0) in v6 and -// later, 1.2.3_react@18.2.0 in v5. Links and other protocols are not versions. +// later, 1.2.3_react@18.2.0 in v5. An alias refers to the package it +// installs by its key: bar@1.2.3 in v9, /bar@1.2.3 in v6, /bar/1.2.3 in v5. +// Links and other protocols are not versions. func (r pnpmRef) version() string { s := string(r) if i := strings.IndexAny(s, "(_"); i >= 0 { s = s[:i] } - if !npmValid(s) { - return "" + if npmValid(s) { + return s } - return s + for _, major := range []int{5, 9} { + if _, v, ok := pnpmKey(string(r), major); ok { + return v + } + } + return "" } type pnpmImporter struct { @@ -419,11 +500,15 @@ func yarnLock(src []byte) npmLock { } case specs != nil: v := strings.Trim(strings.TrimSpace(line[len(" version"):]), `:"' `) + workspace := slices.ContainsFunc(specs, func(spec string) bool { + _, rng, ok := yarnSpec(spec) + return ok && strings.HasPrefix(rng, "workspace:") + }) for _, spec := range specs { name, rng, ok := yarnSpec(spec) switch { case !ok: - case strings.HasPrefix(rng, "workspace:"): + case workspace: lk.links[name] = true case !strings.Contains(rng, ":") && npmValid(v): bySpec[name+"@"+rng] = v @@ -467,3 +552,101 @@ func yarnSpec(spec string) (name, rng string, ok bool) { } return s[:i], strings.TrimPrefix(s[i+1:], "npm:"), true } + +// yarnHeads are the specifiers a yarn v1 lock entry's header names, as +// written: `"ms@2.1.2", ms@^2.1.3:`. +func yarnHeads(line string) []string { + var res []string + for _, s := range strings.Split(strings.TrimSuffix(strings.TrimRight(line, "\r"), ":"), ", ") { + res = append(res, strings.Trim(s, `"`)) + } + return res +} + +// yarnNames says whether every specifier of a header is one of name: by its +// own name, or the package an npm: alias points at. +func yarnNames(line, name string) bool { + for _, spec := range yarnHeads(line) { + n, rng, ok := yarnSpec(spec) + if !ok { + return false + } + if real, _, ok := yarnSpec(rng); ok && strings.HasPrefix(spec[len(n)+1:], "npm:") { + n = real + } + if n != name { + return false + } + } + return true +} + +// yarnDrop removes the yarn v1 lock entries of name, so the next install +// resolves it again, to the newest release its ranges allow. yarn v1 has no +// command that updates one package of the lockfile alone. +func yarnDrop(root, lock, name string) error { + p := filepath.Join(root, filepath.FromSlash(lock)) + src, err := os.ReadFile(p) + if err != nil { + return err + } + var out strings.Builder + drop, dropped := false, 0 + for _, l := range strings.SplitAfter(string(src), "\n") { + t := strings.TrimRight(l, "\r\n") + switch { + case t != "" && t[0] != ' ' && t[0] != '#': + drop = yarnNames(t, name) + if drop { + dropped++ + } + case t == "" && drop: + drop = false + continue + } + if !drop { + out.WriteString(l) + } + } + if dropped == 0 { + return fmt.Errorf("%s has no entry for %s", lock, name) + } + return writeKeepMode(p, []byte(out.String())) +} + +// yarnAlias adds the specifier add to the yarn v1 lock entry whose header +// names have, so an install with add in package.json keeps that entry, and +// with it the version have locked. It reports whether there was one. +func yarnAlias(root, lock, have, add string) (bool, error) { + p := filepath.Join(root, filepath.FromSlash(lock)) + src, err := os.ReadFile(p) + if err != nil { + return false, err + } + lines := strings.SplitAfter(string(src), "\n") + for i, l := range lines { + t := strings.TrimRight(l, "\r\n") + if t == "" || t[0] == ' ' || t[0] == '#' || !slices.Contains(yarnHeads(t), have) { + continue + } + if slices.Contains(yarnHeads(t), add) { + return true, nil + } + lines[i] = strings.TrimSuffix(t, ":") + ", " + yarnKey(add) + ":" + l[len(t):] + return true, writeKeepMode(p, []byte(strings.Join(lines, ""))) + } + return false, nil +} + +// yarnKey writes a specifier the way yarn v1 does: quoted when it would not +// read back bare. +func yarnKey(s string) string { + bare := s != "" && (s[0] >= 'a' && s[0] <= 'z' || s[0] >= 'A' && s[0] <= 'Z') && !strings.ContainsAny(s, ": \t\n\\\",[]") + for _, w := range []string{"true", "false", "null"} { + bare = bare && !strings.HasPrefix(s, w) + } + if bare { + return s + } + return strconv.Quote(s) +} diff --git a/internal/eco/npm_test.go b/internal/eco/npm_test.go index a8b5954..556f3d8 100644 --- a/internal/eco/npm_test.go +++ b/internal/eco/npm_test.go @@ -399,6 +399,7 @@ func TestNpmBumpRefused(t *testing.T) { {"file dependency", core.Dep{Name: "local-lib", Manifest: m, Direct: true}, "1.0.0", core.ErrNotSupported}, {"inside range needs the tool", depIn(t, npm{}, root, "package.json", "debug", true), "4.9.0", core.ToolMissing{Tool: "npm"}}, {"transitive needs the tool", depIn(t, npm{}, root, "package.json", "ms", false), "2.1.4", core.ToolMissing{Tool: "npm"}}, + {"a new range needs the tool", depIn(t, npm{}, root, "package.json", "is-number", true), "8.0.0", core.ToolMissing{Tool: "npm"}}, } ms := depIn(t, npm{}, root, "package.json", "ms", false) if _, err := (npm{}).Bump(ctx, root, ms, "1.0.0", "tiny-ms"); !errors.Is(err, core.ErrNotSupported) { @@ -499,15 +500,55 @@ func TestNpmBumpCommands(t *testing.T) { }) } t.Run("yarn v1 transitive", func(t *testing.T) { - fakeTool(t, "yarn") + logged := toolScript(t, "yarn", `grep -q '^ms@' yarn.lock || printf '\nms@^2.1.3:\n version "2.1.4"\n' >> yarn.lock`+"\n") root := copyTestdata(t, "npm/yarn-v1") d := depIn(t, npm{}, root, "package.json", "ms", false) - if _, err := (npm{}).Bump(ctx, root, d, "2.1.4", ""); !errors.Is(err, core.ErrNotSupported) { - t.Errorf("err = %v", err) + res, err := (npm{}).Bump(ctx, root, d, "2.1.4", "") + if err != nil || !res.Locked { + t.Fatalf("bump = %+v, %v", res, err) + } + if got, want := logged(root), []string{". install --ignore-scripts --non-interactive"}; !reflect.DeepEqual(got, want) { + t.Errorf("ran %q, want %q", got, want) + } + lock, _ := os.ReadFile(filepath.Join(root, "yarn.lock")) + if strings.Contains(string(lock), `version "2.1.3"`) || !strings.Contains(string(lock), "debug@^4.3.4:") { + t.Errorf("yarn.lock:\n%s", lock) } }) } +func TestYarnLockEdits(t *testing.T) { + root := t.TempDir() + src := "# yarn lockfile v1\n\n\n\"@s/a@^1.0.0\":\n version \"1.0.0\"\n\nms@2.1.2, ms@^2.1.3:\n version \"2.1.3\"\n\nms@^1.0.0:\n version \"1.0.0\"\n\npad@npm:left-pad@^1.3.0:\n version \"1.3.0\"\n" + write(t, root, map[string]string{"yarn.lock": src}) + if err := yarnDrop(root, "yarn.lock", "ms"); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(filepath.Join(root, "yarn.lock")) + if want := "# yarn lockfile v1\n\n\n\"@s/a@^1.0.0\":\n version \"1.0.0\"\n\npad@npm:left-pad@^1.3.0:\n version \"1.3.0\"\n"; string(got) != want { + t.Errorf("after drop:\n%s", got) + } + if err := yarnDrop(root, "yarn.lock", "left-pad"); err != nil { + t.Errorf("an alias of left-pad is not its entry: %v", err) + } + if err := yarnDrop(root, "yarn.lock", "nope"); err == nil { + t.Error("dropping what is not there succeeded") + } + write(t, root, map[string]string{"yarn.lock": src}) + if ok, err := yarnAlias(root, "yarn.lock", "@s/a@^1.0.0", "@s/a@1.0.0"); !ok || err != nil { + t.Fatalf("alias = %v, %v", ok, err) + } + if ok, err := yarnAlias(root, "yarn.lock", "ms@2.1.2", "ms@^2.0.0"); !ok || err != nil { + t.Fatalf("alias = %v, %v", ok, err) + } + got, _ = os.ReadFile(filepath.Join(root, "yarn.lock")) + for _, want := range []string{"\"@s/a@^1.0.0\", \"@s/a@1.0.0\":\n", "ms@2.1.2, ms@^2.1.3, ms@^2.0.0:\n"} { + if !strings.Contains(string(got), want) { + t.Errorf("yarn.lock lacks %q:\n%s", want, got) + } + } +} + // lockTool is fakeTool that also rewrites from to to in whichever lockfile // sits in its working directory, the way a lock update moves a package. func lockTool(t *testing.T, name, from, to string) func(root string) []string { @@ -972,3 +1013,204 @@ func TestNpmLockAt(t *testing.T) { t.Errorf("a range that admits the target was rewritten:\n%s", after) } } + +func depLines(ds []core.Dep) []string { + var res []string + for _, d := range ds { + res = append(res, fmt.Sprintf("%s %q direct=%v", d.Name, d.Version, d.Direct)) + } + slices.Sort(res) + return res +} + +// A yarn workspace sibling required by a plain range is no registry package, +// and the root does not repeat what the members require directly. +func TestYarnWorkspaces(t *testing.T) { + tests := []struct { + name, lock string + }{ + {"classic", "# yarn lockfile v1\n\n\nleft-pad@^1.3.0:\n version \"1.3.0\"\n resolved \"https://registry.yarnpkg.com/left-pad/-/left-pad-1.3.0.tgz\"\n\nms@^2.1.3:\n version \"2.1.3\"\n"}, + {"berry", "__metadata:\n version: 8\n\n\"app@workspace:packages/app\":\n version: 0.0.0-use.local\n resolution: \"app@workspace:packages/app\"\n dependencies:\n left-pad: \"npm:^1.3.0\"\n shared: \"npm:^1.0.0\"\n\n\"left-pad@npm:^1.3.0\":\n version: 1.3.0\n resolution: \"left-pad@npm:1.3.0\"\n\n\"ms@npm:^2.1.3\":\n version: 2.1.3\n resolution: \"ms@npm:2.1.3\"\n\n\"root@workspace:.\":\n version: 0.0.0-use.local\n resolution: \"root@workspace:.\"\n\n\"shared@npm:^1.0.0, shared@workspace:packages/shared\":\n version: 1.0.0\n resolution: \"shared@workspace:packages/shared\"\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "package.json": `{"name": "root", "private": true, "workspaces": ["packages/*"], "dependencies": {"ms": "^2.1.3"}}`, + "yarn.lock": tt.lock, + "packages/app/package.json": `{"name": "app", "dependencies": {"shared": "^1.0.0", "left-pad": "^1.3.0"}}`, + "packages/shared/package.json": `{"name": "shared", "version": "1.0.0"}`, + }) + if got, want := depLines(depsIn(t, npm{}, root, "packages/app/package.json")), []string{`left-pad "1.3.0" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("app deps = %q, want %q", got, want) + } + if got, want := depLines(depsIn(t, npm{}, root, "package.json")), []string{`ms "2.1.3" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("root deps = %q, want %q", got, want) + } + if got := depLines(depsIn(t, npm{}, root, "packages/shared/package.json")); len(got) != 0 { + t.Errorf("shared deps = %q", got) + } + }) + } + lk := yarnLock([]byte("\"shared@npm:^1.0.0, shared@workspace:packages/shared\":\n version: 1.0.0\n")) + if len(lk.all) != 0 || !lk.links["shared"] { + t.Errorf("berry workspace block: all = %+v, links = %v", lk.all, lk.links) + } +} + +// Git, file and other tarball installs have a version in package-lock.json +// but no registry release; registry tarballs, custom registries included, +// and entries with no resolved URL stay. +func TestPackageLockSources(t *testing.T) { + lock := `{"lockfileVersion": 3, "packages": { + "": {"dependencies": {"mylib": "github:acme/mylib#v1", "tar": "https://example.com/t/tarlib-2.0.0.tgz", "vendored": "file:vendor/vendored-1.0.0.tgz", "@corp/ui": "^1.0.0", "left-pad": "^1.3.0", "is-number": "^7.0.0"}}, + "node_modules/mylib": {"version": "1.0.0", "resolved": "git+ssh://git@github.com/acme/mylib.git#0123456789abcdef"}, + "node_modules/tar": {"version": "2.0.0", "resolved": "https://example.com/t/tarlib-2.0.0.tgz"}, + "node_modules/vendored": {"version": "1.0.0", "resolved": "file:vendor/vendored-1.0.0.tgz"}, + "node_modules/@corp/ui": {"version": "1.2.0", "resolved": "https://artifactory.corp.example/api/npm/npm/@corp/ui/-/ui-1.2.0.tgz"}, + "node_modules/left-pad": {"version": "1.3.0", "resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz"}, + "node_modules/is-number": {"version": "7.0.0"}, + "node_modules/mylib/node_modules/ms": {"version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz"} + }}` + root := t.TempDir() + write(t, root, map[string]string{ + "package.json": `{"dependencies": {"mylib": "github:acme/mylib#v1", "tar": "https://example.com/t/tarlib-2.0.0.tgz", "vendored": "file:vendor/vendored-1.0.0.tgz", "@corp/ui": "^1.0.0", "left-pad": "^1.3.0", "is-number": "^7.0.0"}}`, + "package-lock.json": lock, + }) + want := []string{`@corp/ui "1.2.0" direct=true`, `is-number "7.0.0" direct=true`, `left-pad "1.3.0" direct=true`, `ms "2.1.3" direct=false`} + if got := depLines(depsIn(t, npm{}, root, "package.json")); !reflect.DeepEqual(got, want) { + t.Errorf("deps = %q\nwant %q", got, want) + } + ls, err := ReadLock("package-lock.json", []byte(lock)) + if err != nil { + t.Fatal(err) + } + var names []string + for _, l := range ls { + names = append(names, l.Name) + } + if want := []string{"@corp/ui", "is-number", "left-pad", "ms"}; !reflect.DeepEqual(names, want) { + t.Errorf("ReadLock = %q, want %q", names, want) + } +} + +// An aliased pnpm dependency resolves to the version of the package it +// installs, in every lockfile format, and is reported once. +func TestPnpmAlias(t *testing.T) { + tests := []struct { + name, req, lock string + }{ + {"v5", "npm:bar@^1.0.0", "lockfileVersion: 5.4\n\nspecifiers:\n foo: npm:bar@^1.0.0\n\ndependencies:\n foo: /bar/1.2.3\n\npackages:\n\n /bar/1.2.3:\n resolution: {integrity: sha512-x}\n dev: false\n"}, + {"v6", "npm:bar@^1.0.0", "lockfileVersion: '6.0'\n\ndependencies:\n foo:\n specifier: npm:bar@^1.0.0\n version: /bar@1.2.3\n\npackages:\n\n /bar@1.2.3:\n resolution: {integrity: sha512-x}\n dev: false\n"}, + {"v9", "npm:bar@^1.0.0", "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n foo:\n specifier: npm:bar@^1.0.0\n version: bar@1.2.3\n\npackages:\n\n bar@1.2.3:\n resolution: {integrity: sha512-x}\n\nsnapshots:\n\n bar@1.2.3: {}\n"}, + {"v9 scoped", "npm:@s/bar@^1.0.0", "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n foo:\n specifier: npm:@s/bar@^1.0.0\n version: '@s/bar@1.2.3(react@18.2.0)'\n\npackages:\n\n '@s/bar@1.2.3':\n resolution: {integrity: sha512-x}\n\nsnapshots:\n\n '@s/bar@1.2.3(react@18.2.0)': {}\n"}, + {"v5 scoped", "npm:@s/bar@^1.0.0", "lockfileVersion: 5.4\n\nspecifiers:\n foo: npm:@s/bar@^1.0.0\n\ndependencies:\n foo: /@s/bar/1.2.3_react@18.2.0\n\npackages:\n\n /@s/bar/1.2.3_react@18.2.0:\n resolution: {integrity: sha512-x}\n dev: false\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + lk, err := pnpmLock([]byte(tt.lock), "") + if err != nil { + t.Fatal(err) + } + if got := lk.resolve("foo", tt.req); got != "1.2.3" { + t.Errorf("resolve = %q", got) + } + root := t.TempDir() + write(t, root, map[string]string{ + "package.json": `{"dependencies": {"foo": "` + tt.req + `"}}`, + "pnpm-lock.yaml": tt.lock, + }) + name, _ := npmRegistryName("foo", tt.req) + if got, want := depLines(depsIn(t, npm{}, root, "package.json")), []string{name + ` "1.2.3" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("deps = %q, want %q", got, want) + } + }) + } + for _, ref := range []pnpmRef{"link:../x", "file:../x", "1.2.3_react@18.2.0", "1.2.3(react@18.2.0)"} { + want := "" + if strings.HasPrefix(string(ref), "1.2.3") { + want = "1.2.3" + } + if got := ref.version(); got != want { + t.Errorf("version(%q) = %q, want %q", ref, got, want) + } + } +} + +// A package.json saved with a byte order mark reads like any other, and a +// bump keeps the mark. +func TestNpmBOM(t *testing.T) { + hideTools(t) + root := t.TempDir() + src := "\xef\xbb\xbf{\"packageManager\": \"pnpm@9.0.0\", \"dependencies\": {\"left-pad\": \"^1.2.0\"}}" + write(t, root, map[string]string{"package.json": src}) + if ms := manifestsIn(t, npm{}, root); len(ms) != 1 || ms[0].Tool != "pnpm" { + t.Errorf("Detect = %+v", ms) + } + d := depIn(t, npm{}, root, "package.json", "left-pad", true) + if _, err := (npm{}).Bump(context.Background(), root, d, "2.0.0", ""); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(filepath.Join(root, "package.json")) + if want := strings.Replace(src, "^1.2.0", "^2.0.0", 1); string(got) != want { + t.Errorf("got %q\nwant %q", got, want) + } + lock := "\xef\xbb\xbf{\"lockfileVersion\": 3, \"packages\": {\"node_modules/ms\": {\"version\": \"2.1.3\"}}}" + if ls, err := ReadLock("package-lock.json", []byte(lock)); err != nil || len(ls) != 1 { + t.Errorf("ReadLock = %+v, %v", ls, err) + } +} + +// tend cannot read or relock bun's lockfiles, so it changes nothing a bun +// lockfile locks and runs bun, not npm, to check a project. +func TestBunLockRefused(t *testing.T) { + for _, lock := range []string{"bun.lock", "bun.lockb"} { + t.Run(lock, func(t *testing.T) { + fakeTool(t, "bun") + root := t.TempDir() + write(t, root, map[string]string{ + "package.json": `{"packageManager": "bun@1.2.0", "scripts": {"test": "bun test"}, "dependencies": {"left-pad": "^1.2.0"}}`, + lock: "{}", + }) + ms := manifestsIn(t, npm{}, root) + if len(ms) != 1 || ms[0].Lock != lock || ms[0].Tool != "bun" { + t.Fatalf("Detect = %+v", ms) + } + c := (npm{}).Commands(root, ms[0]) + if !reflect.DeepEqual(c.Install, []string{"bun install --frozen-lockfile"}) || !reflect.DeepEqual(c.Test, []string{"bun run test"}) { + t.Errorf("commands = %+v", c) + } + d := depIn(t, npm{}, root, "package.json", "left-pad", true) + before := treeSnapshot(t, root) + if _, err := (npm{}).Bump(context.Background(), root, d, "2.0.0", ""); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("bump err = %v", err) + } + if _, err := (npm{}).BumpGroup(context.Background(), root, []core.Dep{d}, "2.0.0"); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("group err = %v", err) + } + if _, err := (npm{}).Remove(context.Background(), root, []core.Dep{d}); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("remove err = %v", err) + } + if !reflect.DeepEqual(before, treeSnapshot(t, root)) { + t.Error("a refused change wrote files") + } + }) + } +} + +// An npm that writes its own lockfile format is run again with the old one. +func TestNpmKeepsLockFormat(t *testing.T) { + logged := toolScript(t, "npm", `case "$*" in *--lockfile-version=1*) sed 's/"lockfileVersion": 3/"lockfileVersion": 1/' package-lock.json > x ;; *) sed 's/"lockfileVersion": 1/"lockfileVersion": 3/' package-lock.json > x ;; esac; mv x package-lock.json`+"\n") + root := copyTestdata(t, "npm/lock-v1") + d := depIn(t, npm{}, root, "package.json", "debug", true) + if _, err := (npm{}).Bump(context.Background(), root, d, "4.9.0", ""); err != nil { + t.Fatal(err) + } + m := d.Manifest + if v := npmLockVersion(root, m); v != 1 { + t.Errorf("lockfileVersion = %d, want 1", v) + } + if got := logged(root); len(got) == 0 || !strings.HasSuffix(got[len(got)-1], "--lockfile-version=1") { + t.Errorf("ran %q", got) + } +} diff --git a/internal/eco/npm_unused.go b/internal/eco/npm_unused.go index ffc3f96..cc201bd 100644 --- a/internal/eco/npm_unused.go +++ b/internal/eco/npm_unused.go @@ -328,7 +328,7 @@ func (f *npmFacts) packageLock(src []byte) { PeerMeta map[string]any `json:"peerDependenciesMeta"` } `json:"packages"` } - if json.Unmarshal(src, &lf) != nil || lf.Packages == nil { + if json.Unmarshal(stripBOM(src), &lf) != nil || lf.Packages == nil { return } f.known = true @@ -420,6 +420,9 @@ func npmInstalledBins(root string, d core.Dep) []string { // that went with each, and has the package manager lock again. func (npm) Remove(ctx context.Context, root string, deps []core.Dep) (*core.Bump, error) { m := deps[0].Manifest + if err := lockUnsupported(m); err != nil { + return nil, err + } p := filepath.Join(root, filepath.FromSlash(m.Path)) src, err := os.ReadFile(p) if err != nil { diff --git a/internal/eco/nuget.go b/internal/eco/nuget.go index 83fdaef..2405ddd 100644 --- a/internal/eco/nuget.go +++ b/internal/eco/nuget.go @@ -517,10 +517,10 @@ func nugetVersion(req, to string) (string, bool) { return to, true case strings.HasSuffix(req, ".*") && plainVersion.MatchString(strings.TrimSuffix(req, ".*")): t := term{num: req} - if t.holds(want, false) { + if t.holds(want, anyDialect) { return req, true } - return t.move(to, false), true + return t.move(to, anyDialect), true } m := nugetRange.FindStringSubmatchIndex(req) if m == nil { diff --git a/internal/eco/python.go b/internal/eco/python.go index dcaaf74..b2672c2 100644 --- a/internal/eco/python.go +++ b/internal/eco/python.go @@ -1,6 +1,7 @@ package eco import ( + "bytes" "cmp" "context" "errors" @@ -24,7 +25,7 @@ type python struct{} func (python) Name() string { return core.Pip } func (python) Detect(root string) ([]core.Manifest, error) { - all, err := walk(root, "pyproject.toml", "Pipfile", "*.txt", "*.in") + all, err := walk(root, "pyproject.toml", "Pipfile", "setup.cfg", "*.txt", "*.in") if err != nil { return nil, err } @@ -36,6 +37,10 @@ func (python) Detect(root string) ([]core.Manifest, error) { if m, ok := pyProjectManifest(root, f); ok { res = append(res, m) } + case base == "setup.cfg": + if src, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(f))); err == nil && len(setupCfgEntries(src)) > 0 { + res = append(res, core.Manifest{Ecosystem: core.Pip, Path: f, Tool: "pip"}) + } case base == "Pipfile": m := core.Manifest{Ecosystem: core.Pip, Path: f, Tool: "pipenv"} if lock := f + ".lock"; onDisk(root, lock) { @@ -63,6 +68,7 @@ func (python) Detect(root string) ([]core.Manifest, error) { compiled[out] = true } } + var reqMs []core.Manifest for _, f := range queue { if compiled[f] { continue @@ -71,12 +77,116 @@ func (python) Detect(root string) ([]core.Manifest, error) { if out := strings.TrimSuffix(f, ".in") + ".txt"; compiled[out] { m.Lock = out } - res = append(res, m) + reqMs = append(reqMs, m) } + res = pyAdoptCompiled(root, append(res, reqMs...)) slices.SortFunc(res, func(a, b core.Manifest) int { return strings.Compare(a.Path, b.Path) }) return res, nil } +// pyAdoptCompiled pairs a compiled requirements file that has no .in beside +// it with the source its header's command names, a pyproject.toml or an .in +// file with no lock of its own, which then locks with it. A compiled file +// that names no such source, or shares it with another output, stays a +// manifest of its own whose pins Deps reads as locked, not required. +func pyAdoptCompiled(root string, ms []core.Manifest) []core.Manifest { + byPath := map[string]int{} + for i, m := range ms { + byPath[m.Path] = i + } + added := map[int]bool{} + outs := map[int][]int{} + for i := range ms { + m := ms[i] + if m.Lock != "" || path.Ext(m.Path) != ".txt" || pyCompiledBy(root, m.Path) == "" { + continue + } + for _, src := range pyCompiledFrom(root, m.Path) { + if path.Base(src) != "pyproject.toml" && path.Ext(src) != ".in" || !pyUnder(path.Dir(src), m.Path) { + continue + } + j, ok := byPath[src] + if !ok && path.Ext(src) == ".in" && onDisk(root, src) { + j, ok = len(ms), true + byPath[src], added[j] = j, true + ms = append(ms, core.Manifest{Ecosystem: core.Pip, Path: src, Tool: "pip"}) + } + if ok && ms[j].Lock == "" { + outs[j] = append(outs[j], i) + } + break + } + } + drop := map[int]bool{} + for j, is := range outs { + if len(is) == 1 { + ms[j].Lock = ms[is[0]].Path + drop[is[0]] = true + } + } + var res []core.Manifest + for i, m := range ms { + if !drop[i] && (!added[i] || m.Lock != "") { + res = append(res, m) + } + } + return res +} + +// pyUnder reports whether rel sits in dir or under it, so a lock command +// run in dir can name it. +func pyUnder(dir, rel string) bool { + return dir == "." || strings.HasPrefix(rel, dir+"/") +} + +// pyCompiledFrom lists the sources the command in a compiled file's header +// compiled it from, relative to the repo root: its arguments that are not +// options or their values. +func pyCompiledFrom(root, rel string) []string { + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel))) + if err != nil { + return nil + } + for i, line := range strings.SplitN(string(b), "\n", 11) { + if i == 10 || !strings.HasPrefix(line, "#") { + break + } + f := strings.Fields(strings.TrimPrefix(line, "#")) + switch { + case len(f) > 0 && f[0] == "pip-compile": + f = f[1:] + case len(f) > 2 && f[0] == "uv" && f[1] == "pip" && f[2] == "compile": + f = f[3:] + default: + continue + } + var res []string + for k := 0; k < len(f); k++ { + switch arg := f[k]; { + case pyValueOpts[arg]: + k++ + case strings.HasPrefix(arg, "-"): + default: + res = append(res, path.Join(path.Dir(rel), arg)) + } + } + return res + } + return nil +} + +// pyValueOpts are the pip-compile and uv pip compile options whose value is +// the next argument. +var pyValueOpts = map[string]bool{ + "-o": true, "--output-file": true, "-c": true, "--constraint": true, "--constraints": true, + "--override": true, "--overrides": true, "--build-constraint": true, "--build-constraints": true, + "-P": true, "--upgrade-package": true, "--extra": true, "--group": true, "-i": true, "--index-url": true, + "--extra-index-url": true, "-f": true, "--find-links": true, "-p": true, "--python": true, + "--python-version": true, "--python-platform": true, "--resolver": true, "--cache-dir": true, + "--pip-args": true, "--annotation-style": true, "--unsafe-package": true, "--no-emit-package": true, + "--config": true, "--index": true, "--default-index": true, +} + // pyReqFile matches requirements.txt, requirements-dev.txt, dev-requirements.in // and anything in a requirements/ directory. func pyReqFile(rel string) bool { @@ -123,6 +233,9 @@ func pyIncludes(root, rel string) (reqs, cons []string) { return reqs, cons } +// pyProjectManifest reads a pyproject.toml that declares a project, or that +// is the virtual root of a uv workspace, whose deps live in its lock alone. +// A uv workspace member shares the lockfile at the workspace root. func pyProjectManifest(root, rel string) (core.Manifest, bool) { var doc map[string]any if readTOML(filepath.Join(root, filepath.FromSlash(rel)), &doc) != nil { @@ -130,7 +243,10 @@ func pyProjectManifest(root, rel string) (core.Manifest, bool) { } tool, _ := doc["tool"].(map[string]any) _, poetry := tool["poetry"] - if _, ok := doc["project"]; !ok && !poetry { + _, pdm := tool["pdm"] + uv, _ := tool["uv"].(map[string]any) + _, workspace := uv["workspace"] + if _, ok := doc["project"]; !ok && !poetry && !workspace { return core.Manifest{}, false } m := core.Manifest{Ecosystem: core.Pip, Path: rel, Tool: "pip"} @@ -140,12 +256,53 @@ func pyProjectManifest(root, rel string) (core.Manifest, bool) { m.Lock, m.Tool = path.Join(dir, "uv.lock"), "uv" case onDisk(root, path.Join(dir, "poetry.lock")): m.Lock, m.Tool = path.Join(dir, "poetry.lock"), "poetry" + case onDisk(root, path.Join(dir, "pdm.lock")): + m.Lock, m.Tool = path.Join(dir, "pdm.lock"), "pdm" case poetry: m.Tool = "poetry" + case pdm: + m.Tool = "pdm" + default: + if lock := uvWorkspaceLock(root, dir); lock != "" { + m.Lock, m.Tool = lock, "uv" + } } return m, true } +// uvWorkspaceLock finds the uv.lock of the workspace dir belongs to: the +// nearest pyproject.toml above it with a [tool.uv.workspace] table, when its +// members globs, less its exclude globs, take dir. +func uvWorkspaceLock(root, dir string) string { + for d := dir; d != "."; { + d = path.Dir(d) + var doc struct { + Tool struct { + UV struct { + Workspace *struct { + Members []string `toml:"members"` + Exclude []string `toml:"exclude"` + } `toml:"workspace"` + } `toml:"uv"` + } `toml:"tool"` + } + if readTOML(filepath.Join(root, filepath.FromSlash(d), "pyproject.toml"), &doc) != nil { + continue + } + ws := doc.Tool.UV.Workspace + if ws == nil { + continue + } + member := memberDir(d, dir) + lock := path.Join(d, "uv.lock") + if !globsMatch(ws.Members, member) || globsMatch(ws.Exclude, member) || !onDisk(root, lock) { + return "" + } + return lock + } + return "" +} + // pyEntry is one requirement as written, with what Bump needs to edit it in // place: raw is the exact text on the line, and the name and specifier // offsets point into it. @@ -173,6 +330,8 @@ func pyEntries(root string, m core.Manifest) ([]pyEntry, error) { return pyProjectEntries(m.Path, src) case "Pipfile": return pipfileEntries(m.Path, src) + case "setup.cfg": + return setupCfgEntries(src), nil } res := pyReqEntries(src) if pyDevFile(m.Path) { @@ -183,6 +342,54 @@ func pyEntries(root string, m core.Manifest) ([]pyEntry, error) { return res, nil } +// setupCfgEntries reads the requirements a setuptools setup.cfg declares: +// [options] install_requires, and each extra of [options.extras_require], +// one per line, as the value or its indented continuation lines. A file: +// or attr: indirection names no requirement here. +func setupCfgEntries(src []byte) []pyEntry { + var res []pyEntry + section, key := "", "" + add := func(text string, n int) { + text = pyStripComment(text) + t := strings.TrimSpace(text) + if t == "" || strings.HasPrefix(t, "file:") || strings.HasPrefix(t, "attr:") { + return + } + r, ok := pyParseReq(t) + if !ok { + return + } + r.line, r.raw = n, t + if section == "options.extras_require" { + r.extra, r.dev = key, pyDevGroups[PyNorm(key)] + } + res = append(res, r) + } + for i, l := range strings.Split(string(src), "\n") { + line := strings.TrimRight(l, "\r") + t := strings.TrimSpace(line) + switch { + case t == "" || t[0] == '#' || t[0] == ';': + case strings.HasPrefix(t, "[") && strings.HasSuffix(t, "]"): + section, key = strings.ToLower(strings.TrimSpace(t[1:len(t)-1])), "" + case line[0] != ' ' && line[0] != '\t': + k, v, ok := strings.Cut(line, "=") + if c := strings.IndexByte(line, ':'); c >= 0 && (!ok || c < len(k)) { + k, v, ok = line[:c], line[c+1:], true + } + key = "" + k = strings.ToLower(strings.TrimSpace(k)) + if ok && (section == "options" && k == "install_requires" || section == "options.extras_require") { + key = k + add(v, i+1) + } + case key != "": + add(line, i+1) + } + } + return res +} + // pyDevFile reports a requirements file named for development or tests: // requirements-dev.txt, test-requirements.in, requirements/lint.txt. func pyDevFile(rel string) bool { @@ -457,6 +664,11 @@ func (python) Deps(root string, m core.Manifest) ([]core.Dep, error) { if err != nil { return nil, err } + uv, err := pyReadUV(root, m) + if err != nil { + return nil, err + } + pinsOnly := m.Lock == "" && path.Ext(m.Path) == ".txt" && pyCompiledBy(root, m.Path) != "" pyLearnModules(root, path.Dir(m.Path)) versions := map[string]string{} for _, l := range locked { @@ -466,7 +678,7 @@ func (python) Deps(root string, m core.Manifest) ([]core.Dep, error) { direct := map[string]bool{} for _, e := range entries { n := PyNorm(e.name) - if direct[n] { + if direct[n] || uv.local[n] { continue } direct[n] = true @@ -478,17 +690,55 @@ func (python) Deps(root string, m core.Manifest) ([]core.Dep, error) { Manifest: m, Line: e.line, Dev: e.dev, - Direct: true, + Direct: !pinsOnly, }) } for _, l := range locked { - if !direct[l.name] { + if !direct[l.name] && !uv.elsewhere(l.name) { res = append(res, core.Dep{Ecosystem: core.Pip, Name: l.name, Version: l.version, Manifest: m, Dev: l.dev || pyDevFile(m.Path)}) } } return res, nil } +// pyUVView is what a manifest makes of a uv.lock it may share with a +// workspace: the packages that come from no registry (members, paths, git), +// which are not registry deps however they are written, and whether each +// locked package is reported by another manifest. A member reports only its +// own requirements, and the root leaves out what members require directly. +type pyUVView struct { + local map[string]bool + elsewhere func(string) bool +} + +func pyReadUV(root string, m core.Manifest) (pyUVView, error) { + view := pyUVView{elsewhere: func(string) bool { return false }} + if path.Base(m.Lock) != "uv.lock" { + return view, nil + } + src, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(m.Lock))) + if err != nil { + return view, err + } + ps, err := uvPackages(src) + if err != nil { + return view, fmt.Errorf("%s: %w", m.Lock, err) + } + view.local = map[string]bool{} + for _, p := range ps { + if _, ok := p.Source["registry"]; !ok { + view.local[PyNorm(p.Name)] = true + } + } + if path.Dir(m.Path) != path.Dir(m.Lock) { + view.elsewhere = func(string) bool { return true } + return view, nil + } + reqs := uvMemberReqs(ps, ".") + view.elsewhere = func(name string) bool { return reqs[name] } + return view, nil +} + // pyPinned is the version an exact == or === pin names, "" for anything looser. func pyPinned(spec string) string { v, ok := strings.CutPrefix(spec, "===") @@ -702,6 +952,9 @@ func (py python) Bump(ctx context.Context, root string, d core.Dep, to, toName s if path.Base(m.Path) == "Pipfile" { return nil, fmt.Errorf("%s is read only: %w", m.Path, core.ErrNotSupported) } + if err := lockUnsupported(m); err != nil { + return nil, err + } if toName != "" && !d.Direct { return nil, fmt.Errorf("%s: replacing %s, which only the lockfile names: %w", m.Path, d.Name, core.ErrNotSupported) } @@ -719,10 +972,7 @@ func (py python) Bump(ctx context.Context, root string, d core.Dep, to, toName s } tool := pyLockTool(root, m) if !have(tool) { - if !edited { - return nil, core.ToolMissing{Tool: tool} - } - return &core.Bump{Files: snap.changed(root), Note: tool + " not found"}, nil + return nil, errors.Join(core.ToolMissing{Tool: tool}, snap.restore(root)) } exact := d.Direct && toName == "" && tool == "poetry" targeted := !edited && !exact @@ -853,6 +1103,8 @@ func pyLockTool(root string, m core.Manifest) string { return "uv" case "poetry.lock": return "poetry" + case "pdm.lock": + return "pdm" } if pyCompiledBy(root, m.Lock) == "uv" { return "uv" @@ -897,7 +1149,7 @@ func poetryLock(ctx context.Context, root, dir string) string { } func (python) Commands(root string, m core.Manifest) core.Commands { - dir := path.Dir(m.Path) + dir := pyProjDir(root, m) install, py := "python3 -m venv .venv && .venv/bin/pip install "+pyPipArgs(root, m), pyRun(m) switch m.Tool { case "uv": @@ -906,6 +1158,11 @@ func (python) Commands(root string, m core.Manifest) core.Commands { install = "poetry install" case "pipenv": install = "pipenv sync --dev" + case "pdm": + install = "pdm install" + if m.Lock != "" { + install = "pdm sync" + } } c := core.Commands{Install: []string{inDir(dir, install)}} if t := pyTestLine(root, m); t != "" { @@ -923,6 +1180,8 @@ func pyRun(m core.Manifest) string { return "poetry run python" case "pipenv": return "pipenv run python" + case "pdm": + return "pdm run python" } return ".venv/bin/python" } @@ -945,23 +1204,65 @@ func pyPipArgs(root string, m core.Manifest) string { } return "-e " + shArg(".["+strings.Join(extras, ",")+"]") } + if path.Base(m.Path) == "setup.cfg" { + return "-e ." + } + proj := pyProjDir(root, m) file := cmp.Or(m.Lock, m.Path) - res := "-r " + shArg(memberDir(dir, file)) - if dev := path.Join(dir, "requirements-dev.txt"); dev != file && onDisk(root, dev) { + res := "-r " + shArg(memberDir(proj, file)) + if dev := path.Join(proj, "requirements-dev.txt"); dev != file && onDisk(root, dev) { res += " -r requirements-dev.txt" } + if pyInstallable(root, proj) && (proj != dir || onDisk(root, path.Join(proj, "src"))) { + res += " -e ." + } return res } +// pyProjMarks are what makes a directory a Python project's: its build +// files, its tests, its pytest configuration. +var pyProjMarks = []string{"setup.py", "setup.cfg", "pyproject.toml", "tests", "test", "pytest.ini", "tox.ini", "conftest.py"} + +// pyProjDir is the directory a requirements file's project runs from: the +// file's own, or the nearest one above it that holds the project, as for +// requirements/tests.txt next to setup.py and tests/. Other manifests sit +// in theirs. +func pyProjDir(root string, m core.Manifest) string { + dir := path.Dir(m.Path) + if b := path.Base(m.Path); b == "pyproject.toml" || b == "Pipfile" || b == "setup.cfg" { + return dir + } + for d := dir; ; d = path.Dir(d) { + if slices.ContainsFunc(pyProjMarks, func(f string) bool { return onDisk(root, path.Join(d, f)) }) { + return d + } + if d == "." || d == "/" { + return dir + } + } +} + +// pyInstallable says whether dir holds a package pip can install with -e. +func pyInstallable(root, dir string) bool { + if onDisk(root, path.Join(dir, "setup.py")) || onDisk(root, path.Join(dir, "setup.cfg")) { + return true + } + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(path.Join(dir, "pyproject.toml")))) + return err == nil && (bytes.Contains(b, []byte("[project]")) || bytes.Contains(b, []byte("[build-system]"))) +} + // pyTestLine picks pytest when the project configures or depends on it, and // unittest discovery when there are test files but no pytest. func pyTestLine(root string, m core.Manifest) string { - dir := filepath.Join(root, filepath.FromSlash(path.Dir(m.Path))) + dir := filepath.Join(root, filepath.FromSlash(pyProjDir(root, m))) if pyUsesPytest(root, m, dir) { return "pytest" } if hits, _ := filepath.Glob(filepath.Join(dir, "tests", "*.py")); len(hits) > 0 { - return "unittest discover -s tests -t ." + if onDisk(dir, filepath.Join("tests", "__init__.py")) { + return "unittest discover -s tests -t ." + } + return "unittest discover -s tests" } if hits, _ := filepath.Glob(filepath.Join(dir, "test*.py")); len(hits) > 0 { return "unittest discover" @@ -991,7 +1292,7 @@ func pyUsesPytest(root string, m core.Manifest, dir string) bool { // pyNewSpec rewrites a version specifier so that it admits to, keeping its // style: ==1.0 -> ==2.0, >=1,<2 -> >=2.1,<3 (when 2.1 is outside), ~=1.4 -> -// ~=2.0, and Poetry's ^1.2 -> ^2.0. A specifier that already admits to comes +// ~=2.0, and Poetry's ^1.2 -> ^2.0 and 2.* -> 3.*. A specifier that already admits to comes // back unchanged. func pyNewSpec(spec, to string) (string, error) { if _, ok := ver.Parse(to); !ok { @@ -1036,16 +1337,21 @@ func pyNewClause(op, v, to string) (string, string) { switch op { case "===": return op, to - case "==": + case "", "==": if prefix, ok := strings.CutSuffix(v, ".*"); ok { return op, pyTrimTo(prefix, to, true) + ".*" } + if op == "" { + return op, to + } return op, pyTrimTo(v, to, false) case ">", ">=": return ">=", pyTrimTo(v, to, false) case "<": return op, pyNextMajor(v, to) - case "~=", "^", "~": + case "~=": + return op, pyCompatible(v, to) + case "^", "~": return op, pyTrimTo(v, to, false) case "!=": return op, v @@ -1085,6 +1391,29 @@ func pyTrimTo(old, to string, prefix bool) string { return strings.Join(parts, ".") } +// pyCompatible rewrites a ~= clause without narrowing it: ~=1.4 admits any +// 1.x from 1.4, so 2.1.3 gives ~=2.1,>=2.1.3, the 2.x series from the fixed +// release on, and 2.0.0 gives plain ~=2.0. +func pyCompatible(old, to string) string { + k := len(strings.Split(old, ".")) + v, ok := ver.Parse(to) + if !ok || k < 2 || len(v.Nums) <= k { + return to + } + parts := make([]string, k) + for i := range parts { + parts[i] = strconv.Itoa(v.Nums[i]) + } + head := strings.Join(parts, ".") + if h, _ := ver.Parse(head); ver.Compare(h, v) == 0 { + return head + } + if res := head + ",>=" + to; pySatisfies("~="+res, to) { + return res + } + return to +} + // pyNextMajor is the next major after to, written with as many parts as old. func pyNextMajor(old, to string) string { v, _ := ver.Parse(to) @@ -1143,7 +1472,7 @@ func pyClause(op, want, version string) bool { if prefix, ok := strings.CutSuffix(want, ".*"); ok { w, _ := ver.Parse(prefix) match := pyPrefix(w.Nums, v.Nums) - return op == "==" && match || op == "!=" && !match + return (op == "==" || op == "") && match || op == "!=" && !match } w, ok := ver.Parse(want) if !ok { diff --git a/internal/eco/python_lock.go b/internal/eco/python_lock.go index 4fd77bd..90a7d8b 100644 --- a/internal/eco/python_lock.go +++ b/internal/eco/python_lock.go @@ -30,6 +30,8 @@ func pyReadLock(root string, m core.Manifest) ([]lockPkg, error) { res, err = poetryLocked(src) case "Pipfile.lock": res, err = pipfileLock(src) + case "pdm.lock": + return nil, nil default: for _, e := range pyReqEntries(src) { if v := pyPinned(e.spec); v != "" { @@ -44,46 +46,81 @@ func pyReadLock(root string, m core.Manifest) ([]lockPkg, error) { return res, nil } -// uvLock keeps registry packages only; the project itself and path or git -// sources have no registry releases. -func uvLock(src []byte) ([]lockPkg, error) { - type dep struct{ Name string } +type uvDep struct{ Name string } + +type uvPackage struct { + Name string + Version string + Source map[string]any + Dependencies []uvDep + Optional map[string][]uvDep `toml:"optional-dependencies"` + Dev map[string][]uvDep `toml:"dev-dependencies"` +} + +func (p uvPackage) requires() []string { + all := p.Dependencies + for _, ds := range p.Optional { + all = append(all, ds...) + } + for _, ds := range p.Dev { + all = append(all, ds...) + } + var res []string + for _, d := range all { + res = append(res, PyNorm(d.Name)) + } + return res +} + +func uvPackages(src []byte) ([]uvPackage, error) { var lf struct { - Package []struct { - Name string - Version string - Source map[string]any - Dependencies []dep - Optional map[string][]dep `toml:"optional-dependencies"` - Dev map[string][]dep `toml:"dev-dependencies"` - } `toml:"package"` + Package []uvPackage `toml:"package"` } if err := tomlDecode(src, &lf); err != nil { return nil, err } + return lf.Package, nil +} + +// uvLock keeps registry packages only; the project itself and path or git +// sources have no registry releases. +func uvLock(src []byte) ([]lockPkg, error) { + ps, err := uvPackages(src) + if err != nil { + return nil, err + } var res []lockPkg - for _, p := range lf.Package { + for _, p := range ps { if _, ok := p.Source["registry"]; !ok || p.Version == "" { continue } - all := p.Dependencies - for _, ds := range p.Optional { - all = append(all, ds...) + res = append(res, lockPkg{name: PyNorm(p.Name), version: p.Version, requires: p.requires()}) + } + return res, nil +} + +// uvMemberReqs lists what the workspace members a uv.lock records, other +// than the project at dir relative to the lockfile, require directly. +func uvMemberReqs(ps []uvPackage, dir string) map[string]bool { + res := map[string]bool{} + for _, p := range ps { + at, ok := p.Source["editable"].(string) + if !ok { + at, ok = p.Source["virtual"].(string) } - for _, ds := range p.Dev { - all = append(all, ds...) + if !ok || path.Clean(at) == path.Clean(dir) { + continue } - var reqs []string - for _, d := range all { - reqs = append(reqs, PyNorm(d.Name)) + for _, r := range p.requires() { + res[r] = true } - res = append(res, lockPkg{name: PyNorm(p.Name), version: p.Version, requires: reqs}) } - return res, nil + return res } // poetryLocked reads poetry.lock: category = "dev" before Poetry 1.5, a -// groups list after it. +// groups list after it. Git, path and URL sources have no index releases; +// packages from a configured index, PyPI mirrors among them, stay. func poetryLocked(src []byte) ([]lockPkg, error) { var lf struct { Package []struct { @@ -92,6 +129,7 @@ func poetryLocked(src []byte) ([]lockPkg, error) { Category string Groups []string Dependencies map[string]any + Source struct{ Type string } } `toml:"package"` } if err := tomlDecode(src, &lf); err != nil { @@ -99,6 +137,13 @@ func poetryLocked(src []byte) ([]lockPkg, error) { } var res []lockPkg for _, p := range lf.Package { + switch p.Source.Type { + case "git", "directory", "file", "url": + continue + } + if p.Version == "" { + continue + } dev := p.Category == "dev" || len(p.Groups) > 0 && !slices.Contains(p.Groups, "main") var reqs []string for _, d := range keys(p.Dependencies) { @@ -114,15 +159,17 @@ func pipfileLock(src []byte) ([]lockPkg, error) { Default map[string]struct{ Version string } `json:"default"` Develop map[string]struct{ Version string } `json:"develop"` } - if err := json.Unmarshal(src, &lf); err != nil { + if err := json.Unmarshal(stripBOM(src), &lf); err != nil { return nil, err } var res []lockPkg for name, p := range lf.Default { - res = append(res, lockPkg{name: PyNorm(name), version: strings.TrimPrefix(p.Version, "==")}) + if p.Version != "" { + res = append(res, lockPkg{name: PyNorm(name), version: strings.TrimPrefix(p.Version, "==")}) + } } for name, p := range lf.Develop { - if _, ok := lf.Default[name]; !ok { + if _, ok := lf.Default[name]; !ok && p.Version != "" { res = append(res, lockPkg{name: PyNorm(name), version: strings.TrimPrefix(p.Version, "=="), dev: true}) } } diff --git a/internal/eco/python_test.go b/internal/eco/python_test.go index 059576e..7c3a378 100644 --- a/internal/eco/python_test.go +++ b/internal/eco/python_test.go @@ -27,6 +27,9 @@ func TestPythonDetect(t *testing.T) { {Ecosystem: "pip", Path: "reqs/requirements.txt", Tool: "pip"}, {Ecosystem: "pip", Path: "reqs/requirements/base.txt", Tool: "pip"}, {Ecosystem: "pip", Path: "uv/pyproject.toml", Lock: "uv/uv.lock", Tool: "uv"}, + {Ecosystem: "pip", Path: "workspace/packages/a/pyproject.toml", Lock: "workspace/uv.lock", Tool: "uv"}, + {Ecosystem: "pip", Path: "workspace/packages/skip/pyproject.toml", Tool: "pip"}, + {Ecosystem: "pip", Path: "workspace/pyproject.toml", Lock: "workspace/uv.lock", Tool: "uv"}, } if !reflect.DeepEqual(got, want) { t.Errorf("Detect = %+v\nwant %+v", got, want) @@ -125,6 +128,7 @@ func TestPythonMetaRecord(t *testing.T) { func TestPythonBump(t *testing.T) { hideTools(t) + stubTools(t, "uv", "poetry", "pip-compile") tests := []struct { name, manifest, dep, to, toName string }{ @@ -293,7 +297,15 @@ func TestPyNewSpec(t *testing.T) { {">= 1.2 < 2.0", "2.1.0", ">=2.1 <3.0", false}, {"<=1.4", "1.5", "<=1.5", false}, {"~=1.4", "2.0.0", "~=2.0", false}, - {"~=1.4", "2.0.1", "~=2.0.1", false}, + {"~=1.4", "2.0.1", "~=2.0,>=2.0.1", false}, + {"~=1.4", "2.1.3", "~=2.1,>=2.1.3", false}, + {"~=1.4,!=1.5", "2.1.3", "~=2.1,>=2.1.3,!=1.5", false}, + {"~=1.4", "2.1.3.post1", "~=2.1,>=2.1.3.post1", false}, + {"~=1.4", "2.1rc1", "~=2.1rc1", false}, + {"~=1.4.0", "2.1.3", "~=2.1.3", false}, + {"2.*", "2.32.0", "2.*", false}, + {"2.*", "3.0.0", "3.*", false}, + {"2.1.*", "2.2.0", "2.2.*", false}, {"~=1.4.2", "1.5.0", "~=1.5.0", false}, {"==1.4.*", "1.5.2", "==1.5.*", false}, {"==1.*", "2.3.0", "==2.*", false}, @@ -341,6 +353,13 @@ func TestPySatisfies(t *testing.T) { {"~=1.4.2", "1.5.0", false}, {"~=1.4", "1.9", true}, {"~=1.4", "2.0", false}, + {"2.*", "2.31.0", true}, + {"2.*", "3.0.0", false}, + {"2.1.*", "2.1.5", true}, + {"2.1.*", "2.2.0", false}, + {"~=2.1,>=2.1.3", "2.5.0", true}, + {"~=2.1,>=2.1.3", "2.1.0", false}, + {"~=2.1,>=2.1.3", "3.0", false}, {"<2.0", "2.0rc1", true}, {">=2.0", "2.0rc1", false}, {">=1.0", "1.0.post1", true}, @@ -469,11 +488,39 @@ func TestPythonCommands(t *testing.T) { m := manifestsIn(t, python{}, plain)[0] want := core.Commands{ Install: []string{"python3 -m venv .venv && .venv/bin/pip install -e '.[dev,test]'"}, - Test: []string{".venv/bin/python -m unittest discover -s tests -t ."}, + Test: []string{".venv/bin/python -m unittest discover -s tests"}, } if got := (python{}).Commands(plain, m); !reflect.DeepEqual(got, want) { t.Errorf("Commands = %+v\nwant %+v", got, want) } + write(t, plain, map[string]string{"tests/__init__.py": ""}) + want.Test = []string{".venv/bin/python -m unittest discover -s tests -t ."} + if got := (python{}).Commands(plain, m); !reflect.DeepEqual(got, want) { + t.Errorf("with a tests package, Commands = %+v\nwant %+v", got, want) + } +} + +// The pallets layout keeps pinned requirements in requirements/, the +// package in src/ and the tests in tests/: the proof runs from the root and +// installs the package too. +func TestPythonCommandsRequirementsDir(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "setup.py": "from setuptools import setup\nsetup()\n", + "setup.cfg": "[metadata]\nname = x\n\n[tool:pytest]\ntestpaths = tests\n", + "src/x/__init__.py": "", + "tests/test_a.py": "def test_a():\n pass\n", + "requirements/tests.in": "pytest\n", + "requirements/tests.txt": "pytest==8.3.3\n", + }) + m := core.Manifest{Ecosystem: core.Pip, Path: "requirements/tests.in", Lock: "requirements/tests.txt", Tool: "pip"} + want := core.Commands{ + Install: []string{"python3 -m venv .venv && .venv/bin/pip install -r requirements/tests.txt -e ."}, + Test: []string{".venv/bin/python -m pytest"}, + } + if got := (python{}).Commands(root, m); !reflect.DeepEqual(got, want) { + t.Errorf("Commands = %+v\nwant %+v", got, want) + } } // wheel writes a pure-Python wheel for name at version into dir. @@ -546,3 +593,234 @@ func TestPythonBumpReal(t *testing.T) { t.Errorf("uv.lock:\n%s", got["uv.lock"]) } } + +// A uv workspace member locks with the workspace's uv.lock: its versions +// come from there, a bump relocks it, and the root reports what only the +// lock names, less what members require directly. +func TestPythonUVWorkspace(t *testing.T) { + root := copyTestdata(t, "python/projects") + if got, want := depLines(depsIn(t, python{}, root, "workspace/packages/a/pyproject.toml")), []string{`requests "2.31.0" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("member deps = %q, want %q", got, want) + } + if got, want := depLines(depsIn(t, python{}, root, "workspace/pyproject.toml")), []string{`certifi "2024.8.30" direct=false`}; !reflect.DeepEqual(got, want) { + t.Errorf("root deps = %q, want %q", got, want) + } + logged := toolScript(t, "uv", "sed 's/2.31.0/2.32.0/' ../../uv.lock > ../../uv.lock.tmp && mv ../../uv.lock.tmp ../../uv.lock\n") + d := depIn(t, python{}, root, "workspace/packages/a/pyproject.toml", "requests", true) + res, err := python{}.Bump(context.Background(), root, d, "2.32.0", "") + if err != nil { + t.Fatal(err) + } + if want := []string{"workspace/packages/a/pyproject.toml", "workspace/uv.lock"}; !res.Locked || !reflect.DeepEqual(res.Files, want) { + t.Errorf("bump = %+v, want files %q", res, want) + } + if got, want := logged(root), []string{"./workspace/packages/a lock --upgrade-package requests==2.32.0"}; !reflect.DeepEqual(got, want) { + t.Errorf("uv ran %q, want %q", got, want) + } + m := manifestsIn(t, python{}, root) + for _, x := range m { + if x.Path == "workspace/packages/a/pyproject.toml" { + if c := (python{}).Commands(root, x); !reflect.DeepEqual(c.Install, []string{"cd workspace/packages/a && uv sync --frozen"}) { + t.Errorf("install = %q", c.Install) + } + } + } + t.Run("sibling member by source", func(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "pyproject.toml": "[project]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\"lib\", \"requests\"]\n\n[tool.uv.sources]\nlib = { workspace = true }\n\n[tool.uv.workspace]\nmembers = [\"lib\"]\n", + "lib/pyproject.toml": "[project]\nname = \"lib\"\nversion = \"0.1.0\"\n", + "uv.lock": "version = 1\n\n[[package]]\nname = \"app\"\nversion = \"0.1.0\"\nsource = { virtual = \".\" }\ndependencies = [{ name = \"lib\" }, { name = \"requests\" }]\n\n[[package]]\nname = \"lib\"\nversion = \"0.1.0\"\nsource = { editable = \"lib\" }\n\n[[package]]\nname = \"requests\"\nversion = \"2.31.0\"\nsource = { registry = \"https://pypi.org/simple\" }\n", + "lib/src/lib/__init__.py": "", + }) + if got, want := depLines(depsIn(t, python{}, root, "pyproject.toml")), []string{`requests "2.31.0" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("deps = %q, want %q", got, want) + } + if ms := manifestsIn(t, python{}, root); len(ms) != 2 || ms[0].Lock != "uv.lock" || ms[1].Lock != "uv.lock" { + t.Errorf("Detect = %+v", ms) + } + }) +} + +// Packages from git, a path or a URL have no PyPI releases, whatever their +// lockfile calls them; those from a configured index, a mirror perhaps, stay. +func TestPythonLockSources(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "poetry/pyproject.toml": "[tool.poetry]\nname = \"app\"\n\n[tool.poetry.dependencies]\npython = \"^3.12\"\nmylib = { git = \"https://github.com/acme/mylib.git\" }\nlocalpkg = { path = \"../localpkg\" }\nprivpkg = \"^1.0\"\n", + "poetry/poetry.lock": "[[package]]\nname = \"mylib\"\nversion = \"0.1.0\"\n\n[package.source]\ntype = \"git\"\nurl = \"https://github.com/acme/mylib.git\"\nreference = \"HEAD\"\nresolved_reference = \"abc\"\n\n" + + "[[package]]\nname = \"localpkg\"\nversion = \"0.0.1\"\n\n[package.source]\ntype = \"directory\"\nurl = \"../localpkg\"\n\n" + + "[[package]]\nname = \"wheelpkg\"\nversion = \"0.2.0\"\n\n[package.source]\ntype = \"file\"\nurl = \"dist/wheelpkg-0.2.0.whl\"\n\n" + + "[[package]]\nname = \"privpkg\"\nversion = \"1.0.0\"\n\n[package.source]\ntype = \"legacy\"\nurl = \"https://pypi.corp.example/simple\"\nreference = \"corp\"\n\n" + + "[[package]]\nname = \"idna\"\nversion = \"3.10\"\n", + "pipenv/Pipfile": "[packages]\nrequests = \"*\"\n", + "pipenv/Pipfile.lock": `{"default": {"requests": {"version": "==2.32.3"}, "mylib": {"git": "https://github.com/acme/mylib.git", "ref": "abc"}, "localpkg": {"path": "../localpkg", "editable": true}}, "develop": {"devlib": {"file": "https://example.com/devlib.zip"}, "pytest": {"version": "==8.3.3"}}}`, + }) + if got, want := depLines(depsIn(t, python{}, root, "poetry/pyproject.toml")), []string{`idna "3.10" direct=false`, `privpkg "1.0.0" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("poetry deps = %q, want %q", got, want) + } + if got, want := depLines(depsIn(t, python{}, root, "pipenv/Pipfile")), []string{`pytest "8.3.3" direct=false`, `requests "2.32.3" direct=true`}; !reflect.DeepEqual(got, want) { + t.Errorf("pipfile deps = %q, want %q", got, want) + } +} + +// A wildcard written bare, as Poetry allows, is a prefix match, and a bump +// keeps it a wildcard. +func TestPoetryBareWildcard(t *testing.T) { + hideTools(t) + root := t.TempDir() + write(t, root, map[string]string{"pyproject.toml": "[tool.poetry]\nname = \"app\"\n\n[tool.poetry.dependencies]\nrequests = \"2.*\"\n"}) + d := depIn(t, python{}, root, "pyproject.toml", "requests", true) + for _, tt := range []struct{ to, want string }{{"2.32.0", `requests = "2.*"`}, {"3.0.0", `requests = "3.*"`}} { + if _, err := (python{}).Bump(context.Background(), root, d, tt.to, ""); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(filepath.Join(root, "pyproject.toml")); !strings.Contains(string(b), tt.want+"\n") { + t.Errorf("to %s: pyproject.toml = %q", tt.to, b) + } + } +} + +// A file pip-compile or uv wrote from a pyproject.toml, with no .in beside +// it, is that project's lock; one whose source tend cannot edit is pins only. +func TestPythonCompiledWithoutIn(t *testing.T) { + compiled := "#\n# This file is autogenerated by pip-compile with Python 3.12\n# by the following command:\n#\n# pip-compile --extra=dev --output-file=requirements.txt pyproject.toml\n#\n" + + "numpy==2.1.0\n # via pandas\npandas==2.2.3\n # via app (pyproject.toml)\npython-dateutil==2.8.2\n # via pandas\npyyaml==6.0.2\n # via app (pyproject.toml)\nsix==1.16.0\n # via python-dateutil\n" + files := map[string]string{ + "pyproject.toml": "[project]\nname = \"app\"\ndependencies = [\"pandas\", \"pyyaml\"]\n", + "requirements.txt": compiled, + "app/main.py": "import pandas\n", + } + root := t.TempDir() + write(t, root, files) + want := []core.Manifest{{Ecosystem: "pip", Path: "pyproject.toml", Lock: "requirements.txt", Tool: "pip"}} + if got := manifestsIn(t, python{}, root); !reflect.DeepEqual(got, want) { + t.Errorf("Detect = %+v\nwant %+v", got, want) + } + wantDeps := []string{`numpy "2.1.0" direct=false`, `pandas "2.2.3" direct=true`, `python-dateutil "2.8.2" direct=false`, `pyyaml "6.0.2" direct=true`, `six "1.16.0" direct=false`} + if got := depLines(depsIn(t, python{}, root, "pyproject.toml")); !reflect.DeepEqual(got, wantDeps) { + t.Errorf("deps = %q\nwant %q", got, wantDeps) + } + if gone, _ := unusedIn(t, files); !reflect.DeepEqual(gone, []string{"pyyaml"}) { + t.Errorf("unused = %q, want only pyyaml", gone) + } + calls := fakeTool(t, "pip-compile") + d := depIn(t, python{}, root, "pyproject.toml", "python-dateutil", false) + if _, err := (python{}).Bump(context.Background(), root, d, "2.9.0", ""); err != nil { + t.Fatal(err) + } + if got, want := calls(root), []string{". --quiet --upgrade-package python-dateutil==2.9.0 pyproject.toml -o requirements.txt"}; !reflect.DeepEqual(got, want) { + t.Errorf("pip-compile ran %q, want %q", got, want) + } + + t.Run("in file of another name", func(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "deps/base.in": "flask\n", + "deps/requirements.txt": "# This file was autogenerated by uv via the following command:\n# uv pip compile base.in -o requirements.txt\nflask==3.0.0\nwerkzeug==3.0.4\n # via flask\n", + "other/requirements.txt": "# This file was autogenerated by uv via the following command:\n# uv pip compile ../deps/base.in -o requirements.txt\nflask==3.0.0\n", + }) + want := []core.Manifest{ + {Ecosystem: "pip", Path: "deps/base.in", Lock: "deps/requirements.txt", Tool: "pip"}, + {Ecosystem: "pip", Path: "other/requirements.txt", Tool: "pip"}, + } + if got := manifestsIn(t, python{}, root); !reflect.DeepEqual(got, want) { + t.Errorf("Detect = %+v\nwant %+v", got, want) + } + if got, want := depLines(depsIn(t, python{}, root, "other/requirements.txt")), []string{`flask "3.0.0" direct=false`}; !reflect.DeepEqual(got, want) { + t.Errorf("pins-only deps = %q, want %q", got, want) + } + }) + t.Run("source with a lock of its own", func(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "pyproject.toml": "[project]\nname = \"app\"\ndependencies = [\"pandas\"]\n", + "uv.lock": "version = 1\n", + "requirements.txt": "# This file was autogenerated by uv via the following command:\n# uv pip compile pyproject.toml -o requirements.txt\npandas==2.2.3\nnumpy==2.1.0\n", + }) + want := []core.Manifest{ + {Ecosystem: "pip", Path: "pyproject.toml", Lock: "uv.lock", Tool: "uv"}, + {Ecosystem: "pip", Path: "requirements.txt", Tool: "pip"}, + } + if got := manifestsIn(t, python{}, root); !reflect.DeepEqual(got, want) { + t.Errorf("Detect = %+v\nwant %+v", got, want) + } + d := depIn(t, python{}, root, "requirements.txt", "numpy", false) + if _, err := (python{}).Bump(context.Background(), root, d, "2.2.0", ""); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("bump of a pin in a compiled file: err = %v", err) + } + }) +} + +// tend cannot read or relock pdm.lock, so it changes nothing PDM locks. +func TestPdmLockRefused(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "pyproject.toml": "[project]\nname = \"app\"\ndependencies = [\"requests>=2.31\"]\n\n[tool.pdm]\ndistribution = false\n", + "pdm.lock": "[metadata]\ngroups = [\"default\"]\n\n[[package]]\nname = \"requests\"\nversion = \"2.31.0\"\n", + "tools/pyproject.toml": "[project]\nname = \"tools\"\ndependencies = [\"black\"]\n\n[tool.pdm]\n", + }) + ms := manifestsIn(t, python{}, root) + want := []core.Manifest{ + {Ecosystem: "pip", Path: "pyproject.toml", Lock: "pdm.lock", Tool: "pdm"}, + {Ecosystem: "pip", Path: "tools/pyproject.toml", Tool: "pdm"}, + } + if !reflect.DeepEqual(ms, want) { + t.Fatalf("Detect = %+v\nwant %+v", ms, want) + } + if c := (python{}).Commands(root, ms[0]); !reflect.DeepEqual(c.Install, []string{"pdm sync"}) { + t.Errorf("install = %q", c.Install) + } + if c := (python{}).Commands(root, ms[1]); !reflect.DeepEqual(c.Install, []string{"cd tools && pdm install"}) { + t.Errorf("install = %q", c.Install) + } + d := depIn(t, python{}, root, "pyproject.toml", "requests", true) + before := treeSnapshot(t, root) + if _, err := (python{}).Bump(context.Background(), root, d, "3.0.0", ""); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("bump err = %v", err) + } + if _, err := (python{}).Remove(context.Background(), root, []core.Dep{d}); !errors.Is(err, core.ErrNotSupported) { + t.Errorf("remove err = %v", err) + } + if !reflect.DeepEqual(before, treeSnapshot(t, root)) { + t.Error("a refused change wrote files") + } +} + +// A setuptools project's runtime pins in setup.cfg are deps like any. +func TestPythonSetupCfg(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "setup.cfg": "[metadata]\nname = pkg\nversion = 0.1\n\n[options]\npackages = pkg\npython_requires = >=3.8\ninstall_requires =\n requests==2.20.0\n click>=7 # cli\n file: more.txt\n\n[options.extras_require]\ntest =\n pytest==6.0\nyaml = pyyaml>=5\n", + "setup.py": "from setuptools import setup; setup()\n", + "pkg/__init__.py": "import requests\n", + }) + ms := manifestsIn(t, python{}, root) + if len(ms) != 1 || ms[0].Path != "setup.cfg" { + t.Fatalf("manifests = %+v", ms) + } + deps, err := python{}.Deps(root, ms[0]) + if err != nil { + t.Fatal(err) + } + var got []string + for _, d := range deps { + got = append(got, fmt.Sprintf("%s %s %s %d %v", d.Name, d.Version, d.Req, d.Line, d.Dev)) + } + want := []string{"requests 2.20.0 ==2.20.0 9 false", "click >=7 10 false", "pytest 6.0 ==6.0 15 true", "pyyaml >=5 16 false"} + if !reflect.DeepEqual(got, want) { + t.Errorf("deps = %q\nwant %q", got, want) + } + hideTools(t) + d := deps[0] + if _, err := (python{}).Bump(context.Background(), root, d, "2.32.4", ""); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(filepath.Join(root, "setup.cfg")) + if !strings.Contains(string(b), "\n requests==2.32.4\n click>=7 # cli\n") { + t.Errorf("setup.cfg:\n%s", b) + } + if c := (python{}).Commands(root, ms[0]); len(c.Install) != 1 || !strings.HasSuffix(c.Install[0], "pip install -e .") { + t.Errorf("commands = %+v", c) + } +} diff --git a/internal/eco/python_unused.go b/internal/eco/python_unused.go index e00212b..45458a2 100644 --- a/internal/eco/python_unused.go +++ b/internal/eco/python_unused.go @@ -102,9 +102,15 @@ func (py python) needs(u *usage, d core.Dep) (need, doubt string) { if why, ok := pyImplicit[n]; ok { return why, "" } + if n == "pytest" && pyTestLine(u.root, d.Manifest) == "pytest" { + return "tend runs it as the test command", "" + } if by := u.pyRequiredBy(n); by != "" { return "pinned for " + by + ", which requires it", "" } + if u.pyBlindFreeze(d.Manifest) { + return "a frozen requirements file pins what its other pins require, and with nothing installed tend cannot tell which those are", "" + } if why := pyExtra(u.root, d.Manifest, n); why != "" { return "", why } @@ -193,6 +199,25 @@ func (u *usage) pyConstraint(rel string) bool { // installed virtualenv says, requires n directly or through others; "" when // none does. n's line then pins what that one installs anyway, and dropping // it would let the version move. +// pyBlindFreeze says whether m is what pip freeze writes, every line +// pinned with ==, with no installed distribution to say what requires +// what: removing any line there may only unpin a dependency of another. +func (u *usage) pyBlindFreeze(m core.Manifest) bool { + entries, err := pyEntries(u.root, m) + if err != nil || len(entries) < 3 || path.Ext(m.Path) != ".txt" { + return false + } + for _, e := range entries { + if !strings.HasPrefix(strings.TrimSpace(e.spec), "==") { + return false + } + if _, ok := pyDistReqs.Load(PyNorm(e.name)); ok { + return false + } + } + return true +} + func (u *usage) pyRequiredBy(n string) string { for _, d := range u.deps { if d.Ecosystem != core.Pip || d.Name == n { @@ -240,6 +265,16 @@ func (python) Remove(ctx context.Context, root string, deps []core.Dep) (*core.B if path.Base(m.Path) == "Pipfile" { return nil, fmt.Errorf("%s is read only: %w", m.Path, core.ErrNotSupported) } + if err := lockUnsupported(m); err != nil { + return nil, err + } + // A manifest its lockfile no longer matches fails every locked install, + // so a removal waits for the tool that locks again. + if m.Lock != "" { + if tool := pyLockTool(root, m); !have(tool) { + return nil, fmt.Errorf("%s not found to update %s", tool, m.Lock) + } + } entries, err := pyEntries(root, m) if err != nil { return nil, err @@ -260,10 +295,6 @@ func (python) Remove(ctx context.Context, root string, deps []core.Dep) (*core.B if m.Lock == "" { return &core.Bump{Files: snap.changed(root), Note: "no lockfile"}, nil } - tool := pyLockTool(root, m) - if !have(tool) { - return &core.Bump{Files: snap.changed(root), Note: tool + " not found"}, nil - } if err := runIn(ctx, root, path.Dir(m.Path), nil, pyRelock(ctx, root, m)); err != nil { return nil, errors.Join(err, snap.restore(root)) } diff --git a/internal/eco/remove_test.go b/internal/eco/remove_test.go index 8a636f9..5450068 100644 --- a/internal/eco/remove_test.go +++ b/internal/eco/remove_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "slices" "strings" "testing" @@ -292,3 +293,38 @@ func TestPythonRemoveRelocks(t *testing.T) { t.Errorf("requirements.in = %q", b) } } + +// A removal waits for the tool that locks again: a manifest its lockfile no +// longer matches fails every locked install. +func TestPythonRemoveNoTool(t *testing.T) { + hideTools(t) + for _, tt := range []struct { + name string + files map[string]string + manifest string + want string + }{ + {"pip-compile", map[string]string{ + "requirements.in": "flask\npyyaml\n", + "requirements.txt": "# This file is autogenerated by pip-compile with Python 3.12\nflask==3.0.0\npyyaml==6.0.1\n", + }, "requirements.in", "pip-compile not found to update requirements.txt"}, + {"uv", map[string]string{ + "pyproject.toml": "[project]\nname = \"app\"\ndependencies = [\"flask\", \"pyyaml\"]\n", + "uv.lock": "version = 1\n", + }, "pyproject.toml", "uv not found to update uv.lock"}, + } { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + write(t, root, tt.files) + d := depIn(t, python{}, root, tt.manifest, "pyyaml", true) + before := treeSnapshot(t, root) + _, err := (python{}).Remove(context.Background(), root, []core.Dep{d}) + if err == nil || err.Error() != tt.want { + t.Errorf("err = %v, want %q", err, tt.want) + } + if !reflect.DeepEqual(before, treeSnapshot(t, root)) { + t.Error("a refused removal wrote files") + } + }) + } +} diff --git a/internal/eco/req.go b/internal/eco/req.go index 7bbb606..3dac25c 100644 --- a/internal/eco/req.go +++ b/internal/eco/req.go @@ -12,6 +12,14 @@ import ( type term struct{ op, gap, num string } +type dialect uint8 + +const ( + anyDialect dialect = iota + cargoDialect + helmDialect +) + var termRe = regexp.MustCompile(`(\^|~>|~|>=|<=|!=|==|>|<|=)?([ \t]*)(v?\d[0-9A-Za-z]*(?:\.[0-9A-Za-z]+)*(?:\.[*xX])?(?:-[0-9A-Za-z.]+)?|[*xX])`) type termAt struct { @@ -66,9 +74,9 @@ func bumpAt(nums []int, i int) ver.V { return ver.V{Nums: res} } -// holds reports whether v satisfies the term. cargo selects the one dialect -// that differs: a bare version is a caret range, ~1.2 pins the minor, =1.2 is a prefix. -func (t term) holds(v ver.V, cargo bool) bool { +// holds reports whether v satisfies the term as d reads it. +func (t term) holds(v ver.V, d dialect) bool { + cargo := d == cargoDialect if n, wild := t.wild(); wild { base, _ := ver.Parse(t.num[:max(len(t.num)-2, 0)]) return n == 0 || prefixOf(v.Nums, base.Nums) @@ -110,14 +118,14 @@ func (t term) holds(v ver.V, cargo bool) bool { switch { case len(nums) == 1: i = 0 - case cargo: + case cargo, d == helmDialect: i = 1 } return c >= 0 && ver.Compare(v, bumpAt(nums, i)) < 0 } // move rewrites the term so that it admits to, keeping its operator, spacing and precision. -func (t term) move(to string, cargo bool) string { +func (t term) move(to string, d dialect) string { n, wild := t.wild() lead := "" if strings.HasPrefix(t.num, "v") { @@ -139,7 +147,7 @@ func (t term) move(to string, cargo bool) string { case "<": return "<" + t.gap + lead + nextMajor(to, len(pv.Nums)) case "": - if !cargo { + if d != cargoDialect { return t.gap + lead + whole } } @@ -186,18 +194,18 @@ func alts(req string) [][2]int { return append(res, [2]int{start, len(req)}) } -func allHold(ts []termAt, v ver.V, cargo bool) bool { +func allHold(ts []termAt, v ver.V, d dialect) bool { for _, t := range ts { - if !t.t.holds(v, cargo) { + if !t.t.holds(v, d) { return false } } return true } -func admits(req string, v ver.V, cargo bool) bool { +func admits(req string, v ver.V, d dialect) bool { for _, a := range alts(req) { - if ts, ok := findTerms(req[a[0]:a[1]]); ok && allHold(ts, v, cargo) { + if ts, ok := findTerms(req[a[0]:a[1]]); ok && allHold(ts, v, d) { return true } } @@ -216,7 +224,7 @@ func raises(ts []termAt, want ver.V) bool { // fixReq returns req changed just enough to admit to. It is req itself when it // already does. Of several alternatives the last one is moved. -func fixReq(req, to string, cargo bool) (string, error) { +func fixReq(req, to string, d dialect) (string, error) { want, ok := ver.Parse(to) if !ok { return "", fmt.Errorf("version %q does not parse", to) @@ -228,7 +236,7 @@ func fixReq(req, to string, cargo bool) (string, error) { if !ok { return "", fmt.Errorf("cannot rewrite requirement %q", req) } - if allHold(ts, want, cargo) && !raises(ts, want) { + if allHold(ts, want, d) && !raises(ts, want) { return req, nil } last, off = ts, a[0] @@ -236,8 +244,8 @@ func fixReq(req, to string, cargo bool) (string, error) { res := req for i := len(last) - 1; i >= 0; i-- { t := last[i] - if !t.t.holds(want, cargo) || raises(last, want) { - res = res[:off+t.start] + t.t.move(to, cargo) + res[off+t.end:] + if !t.t.holds(want, d) || raises(last, want) { + res = res[:off+t.start] + t.t.move(to, d) + res[off+t.end:] } } return res, nil diff --git a/internal/eco/rubygems.go b/internal/eco/rubygems.go index aa66c8d..e23afa4 100644 --- a/internal/eco/rubygems.go +++ b/internal/eco/rubygems.go @@ -442,7 +442,7 @@ func gemEdit(root string, d core.Dep, to, toName string) (bool, error) { return false, nil } old := strings.Join(e.reqs(), ", ") - next, err := fixReq(old, to, false) + next, err := fixReq(old, to, anyDialect) if err != nil { return false, fmt.Errorf("rubygems: %s: %w", d.Name, err) } diff --git a/internal/eco/suite.go b/internal/eco/suite.go index c19683c..048dfc8 100644 --- a/internal/eco/suite.go +++ b/internal/eco/suite.go @@ -126,7 +126,7 @@ func (python) Suite(root string, m core.Manifest) *core.Suite { }, Code: smokePy, Run: func(files []string) string { - return inDir(dir, py+" -m unittest discover -s tests/tend -t .") + return inDir(dir, py+" -m unittest discover -s tests/tend") }, } } diff --git a/internal/eco/terraform.go b/internal/eco/terraform.go index 49ad9e9..02d35da 100644 --- a/internal/eco/terraform.go +++ b/internal/eco/terraform.go @@ -25,7 +25,8 @@ const tfRegistry = "https://registry.terraform.io/v1/" var ( tfBlock = regexp.MustCompile(`^\s*(required_providers|module\s+"[^"]+")\s*\{`) tfEntry = regexp.MustCompile(`^\s*([\w-]+)\s*=\s*\{`) - tfAttr = regexp.MustCompile(`^\s*(source|version)\s*=\s*"([^"]*)"`) + tfAttr = regexp.MustCompile(`(?:^|[\s{,])(source|version)\s*=\s*"([^"]*)"`) + tfLegacy = regexp.MustCompile(`^\s*([\w-]+)\s*=\s*"([^"]*)"`) tfLockHead = regexp.MustCompile(`^provider\s+"(?:registry\.terraform\.io/)?([^"]+)"\s*\{`) tfLockVer = regexp.MustCompile(`^\s*version\s*=\s*"([^"]+)"`) tfModule = regexp.MustCompile(`^[\w-]+/[\w-]+/[\w-]+$`) @@ -77,9 +78,16 @@ func tfPins(b []byte) []tfPin { if in == "required_providers" && depth == 1 { if m := tfEntry.FindStringSubmatch(l); m != nil { cur = &tfPin{name: "hashicorp/" + m[1]} + } else if m := tfLegacy.FindStringSubmatch(l); m != nil { + res = append(res, tfPin{name: "hashicorp/" + m[1], constraint: m[2], line: i + 1}) } } - if m := tfAttr.FindStringSubmatch(l); m != nil && cur != nil { + for _, x := range tfAttr.FindAllStringSubmatchIndex(l, -1) { + at := depth + strings.Count(l[:x[0]], "{") - strings.Count(l[:x[0]], "}") + if cur == nil || cur.module && at != 1 || !cur.module && at != 2 { + continue + } + m := []string{l[x[0]:x[1]], l[x[2]:x[3]], l[x[4]:x[5]]} switch m[1] { case "source": cur.name = m[2] @@ -128,7 +136,7 @@ func (terraform) Deps(root string, m core.Manifest) ([]core.Dep, error) { d := core.Dep{Ecosystem: core.Terraform, Name: strings.ToLower(p.name), Req: p.constraint, Manifest: m, Line: p.line, Direct: true} d.Version = locked[d.Name] if d.Version == "" { - d.Version = strings.TrimSpace(strings.TrimLeft(p.constraint, "~>= 5.0" } + google = { + source = "hashicorp/google" + version = ">= 4.0, < 6.0" + } + null = "~> 3.0" + } +} + +module "vpc" { + source = "terraform-aws-modules/vpc/aws" + version = "5.0.0" + tags = { version = "not-a-constraint" } + min_version = "9.9.9" +} +` + +func TestTerraformInline(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"main.tf": tfInline, "only.tf": "terraform {\n required_providers {\n aws = { source = \"hashicorp/aws\", version = \"~> 5.0\" }\n }\n}\n"}) + ms := manifestsIn(t, terraform{}, root) + if len(ms) != 2 { + t.Fatalf("manifests = %+v", ms) + } + var got []string + for _, d := range depsIn(t, terraform{}, root, "main.tf") { + got = append(got, fmt.Sprintf("%d %s %s (%s)", d.Line, d.Name, d.Version, d.Req)) + } + want := []string{"3 hashicorp/aws 5.0 (~> 5.0)", "6 hashicorp/google 4.0 (>= 4.0, < 6.0)", "8 hashicorp/null 3.0 (~> 3.0)", "14 terraform-aws-modules/vpc/aws 5.0.0 (5.0.0)"} + if !slices.Equal(got, want) { + t.Errorf("deps = %q\nwant %q", got, want) + } + aws := depIn(t, terraform{}, root, "main.tf", "hashicorp/aws", true) + if _, err := (terraform{}).Bump(context.Background(), root, aws, "6.1.0", ""); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(filepath.Join(root, "main.tf")) + if !strings.Contains(string(b), `aws = { source = "hashicorp/aws", version = "~> 6.1" }`) { + t.Errorf("main.tf =\n%s", b) + } +} diff --git a/internal/eco/testdata/docker/bump/compose-digest.golden b/internal/eco/testdata/docker/bump/compose-digest.golden index 27c5d4a..89be56d 100644 --- a/internal/eco/testdata/docker/bump/compose-digest.golden +++ b/internal/eco/testdata/docker/bump/compose-digest.golden @@ -2,5 +2,5 @@ files: [compose.yaml] locked: false note: no lockfile --- compose.yaml -16: - image: busybox:1.36@sha256:a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90 -16: + image: busybox:1.37@sha256:3333333333333333333333333333333333333333333333333333333333333333 +18: - image: busybox:1.36@sha256:a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90 +18: + image: busybox:1.37@sha256:3333333333333333333333333333333333333333333333333333333333333333 diff --git a/internal/eco/testdata/docker/bump/compose-host.golden b/internal/eco/testdata/docker/bump/compose-host.golden index 25c63a6..2e0e85e 100644 --- a/internal/eco/testdata/docker/bump/compose-host.golden +++ b/internal/eco/testdata/docker/bump/compose-host.golden @@ -2,5 +2,5 @@ files: [compose.yaml] locked: false note: no lockfile --- compose.yaml -10: - image: ghcr.io/acme/tool:2.1.0 -10: + image: ghcr.io/acme/tool:2.2.0 +9: - image: ghcr.io/acme/tool:2.1.0 +9: + image: ghcr.io/acme/tool:2.2.0 diff --git a/internal/eco/testdata/docker/bump/compose-inline-default.golden b/internal/eco/testdata/docker/bump/compose-inline-default.golden index 02ce8db..6e7dae5 100644 --- a/internal/eco/testdata/docker/bump/compose-inline-default.golden +++ b/internal/eco/testdata/docker/bump/compose-inline-default.golden @@ -2,5 +2,5 @@ files: [compose.yaml] locked: false note: no lockfile --- compose.yaml -8: - image: ${PROXY_IMAGE:-nginx}:${PROXY_TAG:-1.25} -8: + image: ${PROXY_IMAGE:-nginx}:${PROXY_TAG:-1.27} +7: - image: ${PROXY_IMAGE:-nginx}:${PROXY_TAG:-1.25} +7: + image: ${PROXY_IMAGE:-nginx}:${PROXY_TAG:-1.27} diff --git a/internal/eco/testdata/docker/deps/compose.golden.json b/internal/eco/testdata/docker/deps/compose.golden.json index 9780ea4..2d5e36a 100644 --- a/internal/eco/testdata/docker/deps/compose.golden.json +++ b/internal/eco/testdata/docker/deps/compose.golden.json @@ -42,7 +42,7 @@ "Lock": "", "Tool": "docker" }, - "Line": 8, + "Line": 7, "Dev": false, "Direct": true, "Pin": "" @@ -58,7 +58,7 @@ "Lock": "", "Tool": "docker" }, - "Line": 10, + "Line": 9, "Dev": false, "Direct": true, "Pin": "" @@ -74,7 +74,7 @@ "Lock": "", "Tool": "docker" }, - "Line": 16, + "Line": 18, "Dev": false, "Direct": true, "Pin": "sha256:a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90" diff --git a/internal/eco/testdata/docker/project/compose.yaml b/internal/eco/testdata/docker/project/compose.yaml index de18cf5..29b63c2 100644 --- a/internal/eco/testdata/docker/project/compose.yaml +++ b/internal/eco/testdata/docker/project/compose.yaml @@ -3,13 +3,15 @@ services: image: postgres:11 cache: image: "redis:7.2-alpine" # keep small - build: . proxy: image: ${PROXY_IMAGE:-nginx}:${PROXY_TAG:-1.25} tool: image: ghcr.io/acme/tool:2.1.0 app: build: . + node-app: + build: . + image: node-app other: image: ${UNSET_IMAGE} pinned: diff --git a/internal/eco/testdata/npm/bump/caret-major.golden b/internal/eco/testdata/npm/bump/caret-major.golden index 11b4480..14871b5 100644 --- a/internal/eco/testdata/npm/bump/caret-major.golden +++ b/internal/eco/testdata/npm/bump/caret-major.golden @@ -1,6 +1,6 @@ files: [package.json] -locked: false -note: npm not found +locked: true +note: --- package.json 13: - "is-number": "^7.0.0", 13: + "is-number": "^8.0.0", diff --git a/internal/eco/testdata/npm/bump/caret-v1.golden b/internal/eco/testdata/npm/bump/caret-v1.golden index bea1f93..eca8ae7 100644 --- a/internal/eco/testdata/npm/bump/caret-v1.golden +++ b/internal/eco/testdata/npm/bump/caret-v1.golden @@ -1,6 +1,6 @@ files: [package.json] -locked: false -note: npm not found +locked: true +note: --- package.json 8: - "debug": "^2.6.9", 8: + "debug": "^4.4.3", diff --git a/internal/eco/testdata/npm/bump/exact.golden b/internal/eco/testdata/npm/bump/exact.golden index 6840ac8..a0af4b0 100644 --- a/internal/eco/testdata/npm/bump/exact.golden +++ b/internal/eco/testdata/npm/bump/exact.golden @@ -1,6 +1,6 @@ files: [package.json] -locked: false -note: npm not found +locked: true +note: --- package.json 17: - "left-pad": "1.3.0" 17: + "left-pad": "1.3.1" diff --git a/internal/eco/testdata/npm/bump/member.golden b/internal/eco/testdata/npm/bump/member.golden index da85a58..45971e7 100644 --- a/internal/eco/testdata/npm/bump/member.golden +++ b/internal/eco/testdata/npm/bump/member.golden @@ -1,6 +1,6 @@ files: [packages/a/package.json] -locked: false -note: npm not found +locked: true +note: --- packages/a/package.json 6: - "is-number": "^6.0.0" 6: + "is-number": "^7.0.0" diff --git a/internal/eco/testdata/npm/bump/swap-sorted.golden b/internal/eco/testdata/npm/bump/swap-sorted.golden index 63016e3..20ba741 100644 --- a/internal/eco/testdata/npm/bump/swap-sorted.golden +++ b/internal/eco/testdata/npm/bump/swap-sorted.golden @@ -1,6 +1,6 @@ files: [package.json] -locked: false -note: npm not found +locked: true +note: --- package.json 11: - "compare-alias": "npm:@isaacs/string-locale-compare@^1.0.0", 11: + "@sindresorhus/is": "^2.1.0", diff --git a/internal/eco/testdata/npm/bump/tilde.golden b/internal/eco/testdata/npm/bump/tilde.golden index a2db10e..263fe51 100644 --- a/internal/eco/testdata/npm/bump/tilde.golden +++ b/internal/eco/testdata/npm/bump/tilde.golden @@ -1,6 +1,6 @@ files: [package.json] -locked: false -note: npm not found +locked: true +note: --- package.json 10: - "send": "~0.17.1" 10: + "send": "~1.2.0" diff --git a/internal/eco/testdata/python/bump/pep621-extra.golden b/internal/eco/testdata/python/bump/pep621-extra.golden index 5061ef2..c220e82 100644 --- a/internal/eco/testdata/python/bump/pep621-extra.golden +++ b/internal/eco/testdata/python/bump/pep621-extra.golden @@ -1,6 +1,6 @@ files: [uv/pyproject.toml] -locked: false -note: uv not found +locked: true +note: --- uv/pyproject.toml 15: - "ruff==0.6.9", 15: + "ruff==0.7.0", diff --git a/internal/eco/testdata/python/bump/pep621-single-quoted.golden b/internal/eco/testdata/python/bump/pep621-single-quoted.golden index 28f3821..bd95b67 100644 --- a/internal/eco/testdata/python/bump/pep621-single-quoted.golden +++ b/internal/eco/testdata/python/bump/pep621-single-quoted.golden @@ -1,6 +1,6 @@ files: [uv/pyproject.toml] -locked: false -note: uv not found +locked: true +note: --- uv/pyproject.toml 8: - 'PyYAML>=6.0,<7 ; sys_platform != "win32"', 8: + 'PyYAML>=7.0,<8 ; sys_platform != "win32"', diff --git a/internal/eco/testdata/python/bump/pep621.golden b/internal/eco/testdata/python/bump/pep621.golden index 9ec882a..79abc55 100644 --- a/internal/eco/testdata/python/bump/pep621.golden +++ b/internal/eco/testdata/python/bump/pep621.golden @@ -1,6 +1,6 @@ files: [uv/pyproject.toml] -locked: false -note: uv not found +locked: true +note: --- uv/pyproject.toml 6: - "httpx[http2]>=0.27,<1", 6: + "httpx[http2]>=1.0,<2", diff --git a/internal/eco/testdata/python/bump/pip-compile.golden b/internal/eco/testdata/python/bump/pip-compile.golden index bc801e7..52a57fa 100644 --- a/internal/eco/testdata/python/bump/pip-compile.golden +++ b/internal/eco/testdata/python/bump/pip-compile.golden @@ -1,6 +1,6 @@ files: [reqs/dev-requirements.in] -locked: false -note: pip-compile not found +locked: true +note: --- reqs/dev-requirements.in 1: -pytest~=8.3 1: +pytest~=9.0 diff --git a/internal/eco/testdata/python/bump/poetry-caret.golden b/internal/eco/testdata/python/bump/poetry-caret.golden index 1cdedb7..94030ec 100644 --- a/internal/eco/testdata/python/bump/poetry-caret.golden +++ b/internal/eco/testdata/python/bump/poetry-caret.golden @@ -1,6 +1,6 @@ files: [poetry/pyproject.toml] -locked: false -note: poetry not found +locked: true +note: --- poetry/pyproject.toml 9: -requests = "^2.31" 9: +requests = "^3.0" diff --git a/internal/eco/testdata/python/bump/poetry-exact.golden b/internal/eco/testdata/python/bump/poetry-exact.golden index 395212f..fed5ae3 100644 --- a/internal/eco/testdata/python/bump/poetry-exact.golden +++ b/internal/eco/testdata/python/bump/poetry-exact.golden @@ -1,6 +1,6 @@ files: [poetry/pyproject.toml] -locked: false -note: poetry not found +locked: true +note: --- poetry/pyproject.toml 12: -sqlalchemy = "2.0.35" 12: +sqlalchemy = "2.0.36" diff --git a/internal/eco/testdata/python/bump/poetry-inline-table.golden b/internal/eco/testdata/python/bump/poetry-inline-table.golden index f373cd5..8cd689a 100644 --- a/internal/eco/testdata/python/bump/poetry-inline-table.golden +++ b/internal/eco/testdata/python/bump/poetry-inline-table.golden @@ -1,6 +1,6 @@ files: [poetry/pyproject.toml] -locked: false -note: poetry not found +locked: true +note: --- poetry/pyproject.toml 10: -"Flask" = { version = "~2.3", extras = ["async"] } 10: +"Flask" = { version = "~3.0.3", extras = ["async"] } diff --git a/internal/eco/testdata/python/projects/workspace/packages/a/pyproject.toml b/internal/eco/testdata/python/projects/workspace/packages/a/pyproject.toml new file mode 100644 index 0000000..660c1bd --- /dev/null +++ b/internal/eco/testdata/python/projects/workspace/packages/a/pyproject.toml @@ -0,0 +1,6 @@ +[project] +name = "a" +version = "0.1.0" +dependencies = [ + "requests==2.31.0", +] diff --git a/internal/eco/testdata/python/projects/workspace/packages/skip/pyproject.toml b/internal/eco/testdata/python/projects/workspace/packages/skip/pyproject.toml new file mode 100644 index 0000000..b38af03 --- /dev/null +++ b/internal/eco/testdata/python/projects/workspace/packages/skip/pyproject.toml @@ -0,0 +1,4 @@ +[project] +name = "skip" +version = "0.1.0" +dependencies = [] diff --git a/internal/eco/testdata/python/projects/workspace/pyproject.toml b/internal/eco/testdata/python/projects/workspace/pyproject.toml new file mode 100644 index 0000000..bcd68ff --- /dev/null +++ b/internal/eco/testdata/python/projects/workspace/pyproject.toml @@ -0,0 +1,3 @@ +[tool.uv.workspace] +members = ["packages/*"] +exclude = ["packages/skip"] diff --git a/internal/eco/testdata/python/projects/workspace/uv.lock b/internal/eco/testdata/python/projects/workspace/uv.lock new file mode 100644 index 0000000..3f8ab05 --- /dev/null +++ b/internal/eco/testdata/python/projects/workspace/uv.lock @@ -0,0 +1,29 @@ +version = 1 +requires-python = ">=3.12" + +[manifest] +members = ["a"] + +[[package]] +name = "a" +version = "0.1.0" +source = { editable = "packages/a" } +dependencies = [ + { name = "requests" }, +] + +[package.metadata] +requires-dist = [{ name = "requests", specifier = "==2.31.0" }] + +[[package]] +name = "certifi" +version = "2024.8.30" +source = { registry = "https://pypi.org/simple" } + +[[package]] +name = "requests" +version = "2.31.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, +] diff --git a/internal/eco/toolchain.go b/internal/eco/toolchain.go index 405182f..d556f89 100644 --- a/internal/eco/toolchain.go +++ b/internal/eco/toolchain.go @@ -302,6 +302,9 @@ func (toolchain) Bump(ctx context.Context, root string, d core.Dep, to, toName s if err != nil { return nil, fmt.Errorf("toolchain: %s in %s: %w", d.Name, d.Manifest.Path, err) } + if path.Base(d.Manifest.Path) == "go.mod" { + return goRaise(ctx, root, d, next, to) + } if err := rewriteLine(p, d.Line, d.Req, next); err != nil { return nil, fmt.Errorf("toolchain: %w", err) } @@ -330,6 +333,36 @@ func (toolchain) Bump(ctx context.Context, root string, d core.Dep, to, toName s return res, nil } +func goRaise(ctx context.Context, root string, d core.Dep, next, to string) (*core.Bump, error) { + m := d.Manifest + tidy := ver.Less(d.Version, "1.17") && !ver.Less(to, "1.17") + if tidy && !have("go") { + return nil, core.ToolMissing{Tool: "go"} + } + dir := path.Dir(m.Path) + snap := snapFiles(root, m.Path, path.Join(dir, "go.sum")) + if err := rewriteLine(filepath.Join(root, filepath.FromSlash(m.Path)), d.Line, d.Req, next); err != nil { + return nil, fmt.Errorf("toolchain: %w", err) + } + if !tidy { + return &core.Bump{Files: []string{m.Path}, Note: "no lockfile"}, nil + } + if err := runIn(ctx, root, dir, goEnv(), "go mod tidy"); err != nil { + return nil, fmt.Errorf("toolchain: %w", err) + } + if err := goKeep(root, m, snap); err != nil { + return nil, fmt.Errorf("toolchain: %w", err) + } + files := snap.changed(root) + if onDisk(root, path.Join(dir, "vendor/modules.txt")) { + if err := runIn(ctx, root, dir, goEnv(), "go mod vendor"); err != nil { + return nil, fmt.Errorf("toolchain: %w", err) + } + files = append(files, path.Join(dir, "vendor")) + } + return &core.Bump{Files: files, Locked: true}, nil +} + // lockEngines moves engines.node in package-lock.json's entry for the // project itself, which comes before any installed package's. func lockEngines(p, from, to string) error { diff --git a/internal/eco/toolchain_test.go b/internal/eco/toolchain_test.go index a874ca8..36a91d0 100644 --- a/internal/eco/toolchain_test.go +++ b/internal/eco/toolchain_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "slices" + "strings" "testing" "github.com/mohsensc/tend-cli/internal/core" @@ -183,3 +184,48 @@ func TestLowestAndRaise(t *testing.T) { } } } + +func TestToolchainGoPruning(t *testing.T) { + if !have("go") { + t.Skip("go not found") + } + t.Setenv("GOFLAGS", "") + t.Setenv("GOPROXY", "off") + t.Setenv("GOTOOLCHAIN", "local") + root := t.TempDir() + write(t, root, map[string]string{ + "go.mod": "module example.com/main\n\ngo 1.16\n\nrequire example.com/a v0.0.0\n\nreplace (\n\texample.com/a => ./a\n\texample.com/b => ./b\n)\n", + "main.go": "package main\n\nimport \"example.com/a\"\n\nfunc main() { a.A() }\n", + "a/go.mod": "module example.com/a\n\ngo 1.16\n\nrequire example.com/b v0.0.0\n\nreplace example.com/b => ../b\n", + "a/a.go": "package a\n\nimport \"example.com/b\"\n\nfunc A() { b.B() }\n", + "b/go.mod": "module example.com/b\n\ngo 1.16\n", + "b/b.go": "package b\n\nfunc B() {}\n", + "other/x.go": "package other\n", + }) + if out, err := run(context.Background(), root, nil, "go mod tidy && go build ./..."); err != nil { + t.Fatalf("%v\n%s", err, out) + } + var d core.Dep + for _, x := range depsIn(t, toolchain{}, root, "go.mod") { + if x.Min { + d = x + } + } + if d.Version != "1.16" { + t.Fatalf("dep = %+v", d) + } + b, err := toolchain{}.Bump(context.Background(), root, d, "1.26", "") + if err != nil { + t.Fatal(err) + } + if !b.Locked || !slices.Contains(b.Files, "go.mod") { + t.Errorf("bump = %+v", b) + } + got, _ := os.ReadFile(filepath.Join(root, "go.mod")) + if !strings.Contains(string(got), "go 1.26") || !strings.Contains(string(got), "example.com/b v0.0.0 // indirect") { + t.Errorf("go.mod =\n%s", got) + } + if out, err := run(context.Background(), root, nil, "go build ./... && go vet ./..."); err != nil { + t.Errorf("build after the bump: %v\n%s", err, out) + } +} diff --git a/internal/eco/unused.go b/internal/eco/unused.go index 9414ac1..bfeefa5 100644 --- a/internal/eco/unused.go +++ b/internal/eco/unused.go @@ -64,7 +64,7 @@ func Unused(inv *core.Inventory, keep func(core.Dep) bool) ([]core.Dep, []core.A // usage is what a repository says about the packages it uses besides its // imports: the text of every file that is neither documentation nor a -// lockfile, lowercased, with each line that declares a dependency blanked, +// lockfile, compiled requirements files included, lowercased, with each line that declares a dependency blanked, // so a declaration is never taken for a use. type usage struct { root string @@ -143,14 +143,18 @@ func (u *usage) load() { } u.text = map[string][]byte{} decl := map[string][]int{} + locks := map[string]bool{} for _, d := range u.deps { if d.Line > 0 { decl[d.Manifest.Path] = append(decl[d.Manifest.Path], d.Line) } + if d.Manifest.Lock != "" { + locks[d.Manifest.Lock] = true + } } for _, f := range u.files { md := markdown(f) - if prose(f) && !md || lockfile(f) || foreign(f) { + if prose(f) && !md || lockfile(f) || locks[f] || foreign(f) { continue } b := readText(filepath.Join(u.root, filepath.FromSlash(f))) diff --git a/internal/eco/unused_test.go b/internal/eco/unused_test.go index 6889412..59278ba 100644 --- a/internal/eco/unused_test.go +++ b/internal/eco/unused_test.go @@ -474,6 +474,10 @@ func TestUnusedPython(t *testing.T) { "notebooks/fit.ipynb": `{"cells": [{"cell_type": "markdown", "source": "pyyaml"}, {"cell_type": "code", "source": ["from sklearn import svm\\n"], "outputs": [{"data": {"image/png": "` + strings.Repeat("A", maxText) + `"}}]}], "nbformat": 4}`, }), gone: []string{"pyyaml"}}, + {name: "a frozen file with nothing installed keeps every pin", + files: with(map[string]string{"requirements.txt": "aiosmtpd==1.4.4\natpublic==4.0\nattrs==23.1.0\nrequests==2.31.0\ncertifi==2023.11.17\n", "app/mail.py": "import aiosmtpd\nimport requests\n"})}, + {name: "the test runner tend runs", + files: with(map[string]string{"requirements.txt": "pytest==8.3.3\n", "tests/test_a.py": "def test_a():\n assert True\n"})}, {name: "plugins and stubs", files: with(map[string]string{"requirements-dev.txt": "pytest-cov\ntypes-requests\npandas-stubs\n"}), kept: map[string]string{"pytest-cov": "plugin pytest loads", "types-requests": "plugin mypy loads", "pandas-stubs": "stubs mypy reads"}}, diff --git a/internal/fetch/fetch.go b/internal/fetch/fetch.go index 6f94613..1668627 100644 --- a/internal/fetch/fetch.go +++ b/internal/fetch/fetch.go @@ -5,12 +5,14 @@ import ( "bytes" "context" "crypto/sha256" + "crypto/tls" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log" + "net" "net/http" "net/url" "os" @@ -18,6 +20,7 @@ import ( "slices" "strconv" "strings" + "syscall" "time" "github.com/mohsensc/tend-cli/internal/core" @@ -81,8 +84,13 @@ func TTL(d time.Duration) core.FetchOpt { return func(o *core.FetchOpts) { o.TTL func NoCache() core.FetchOpt { return func(o *core.FetchOpts) { o.NoCache = true } } -// Idempotent marks a Post as safe to send again after a 429 or 5xx. Without -// it a Post is sent once: the server may have acted on it already. +// Timeout gives one request d, its body read too, in place of the client's +// own limit: a release archive takes longer than an API answer. +func Timeout(d time.Duration) core.FetchOpt { return func(o *core.FetchOpts) { o.Timeout = d } } + +// Idempotent marks a Post as safe to send again after a 429, a 5xx or a +// dropped connection. Without it a Post is sent once: the server may have +// acted on it already. func Idempotent() core.FetchOpt { return func(o *core.FetchOpts) { o.Idempotent = true } } func (c *Client) Get(ctx context.Context, u string, opts ...core.FetchOpt) (*core.Response, error) { @@ -163,6 +171,7 @@ func (c *Client) do(ctx context.Context, method, u string, body []byte, h http.H if method != http.MethodGet && !o.Idempotent { limit = 0 } + timeouts := 0 for attempt := 0; ; attempt++ { req, err := http.NewRequestWithContext(ctx, method, u, bytes.NewReader(body)) if err != nil { @@ -170,14 +179,19 @@ func (c *Client) do(ctx context.Context, method, u string, body []byte, h http.H } req.Header = h.Clone() start := c.now() - res, err := c.client().Do(req) + res, b, err := c.send(req, o.Timeout) if err != nil { - return nil, fmt.Errorf("%s %s: %w", method, u, err) - } - b, err := io.ReadAll(io.LimitReader(res.Body, maxBody+1)) - res.Body.Close() - if err != nil { - return nil, fmt.Errorf("%s %s: %w", method, u, err) + if timedOut(err) { + timeouts++ + } + if ctx.Err() != nil || !transient(err) || attempt == limit || timeouts > 1 { + return nil, attemptsError(method, u, err, attempt) + } + c.logf("%s %s: %v", method, u, err) + if err := c.sleep(ctx, backoff(attempt, "", c.now())); err != nil { + return nil, fmt.Errorf("%s %s: %w", method, u, err) + } + continue } if len(b) > maxBody { return nil, fmt.Errorf("%s %s: body larger than %d bytes", method, u, maxBody) @@ -196,6 +210,53 @@ func (c *Client) do(ctx context.Context, method, u string, body []byte, h http.H } } +func (c *Client) send(req *http.Request, timeout time.Duration) (*http.Response, []byte, error) { + hc := c.client() + if timeout > 0 { + cp := *hc + cp.Timeout = timeout + hc = &cp + } + res, err := hc.Do(req) + if err != nil { + return nil, nil, err + } + defer res.Body.Close() + b, err := io.ReadAll(io.LimitReader(res.Body, maxBody+1)) + if err != nil { + return nil, nil, err + } + return res, b, nil +} + +func attemptsError(method, u string, err error, attempt int) error { + if attempt == 0 { + return fmt.Errorf("%s %s: %w", method, u, err) + } + return fmt.Errorf("%s %s: %w after %d attempts", method, u, err, attempt+1) +} + +func transient(err error) bool { + var cert *tls.CertificateVerificationError + var record tls.RecordHeaderError + if errors.As(err, &cert) || errors.As(err, &record) { + return false + } + var dns *net.DNSError + if errors.As(err, &dns) { + return dns.IsTimeout || dns.IsTemporary + } + var op *net.OpError + return timedOut(err) || errors.As(err, &op) || + errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || + errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EPIPE) +} + +func timedOut(err error) bool { + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} + // backoff doubles from one second unless the server says how long to wait. func backoff(attempt int, retryAfter string, now time.Time) time.Duration { if retryAfter != "" { diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go index 3bd63c0..09ee0b7 100644 --- a/internal/fetch/fetch_test.go +++ b/internal/fetch/fetch_test.go @@ -394,3 +394,158 @@ func TestPrune(t *testing.T) { t.Errorf("a missing cache: %v", err) } } + +func hangUp(t *testing.T, w http.ResponseWriter, partial bool) { + t.Helper() + conn, buf, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + if partial { + _, _ = buf.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\nhalf") + _ = buf.Flush() + } + conn.Close() +} + +func TestRetryDroppedConnection(t *testing.T) { + tests := []struct { + name string + post bool + opts []core.FetchOpt + partial bool + drops int + sent int + err bool + }{ + {"get", false, nil, false, 1, 2, false}, + {"get body cut short", false, nil, true, 1, 2, false}, + {"get gives up", false, nil, false, 9, 4, true}, + {"post sent once", true, nil, false, 1, 1, true}, + {"idempotent post", true, []core.FetchOpt{Idempotent()}, false, 1, 2, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var n atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if int(n.Add(1)) <= tt.drops { + hangUp(t, w, tt.partial) + return + } + fmt.Fprint(w, "body") + })) + defer srv.Close() + + cl := newClock().client("") + ws := waits(cl) + var res *core.Response + var err error + if tt.post { + res, err = cl.Post(context.Background(), srv.URL, []byte(`{}`), tt.opts...) + } else { + res, err = cl.Get(context.Background(), srv.URL, tt.opts...) + } + if tt.err != (err != nil) { + t.Fatalf("res = %+v, err = %v", res, err) + } + if !tt.err && string(res.Body) != "body" { + t.Errorf("body = %q", res.Body) + } + if got := int(n.Load()); got != tt.sent || len(*ws) != tt.sent-1 { + t.Errorf("sent %d times with waits %v, want %d", got, *ws, tt.sent) + } + if tt.err && tt.sent > 1 && !strings.Contains(err.Error(), fmt.Sprintf("after %d attempts", tt.sent)) { + t.Errorf("err = %v, want the attempts counted", err) + } + }) + } +} + +func TestNoRetryAfterCancel(t *testing.T) { + var n atomic.Int32 + ctx, cancel := context.WithCancel(context.Background()) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n.Add(1) + cancel() + hangUp(t, w, false) + })) + defer srv.Close() + + cl := newClock().client("") + waits(cl) + if _, err := cl.Get(ctx, srv.URL); err == nil { + t.Fatal("no error") + } + if got := n.Load(); got != 1 { + t.Errorf("sent %d times, want once after the context ended", got) + } +} + +func TestRetryTimeoutOnce(t *testing.T) { + var n atomic.Int32 + block := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n.Add(1) + select { + case <-block: + case <-r.Context().Done(): + } + })) + defer srv.Close() + defer close(block) + + cl := newClock().client("") + cl.HTTP.Timeout = 50 * time.Millisecond + ws := waits(cl) + _, err := cl.Get(context.Background(), srv.URL) + if err == nil || !strings.Contains(err.Error(), "after 2 attempts") { + t.Fatalf("err = %v, want a timeout after 2 attempts", err) + } + if len(*ws) != 1 { + t.Errorf("waits = %v, want one retry", *ws) + } +} + +func TestNoRetryPermanent(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "body") + })) + defer srv.Close() + + cl := newClock().client("") + ws := waits(cl) + for _, u := range []string{srv.URL, "ftp://example.invalid/x"} { + if _, err := cl.Get(context.Background(), u); err == nil || strings.Contains(err.Error(), "attempts") { + t.Errorf("%s: err = %v, want one failed attempt", u, err) + } + } + if len(*ws) != 0 { + t.Errorf("waits = %v, want none", *ws) + } +} + +// A body that takes longer than the client's own limit fails, unless the +// request is given longer, and the client's limit stays as it was. +func TestTimeout(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.(http.Flusher).Flush() + time.Sleep(300 * time.Millisecond) + fmt.Fprint(w, "slow") + })) + defer srv.Close() + c := New("", "test") + c.HTTP = &http.Client{Timeout: 100 * time.Millisecond} + c.wait = func(context.Context, time.Duration) error { return nil } + if _, err := c.Get(context.Background(), srv.URL, NoCache()); err == nil { + t.Fatal("a slow body within the client's limit") + } + res, err := c.Get(context.Background(), srv.URL, NoCache(), Timeout(5*time.Second)) + if err != nil || string(res.Body) != "slow" { + t.Fatalf("with a longer timeout: %v", err) + } + if c.HTTP.Timeout != 100*time.Millisecond { + t.Errorf("the client's timeout became %s", c.HTTP.Timeout) + } +} diff --git a/internal/gitx/gitx.go b/internal/gitx/gitx.go index 82daff4..6f09cc3 100644 --- a/internal/gitx/gitx.go +++ b/internal/gitx/gitx.go @@ -4,6 +4,7 @@ package gitx import ( "bytes" "context" + "errors" "fmt" "os" "os/exec" @@ -12,16 +13,21 @@ import ( "slices" "strings" "sync" + "time" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/proc" ) // Cmd is one git call: where it runs, what it adds to the environment and -// what it reads on stdin. +// what it reads on stdin. Git runs in a process group of its own, so an +// interrupt at the terminal reaches tend alone, unless Terminal says it may +// need the terminal, as ssh does to ask for a passphrase. type Cmd struct { - Dir string - Env []string - Stdin string + Dir string + Env []string + Stdin string + Terminal bool } // Run runs git in dir and returns its output with the surrounding space trimmed. @@ -35,6 +41,11 @@ func Raw(ctx context.Context, dir string, args ...string) (string, error) { return Cmd{Dir: dir}.Run(ctx, args...) } +// waitDelay is how long Run waits, once git is killed, for what git started +// to let go of its output: a stuck git-remote-https or ssh would hold it, +// and the run with it, long after a cancel. +const waitDelay = 2 * time.Second + // Run runs git and returns what it wrote to stdout. Hooks and the file // system monitor never run, whatever a config says, and git sees tend's // environment without its tokens. A worktree that was pinned uses the git dir @@ -44,12 +55,21 @@ func (c Cmd) Run(ctx context.Context, args ...string) (string, error) { if runtime.GOOS == "windows" { null = "NUL" } - full := append([]string{"-c", "core.hooksPath=" + null, "-c", "core.fsmonitor=false"}, args...) + full := []string{"-c", "core.hooksPath=" + null, "-c", "core.fsmonitor=false"} + pin, isPinned := pinned(c.Dir) + if isPinned && pin.exclude != "" { + full = append(full, "-c", "core.excludesFile="+pin.exclude) + } + full = append(full, args...) cmd := exec.CommandContext(ctx, bin(), full...) + cmd.WaitDelay = waitDelay + if !c.Terminal { + proc.Group(cmd) + } cmd.Dir = c.Dir cmd.Env = append(local(core.Scrub(os.Environ(), nil)), "GIT_TERMINAL_PROMPT=0") - if wt, gitDir, ok := pinned(c.Dir); ok { - cmd.Env = append(cmd.Env, "GIT_DIR="+gitDir, "GIT_WORK_TREE="+wt) + if isPinned { + cmd.Env = append(cmd.Env, "GIT_DIR="+pin.gitDir, "GIT_WORK_TREE="+pin.dir) } cmd.Env = append(cmd.Env, c.Env...) if c.Stdin != "" { @@ -62,11 +82,29 @@ func (c Cmd) Run(ctx context.Context, args ...string) (string, error) { if msg == "" { msg = err.Error() } - return out.String(), fmt.Errorf("git %s: %s", args[0], msg) + return out.String(), &Error{msg: fmt.Sprintf("git %s: %s", args[0], msg), err: err} } return out.String(), nil } +// Error is a git call that failed: what git said, and how it exited. +type Error struct { + msg string + err error +} + +func (e *Error) Error() string { return e.msg } +func (e *Error) Unwrap() error { return e.err } + +// Code is the status git exited with, or -1 when err is not git exiting. +func Code(err error) int { + var x *exec.ExitError + if errors.As(err, &x) { + return x.ExitCode() + } + return -1 +} + // located are the variables that tell git which repository, index or object // store to use. Set by a hook or a wrapper that runs tend, they would point // every call at the caller's repository instead of the directory asked for. @@ -95,27 +133,33 @@ var bin = sync.OnceValue(func() string { return "git" }) -var pins sync.Map // worktree dir -> its git dir +var pins sync.Map // worktree dir -> pin + +type pin struct{ dir, gitDir, exclude string } // Pin ties the worktree at dir to gitDir. A command that later rewrites // dir/.git to point at a git dir of its own, with hooks or filters in its -// config, then changes nothing tend runs there. -func Pin(dir, gitDir string) { pins.Store(filepath.Clean(dir), gitDir) } +// config, then changes nothing tend runs there. Exclude, when set, is the +// excludes file git reads there in place of the user's own. +func Pin(dir, gitDir, exclude string) { + dir = filepath.Clean(dir) + pins.Store(dir, pin{dir, gitDir, exclude}) +} // Unpin forgets the worktree at dir. func Unpin(dir string) { pins.Delete(filepath.Clean(dir)) } // pinned finds the pinned worktree dir is in, if any. -func pinned(dir string) (wt, gitDir string, ok bool) { +func pinned(dir string) (pin, bool) { if dir == "" { - return "", "", false + return pin{}, false } for d := filepath.Clean(dir); ; d = filepath.Dir(d) { if v, ok := pins.Load(d); ok { - return d, v.(string), true + return v.(pin), true } if filepath.Dir(d) == d { - return "", "", false + return pin{}, false } } } diff --git a/internal/gitx/gitx_test.go b/internal/gitx/gitx_test.go index 52e0b24..2f2cdfc 100644 --- a/internal/gitx/gitx_test.go +++ b/internal/gitx/gitx_test.go @@ -9,6 +9,7 @@ import ( "slices" "strings" "testing" + "time" ) func repo(t *testing.T) string { @@ -127,3 +128,21 @@ func TestFilesListsAConflictOnce(t *testing.T) { t.Errorf("Files = %q, want %q", got, want) } } + +// A cancel stops the call even while something git started still holds its +// output, as a push stuck on the network would. +func TestRunReturnsOnCancel(t *testing.T) { + dir := repo(t) + if _, err := Run(context.Background(), dir, "config", "alias.hang", "!sleep 5"); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + start := time.Now() + if _, err := Run(ctx, dir, "hang"); err == nil { + t.Fatal("a cancelled call succeeded") + } + if took := time.Since(start); took > waitDelay+2*time.Second { + t.Errorf("Run returned after %s", took) + } +} diff --git a/internal/model/anthropic.go b/internal/model/anthropic.go index 3569938..d63ba08 100644 --- a/internal/model/anthropic.go +++ b/internal/model/anthropic.go @@ -100,12 +100,15 @@ func (a *anthropic) Chat(ctx context.Context, system string, turns []Turn, tools switch t.Role { case "assistant": var blocks []anthropicBlock - if t.Text != "" { + if strings.TrimSpace(t.Text) != "" { blocks = append(blocks, anthropicBlock{Type: "text", Text: t.Text}) } for _, c := range t.Calls { blocks = append(blocks, anthropicBlock{Type: "tool_use", ID: c.ID, Name: c.Name, Input: object(c.Args)}) } + if len(blocks) == 0 { + blocks = []anthropicBlock{{Type: "text", Text: noReply}} + } msgs = append(msgs, anthropicTurn{Role: "assistant", Content: blocks}) case "tool": b := anthropicBlock{Type: "tool_result", ToolUseID: t.CallID, Content: t.Text} @@ -115,7 +118,11 @@ func (a *anthropic) Chat(ctx context.Context, system string, turns []Turn, tools } msgs = append(msgs, anthropicTurn{Role: "user", Content: []anthropicBlock{b}}) default: - msgs = append(msgs, anthropicTurn{Role: "user", Content: []anthropicBlock{{Type: "text", Text: t.Text}}}) + text := t.Text + if strings.TrimSpace(text) == "" { + text = noText + } + msgs = append(msgs, anthropicTurn{Role: "user", Content: []anthropicBlock{{Type: "text", Text: text}}}) } } var defs []anthropicTool diff --git a/internal/model/command.go b/internal/model/command.go index 79ad8e8..9eb3861 100644 --- a/internal/model/command.go +++ b/internal/model/command.go @@ -12,6 +12,7 @@ import ( "github.com/mohsensc/tend-cli/internal/config" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/proc" ) type command struct { @@ -49,6 +50,7 @@ func (c *command) Complete(ctx context.Context, system, prompt string) (string, var out, errOut bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errOut cmd.WaitDelay = time.Second + proc.Group(cmd) if err := cmd.Run(); err != nil { if ctx.Err() != nil { return "", fmt.Errorf("model: %s: %w", c.name, ctx.Err()) diff --git a/internal/model/model.go b/internal/model/model.go index 27c89e6..c7369df 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -6,8 +6,10 @@ import ( "cmp" "context" "encoding/json" + "errors" "fmt" "io" + "net" "net/http" "regexp" "strconv" @@ -19,11 +21,14 @@ import ( ) const ( - timeout = 120 * time.Second + timeout = 10 * time.Minute retries = 3 maxWait = time.Minute maxBody = 32 << 20 replyMax = 8000 // tokens in one reply + + noReply = "(no reply)" + noText = "(empty)" ) // presets are providers that speak the chat completions API at their own @@ -101,8 +106,8 @@ func apiKey(cfg config.Model, usual string, getenv func(string) string) (string, return "", fmt.Errorf("model: no API key: set %s or TEND_MODEL_KEY", usual) } -// poster is one JSON POST with retries on 429, 5xx, and a tool call the -// model sent malformed. +// poster is one JSON POST with retries on 429, 5xx, a dropped connection, and +// a tool call the model sent malformed. type poster struct { url string header map[string]string @@ -129,13 +134,19 @@ func (p *poster) post(ctx context.Context, body any) ([]byte, error) { req.Header.Set(k, v) } resp, err := p.http.Do(req) - if err != nil { - return nil, err + var data []byte + if err == nil { + data, err = io.ReadAll(io.LimitReader(resp.Body, maxBody)) + resp.Body.Close() } - data, err := io.ReadAll(io.LimitReader(resp.Body, maxBody)) - resp.Body.Close() if err != nil { - return nil, err + if ctx.Err() != nil || timedOut(err) || attempt == retries { + return nil, err + } + if err := p.sleep(ctx, delay(attempt, "", time.Now())); err != nil { + return nil, err + } + continue } if resp.StatusCode/100 == 2 { return data, nil @@ -151,6 +162,11 @@ func (p *poster) post(ctx context.Context, body any) ([]byte, error) { } } +func timedOut(err error) bool { + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} + func (p *poster) sleep(ctx context.Context, d time.Duration) error { if p.wait != nil { return p.wait(ctx, d) diff --git a/internal/model/model_test.go b/internal/model/model_test.go index 4073464..766be63 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -10,8 +10,10 @@ import ( "os" "path/filepath" "reflect" + "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -692,3 +694,138 @@ func TestSteps(t *testing.T) { t.Errorf("chats = %+v", s.Chats) } } + +func TestChatEmptyTurns(t *testing.T) { + for _, empty := range []string{"", "\n", " "} { + turns := []Turn{{Role: "user", Text: "hi"}, {Role: "assistant", Text: empty}, {Role: "user", Text: empty}} + t.Run("anthropic "+strconv.Quote(empty), func(t *testing.T) { + srv := serve(t, reply{200, "anthropic_tools.json", ""}) + m, _ := newAnthropic(config.Model{Provider: "anthropic", Model: "model-id"}, "k") + m.url = srv.URL + if _, err := m.Chat(context.Background(), "", turns, tools); err != nil { + t.Fatal(err) + } + msgs := srv.bodies[0]["messages"].([]any) + if len(msgs) != 3 { + t.Fatalf("%d messages, want 3 so the roles still alternate", len(msgs)) + } + for _, m := range msgs { + content, ok := m.(map[string]any)["content"].([]any) + if !ok || len(content) == 0 { + t.Fatalf("message %v has no content blocks", m) + } + for _, b := range content { + b := b.(map[string]any) + if text, ok := b["text"].(string); b["type"] == "text" && (!ok || strings.TrimSpace(text) == "") { + t.Errorf("message %v has a blank text block", m) + } + } + } + }) + t.Run("openai "+strconv.Quote(empty), func(t *testing.T) { + srv := serve(t, reply{200, "openai_tools.json", ""}) + m, _ := newOpenAI(config.Model{Provider: "openai", Model: "model-id"}, "k") + m.url = srv.URL + if _, err := m.Chat(context.Background(), "", turns, tools); err != nil { + t.Fatal(err) + } + msgs := srv.bodies[0]["messages"].([]any) + if len(msgs) != 3 { + t.Fatalf("%d messages, want 3", len(msgs)) + } + for _, m := range msgs { + m := m.(map[string]any) + if _, ok := m["content"].(string); !ok && m["tool_calls"] == nil { + t.Errorf("message %v has no content and no tool calls", m) + } + } + }) + } +} + +func TestOpenAIChatCallsOnly(t *testing.T) { + srv := serve(t, reply{200, "openai_tools.json", ""}) + m, _ := newOpenAI(config.Model{Provider: "openai", Model: "model-id"}, "k") + m.url = srv.URL + turns := []Turn{{Role: "user", Text: "hi"}, {Role: "assistant", Calls: []ToolCall{{ID: "c1", Name: "read"}}}, {Role: "tool", CallID: "c1", Text: "x"}} + if _, err := m.Chat(context.Background(), "", turns, tools); err != nil { + t.Fatal(err) + } + sent, _ := json.Marshal(srv.bodies[0]["messages"].([]any)[1]) + if want := `{"content":null,"role":"assistant","tool_calls":[{"function":{"arguments":"{}","name":"read"},"id":"c1","type":"function"}]}`; string(sent) != want { + t.Errorf("assistant = %s, want %s", sent, want) + } +} + +func hangUpFirst(t *testing.T, ok string) (*httptest.Server, *atomic.Int32) { + t.Helper() + calls := new(atomic.Int32) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if calls.Add(1) == 1 { + conn, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + conn.Close() + return + } + _, _ = w.Write(read(t, ok)) + })) + t.Cleanup(srv.Close) + return srv, calls +} + +func TestRetryDroppedConnection(t *testing.T) { + srv, calls := hangUpFirst(t, "anthropic_ok.json") + m, _ := newAnthropic(config.Model{Provider: "anthropic", Model: "m"}, "k") + var waits []time.Duration + m.url, m.wait = srv.URL, func(_ context.Context, d time.Duration) error { waits = append(waits, d); return nil } + if _, err := m.Complete(context.Background(), "", "p"); err != nil { + t.Fatal(err) + } + if calls.Load() != 2 || !reflect.DeepEqual(waits, []time.Duration{time.Second}) { + t.Errorf("calls = %d, waits = %v; want a second try after 1s", calls.Load(), waits) + } +} + +func TestNoRetryAfterCancel(t *testing.T) { + srv, calls := hangUpFirst(t, "anthropic_ok.json") + m, _ := newAnthropic(config.Model{Provider: "anthropic", Model: "m"}, "k") + ctx, cancel := context.WithCancel(context.Background()) + m.url, m.wait = srv.URL, func(context.Context, time.Duration) error { return nil } + m.http = &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { + cancel() + return http.DefaultTransport.RoundTrip(r) + })} + if _, err := m.Complete(ctx, "", "p"); err == nil { + t.Fatal("no error after cancel") + } + if calls.Load() > 1 { + t.Errorf("calls = %d, want no retry once the context is done", calls.Load()) + } +} + +func TestNoRetryOnTimeout(t *testing.T) { + block := make(chan struct{}) + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + <-block + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(block) }) + m, _ := newAnthropic(config.Model{Provider: "anthropic", Model: "m"}, "k") + m.url, m.wait = srv.URL, func(context.Context, time.Duration) error { return nil } + m.http.Timeout = 50 * time.Millisecond + if _, err := m.Complete(context.Background(), "", "p"); err == nil { + t.Fatal("no error after timeout") + } + if calls.Load() > 1 { + t.Errorf("calls = %d, want one: a timed out reply is not sent again", calls.Load()) + } +} + +type roundTrip func(*http.Request) (*http.Response, error) + +func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } diff --git a/internal/model/openai.go b/internal/model/openai.go index 7d8c7ab..bfa7b12 100644 --- a/internal/model/openai.go +++ b/internal/model/openai.go @@ -115,8 +115,12 @@ func (o *openai) Chat(ctx context.Context, system string, turns []Turn, tools [] } for _, t := range turns { m := openaiTurn{Role: t.Role, Content: text(t.Text), ToolCallID: t.CallID} - if t.Role == "assistant" && t.Text == "" { + switch { + case t.Role != "assistant" || t.Text != "": + case len(t.Calls) > 0: m.Content = nil + default: + m.Content = text(noReply) } for _, c := range t.Calls { var call openaiCall diff --git a/internal/patch/agent.go b/internal/patch/agent.go index 8b83a92..339cfa2 100644 --- a/internal/patch/agent.go +++ b/internal/patch/agent.go @@ -72,6 +72,8 @@ type session struct { results []string // pass or fail of each run, in order log *os.File bench string // the one test file a characterization may write, "" for a migration + + generatedPaths []string } // work hands the remaining sites to a model that calls tools. It ends when the @@ -148,12 +150,12 @@ func (o Options) turns() int { // brief is the first message: the change, what was already done, where the // code uses it, and the failure that brought tend here, if any. func (s *session) brief() (string, error) { - _, user, err := prompt(s.t, s.in, s.o, "", "") + _, user, err := prompt(s.t, s.in, s.o, "", "", false) if err != nil { return "", err } - // edit also takes test files, which the diff prompt does not offer. - user = strings.Replace(user, "Files you may edit:", "Files you may edit, along with test files:", 1) + // edit also takes the tests of those files, which the diff prompt does not offer. + user = strings.Replace(user, "Files you may edit:", "Files you may edit, along with the tests that reach them, but never the tests tend wrote:", 1) return user, nil } @@ -294,14 +296,22 @@ func (s *session) grep(pattern, glob string) string { return strings.Join(lines, "\n") } -// edit changes a site file, a manifest the change explains, or a test. +// edit changes a site file, a manifest the change explains, or a test of +// one of them. A migration never edits the tests tend wrote itself: a model +// that weakens what proves its work would prove nothing. func (s *session) edit(p, old, now string) string { rel, err := s.inside(p) if err != nil { return "error: " + err.Error() } - if !slices.Contains(s.in.allowed, rel) && (s.bench != "" || !scan.IsTest(rel)) { - return "error: " + rel + " is not one of the files this change explains; edit the files listed at the start, or tests" + switch { + case s.bench == "" && s.generated(rel): + return "error: " + rel + " holds tests tend wrote to prove changes, and a migration never edits them; change the code so they pass" + case slices.Contains(s.in.allowed, rel): + case s.bench != "" || !scan.IsTest(rel): + return "error: " + rel + " is not one of the files this change explains; edit the files listed at the start, or their tests" + case !s.covers(rel): + return "error: " + rel + " tests none of the files this change explains; edit only the files listed at the start and the tests that reach them" } b := s.t.read(rel) if b == nil { @@ -325,6 +335,53 @@ func (s *session) edit(p, old, now string) string { return "edited " + rel } +// generated reports whether rel is a test tend wrote: the characterization +// tests of a Go package, the smoke and characterization tests of a suite +// next to a manifest the change moves, or a test the worktree has that the +// base does not, which only a baseline tend put there can be. +func (s *session) generated(rel string) bool { + if path.Base(rel) == "tend_characterization_test.go" || slices.Contains(s.suites(), rel) { + return true + } + if !scan.IsTest(rel) { + return false + } + _, err := gitx.Raw(s.ctx, s.t.wt, "cat-file", "-e", head+":"+rel) + return err != nil +} + +// suites are the paths of the tests tend generates next to each manifest +// the change moves. +func (s *session) suites() []string { + if s.generatedPaths != nil { + return s.generatedPaths + } + s.generatedPaths = []string{} + if s.in.ch == nil { + return s.generatedPaths + } + for _, d := range s.in.ch.Deps { + b, ok := s.o.Ecos[d.Ecosystem].(core.Baseliner) + if !ok || d.Manifest.Path == "" { + continue + } + if su := b.Suite(s.t.wt, d.Manifest); su != nil { + for _, f := range []string{su.Smoke, su.Tests} { + if f != "" && !slices.Contains(s.generatedPaths, f) { + s.generatedPaths = append(s.generatedPaths, f) + } + } + } + } + return s.generatedPaths +} + +// covers reports whether a test reaches one of the files the change +// explains. +func (s *session) covers(test string) bool { + return s.o.Index != nil && slices.ContainsFunc(s.in.allowed, func(f string) bool { return core.Reaches(s.o.Index, test, f) }) +} + // write creates the test file a characterization writes, or replaces it. func (s *session) write(p, content string) string { rel, err := s.inside(p) diff --git a/internal/patch/agent_test.go b/internal/patch/agent_test.go index d3f53ef..75292b9 100644 --- a/internal/patch/agent_test.go +++ b/internal/patch/agent_test.go @@ -223,3 +223,61 @@ func TestAgentGrepGlob(t *testing.T) { } } } + +// suiteEco is fakeEco with a generated test suite next to each manifest. +type suiteEco struct{ fakeEco } + +func (suiteEco) Suite(root string, m core.Manifest) *core.Suite { + dir := filepath.ToSlash(filepath.Dir(m.Path)) + return &core.Suite{Smoke: filepath.ToSlash(filepath.Join(dir, "test/tend/smoke.js")), Tests: filepath.ToSlash(filepath.Join(dir, "test/tend/characterization.js"))} +} + +// A migration edits the files its change explains and the tests that reach +// them, never a test that reaches none of them and never the tests tend +// wrote, committed or still only in the worktree. +func TestAgentEditsTests(t *testing.T) { + f := newFixture(t) + for name, body := range map[string]string{ + "test/billing.test.js": "assert.equal(total(), 42)\n", + "test/unrelated.test.js": "assert.equal(other(), 1)\n", + "test/tend/smoke.js": "assert.ok(load())\n", + "pkg/tend_characterization_test.go": "if got != 42 { t.Fatal(got) }\n", + } { + if err := place(f.dir, name, body); err != nil { + t.Fatal(err) + } + } + run(t, f.dir, "add", "-A") + run(t, f.dir, "-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-qm", "tests") + if err := place(f.dir, "test/tend/characterization.js", "assert.equal(total(), 42)\n"); err != nil { + t.Fatal(err) + } + if err := place(f.dir, "test/new.test.js", "assert.equal(total(), 42)\n"); err != nil { + t.Fatal(err) + } + o := f.opts(nil) + o.Ecos[core.Npm] = &suiteEco{fakeEco: *f.eco} + o.Index = &fakeIndex{reach: map[string][]string{"test/billing.test.js": {"src/billing.js"}, "test/new.test.js": {"src/billing.js"}}} + s := &session{t: &tree{wt: f.dir}, in: job{ch: f.ch, allowed: []string{"package.json", "src/billing.js"}}, o: o, ctx: context.Background(), counts: map[string]int{}} + for file, want := range map[string]string{ + "src/billing.js": "edited", + "test/billing.test.js": "edited", + "test/unrelated.test.js": "tests none of the files this change explains", + "test/tend/smoke.js": "tests tend wrote", + "test/tend/characterization.js": "tests tend wrote", + "test/new.test.js": "tests tend wrote", + "pkg/tend_characterization_test.go": "tests tend wrote", + "README.md": "is not one of the files this change explains", + } { + body := "x" + if file != "README.md" { + body = readFile(t, f.dir, file) + } + if got := s.edit(file, strings.Split(body, "\n")[0], "z"); !strings.Contains(got, want) { + t.Errorf("edit %s = %q, want it to contain %q", file, got, want) + } + } + if !slices.Equal(s.edited, []string{"src/billing.js", "test/billing.test.js"}) { + t.Errorf("edited %q", s.edited) + } +} diff --git a/internal/patch/apply.go b/internal/patch/apply.go index 65987f7..1a1ecb8 100644 --- a/internal/patch/apply.go +++ b/internal/patch/apply.go @@ -86,7 +86,11 @@ func Apply(ctx context.Context, wt string, ch *core.Change, o Options) (*core.Pa if err != nil { return decide(ctx, wt, fmt.Sprintf("Pinning did not work out (%v); add the snippet under the option by hand.", err)) } - p := &core.Patch{Applied: []string{fmt.Sprintf("pinned %s at %s, ignoring %s and later (%s)", ch.Deps[0].Name, opt.To, ch.To, file)}} + line := fmt.Sprintf("pinned %s at %s, ignoring %s and later (%s)", ch.Deps[0].Name, opt.To, ch.To, file) + if ch.To == "" { + line = fmt.Sprintf("pinned %s at %s, ignoring every release, and tend stops proposing anything for it (%s)", ch.Deps[0].Name, opt.To, file) + } + p := &core.Patch{Applied: []string{line}} return finish(ctx, wt, p) } @@ -145,7 +149,11 @@ func Apply(ctx context.Context, wt string, ch *core.Change, o Options) (*core.Pa return finish(ctx, wt, p) } if ch.Kind == core.Security || len(bumped) > 0 && o.Proven && !o.Strict { - p.Applied = append(p.Applied, fmt.Sprintf("%s left as written, with no model to move them", sites(len(rest)))) + them := "them" + if core.Lines(rest) == 1 { + them = "it" + } + p.Applied = append(p.Applied, fmt.Sprintf("%s left as written, with no model to move %s", sites(core.Lines(rest)), them)) return finish(ctx, wt, p) } why := "" @@ -155,7 +163,7 @@ func Apply(ctx context.Context, wt string, ch *core.Change, o Options) (*core.Pa case !o.Proven: why = ", and there is no build or test command to prove a plain bump" } - return decide(ctx, wt, fmt.Sprintf("No model is configured to move the %s%s.", sites(len(rest)), why)) + return decide(ctx, wt, fmt.Sprintf("No model is configured to move the %s%s.", sites(core.Lines(rest)), why)) } func sites(n int) string { diff --git a/internal/patch/apply_test.go b/internal/patch/apply_test.go index 8570971..dcac997 100644 --- a/internal/patch/apply_test.go +++ b/internal/patch/apply_test.go @@ -452,7 +452,7 @@ func TestPrompt(t *testing.T) { allowed: []string{"package.json", "src/billing.js"}, } o := Options{Ecos: map[string]core.Ecosystem{core.Npm: &fakeEco{name: core.Npm, imports: []string{"@fixture/pay"}}}} - sys, user, err := prompt(&tree{wt: dir}, in, o, "", "") + sys, user, err := prompt(&tree{wt: dir}, in, o, "", "", false) if err != nil { t.Fatal(err) } @@ -496,3 +496,54 @@ func TestApplyReusesIndex(t *testing.T) { }) } } + +func TestApplyStay(t *testing.T) { + for _, tt := range []struct { + to string + want string + }{ + {"2.0.0", "pinned @fixture/pay at 1.4.0, ignoring 2.0.0 and later (tend.yml)"}, + {"", "pinned @fixture/pay at 1.4.0, ignoring every release, and tend stops proposing anything for it (tend.yml)"}, + } { + f := newFixture(t) + f.ch.Kind, f.ch.To = core.Deprecation, tt.to + f.ch.Options = []core.Option{{Title: "Pin to 1.4.0 and ignore", To: "1.4.0", Stay: true}} + o := f.opts(nil) + o.Option = 1 + p, err := Apply(context.Background(), f.dir, f.ch, o) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(p.Applied, []string{tt.want}) { + t.Errorf("to %q: applied %q, want %q", tt.to, p.Applied, tt.want) + } + } +} + +// A model without tools whose diff applies but fails the project's tests +// gets their output back, from the tree as it was before that diff. +func TestApplyModelFeedback(t *testing.T) { + f := newFixture(t) + half := f.edit(t, " return pay?.charges?.retrieve(res.id);", " return pay?.charges?.retrieve(res.id); // half") + m := &model.Script{Replies: []string{"```diff\n" + half + "```", "```diff\n" + f.edit(t, unmigrated, migrated) + "```"}} + pr := &prover{dir: f.dir, pass: []bool{false}} + o := f.opts(m) + o.Commands, o.Prove = core.Commands{Test: []string{"npm test"}}, pr.prove + p, err := Apply(context.Background(), f.dir, f.ch, o) + if err != nil { + t.Fatal(err) + } + if p.Decision || !p.Model || len(m.Calls) != 2 || len(pr.saw) != 1 { + t.Fatalf("decision=%v model=%v calls=%d proofs=%d note=%q", p.Decision, p.Model, len(m.Calls), len(pr.saw), p.Note) + } + if !strings.Contains(pr.saw[0], "// half") { + t.Errorf("the proof did not see the first diff:\n%s", pr.saw[0]) + } + retry := m.Calls[1].Prompt + if !strings.Contains(retry, "Your previous diff applied, but the project's commands failed:\nnpm test exited 1\nTypeError") || strings.Contains(retry, "could not be applied") { + t.Errorf("second prompt:\n%s", retry) + } + if strings.Contains(p.Diff, "// half") || !strings.Contains(p.Diff, "paymentIntents?.retrieve") { + t.Errorf("diff:\n%s", p.Diff) + } +} diff --git a/internal/patch/bump.go b/internal/patch/bump.go index 864ce60..e118596 100644 --- a/internal/patch/bump.go +++ b/internal/patch/bump.go @@ -13,8 +13,9 @@ import ( ) // bump moves every dep to `to` (or swaps it for toName) with its ecosystem's native -// tooling and returns the files that changed. A missing tool is not fatal: the -// manifest still moves and the proof shows what the lockfile could not. +// tooling and returns the files that changed. A missing tool is fatal when it +// leaves nothing changed; otherwise the manifest still moves and the proof +// shows what the lockfile could not. func bump(ctx context.Context, wt string, deps []core.Dep, to, toName string, o Options, p *core.Patch) ([]string, error) { var res []string done := map[int]bool{} @@ -43,7 +44,7 @@ func bump(ctx context.Context, wt string, deps []core.Dep, to, toName string, o files := uniq(b.Files) res = append(res, files...) names := core.Names(&core.Change{Deps: group}) - o.logf("bumped %s in %s", strings.Join(names, ", "), strings.Join(files, ", ")) + o.logf("bumped %s%s", strings.Join(names, ", "), in(files)) p.Applied = append(p.Applied, fmt.Sprintf("bumped %s %s -> %s together (%s)", strings.Join(names, ", "), from(d), to, strings.Join(files, ", "))) if note := "lockfile not regenerated, " + b.Note; !b.Locked && b.Note != "" && !slices.Contains(p.Applied, note) { p.Applied = append(p.Applied, note) @@ -64,12 +65,9 @@ func bump(ctx context.Context, wt string, deps []core.Dep, to, toName string, o switch { case errors.Is(err, core.ErrNotSupported): return nil, err - case err != nil && !errors.As(err, &tm): + case err != nil && (!errors.As(err, &tm) || b == nil || len(b.Files) == 0): return nil, fmt.Errorf("patch: %s: %w", d.Name, err) } - if b == nil { - b = &core.Bump{} - } if err != nil && b.Note == "" { b.Note = err.Error() } @@ -79,19 +77,22 @@ func bump(ctx context.Context, wt string, deps []core.Dep, to, toName string, o } } files := uniq(b.Files) + if len(files) == 0 && !b.Locked { + continue + } res = append(res, files...) - o.logf("bumped %s in %s", d.Name, strings.Join(files, ", ")) + o.logf("bumped %s%s", d.Display(), in(files)) - line := fmt.Sprintf("bumped %s %s -> %s", d.Name, from(d), to) + line := fmt.Sprintf("bumped %s %s -> %s", d.Display(), from(d), to) switch { case toName != "": - line = fmt.Sprintf("swapped %s for %s", d.Name, toName) + line = fmt.Sprintf("swapped %s for %s", d.Display(), strings.TrimPrefix(toName, "library/")) case b.Landed != "": if p.Landed == nil { p.Landed = map[string]string{} } p.Landed[d.Ecosystem+"/"+d.Name] = b.Landed - line = fmt.Sprintf("bumped %s %s -> %s, the newest release from %s its ranges allow", d.Name, from(d), b.Landed, to) + line = fmt.Sprintf("bumped %s %s -> %s, the newest release from %s its ranges allow", d.Display(), from(d), b.Landed, to) } if len(files) > 0 { line += " (" + strings.Join(files, ", ") + ")" @@ -137,6 +138,14 @@ func together(deps []core.Dep, to, toName string, o Options) [][]int { return res } +// in names the files a bump changed, for a log line. +func in(files []string) string { + if len(files) == 0 { + return "" + } + return " in " + strings.Join(files, ", ") +} + func from(d core.Dep) string { if d.Version != "" { return d.Version diff --git a/internal/patch/bump_test.go b/internal/patch/bump_test.go index 0559f87..707bf25 100644 --- a/internal/patch/bump_test.go +++ b/internal/patch/bump_test.go @@ -212,3 +212,22 @@ func TestBumpLanded(t *testing.T) { }) } } + +type bareEco struct{ fakeEco } + +func (e *bareEco) Bump(context.Context, string, core.Dep, string, string) (*core.Bump, error) { + return nil, core.ToolMissing{Tool: "yarn"} +} + +func TestBumpMissingToolChangingNothing(t *testing.T) { + dir := repo(t, map[string]string{"package.json": manifest}) + o := Options{Ecos: map[string]core.Ecosystem{core.Npm: &bareEco{fakeEco{name: core.Npm}}}} + p := &core.Patch{} + _, err := bump(context.Background(), dir, []core.Dep{npmDep("joi", "17.0.0")}, "17.13.0", "", o, p) + if err == nil || err.Error() != "patch: joi: yarn not found in PATH" { + t.Errorf("err = %v", err) + } + if len(p.Applied) != 0 { + t.Errorf("applied = %q", p.Applied) + } +} diff --git a/internal/patch/helpers_test.go b/internal/patch/helpers_test.go index f4a52aa..8410a54 100644 --- a/internal/patch/helpers_test.go +++ b/internal/patch/helpers_test.go @@ -101,8 +101,11 @@ type fakeIndex struct { imports []core.Import fields []core.Site files []string + reach map[string][]string // the files each test reaches } +func (x *fakeIndex) Reaches(test, p string) bool { return slices.Contains(x.reach[test], p) } + func (x *fakeIndex) Uses([]string) []core.Site { return nil } func (x *fakeIndex) Endpoints([]string) []core.URLUse { return nil } func (x *fakeIndex) URLs() []core.URLUse { return nil } diff --git a/internal/patch/migrate.go b/internal/patch/migrate.go index 26f3f08..212f0f3 100644 --- a/internal/patch/migrate.go +++ b/internal/patch/migrate.go @@ -17,16 +17,27 @@ const defaultAttempts = 2 var errNoDiff = errors.New("the reply holds no unified diff") // migrate asks the model for a diff over the remaining sites and applies it. A reply -// that cannot be used is sent back with the reason while attempts remain. +// that cannot be used is sent back with the reason while attempts remain. With +// o.Prove set, a diff that applies runs the project's commands too, and one that +// fails them is taken back and sent back with their output; the last attempt's +// diff stays for the caller's proof to judge. func migrate(ctx context.Context, t *tree, in job, o Options, p *core.Patch) error { n := o.Attempts if n < 1 { n = defaultAttempts } + snap := "" + if o.Prove != nil && n > 1 { + var err error + if snap, err = stage(ctx, t.wt); err != nil { + return err + } + } var fails []string var why, prev string + ran := false for i := 0; i < n; i++ { - sys, user, err := prompt(t, in, o, why, prev) + sys, user, err := prompt(t, in, o, why, prev, ran) if err != nil { return err } @@ -53,9 +64,24 @@ func migrate(ctx context.Context, t *tree, in job, o Options, p *core.Patch) err if err != nil { o.logf("model attempt %d: %v", i+1, err) fails = append(fails, fmt.Sprintf("attempt %d: %v", i+1, err)) - why, prev = err.Error(), diff + why, prev, ran = err.Error(), diff, false continue } + if snap != "" && i < n-1 { + failed, err := check(ctx, t.wt, o) + if err != nil { + return err + } + if failed != "" { + o.logf("model attempt %d: the diff applies, but %s", i+1, strings.SplitN(failed, "\n", 2)[0]) + fails = append(fails, fmt.Sprintf("attempt %d: %s", i+1, strings.SplitN(failed, "\n", 2)[0])) + if err := restore(ctx, t.wt, snap); err != nil { + return err + } + why, prev, ran = failed, diff, true + continue + } + } p.Model = true p.Edited = touched(diff) p.Applied = append(p.Applied, "the model edited "+strings.Join(p.Edited, ", ")) @@ -64,6 +90,49 @@ func migrate(ctx context.Context, t *tree, in job, o Options, p *core.Patch) err return errors.New(strings.Join(fails, "; ")) } +// check stages what a diff changed and runs the project's commands on it. +// It returns the failing command and the end of its output, "" when they +// pass. +func check(ctx context.Context, wt string, o Options) (string, error) { + if _, err := stage(ctx, wt); err != nil { + return "", err + } + r, err := o.Prove(ctx, o.Commands) + if err != nil { + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", nil + } + if r.Pass { + return "", nil + } + for _, st := range r.Steps { + if st.Skipped == "" && st.Exit != 0 { + return fmt.Sprintf("%s exited %d\n%s", st.Cmd, st.Exit, tail(st.Tail, feedbackMax)), nil + } + } + return "the project's commands failed", nil +} + +// stage stages everything in wt and returns its tree. +func stage(ctx context.Context, wt string) (string, error) { + if _, err := gitx.Raw(ctx, wt, "add", "-A"); err != nil { + return "", err + } + tree, err := gitx.Run(ctx, wt, "write-tree") + return tree, err +} + +// restore puts wt back to tree, staged, with nothing else left in it. +func restore(ctx context.Context, wt, tree string) error { + if _, err := gitx.Raw(ctx, wt, "read-tree", "--reset", "-u", tree); err != nil { + return err + } + _, err := gitx.Raw(ctx, wt, "clean", "-fdq") + return err +} + // extract pulls the diff out of a reply: the first ```diff or bare ``` block, else the // text from the first diff header on. none is true for a NOCHANGE reply. func extract(reply string) (diff string, none bool, err error) { diff --git a/internal/patch/prompt.go b/internal/patch/prompt.go index 9839fdb..8ef01c5 100644 --- a/internal/patch/prompt.go +++ b/internal/patch/prompt.go @@ -43,6 +43,7 @@ type promptData struct { Files []promptFile Retry string Previous string + Ran bool } type promptFile struct { @@ -53,8 +54,9 @@ type promptFile struct { } // prompt renders the system text and the user prompt. retry and previous carry the -// last failed reply, empty on the first turn. -func prompt(t *tree, in job, o Options, retry, previous string) (string, string, error) { +// last failed reply, empty on the first turn; ran says the reply applied, and +// retry is what the project's commands made of it. +func prompt(t *tree, in job, o Options, retry, previous string, ran bool) (string, string, error) { d := promptData{ Change: summary(in.ch, in.to, in.toName), Bumped: len(in.ch.Deps) > 0, @@ -62,6 +64,7 @@ func prompt(t *tree, in job, o Options, retry, previous string) (string, string, Allowed: in.allowed, Retry: retry, Previous: core.Clip(previous, previousMax), + Ran: ran, } for i, ev := range in.ch.Evidence { if i == maxEvidence { diff --git a/internal/patch/prompt.tmpl b/internal/patch/prompt.tmpl index 772c410..7474853 100644 --- a/internal/patch/prompt.tmpl +++ b/internal/patch/prompt.tmpl @@ -70,7 +70,12 @@ Context: {{- end}} {{- if .Retry}} +{{- if .Ran}} +Your previous diff applied, but the project's commands failed: +{{.Retry}} +{{- else}} Your previous reply could not be applied: {{.Retry}} +{{- end}} {{- if .Previous}} It was: {{.Previous}} diff --git a/internal/patch/remove.go b/internal/patch/remove.go index cf9635c..05244ab 100644 --- a/internal/patch/remove.go +++ b/internal/patch/remove.go @@ -3,7 +3,6 @@ package patch import ( "cmp" "context" - "errors" "fmt" "slices" "strings" @@ -31,18 +30,17 @@ func Remove(ctx context.Context, wt string, deps []core.Dep, o Options, p *core. if !ok { return fmt.Errorf("patch: %s cannot remove dependencies", group[0].Ecosystem) } - b, err := r.Remove(ctx, wt, group) - var tm core.ToolMissing - if err != nil && !errors.As(err, &tm) { - return fmt.Errorf("patch: %s: %w", group[0].Manifest.Path, err) - } - if b == nil { - b = &core.Bump{Note: err.Error()} - } var names []string for _, d := range group { names = append(names, d.Name) } + b, err := r.Remove(ctx, wt, group) + if err != nil { + return fmt.Errorf("patch: %s: %w", group[0].Manifest.Path, err) + } + if b == nil || len(b.Files) == 0 { + return fmt.Errorf("patch: %s: removing %s changed nothing", group[0].Manifest.Path, strings.Join(names, ", ")) + } files := uniq(b.Files) o.logf("removed %s from %s", strings.Join(names, ", "), group[0].Manifest.Path) line := "removed " + strings.Join(names, ", ") diff --git a/internal/patch/remove_test.go b/internal/patch/remove_test.go index 544b711..4bac053 100644 --- a/internal/patch/remove_test.go +++ b/internal/patch/remove_test.go @@ -42,6 +42,17 @@ func (e *pruneEco) Remove(ctx context.Context, root string, deps []core.Dep) (*c return &core.Bump{Files: []string{deps[0].Manifest.Path, deps[0].Manifest.Lock}, Locked: true}, nil } +// idleEco removes nothing and says so with what it returns. +type idleEco struct { + fakeEco + b *core.Bump + err error +} + +func (e *idleEco) Remove(context.Context, string, []core.Dep) (*core.Bump, error) { + return e.b, e.err +} + func TestRemove(t *testing.T) { dir := repo(t, map[string]string{ "package.json": "{\n \"a\": \"1\",\n \"b\": \"1\"\n}\n", @@ -73,6 +84,18 @@ func TestRemove(t *testing.T) { t.Errorf("applied %q", p.Applied) } + for _, e := range []*idleEco{ + {err: core.ToolMissing{Tool: "go"}}, + {}, + {b: &core.Bump{Note: "nothing to do"}}, + } { + o.Ecos[core.Npm] = e + p := &core.Patch{} + if err := Remove(context.Background(), dir, []core.Dep{in("package.json", "a")}, o, p); err == nil || len(p.Applied) > 0 { + t.Errorf("a removal that changed nothing (%v, %v): err %v, applied %q", e.b, e.err, err, p.Applied) + } + } + o.Ecos[core.Npm] = &fakeEco{name: core.Npm} if err := Remove(context.Background(), dir, []core.Dep{in("package.json", "a")}, o, &core.Patch{}); err == nil { t.Error("an ecosystem that cannot remove removed") diff --git a/internal/plan/first.go b/internal/plan/first.go index 1345641..a40556b 100644 --- a/internal/plan/first.go +++ b/internal/plan/first.go @@ -41,14 +41,14 @@ func StageName(k int) string { } // Tier is the catch-up stage a queued change belongs to. The first rule that -// matches wins: a migration past Spread call sites, or a choice between +// matches wins: a migration past Spread call sites to move, or a choice between // replacements, waits for the last stage; an API change and a security fix // come first; what pins the project's runtime or build comes next, then the // releases that are only new; any other move off something deprecated is a // fix. func Tier(ch *core.Change) int { switch { - case len(core.Calls(ch)) > Spread: + case MovesCode(ch) && core.Lines(core.Calls(ch)) > Spread: return Migrations case ch.API == nil && ch.To == "" && ch.ToName == "": return Migrations @@ -62,6 +62,15 @@ func Tier(ch *core.Change) int { return Fixes } +// MovesCode reports whether a change has call sites to move: an API change, +// a breaking release, a move off something deprecated, a major, or an option +// that is not a plain bump. A patch or minor release moves none of the sites +// that use the package. +func MovesCode(ch *core.Change) bool { + return ch.API != nil || ch.Kind == core.Breaking || ch.Kind == core.Deprecation || ch.Level == "major" || + slices.ContainsFunc(ch.Options, func(o core.Option) bool { return !o.Safe }) +} + // tooling reports whether every dep a change moves is something the project // runs or builds on rather than code it calls: a runtime pin or minimum, a // base image, an Action, or a dev dependency nothing outside the tests calls, @@ -130,7 +139,7 @@ func stage(p *Plan, after int, gone []core.Dep) *core.Batch { switch { case t > b.Stage: b.Next = append(b.Next, core.Later{Change: ch, Stage: t}) - case slices.ContainsFunc(ch.Deps, func(d core.Dep) bool { return slices.ContainsFunc(held, same(d)) }): + case slices.ContainsFunc(ch.Deps, func(d core.Dep) bool { return slices.ContainsFunc(held, sameCopy(d)) }): b.Next = append(b.Next, core.Later{Change: ch, Why: "another change here moves the same package, so this one comes after it"}) default: held = append(held, ch.Deps...) @@ -177,6 +186,14 @@ func removed(ch *core.Change, gone []core.Dep) bool { }) } +// sameCopy matches what same does, except that two copies of a package only +// the lockfile names are apart when they sit at different versions. +func sameCopy(d core.Dep) func(core.Dep) bool { + return func(x core.Dep) bool { + return same(d)(x) && (x.Direct || d.Direct || x.Version == d.Version) + } +} + // same matches a dependency declared in the same manifest as d. func same(d core.Dep) func(core.Dep) bool { return func(x core.Dep) bool { diff --git a/internal/plan/first_test.go b/internal/plan/first_test.go index 942d883..9c4b8bf 100644 --- a/internal/plan/first_test.go +++ b/internal/plan/first_test.go @@ -65,7 +65,6 @@ func TestFirst(t *testing.T) { {ID: "npm/moment@", Kind: core.Deprecation, Deps: []core.Dep{moment}, Options: []core.Option{{Title: "Migrate to dayjs"}}}, {ID: "npm/request->undici@6.19.8", Kind: core.Deprecation, Deps: []core.Dep{request}, ToName: "undici", To: "6.19.8", Sites: many}, {ID: "npm/vitest@3.2.4", Kind: core.Breaking, Level: "major", Deps: []core.Dep{vitest}, To: "3.2.4", Sites: []core.Site{site("test/a.test.js", 1)}}, - // deprecated and unused: the first PR removes it rather than moves off it {ID: "npm/left-pad@1.3.0", Kind: core.Deprecation, Deps: []core.Dep{pad}, To: "1.3.0", Evidence: []core.Evidence{{Source: "registry"}}}, }} @@ -181,9 +180,11 @@ func TestTier(t *testing.T) { site := func(file string) core.Site { return core.Site{File: file, Line: 1} } lib := core.Dep{Ecosystem: core.Npm, Name: "lib", Version: "1.0.0", Direct: true} tool := core.Dep{Ecosystem: core.Npm, Name: "webpack", Version: "4.0.0", Direct: true, Dev: true} - var many []core.Site + runner := core.Dep{Ecosystem: core.Npm, Name: "vitest", Version: "1.6.0", Direct: true, Dev: true} + var many, tests []core.Site for i := range Spread + 1 { many = append(many, core.Site{File: "src/a.js", Line: i + 1}) + tests = append(tests, core.Site{File: fmt.Sprintf("test/%d.test.js", i), Line: 1}) } for _, tt := range []struct { name string @@ -191,7 +192,12 @@ func TestTier(t *testing.T) { want int }{ {"security", core.Change{Kind: core.Security, Deps: []core.Dep{lib}, To: "1.0.1"}, Fixes}, - {"security past Spread", core.Change{Kind: core.Security, Deps: []core.Dep{lib}, To: "2.0.0", Sites: many}, Migrations}, + {"security past Spread", core.Change{Kind: core.Security, Level: "major", Deps: []core.Dep{lib}, To: "2.0.0", Sites: many}, Migrations}, + {"security patch of a wide package", core.Change{Kind: core.Security, Level: "patch", Deps: []core.Dep{lib}, To: "1.0.1", Sites: many}, Fixes}, + {"minor of a wide package", core.Change{Kind: core.Update, Level: "minor", Deps: []core.Dep{lib}, To: "1.1.0", Sites: many}, Majors}, + {"test runner minor in many tests", core.Change{Kind: core.Update, Level: "minor", Deps: []core.Dep{runner}, To: "1.7.0", Sites: tests}, Runtimes}, + {"test runner major in many tests", core.Change{Kind: core.Breaking, Level: "major", Deps: []core.Dep{runner}, To: "3.0.0", Sites: tests}, Migrations}, + {"unsafe option past Spread", core.Change{Kind: core.Security, Level: "patch", Deps: []core.Dep{lib}, To: "1.0.1", Sites: many, Options: []core.Option{{Title: "Rewrite the calls"}}}, Migrations}, {"api", core.Change{Kind: core.Breaking, API: &core.APIChange{Provider: "x"}}, Fixes}, {"deprecated version", core.Change{Kind: core.Deprecation, Deps: []core.Dep{lib}, To: "2.0.0"}, Fixes}, {"no single replacement", core.Change{Kind: core.Deprecation, Deps: []core.Dep{lib}}, Migrations}, diff --git a/internal/plan/merge.go b/internal/plan/merge.go index 29fb3ef..434d4fe 100644 --- a/internal/plan/merge.go +++ b/internal/plan/merge.go @@ -38,8 +38,10 @@ func mergeKey(ch *core.Change) string { } // merge collapses changes that move the same packages to the same place. -// Security changes on the same packages first collapse onto the highest fixed -// version any advisory names, since only that one fixes them all. +// Security changes on the same copy of a package first collapse onto the +// highest fixed version any advisory names, since only that one fixes them +// all. Copies on different release lines keep their own fix: a lockfile with +// ansi-regex 4.1.0 and 5.0.0 moves to 4.1.1 and 5.0.1. func merge(chs []core.Change) []core.Change { chs = slices.Clone(chs) fix := map[string]string{} @@ -47,14 +49,14 @@ func merge(chs []core.Change) []core.Change { if ch.Kind != core.Security || ch.API != nil { continue } - k := depSet(&ch) + " ->" + ch.ToName + k := fixKey(&ch) if to, ok := fix[k]; !ok || ver.Less(to, ch.To) { fix[k] = ch.To } } for i := range chs { if chs[i].Kind == core.Security && chs[i].API == nil { - chs[i].To = fix[depSet(&chs[i])+" ->"+chs[i].ToName] + chs[i].To = fix[fixKey(&chs[i])] } } @@ -73,12 +75,28 @@ func merge(chs []core.Change) []core.Change { return res } +// fixKey is equal for security changes on copies of the same packages that +// sit on one release line. +func fixKey(ch *core.Change) string { + k := depSet(ch) + " ->" + ch.ToName + if v, ok := ver.Parse(Lowest(ch.Deps)); ok { + k += " " + v.Line() + } + return k +} + // combine folds b into a: the stronger kind and the higher severity win, // everything else is a union. func combine(a, b core.Change) core.Change { a.Kind = stronger(a, b) - if sevRank(b.Severity) < sevRank(a.Severity) { + first, then := a.Evidence, b.Evidence + older := len(a.Deps) > 0 && len(b.Deps) > 0 && ver.Less(Lowest(b.Deps), Lowest(a.Deps)) + switch { + case sevRank(b.Severity) < sevRank(a.Severity): a.Severity = b.Severity + first, then = b.Evidence, a.Evidence + case sevRank(b.Severity) == sevRank(a.Severity) && older: + first, then = b.Evidence, a.Evidence } if a.ID == "" { a.ID = b.ID @@ -93,7 +111,7 @@ func combine(a, b core.Change) core.Change { a.API = b.API } a.Deps = unionDeps(a.Deps, b.Deps) - a.Evidence = addEvidence(a.Evidence, b.Evidence...) + a.Evidence = addEvidence(first, then...) a.Options = slices.Clone(a.Options) for _, o := range b.Options { if !slices.ContainsFunc(a.Options, func(x core.Option) bool { return x.Title == o.Title }) { @@ -358,6 +376,12 @@ func sevRank(s string) int { // soon is how close a sunset has to be for a deprecation to rank as breaking. const soon = 30 * 24 * time.Hour +// Urgent says whether ch is a deprecation whose sunset is within soon or +// already past, which is as urgent as a break. +func Urgent(ch *core.Change, now time.Time) bool { + return ch.Kind == core.Deprecation && !ch.Sunset.IsZero() && ch.Sunset.Sub(now) <= soon +} + // Rank orders a queue: kind (the first PR, security, a removed API, a // deprecation, a major bump, an update), severity, nearest sunset, most // sites, oldest upstream change, then id so the order never depends on map @@ -391,7 +415,7 @@ func compare(a, b *core.Change, now time.Time) int { // moving off something deprecated, since nothing is broken until it lands. func effectiveRank(ch *core.Change, now time.Time) int { switch { - case ch.Kind == core.Deprecation && !ch.Sunset.IsZero() && ch.Sunset.Sub(now) <= soon: + case Urgent(ch, now): return 2 * kindRank(core.Breaking) case ch.Kind == core.Breaking && ch.API == nil: return 2*kindRank(core.Deprecation) + 1 diff --git a/internal/plan/plan.go b/internal/plan/plan.go index 56d39cb..ea22422 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -7,6 +7,7 @@ import ( "fmt" "maps" "os" + "path" "path/filepath" "slices" "strings" @@ -57,6 +58,36 @@ type Input struct { Base string // the base commit, for verdicts that hold only on it } +// fixtureDirs hold what a project's tests read, not manifests of its own. +var fixtureDirs = map[string]bool{"tests": true, "test": true, "__tests__": true, "fixtures": true, "__fixtures__": true, "spec": true} + +// fixture says whether m is a test fixture: under a test directory, with +// no lockfile, and named by no other manifest, as a workspace member or a +// path dependency is. +func fixture(root string, m core.Manifest, all []core.Manifest) bool { + dir := path.Dir(m.Path) + if m.Lock != "" || !slices.ContainsFunc(strings.Split(dir, "/"), func(p string) bool { return fixtureDirs[p] }) { + return false + } + for _, f := range append([]string{"go.work"}, manifestPaths(all)...) { + if f == m.Path { + continue + } + if b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(f))); err == nil && strings.Contains(string(b), dir) { + return false + } + } + return true +} + +func manifestPaths(ms []core.Manifest) []string { + var res []string + for _, m := range ms { + res = append(res, m.Path) + } + return res +} + // Inventory reads every manifest of the enabled ecosystems under root and scans // the code. A manifest that cannot be read is untracked, not a failure. func Inventory(root string, cfg *config.Config) (*core.Inventory, []Untracked, error) { @@ -67,13 +98,24 @@ func Inventory(root string, cfg *config.Config) (*core.Inventory, []Untracked, e } defer done() var notes []Untracked - for _, e := range eco.For(cfg) { + ecos := eco.For(cfg) + found := make([][]core.Manifest, len(ecos)) + var all []core.Manifest + for i, e := range ecos { ms, err := e.Detect(root) if err != nil { notes = append(notes, Untracked{What: e.Name() + " manifests", Why: err.Error()}) continue } - for _, m := range ms { + found[i] = ms + all = append(all, ms...) + } + for i, e := range ecos { + for _, m := range found[i] { + if fixture(root, m, all) { + notes = append(notes, Untracked{What: m.Path, Why: "a test fixture: it sits among the tests with no lockfile of its own, and no other manifest names it"}) + continue + } deps, err := e.Deps(root, m) if err != nil { notes = append(notes, Untracked{What: m.Path, Why: "cannot be read: " + err.Error()}) @@ -90,6 +132,16 @@ func Inventory(root string, cfg *config.Config) (*core.Inventory, []Untracked, e if err != nil { return nil, nil, err } + for _, f := range files { + if path.Base(f) != "setup.py" || slices.ContainsFunc(inv.Manifests, func(m core.Manifest) bool { + return path.Dir(m.Path) == path.Dir(f) && m.Ecosystem == core.Pip && (path.Base(m.Path) == "setup.cfg" || path.Base(m.Path) == "pyproject.toml") + }) { + continue + } + if b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(f))); err == nil && strings.Contains(string(b), "install_requires") { + notes = append(notes, Untracked{What: f + " install_requires", Why: "tend does not run setup.py to read them; move the pins to setup.cfg or pyproject.toml"}) + } + } idx, err := scan.Build(scan.Options{Root: root, Files: files}) if err != nil { return nil, nil, fmt.Errorf("scan: %w", err) @@ -208,7 +260,12 @@ func Build(ctx context.Context, in Input) (*Plan, error) { b.metas(ctx, b.direct()) found := b.sources(ctx) all := append(b.registryPass(ctx, found), found...) - all = b.fixes(merge(all)) + // A source cut short by a cancel is no source that is down: the plan + // stops rather than going on without it. + if err := ctx.Err(); err != nil { + return nil, err + } + all = b.tagged(after(b.fixes(merge(all)))) all = b.companions(b.group(all)) for i := range all { all[i].ID = core.ChangeID(&all[i]) @@ -245,6 +302,9 @@ func Build(ctx context.Context, in Input) (*Plan, error) { for i := range min(5, len(p.Queue)) { b.attachNotes(ctx, &p.Queue[i]) } + if err := ctx.Err(); err != nil { + return nil, err + } b.record(p) slices.Sort(b.notes) p.Notes = slices.Compact(b.notes) @@ -279,7 +339,9 @@ func (b *builder) sources(ctx context.Context) []core.Change { for _, s := range b.in.Sources { chs, err := s.Changes(ctx, b.in.Inv) if err != nil { - b.note("%s: unavailable, planned without it: %v", s.Name(), err) + if ctx.Err() == nil { + b.note("%s: unavailable, planned without it: %v", s.Name(), err) + } continue } res = append(res, chs...) @@ -331,6 +393,14 @@ func (b *builder) registryPass(ctx context.Context, found []core.Change) []core. res = append(res, *b.swap(ctx, d, m, ev)) continue } + if st, ok := b.ecos[d.Ecosystem].(core.Settler); ok { + settled, err := st.Settle(d, m) + if err != nil { + b.note("%s: %s: %v", d.Ecosystem, d.Name, err) + continue + } + d = settled + } if ch := b.registry(ctx, d, m); ch != nil { res = append(res, *ch) } @@ -348,7 +418,7 @@ func (b *builder) archived(ctx context.Context) map[string]core.Evidence { } } res, err := source.Archived(ctx, b.in.Fetch, repos) - if err != nil { + if err != nil && ctx.Err() == nil { b.note("archived: unavailable, planned without it: %v", err) } return res @@ -363,14 +433,69 @@ func (b *builder) fixes(chs []core.Change) []core.Change { continue } d := ch.Deps[0] - if rel, ok := fixFor(b.meta[pkg{d.Ecosystem, d.Name}], ch.To); ok { + if rel, ok := fixFor(d, b.meta[pkg{d.Ecosystem, d.Name}], ch.To); ok { ch.To = rel.Version } - ch.Level = ver.Step(Lowest(ch.Deps), ch.To) + ch.Level = ver.StepIn(d.Ecosystem, Lowest(ch.Deps), ch.To) } return merge(chs) } +// tagged moves an image change off a tag the registry does not have: an +// end-of-life move keeps the old tag's suffix, and mongo:4.2.1-bionic has no +// 9.0-bionic among the -bionic tags the registry lists, so it goes to the +// plain 9.0. +func (b *builder) tagged(chs []core.Change) []core.Change { + for i := range chs { + ch := &chs[i] + if len(ch.Deps) == 0 || ch.Deps[0].Ecosystem != core.Docker || ch.To == "" || ch.ToName != "" { + continue + } + m := b.meta[pkg{core.Docker, ch.Deps[0].Name}] + if m == nil || len(m.Releases) == 0 { + continue + } + if _, ok := release(m, ch.To); ok { + continue + } + if head, _, cut := strings.Cut(ch.To, "-"); cut { + ch.To = head + ch.ID = core.ChangeID(ch) + } + } + return chs +} + +// after measures a bump of a package from the release its security fix +// moves it to, the step left once that fix lands: pytest 6.2.4 to 9.1.1 +// after a fix to 9.0.3 is a minor upgrade, not a second major one. +func after(chs []core.Change) []core.Change { + fix := map[string]string{} + for _, ch := range chs { + if ch.Kind == core.Security && ch.API == nil && ch.To != "" { + k := depSet(&ch) + " ->" + ch.ToName + if to, ok := fix[k]; !ok || ver.Less(to, ch.To) { + fix[k] = ch.To + } + } + } + for i := range chs { + ch := &chs[i] + if ch.API != nil || ch.ToName != "" || ch.Kind != core.Breaking && ch.Kind != core.Update || len(ch.Deps) == 0 { + continue + } + to, ok := fix[depSet(ch)+" ->"] + if !ok || !ver.Less(to, ch.To) { + continue + } + ch.Level = ver.StepIn(ch.Deps[0].Ecosystem, to, ch.To) + if ch.Level != "major" { + ch.Kind = core.Update + } + } + return chs +} + // Lowest is the version the least advanced of deps is at, as Current reads it. func Lowest(deps []core.Dep) string { res := "" diff --git a/internal/plan/plan_test.go b/internal/plan/plan_test.go index 626758f..bd1e0d7 100644 --- a/internal/plan/plan_test.go +++ b/internal/plan/plan_test.go @@ -154,11 +154,11 @@ func TestFixFor(t *testing.T) { {"4.18.0", "4.18.1"}, } for _, tt := range tests { - if got, _ := fixFor(m, tt.to); got.Version != tt.want { + if got, _ := fixFor(core.Dep{}, m, tt.to); got.Version != tt.want { t.Errorf("fixFor(%s) = %s, want %s", tt.to, got.Version, tt.want) } } - if got, ok := fixFor(nil, "1.2.3"); ok || got.Version != "1.2.3" { + if got, ok := fixFor(core.Dep{}, nil, "1.2.3"); ok || got.Version != "1.2.3" { t.Errorf("fixFor without meta = %v, %v", got, ok) } } @@ -196,7 +196,7 @@ func TestMerge(t *testing.T) { for _, ev := range sec.Evidence { titles = append(titles, ev.Source+":"+strings.Fields(ev.Title)[0]) } - if want := []string{"releases:1.0.2", "osv:GHSA-aaaa-bbbb-cccc", "osv:CVE-2026-1234"}; !slices.Equal(titles, want) { + if want := []string{"osv:GHSA-aaaa-bbbb-cccc", "osv:CVE-2026-1234", "releases:1.0.2"}; !slices.Equal(titles, want) { t.Errorf("evidence = %v, want %v", titles, want) } if got[1].To != "1.1.0" || got[1].Kind != core.Update { @@ -1189,3 +1189,166 @@ func TestStale(t *testing.T) { } } } + +func TestCandidateKeepsQualifier(t *testing.T) { + guava := []core.Release{rel("32.1.2-android", 400), rel("32.1.2-jre", 400), rel("33.4.0-android", 30), rel("33.4.0-jre", 30)} + tests := []struct { + eco, from, want string + rels []core.Release + }{ + {"maven", "32.1.2-jre", "33.4.0-jre", guava}, + {"gradle", "32.1.2-jre", "33.4.0-jre", guava}, + {"maven", "32.1.2-android", "33.4.0-android", guava}, + {"maven", "20.0", "33.4.0-jre", guava}, + {"maven", "5.4.0.Final", "6.0.0.Final", []core.Release{rel("5.4.0.Final", 400), rel("6.0.0.Final", 30), rel("6.0.0.CR1", 60)}}, + {"maven", "5.2.0.RELEASE", "5.3.0", []core.Release{rel("5.2.0.RELEASE", 400), rel("5.2.9.RELEASE", 200), rel("5.3.0", 30)}}, + {"maven", "1.0", "2.0", []core.Release{rel("2.0-jre", 30), rel("2.0", 30)}}, + } + for _, tt := range tests { + d := core.Dep{Ecosystem: tt.eco, Name: "com.google.guava:guava", Version: tt.from} + got, ok := candidate(d, &core.Meta{Releases: tt.rels}, time.Now(), 72*time.Hour, -1) + if !ok || got.Version != tt.want { + t.Errorf("%s %s: candidate = %q, %v; want %s", tt.eco, tt.from, got.Version, ok, tt.want) + } + } + d := core.Dep{Ecosystem: "maven", Name: "com.google.guava:guava", Version: "31.0-jre"} + m := &core.Meta{Releases: []core.Release{rel("32.0.0-android", 300), rel("32.0.0-jre", 300), rel("32.0.1-jre", 200)}} + if got, _ := fixFor(d, m, "32.0.0-android"); got.Version != "32.0.0-jre" { + t.Errorf("fixFor = %s, want 32.0.0-jre", got.Version) + } + if got, _ := fixFor(d, nil, "32.0.0-android"); got.Version != "32.0.0-jre" { + t.Errorf("fixFor without meta = %s, want 32.0.0-jre", got.Version) + } +} + +// A commit sha that starts with digits is no version. +func TestCandidateNotACommit(t *testing.T) { + d := core.Dep{Ecosystem: "actions", Name: "actions/checkout", Version: "11bd71901bbe5b1630ceea73d27597364c9af683"} + if got, ok := candidate(d, names([]core.Release{rel("v12.0.0", 30)}), time.Now(), 0, -1); ok { + t.Errorf("candidate = %s", got.Version) + } +} + +func TestMergeSecurityPerLine(t *testing.T) { + old := npmDep("ansi-regex", "4.1.0", "package.json") + root := npmDep("ansi-regex", "5.0.0", "package.json") + old.Direct, root.Direct = false, false + ev := core.Evidence{Source: "osv", Title: "GHSA-93q8-gq69-wqmw", URL: "https://osv.dev/vulnerability/GHSA-93q8-gq69-wqmw"} + both := core.Evidence{Source: "osv", Title: "GHSA-xxxx", URL: "https://osv.dev/vulnerability/GHSA-xxxx"} + got := merge([]core.Change{ + {Kind: core.Security, Deps: []core.Dep{old}, To: "4.1.1", Evidence: []core.Evidence{ev}}, + {Kind: core.Security, Deps: []core.Dep{old}, To: "4.1.2", Evidence: []core.Evidence{both}}, + {Kind: core.Security, Deps: []core.Dep{root}, To: "5.0.1", Evidence: []core.Evidence{ev}}, + }) + var rows []string + for _, ch := range got { + rows = append(rows, Lowest(ch.Deps)+"->"+ch.To) + } + if want := []string{"4.1.0->4.1.2", "5.0.0->5.0.1"}; !slices.Equal(rows, want) { + t.Errorf("rows = %v, want %v", rows, want) + } +} + +// A lockless manifest among the tests is a fixture the tests read; one with +// a lockfile of its own, or that another manifest names, is a project. +func TestInventorySkipsTestFixtures(t *testing.T) { + root := t.TempDir() + files := map[string]string{ + "pyproject.toml": "[tool.poetry]\nname = \"tomlkit\"\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^6.0\"\n", + "poetry.lock": "[[package]]\nname = \"pytest\"\nversion = \"6.2.5\"\n", + "tests/examples/pyproject.toml": "[tool.poetry]\nname = \"poetry\"\n\n[tool.poetry.dependencies]\npython = \"^3.6\"\nblack = \"18.3-alpha.0\"\n\n[tool.poetry.dev-dependencies]\npytest = \"3.4\"\n", + "tests/e2e/package.json": `{"name": "e2e", "dependencies": {"left-pad": "1.3.0"}}`, + "tests/e2e/package-lock.json": `{"lockfileVersion": 3, "packages": {"": {"name": "e2e"}, "node_modules/left-pad": {"version": "1.3.0"}}}`, + } + for name, body := range files { + p := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + inv, notes, err := Inventory(root, config.Default()) + if err != nil { + t.Fatal(err) + } + var paths []string + for _, m := range inv.Manifests { + paths = append(paths, m.Path) + } + if slices.Contains(paths, "tests/examples/pyproject.toml") || !slices.Contains(paths, "tests/e2e/package.json") || !slices.Contains(paths, "pyproject.toml") { + t.Errorf("manifests = %v", paths) + } + if !slices.ContainsFunc(notes, func(u Untracked) bool { return u.What == "tests/examples/pyproject.toml" }) { + t.Errorf("notes = %+v", notes) + } +} + +// Two go.mod files past end of life merge into one change whose evidence +// speaks for the older, whichever order they come in. +func TestMergeEndOfLifeOldestLeads(t *testing.T) { + dep := func(path, v string) core.Dep { + return core.Dep{Ecosystem: core.Toolchain, Name: "go", Version: v, Min: true, Manifest: core.Manifest{Path: path}} + } + ev := func(v string) core.Evidence { + return core.Evidence{Source: "eol", Title: "go " + v + " reached end of life", URL: "https://endoflife.date/go"} + } + root := core.Change{ID: "toolchain/go@1.26", Kind: core.Deprecation, To: "1.26", Deps: []core.Dep{dep("go.mod", "1.13")}, Evidence: []core.Evidence{ev("1.13")}, Sunset: ago(2000)} + ci := core.Change{ID: "toolchain/go@1.26", Kind: core.Deprecation, To: "1.26", Deps: []core.Dep{dep("ci/go.mod", "1.15")}, Evidence: []core.Evidence{ev("1.15")}, Sunset: ago(1500)} + for _, order := range [][]core.Change{{root, ci}, {ci, root}} { + got := merge(order) + if len(got) != 1 || got[0].Evidence[0].Title != "go 1.13 reached end of life" || !got[0].Sunset.Equal(ago(2000)) { + t.Errorf("merged = %+v", got) + } + } +} + +func TestAfterSecurityFix(t *testing.T) { + d := core.Dep{Ecosystem: core.Pip, Name: "pytest", Version: "6.2.4", Direct: true, Manifest: core.Manifest{Path: "requirements.txt"}} + got := after([]core.Change{ + {Kind: core.Security, To: "9.0.3", Level: "major", Deps: []core.Dep{d}}, + {Kind: core.Breaking, To: "9.1.1", Level: "major", Deps: []core.Dep{d}}, + {Kind: core.Breaking, To: "10.0.0", Level: "major", Deps: []core.Dep{{Ecosystem: core.Pip, Name: "other", Version: "1.0"}}}, + }) + if got[1].Kind != core.Update || got[1].Level != "minor" { + t.Errorf("follow-up = %s %s", got[1].Kind, got[1].Level) + } + if got[2].Kind != core.Breaking { + t.Errorf("an unrelated bump moved: %+v", got[2]) + } +} + +func TestInventoryNotesSetupPy(t *testing.T) { + root := t.TempDir() + writeFile(t, root, "setup.py", "from setuptools import setup\nsetup(name='x', install_requires=['requests==2.20.0'])\n") + writeFile(t, root, "requirements.txt", "flask==2.0.0\n") + _, notes, err := Inventory(root, config.Default()) + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(notes, func(u Untracked) bool { return u.What == "setup.py install_requires" }) { + t.Errorf("notes = %+v", notes) + } +} + +func TestTaggedDropsAMissingSuffix(t *testing.T) { + rels := func(vs ...string) *core.Meta { + m := &core.Meta{} + for _, v := range vs { + m.Releases = append(m.Releases, core.Release{Version: v}) + } + return m + } + b := &builder{meta: map[pkg]*core.Meta{ + {core.Docker, "library/mongo"}: rels("4.2.1-bionic", "4.4.6-bionic"), + {core.Docker, "library/node"}: rels("22-alpine", "24-alpine"), + }} + got := b.tagged([]core.Change{ + {Kind: core.Deprecation, To: "9.0-bionic", Deps: []core.Dep{{Ecosystem: core.Docker, Name: "library/mongo", Version: "4.2.1-bionic"}}}, + {Kind: core.Deprecation, To: "24-alpine", Deps: []core.Dep{{Ecosystem: core.Docker, Name: "library/node", Version: "16-alpine"}}}, + }) + if got[0].To != "9.0" || got[1].To != "24-alpine" { + t.Errorf("targets = %s, %s", got[0].To, got[1].To) + } +} diff --git a/internal/plan/proof.go b/internal/plan/proof.go index 52d0f4c..989f344 100644 --- a/internal/plan/proof.go +++ b/internal/plan/proof.go @@ -2,29 +2,8 @@ package plan import "github.com/mohsensc/tend-cli/internal/core" -// Proven says whether the patched tree did its part: it passes, or the base -// already fails and the patch stops at the very step the base stops at. The -// PR for the second goes out as a draft. -func Proven(pr *core.Proof) bool { - if pr.Patched != nil && pr.Patched.Pass { - return true - } - if pr.Base == nil || pr.Base.Pass || pr.Patched == nil { - return false - } - fp, fb := pr.Patched.Last(), pr.Base.Last() - return fp != nil && fb != nil && fp.Cmd == fb.Cmd && reached(pr.Patched) == reached(pr.Base) -} - -// reached is how many steps of a run passed before the first that failed. -func reached(run *core.Run) int { - for i, st := range run.Steps { - if st.Skipped != "" || st.Exit != 0 { - return i - } - } - return len(run.Steps) -} +// Proven says whether the patched tree did its part; see core.Proof.Proven. +func Proven(pr *core.Proof) bool { return pr.Proven() } // Decides says whether a change that could not be proven still deserves a PR // that lays out the choice: a security hole, options, or code that must move diff --git a/internal/plan/registry.go b/internal/plan/registry.go index b72c69e..7f03d1c 100644 --- a/internal/plan/registry.go +++ b/internal/plan/registry.go @@ -35,7 +35,7 @@ func (b *builder) metas(ctx context.Context, pkgs []pkg) { switch err := errs[i]; { case errors.Is(err, core.ErrNotSupported): case err != nil: - b.note("%s: %s: %v", p.eco, p.name, err) + b.note("%s: %s: %s", p.eco, p.name, strings.TrimPrefix(err.Error(), p.eco+": "+p.name+": ")) case got[i] != nil: b.meta[p] = got[i] } @@ -92,10 +92,35 @@ func traits(d core.Dep) core.Traits { // not yanked or deprecated, not past the registry's latest, and, when one // exists, older than the cooldown. When every newer release is still cooling // down the newest of those comes back so the caller can record it as such. -// maxMajor caps the major version; -1 means no cap. +// maxMajor caps the major version; -1 means no cap. Where versions carry a +// qualifier, as guava's -jre and -android do, the release keeps d's; a d +// with none takes a release with none, else a -jre one, else any. func candidate(d core.Dep, m *core.Meta, now time.Time, cooldown time.Duration, maxMajor int) (core.Release, bool) { + if !traits(d).KeepSuffix { + return pick(d, m, now, cooldown, maxMajor, nil) + } + q := qualifier(Current(d)) + wants := []string{q} + if q == "" { + wants = append(wants, "-jre") + } + for _, want := range wants { + if r, ok := pick(d, m, now, cooldown, maxMajor, func(v string) bool { return qualifier(v) == want }); ok { + return r, true + } + } + if q != "" { + return core.Release{}, false + } + return pick(d, m, now, cooldown, maxMajor, func(string) bool { return true }) +} + +// pick is candidate over the releases match lets through, all of them when +// it is nil. Two releases of one version, which differ only in qualifier, +// go to the one that sorts last, so the choice does not hang on their order. +func pick(d core.Dep, m *core.Meta, now time.Time, cooldown time.Duration, maxMajor int, match func(string) bool) (core.Release, bool) { cur, ok := ver.Parse(Current(d)) - if !ok { + if !ok || commit(Current(d)) { return core.Release{}, false } n, suffix := shape(Current(d)) @@ -104,11 +129,18 @@ func candidate(d core.Dep, m *core.Meta, now time.Time, cooldown time.Duration, var best, young core.Release var bestV, youngV ver.V found, foundYoung := false, false + better := func(v, than ver.V, r, was core.Release) bool { + c := ver.Compare(v, than) + return c > 0 || c == 0 && match != nil && r.Version > was.Version + } for _, r := range m.Releases { v, ok := ver.Parse(r.Version) if !ok || ver.Compare(v, cur) <= 0 || r.Yanked || r.Deprecated != "" { continue } + if match != nil && !match(r.Version) { + continue + } pre := r.Pre || v.Pre != "" if pre && (cur.Pre == "" || v.Major() != cur.Major()) { continue @@ -125,12 +157,12 @@ func candidate(d core.Dep, m *core.Meta, now time.Time, cooldown time.Duration, } } if !r.Time.IsZero() && now.Sub(r.Time) < cooldown { - if !foundYoung || ver.Compare(v, youngV) > 0 { + if !foundYoung || better(v, youngV, r, young) { young, youngV, foundYoung = r, v, true } continue } - if !found || ver.Compare(v, bestV) > 0 { + if !found || better(v, bestV, r, best) { best, bestV, found = r, v, true } } @@ -140,10 +172,39 @@ func candidate(d core.Dep, m *core.Meta, now time.Time, cooldown time.Duration, return young, foundYoung } +// commit reports whether v is a full git commit sha, which can start with +// digits and read as a version: 11bd719... is no release 11. +func commit(v string) bool { + return len(v) == 40 && strings.Trim(v, "0123456789abcdef") == "" +} + +// qualifier is what follows a version's numbers, lowercased, with the +// .Final, .RELEASE and .GA that mean a plain release dropped: "-jre" for +// 33.0.0-jre, "" for 5.4.0.Final and 5.3.0 alike. +func qualifier(v string) string { + _, s := shape(v) + s = strings.ToLower(s) + for _, q := range []string{"final", "release", "ga"} { + for _, sep := range []string{".", "-"} { + s = strings.TrimSuffix(s, sep+q) + } + } + return s +} + // fixFor is the smallest release at or above to that can be installed: not -// yanked, deprecated or a pre-release. It is to itself when the registry knows -// nothing better. -func fixFor(m *core.Meta, to string) (core.Release, bool) { +// yanked, deprecated or a pre-release, and with d's qualifier where its +// ecosystem keeps one. It is to itself when the registry knows nothing +// better, with d's qualifier in place of its own. +func fixFor(d core.Dep, m *core.Meta, to string) (core.Release, bool) { + keep := traits(d).KeepSuffix + q := qualifier(Current(d)) + if keep && qualifier(to) != q { + if _, s := shape(to); q != "" { + _, raw := shape(Current(d)) + to = to[:len(to)-len(s)] + raw + } + } want, ok := ver.Parse(to) if !ok || m == nil { return core.Release{Version: to}, false @@ -153,6 +214,9 @@ func fixFor(m *core.Meta, to string) (core.Release, bool) { if !ok || ver.Compare(v, want) < 0 || r.Yanked || r.Pre || v.Pre != "" || r.Deprecated != "" { continue } + if keep && qualifier(r.Version) != q { + continue + } return r, true } return core.Release{Version: to}, false @@ -190,7 +254,7 @@ func (b *builder) registry(ctx context.Context, d core.Dep, m *core.Meta) *core. // When the version was deprecated is not on record, so Published stays // zero: the target's release date is not the deprecation's. if ok { - ch.To, ch.Level = rel.Version, ver.Step(Current(d), rel.Version) + ch.To, ch.Level = rel.Version, ver.StepIn(d.Ecosystem, Current(d), rel.Version) } return ch } @@ -199,7 +263,7 @@ func (b *builder) registry(ctx context.Context, d core.Dep, m *core.Meta) *core. } ch := &core.Change{ Kind: core.Update, - Level: ver.Step(Current(d), rel.Version), + Level: ver.StepIn(d.Ecosystem, Current(d), rel.Version), Deps: []core.Dep{d}, To: rel.Version, Published: rel.Time, diff --git a/internal/proc/proc.go b/internal/proc/proc.go new file mode 100644 index 0000000..c3c0a35 --- /dev/null +++ b/internal/proc/proc.go @@ -0,0 +1,2 @@ +// Package proc keeps the processes tend starts in their own groups. +package proc diff --git a/internal/proc/proc_other.go b/internal/proc/proc_other.go new file mode 100644 index 0000000..d2ddd70 --- /dev/null +++ b/internal/proc/proc_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package proc + +import "os/exec" + +// Group does nothing where there are no process groups to signal: a cancel +// kills the first process only, and children it started may outlive it. +func Group(cmd *exec.Cmd) {} + +func Reap(cmd *exec.Cmd) {} diff --git a/internal/proc/proc_unix.go b/internal/proc/proc_unix.go new file mode 100644 index 0000000..f4a309a --- /dev/null +++ b/internal/proc/proc_unix.go @@ -0,0 +1,23 @@ +//go:build unix + +package proc + +import ( + "os/exec" + "syscall" +) + +// Group puts cmd in its own process group, so an interrupt at the terminal +// reaches tend alone, and a cancel or a timeout kills the whole tree it +// started, not just its first process. +func Group(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } +} + +// Reap kills whatever cmd left behind in its group after it exited. +func Reap(cmd *exec.Cmd) { + if cmd.Process != nil { + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } +} diff --git a/internal/scan/index.go b/internal/scan/index.go index a32304b..f3c7e19 100644 --- a/internal/scan/index.go +++ b/internal/scan/index.go @@ -33,7 +33,10 @@ type key struct { type ref struct{ file, n int } -var _ core.ScanIndex = (*Index)(nil) +var ( + _ core.ScanIndex = (*Index)(nil) + _ core.TestReacher = (*Index)(nil) +) // Build scans the source files under o.Root: what git tracks or would track, // or every file when git is not there. Files it cannot use are skipped with a @@ -201,7 +204,7 @@ func walkFiles(root string, skip []string) ([]string, error) { return err } if d.IsDir() { - if p != root && slices.Contains(skip, d.Name()) { + if p != root && (slices.Contains(skip, d.Name()) || core.NestedRepo(p)) { return filepath.SkipDir } return nil @@ -449,47 +452,86 @@ func (x *Index) Files() []string { // Reached reports whether a test reaches the file p: a JavaScript or // TypeScript test names a relative path that resolves to it, a Python test // imports the module it is, or a Go test sits in its package's directory. -// In the other languages a test whose file name holds p's base name counts, -// as FooTest.java does for Foo.java. +// In the other languages a test named for p counts, as FooTest.java, +// FooTests.cs, foo_spec.rb or test_foo.rb is for Foo: the name less its test +// marker must be p's base name. A Rust file with a #[test] or #[cfg(test)] +// of its own is reached by it, and a crate's src/ by the tests/ and +// benches/ next to it. func (x *Index) Reached(p string) bool { + return slices.ContainsFunc(x.files, func(f *file) bool { + return reaches(f, p) || f.File == p && f.Lang == "rust" && (bytes.Contains(f.code, []byte("#[test]")) || bytes.Contains(f.code, []byte("#[cfg(test)]"))) + }) +} + +// Reaches reports whether the test file test reaches the file p, as Reached +// reads it. +func (x *Index) Reaches(test, p string) bool { + return slices.ContainsFunc(x.files, func(f *file) bool { return f.File == test && reaches(f, p) }) +} + +func reaches(f *file, p string) bool { + if f.File == p || !IsTest(f.File) { + return false + } stem := strings.TrimSuffix(p, path.Ext(p)) - for _, f := range x.files { - if f.File == p || !IsTest(f.File) { - continue - } - switch strings.TrimSuffix(f.Lang, "?") { - case "go": - if path.Dir(f.File) == path.Dir(p) { + switch strings.TrimSuffix(f.Lang, "?") { + case "go": + return path.Dir(f.File) == path.Dir(p) + case "js": + for _, l := range f.lits { + if !strings.HasPrefix(l.Text, ".") { + continue + } + r := path.Join(path.Dir(f.File), l.Text) + if r == p || r == stem || path.Join(r, "index") == stem { return true } - case "js": - for _, l := range f.lits { - if !strings.HasPrefix(l.Text, ".") { - continue - } - r := path.Join(path.Dir(f.File), l.Text) - if r == p || r == stem || path.Join(r, "index") == stem { + } + case "python": + for _, im := range f.imps { + for _, q := range im.quals { + m := strings.ReplaceAll(q, ".", "/") + if stem == m || strings.HasSuffix(stem, "/"+m) || stem == m+"/__init__" || strings.HasSuffix(stem, "/"+m+"/__init__") { return true } } - case "python": - for _, im := range f.imps { - for _, q := range im.quals { - m := strings.ReplaceAll(q, ".", "/") - if stem == m || strings.HasSuffix(stem, "/"+m) || stem == m+"/__init__" || strings.HasSuffix(stem, "/"+m+"/__init__") { - return true - } - } - } - default: - if strings.Contains(strings.ToLower(path.Base(f.File)), strings.ToLower(path.Base(stem))) { - return true - } } + case "rust": + dir := path.Dir(f.File) + if b := path.Base(dir); b != "tests" && b != "benches" || path.Ext(p) != ".rs" { + return false + } + src := path.Join(path.Dir(dir), "src") + "/" + return strings.HasPrefix(p, strings.TrimPrefix(src, "./")) + default: + return slices.ContainsFunc(subjects(f.File), func(s string) bool { return strings.EqualFold(s, path.Base(stem)) }) } return false } +var ( + testSuffixes = []string{"Tests", "Test", "IT", "Spec", "_test", "_spec"} + testPrefixes = []string{"test_", "Test"} +) + +func subjects(p string) []string { + name := strings.TrimSuffix(path.Base(p), path.Ext(p)) + var res []string + for _, a := range testSuffixes { + if s, ok := strings.CutSuffix(name, a); ok && s != "" { + res = append(res, s) + break + } + } + for _, a := range testPrefixes { + if s, ok := strings.CutPrefix(name, a); ok && s != "" { + res = append(res, s) + break + } + } + return res +} + // Notes lists the files left out or only partly read, and why. func (x *Index) Notes() []string { return x.notes } diff --git a/internal/scan/index_test.go b/internal/scan/index_test.go index fd6faef..10a0517 100644 --- a/internal/scan/index_test.go +++ b/internal/scan/index_test.go @@ -670,18 +670,33 @@ client.charges.create func TestReached(t *testing.T) { root := t.TempDir() files := map[string]string{ - "src/app.js": "module.exports = {}\n", - "src/lib/index.js": "module.exports = {}\n", - "src/alone.js": "module.exports = {}\n", - "test/app.test.js": "const app = require('../src/app')\nconst lib = require('../src/lib')\n", - "shop/billing.py": "def charge(): pass\n", - "shop/orders.py": "def order(): pass\n", - "tests/test_billing.py": "from shop.billing import charge\n", - "pkg/a/a.go": "package a\n", - "pkg/a/a_test.go": "package a\n", - "pkg/b/b.go": "package b\n", - "src/main/java/shop/Cart.java": "class Cart {}\n", - "src/test/java/shop/CartTest.java": "class CartTest {}\n", + "src/app.js": "module.exports = {}\n", + "src/lib/index.js": "module.exports = {}\n", + "src/alone.js": "module.exports = {}\n", + "test/app.test.js": "const app = require('../src/app')\nconst lib = require('../src/lib')\n", + "shop/billing.py": "def charge(): pass\n", + "shop/orders.py": "def order(): pass\n", + "tests/test_billing.py": "from shop.billing import charge\n", + "pkg/a/a.go": "package a\n", + "pkg/a/a_test.go": "package a\n", + "pkg/b/b.go": "package b\n", + "src/main/java/shop/Cart.java": "class Cart {}\n", + "src/test/java/shop/CartTest.java": "class CartTest {}\n", + "src/main/java/shop/Db.java": "class Db {}\n", + "src/test/java/shop/FeedbackTest.java": "class FeedbackTest {}\n", + "lib/api.rb": "class Api; end\n", + "lib/cart.rb": "class Cart; end\n", + "spec/capital_spec.rb": "describe 'x' do; end\n", + "spec/cart_spec.rb": "describe Cart do; end\n", + "lib/order.rb": "class Order; end\n", + "test/test_order.rb": "class TestOrder; end\n", + "src/Billing.cs": "class Billing {}\n", + "Shop.Tests/BillingTests.cs": "class BillingTests {}\n", + "src/a.rs": "fn a() {}\n", + "tests/data_test.rs": "fn t() {}\n", + "crates/x/src/lib.rs": "fn f() {}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {}\n}\n", + "crates/x/src/other.rs": "fn g() {}\n", + "crates/x/src/cli.rs": "fn main() {}\n#[test]\nfn t() {}\n", } for name, body := range files { p := filepath.Join(root, filepath.FromSlash(name)) @@ -700,10 +715,55 @@ func TestReached(t *testing.T) { "src/app.js": true, "src/lib/index.js": true, "src/alone.js": false, "shop/billing.py": true, "shop/orders.py": false, "pkg/a/a.go": true, "pkg/b/b.go": false, - "src/main/java/shop/Cart.java": true, + "src/main/java/shop/Cart.java": true, "src/main/java/shop/Db.java": false, + "lib/api.rb": false, "lib/cart.rb": true, "lib/order.rb": true, + "src/Billing.cs": true, "src/a.rs": true, + "crates/x/src/lib.rs": true, "crates/x/src/cli.rs": true, "crates/x/src/other.rs": false, } { if got := x.Reached(p); got != want { t.Errorf("Reached(%s) = %v, want %v", p, got, want) } } } + +func TestRegexKeepsLaterCalls(t *testing.T) { + root := t.TempDir() + write(t, root, "a.js", "import Stripe from 'stripe';\n"+ + "const stripe = new Stripe(key);\n"+ + "const isTick = c => /`/.test(c);\n"+ + "function isUrl(u) {\n"+ + " return /^https?:\\/\\//.test(u) && stripe.refunds.create({});\n"+ + "}\n"+ + "stripe.charges.create({});\n"+ + "const u = 'https://api.stripe.com/v1/charges';\n") + x, err := Build(Options{Root: root, Files: []string{"a.js"}}) + if err != nil { + t.Fatal(err) + } + got := sites(x.Uses([]string{"stripe"})) + for _, want := range []string{"a.js:5:36 stripe.refunds.create", "a.js:7:1 stripe.charges.create"} { + if !slices.Contains(got, want) { + t.Errorf("Uses = %q, want %s among them", got, want) + } + } + urls := x.URLs() + if len(urls) != 1 || urls[0].URL != "https://api.stripe.com/v1/charges" { + t.Errorf("URLs = %+v", urls) + } + if len(x.Notes()) != 0 { + t.Errorf("notes = %q", x.Notes()) + } +} + +func TestReaches(t *testing.T) { + x := &Index{files: []*file{ + {FileScan: FileScan{File: "test/a.test.js", Lang: "js"}, lits: []lit{{Text: "../src/a"}}}, + {FileScan: FileScan{File: "test/b.test.js", Lang: "js"}, lits: []lit{{Text: "../src/b"}}}, + }} + if !x.Reaches("test/a.test.js", "src/a.js") || x.Reaches("test/b.test.js", "src/a.js") || x.Reaches("test/a.test.js", "src/b.js") { + t.Error("Reaches does not tell the tests apart") + } + if !x.Reached("src/a.js") || !x.Reached("src/b.js") || x.Reached("src/c.js") { + t.Error("Reached") + } +} diff --git a/internal/scan/lexer.go b/internal/scan/lexer.go index 91beb67..b25058c 100644 --- a/internal/scan/lexer.go +++ b/internal/scan/lexer.go @@ -129,6 +129,11 @@ func (l *lexer) comment() bool { return false case l.lineComment(): end := l.eol(l.i) + if l.php { + if k := bytes.Index(l.src[l.i:end], []byte("?>")); k >= 0 { + end = l.i + k + } + } l.blank(l.i, end) l.i = end case l.block && l.at("/*"): @@ -217,7 +222,7 @@ func (l *lexer) str() bool { l.closed(l.i+1, string(c), false) case strings.IndexByte(l.quotes, c) >= 0: return l.quoted(c) - case l.regex && c == '/' && (l.prev == 0 || strings.IndexByte("(,=:[!&|?;{~", l.prev) >= 0): + case l.regex && c == '/' && l.regexAllowed(): return l.re() case l.ruby && c == '%': return l.percent() @@ -292,6 +297,46 @@ func (l *lexer) tmpl() { l.fail() } +var ( + regexAfter = map[string]bool{ + "return": true, "typeof": true, "instanceof": true, "in": true, "of": true, "new": true, "delete": true, + "void": true, "throw": true, "case": true, "do": true, "else": true, "yield": true, "await": true, + } + rubyRegexAfter = map[string]bool{ + "if": true, "elsif": true, "unless": true, "when": true, "and": true, "or": true, "not": true, "while": true, "until": true, + } +) + +func (l *lexer) regexAllowed() bool { + switch { + case l.prev == 0 || strings.IndexByte("(,=:[!&|?;{~>*%^", l.prev) >= 0: + return true + case l.prev == '+' || l.prev == '-': + j := l.back(l.i) + return j < 1 || l.code[j-1] != l.prev + case !isIdent(l.prev): + return false + } + end := l.back(l.i) + 1 + start := end + for start > 0 && isIdent(l.code[start-1]) { + start-- + } + if start > 0 && l.code[start-1] == '.' { + return false + } + word := l.code[start:end] + return regexAfter[string(word)] || l.ruby && rubyRegexAfter[string(word)] +} + +func (l *lexer) back(j int) int { + j-- + for j >= 0 && isSpace(l.code[j]) { + j-- + } + return j +} + func (l *lexer) re() bool { class := false for j := l.i + 1; j < len(l.src); j++ { diff --git a/internal/scan/lexer_test.go b/internal/scan/lexer_test.go index 885a650..822cde6 100644 --- a/internal/scan/lexer_test.go +++ b/internal/scan/lexer_test.go @@ -62,6 +62,72 @@ func TestStrip(t *testing.T) { code: `a = b / c / " "`, lits: []string{"1:14:d"}, }, + { + name: "regex after an arrow", + syn: jsSyntax, + src: `f = u => /^https?:\/\//.test(u) && g()`, + code: `f = u => .test(u) && g()`, + }, + { + name: "regex after return", + syn: jsSyntax, + src: "return /`/.test(c)\nb = 'x'", + code: "return .test(c)\nb = ' '", + lits: []string{"2:6:x"}, + }, + { + name: "regex after typeof", + syn: jsSyntax, + src: `if (typeof /a/ === 'x')`, + code: `if (typeof === ' ')`, + lits: []string{"1:21:x"}, + }, + { + name: "regex after a keyword on the line before", + syn: jsSyntax, + src: "yield /* c */\n /'/g", + code: "yield \n ", + }, + { + name: "property named like a keyword is division", + syn: jsSyntax, + src: `x.return / 2 / "d"`, + code: `x.return / 2 / " "`, + lits: []string{"1:17:d"}, + }, + { + name: "division after increment", + syn: jsSyntax, + src: `a++ / b / "d"`, + code: `a++ / b / " "`, + lits: []string{"1:12:d"}, + }, + { + name: "regex after a binary plus", + syn: jsSyntax, + src: `s = a + /'/.source`, + code: `s = a + .source`, + }, + { + name: "division after a closing paren", + syn: jsSyntax, + src: `m = (a + b) / 2 // "c"`, + code: `m = (a + b) / 2 `, + }, + { + name: "ruby regex after if", + syn: rubySyntax, + src: "x if /'/ =~ s\ny = 'z'", + code: "x if =~ s\ny = ' '", + lits: []string{"2:6:z"}, + }, + { + name: "ruby keywords are names in js", + syn: jsSyntax, + src: `r = not / 2 / "d"`, + code: `r = not / 2 / " "`, + lits: []string{"1:16:d"}, + }, { name: "apostrophe in jsx text", syn: jsSyntax, @@ -165,6 +231,13 @@ func TestStrip(t *testing.T) { code: " \n \n$a = \n \n ;\n$b = \n \n ;\n \n#[Attr]\n \n ", lits: []string{"4:1:hi 'x'", "7:1:$y"}, }, + { + name: "php line comment ends at the close tag", + syn: phpSyntax, + src: "\n

it's

\n'", + code: " \n \n $u = ' '; ", + lits: []string{"3:13:https://api.x.com/v1/h"}, + }, { name: "crlf", syn: pySyntax, diff --git a/internal/scan/scan.go b/internal/scan/scan.go index 5d5774c..ed4b7e6 100644 --- a/internal/scan/scan.go +++ b/internal/scan/scan.go @@ -501,7 +501,7 @@ func isUpper(c byte) bool { return 'A' <= c && c <= 'Z' } // by convention. var testDirs = map[string]bool{"test": true, "tests": true, "__tests__": true, "spec": true, "specs": true, "testdata": true} -var testName = regexp.MustCompile(`(_test\.go|\.(test|spec)\.[cm]?[jt]sx?|^test_.*\.py|_test\.py|^conftest\.py|_(spec|test)\.rb|Tests?\.(java|kt|cs|php)|IT\.java)$`) +var testName = regexp.MustCompile(`(_test\.go|\.(test|spec)(-d)?\.[cm]?[jt]sx?|^tests?\.([cm]?[jt]sx?|py)|^test_.*\.py|_test\.py|^conftest\.py|_(spec|test)\.rb|Tests?\.(java|kt|cs|php)|IT\.java)$`) // IsTest reports whether a repo-relative path is test code by its language's // conventions: a _test.go file, a .test.js file, anything under tests/, and so on. diff --git a/internal/scan/scan_test.go b/internal/scan/scan_test.go index ea5212d..c2e30cc 100644 --- a/internal/scan/scan_test.go +++ b/internal/scan/scan_test.go @@ -109,6 +109,9 @@ func TestIsTest(t *testing.T) { {"main.go", false}, {"src/billing.test.js", true}, {"src/billing.spec.tsx", true}, + {"typings/index.test-d.ts", true}, + {"index.spec-d.ts", true}, + {"typings/index.d.ts", false}, {"src/__tests__/billing.js", true}, {"test/billing.js", true}, {"src/billing.js", false}, @@ -127,6 +130,13 @@ func TestIsTest(t *testing.T) { {"Acme.Billing/Charge.cs", false}, {"testdata/projects/x/package.json", true}, {"contest/entry.go", false}, + {"test.js", true}, + {"tests.js", true}, + {"packages/foo/test.mjs", true}, + {"test.py", true}, + {"app/tests.py", true}, + {"latest.js", false}, + {"contests.py", false}, } for _, tt := range tests { if got := IsTest(tt.path); got != tt.want { diff --git a/internal/scan/testdata/golden/App.cs.json b/internal/scan/testdata/golden/App.cs.json index 0e4539f..7810061 100644 --- a/internal/scan/testdata/golden/App.cs.json +++ b/internal/scan/testdata/golden/App.cs.json @@ -120,7 +120,8 @@ "Line": 24, "Method": "GET", "URL": "https://api.stripe.com/v1/charges", - "Host": "api.stripe.com" + "Host": "api.stripe.com", + "Text": "http.GetAsync(\"https://api.stripe.com/v1/charges\");" } ] } diff --git a/internal/scan/testdata/golden/App.java.json b/internal/scan/testdata/golden/App.java.json index a56759b..39bbeff 100644 --- a/internal/scan/testdata/golden/App.java.json +++ b/internal/scan/testdata/golden/App.java.json @@ -181,7 +181,8 @@ "Line": 25, "Method": "", "URL": "https://api.stripe.com/v1/charges", - "Host": "api.stripe.com" + "Host": "api.stripe.com", + "Text": ".uri(URI.create(\"https://api.stripe.com/v1/charges\"))" } ] } diff --git a/internal/scan/testdata/golden/app.go.json b/internal/scan/testdata/golden/app.go.json index e367816..68c896d 100644 --- a/internal/scan/testdata/golden/app.go.json +++ b/internal/scan/testdata/golden/app.go.json @@ -364,7 +364,8 @@ "Line": 47, "Method": "POST", "URL": "https://api.stripe.com/v1/refunds", - "Host": "api.stripe.com" + "Host": "api.stripe.com", + "Text": "req, _ := http.NewRequest(http.MethodPost, \"https://api.stripe.com/v1/refunds\", nil)" } ] } diff --git a/internal/scan/testdata/golden/app.php.json b/internal/scan/testdata/golden/app.php.json index 8c58187..fd18e62 100644 --- a/internal/scan/testdata/golden/app.php.json +++ b/internal/scan/testdata/golden/app.php.json @@ -161,14 +161,16 @@ "Line": 17, "Method": "", "URL": "https://api.example.com", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "$this-\u003ehttp = new Http(['base_uri' =\u003e 'https://api.example.com']);" }, { "File": "app.php", "Line": 29, "Method": "DELETE", "URL": "/v1/orders/1", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "$this-\u003ehttp-\u003erequest('DELETE', '/v1/orders/1');" } ] } diff --git a/internal/scan/testdata/golden/app.py.json b/internal/scan/testdata/golden/app.py.json index 6082618..923c993 100644 --- a/internal/scan/testdata/golden/app.py.json +++ b/internal/scan/testdata/golden/app.py.json @@ -252,28 +252,32 @@ "Line": 14, "Method": "", "URL": "https://api.example.com", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "API = \"https://api.example.com\"" }, { "File": "app.py", "Line": 20, "Method": "", "URL": "/hooks", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "@app.route(\"/hooks\")" }, { "File": "app.py", "Line": 29, "Method": "POST", "URL": "/v1/orders", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "r = requests.post(f\"{API}/v1/orders\", json={\"total_cents\": 5})" }, { "File": "app.py", "Line": 33, "Method": "PUT", "URL": "/v1/refunds", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "urllib.request.Request(\"/v1/refunds\", method=\"PUT\")" } ] } diff --git a/internal/scan/testdata/golden/app.rb.json b/internal/scan/testdata/golden/app.rb.json index cc59c16..118a7ce 100644 --- a/internal/scan/testdata/golden/app.rb.json +++ b/internal/scan/testdata/golden/app.rb.json @@ -106,7 +106,8 @@ "Line": 24, "Method": "POST", "URL": "https://api.example.com/v1/events", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "Faraday.post(\"https://api.example.com/v1/events\") # Stripe.x" } ] } diff --git a/internal/scan/testdata/golden/app.tsx.json b/internal/scan/testdata/golden/app.tsx.json index 35bdb74..66d11cb 100644 --- a/internal/scan/testdata/golden/app.tsx.json +++ b/internal/scan/testdata/golden/app.tsx.json @@ -366,21 +366,24 @@ "Line": 23, "Method": "POST", "URL": "https://api.example.com/v1/orders", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "const res = await axios.post('https://api.example.com/v1/orders', { total_cents: 5 });" }, { "File": "app.tsx", "Line": 24, "Method": "DELETE", "URL": "/v1/orders/${id}", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "const r2 = await fetch(`${BASE}/v1/orders/${id}`, {" }, { "File": "app.tsx", "Line": 37, "Method": "", "URL": "https://docs.example.com/x", - "Host": "docs.example.com" + "Host": "docs.example.com", + "Text": "return \u003ca href=\"https://docs.example.com/x\"\u003eDon't {stripe.balance.retrieve()}\u003c/a\u003e;" } ] } diff --git a/internal/scan/testdata/golden/main.rs.json b/internal/scan/testdata/golden/main.rs.json index d6d4a1b..7b27f87 100644 --- a/internal/scan/testdata/golden/main.rs.json +++ b/internal/scan/testdata/golden/main.rs.json @@ -196,7 +196,8 @@ "Line": 12, "Method": "GET", "URL": "https://api.example.com/v1/items", - "Host": "api.example.com" + "Host": "api.example.com", + "Text": "let res = client.get(\"https://api.example.com/v1/items\").headers(h).send().await?;" } ] } diff --git a/internal/scan/urls.go b/internal/scan/urls.go index b400544..ddaf0ff 100644 --- a/internal/scan/urls.go +++ b/internal/scan/urls.go @@ -33,7 +33,7 @@ func (f *file) endpoints() []core.URLUse { if h != "" && (host == "" || strings.HasPrefix(h, "api.") && !strings.HasPrefix(host, "api.")) { host = h } - res = append(res, core.URLUse{File: f.File, Line: l.Line, URL: u, Host: h}) + res = append(res, core.URLUse{File: f.File, Line: l.Line, URL: u, Host: h, Text: f.text(l.Line)}) cols = append(cols, l.Col) } lines := map[int]bool{} diff --git a/internal/selfupdate/action_test.go b/internal/selfupdate/action_test.go new file mode 100644 index 0000000..bb88519 --- /dev/null +++ b/internal/selfupdate/action_test.go @@ -0,0 +1,174 @@ +package selfupdate + +import ( + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +type actionStep struct { + Shell string `yaml:"shell"` + Run string `yaml:"run"` + Uses string `yaml:"uses"` + If string `yaml:"if"` + Env map[string]string `yaml:"env"` + With map[string]string `yaml:"with"` +} + +func actionSteps(t *testing.T) []actionStep { + t.Helper() + b, err := os.ReadFile("../../action.yml") + if err != nil { + t.Fatal(err) + } + var a struct { + Runs struct { + Using string `yaml:"using"` + Steps []actionStep `yaml:"steps"` + } `yaml:"runs"` + } + if err := yaml.Unmarshal(b, &a); err != nil { + t.Fatal(err) + } + if a.Runs.Using != "composite" || len(a.Runs.Steps) == 0 { + t.Fatalf("action.yml runs = %+v", a.Runs) + } + return a.Runs.Steps +} + +var startsTend = regexp.MustCompile(`(^|[;&|]\s*|\n\s*)(exec\s+)?tend\s`) + +func TestActionExecsTend(t *testing.T) { + var found []actionStep + for _, s := range actionSteps(t) { + if startsTend.MatchString(s.Run) { + found = append(found, s) + } + } + if len(found) != 1 { + t.Fatalf("%d steps start tend, want 1", len(found)) + } + s := found[0] + if _, ok := s.Env["GITHUB_TOKEN"]; !ok { + t.Fatal("the step that runs tend has no GITHUB_TOKEN; the wrong step was found") + } + run := strings.TrimSpace(s.Run) + if strings.Contains(run, "\n") { + t.Fatalf("the tend step runs more than one line, so bash outlives tend:\n%s", run) + } + last := run[strings.LastIndex(run, ";")+1:] + if !strings.HasPrefix(strings.TrimSpace(last), "exec tend ") { + t.Errorf("the tend step runs %q; without exec, bash stays as tend's parent with the token in its environment", run) + } +} + +func TestActionCacheSkipsWorktrees(t *testing.T) { + var caches int + for _, s := range actionSteps(t) { + if !strings.HasPrefix(s.Uses, "actions/cache/") { + continue + } + caches++ + path := s.With["path"] + for _, want := range []string{"/tend/repos\n", "!${{ runner.temp }}/tend/repos/*/wt\n", "!${{ runner.temp }}/tend/repos/*/baseline\n"} { + if !strings.Contains(path+"\n", want) { + t.Errorf("%s path does not hold %q:\n%s", s.Uses, strings.TrimSpace(want), path) + } + } + } + if caches != 2 { + t.Errorf("%d cache steps, want a restore and a save", caches) + } +} + +func git(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return string(out) +} + +func TestScrub(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("bash may be WSL's here; the action job runs the scrub on Windows") + } + for _, tool := range []string{"bash", "git"} { + if _, err := exec.LookPath(tool); err != nil { + t.Skip(tool + " not found") + } + } + script, err := filepath.Abs("../../action/scrub.sh") + if err != nil { + t.Fatal(err) + } + root := t.TempDir() + repo, temp, elsewhere := filepath.Join(root, "work dir", "repo"), filepath.Join(root, "_temp"), filepath.Join(root, "home") + for _, d := range []string{repo, temp, elsewhere} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + git(t, repo, "init", "-q") + gitDir := filepath.Join(repo, ".git") + creds := filepath.Join(temp, "git-credentials-1b0c.config") + second := filepath.Join(temp, "git-credentials-77aa.config") + outside := filepath.Join(elsewhere, "git-credentials-0000.config") + mine := filepath.Join(elsewhere, "mine.config") + for _, f := range []string{creds, second, outside} { + if err := os.WriteFile(f, []byte("[http \"https://github.com/\"]\n\textraheader = AUTHORIZATION: basic c2VjcmV0\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(mine, []byte("[user]\n\tname = me\n"), 0o644); err != nil { + t.Fatal(err) + } + git(t, repo, "config", "--local", "http.https://github.com/.extraheader", "AUTHORIZATION: basic c2VjcmV0") + git(t, repo, "config", "--local", "includeIf.gitdir:"+gitDir+".path", creds) + git(t, repo, "config", "--local", "includeIf.gitdir:"+gitDir+"/worktrees/*.path", creds) + git(t, repo, "config", "--local", "includeIf.gitdir:/github/workspace/.git.path", outside) + git(t, repo, "config", "--local", "includeIf.gitdir:"+gitDir+"/modules/x.path", mine) + if !strings.Contains(git(t, repo, "config", "--get-all", "http.https://github.com/.extraheader"), "c2VjcmV0") { + t.Fatal("the fixture does not resolve the token before the scrub") + } + + cmd := exec.Command("bash", script) + cmd.Dir = repo + cmd.Env = append(os.Environ(), "RUNNER_TEMP="+temp, "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("scrub: %v\n%s", err, out) + } + + cfg := git(t, repo, "config", "--local", "--list") + if strings.Contains(cfg, "c2VjcmV0") || strings.Contains(cfg, "git-credentials-") { + t.Errorf("the token is still in the config:\n%s", cfg) + } + if !strings.Contains(cfg, "mine.config") { + t.Errorf("an include that holds no credentials was removed:\n%s", cfg) + } + for _, f := range []string{creds, second} { + if _, err := os.Stat(f); !os.IsNotExist(err) { + t.Errorf("%s is still there", filepath.Base(f)) + } + } + if _, err := os.Stat(outside); err != nil { + t.Error("a credentials file outside RUNNER_TEMP was deleted") + } + + cmd = exec.Command("bash", script) + cmd.Dir = repo + cmd.Env = append(os.Environ(), "RUNNER_TEMP="+temp) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("a second scrub fails: %v\n%s", err, out) + } +} diff --git a/internal/selfupdate/install_test.go b/internal/selfupdate/install_test.go index e4eaf39..4f2d3ec 100644 --- a/internal/selfupdate/install_test.go +++ b/internal/selfupdate/install_test.go @@ -1,6 +1,7 @@ package selfupdate import ( + "cmp" "crypto/ed25519" "crypto/rand" "crypto/sha256" @@ -13,6 +14,8 @@ import ( "os" "os/exec" "path/filepath" + "runtime" + "strconv" "strings" "sync" "testing" @@ -27,6 +30,7 @@ type installFixture struct { action string // GITHUB_ACTION_PATH with action/pubkey.pem in it releases []*release priv ed25519.PrivateKey + tags [][2]string // name and commit, in the order /tags lists them mu sync.Mutex apiHit []string // Authorization headers seen on API paths @@ -37,16 +41,30 @@ func fakeBinary(version string) []byte { return []byte("#!/bin/sh\necho " + version + "\n") } +func commitOf(name string) string { + sum := sha256.Sum256([]byte(name)) + return fmt.Sprintf("%x", sum)[:40] +} + func (fx *installFixture) add(t *testing.T, tag string) *release { t.Helper() version := strings.TrimPrefix(tag, "v") - name := fmt.Sprintf("tend_%s_linux_amd64.tar.gz", version) - r := &release{tag: tag, priv: fx.priv, assets: map[string][]byte{name: tarball(t, map[string]string{"tend": string(fakeBinary(version))})}} + bin := string(fakeBinary(version)) + r := &release{tag: tag, priv: fx.priv, assets: map[string][]byte{ + fmt.Sprintf("tend_%s_linux_amd64.tar.gz", version): tarball(t, map[string]string{"tend": bin}), + fmt.Sprintf("tend_%s_darwin_arm64.tar.gz", version): tarball(t, map[string]string{"tend": bin}), + fmt.Sprintf("tend_%s_windows_amd64.zip", version): zipfile(t, map[string]string{"tend.exe": bin}), + }} r.resign() fx.releases = append(fx.releases, r) + fx.tag(tag, commitOf(tag)) return r } +func (fx *installFixture) tag(name, commit string) { + fx.tags = append(fx.tags, [2]string{name, commit}) +} + func newInstallFixture(t *testing.T) *installFixture { t.Helper() pub, priv, err := ed25519.GenerateKey(rand.Reader) @@ -84,6 +102,20 @@ func (fx *installFixture) start(t *testing.T) { } fmt.Fprintf(w, "[%s]", strings.Join(items, ", ")) }) + mux.HandleFunc("/repos"+repoPath+"/tags", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("per_page") != "100" { + http.Error(w, "want per_page=100", http.StatusBadRequest) + return + } + page, _ := strconv.Atoi(cmp.Or(r.URL.Query().Get("page"), "1")) + var items []string + for i, tg := range fx.tags { + if i/100 == page-1 { + items = append(items, fmt.Sprintf("{\"name\":%q,\"zipball_url\":\"z\",\"commit\":{\"sha\":%q,\"url\":\"u\"},\"node_id\":\"n\"}", tg[0], tg[1])) + } + } + fmt.Fprintf(w, "[%s]", strings.Join(items, ",")) + }) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fx.mu.Lock() if strings.HasPrefix(r.URL.Path, "/repos/") { @@ -116,6 +148,9 @@ func runInstall(t *testing.T, fx *installFixture, env []string, expect, match st func needTools(t *testing.T) { t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the fixture binaries are shell scripts; the action job runs install.sh on Windows") + } for _, tool := range []string{"bash", "openssl", "curl", "tar"} { if _, err := exec.LookPath(tool); err != nil { t.Skip(tool + " not found") @@ -152,6 +187,16 @@ func TestInstallScript(t *testing.T) { {"empty ref gets the latest release", "", nil, "ok", "2.0.0"}, {"input beats the ref", "v1", []string{"1.2.0"}, "ok", "1.2.0"}, {"major with no release", "v3", nil, "fail", "no release of mohsensc/tend-cli matches"}, + {"minor ref stays on its minor", "v1.2", nil, "ok", "1.2.0"}, + {"minor with no release", "v1.3", nil, "fail", "no release of mohsensc/tend-cli matches"}, + {"commit of a v1 release while v2 exists", commitOf("v1.2.0"), nil, "ok", "1.2.0"}, + {"commit the major tag also points at", commitOf("v1.10.0"), nil, "ok", "1.10.0"}, + {"commit in upper case", strings.ToUpper(commitOf("v1.9.5")), nil, "ok", "1.9.5"}, + {"commit that is no release", commitOf("main"), nil, "fail", "is not a release"}, + {"commit tagged only with a major", commitOf("v0"), nil, "fail", "is not a release"}, + {"input beats a commit", commitOf("v1.2.0"), []string{"1.9.5"}, "ok", "1.9.5"}, + {"release-like branch", "v2-dev", nil, "fail", "not a release tag"}, + {"four-part ref", "v1.2.0.1", nil, "fail", "not a release tag"}, {"unknown version", "", []string{"9.9.9"}, "fail", "could not download"}, } for _, tc := range tests { @@ -161,6 +206,8 @@ func TestInstallScript(t *testing.T) { fx.add(t, "v1.10.0") fx.add(t, "v1.2.0") fx.add(t, "v1.9.5") + fx.tag("v1", commitOf("v1.10.0")) + fx.tag("v0", commitOf("v0")) fx.start(t) runInstall(t, fx, []string{"GITHUB_ACTION_REF=" + tc.ref}, tc.expect, tc.match, tc.args...) }) @@ -208,7 +255,52 @@ func TestInstallScript(t *testing.T) { }) } - t.Run("the newest of a major still uploading", func(t *testing.T) { + t.Run("commit found on a later page of tags", func(t *testing.T) { + fx := newInstallFixture(t) + fx.add(t, "v2.0.0") + for i := range 150 { + fx.tag(fmt.Sprintf("v0.0.%d", i), commitOf(fmt.Sprint(i))) + } + fx.add(t, "v1.2.0") + fx.start(t) + runInstall(t, fx, []string{"GITHUB_ACTION_REF=" + commitOf("v1.2.0")}, "ok", "1.2.0") + }) + + t.Run("macOS on arm64", func(t *testing.T) { + fx := newInstallFixture(t) + fx.add(t, "v1.2.0") + fx.start(t) + runInstall(t, fx, []string{"RUNNER_OS=macOS", "RUNNER_ARCH=ARM64"}, "ok", "1.2.0", "1.2.0") + }) + + t.Run("Windows on x64", func(t *testing.T) { + if _, err := exec.LookPath("unzip"); err != nil { + t.Skip("unzip not found") + } + fx := newInstallFixture(t) + fx.add(t, "v1.2.0") + fx.start(t) + runInstall(t, fx, []string{"RUNNER_OS=Windows", "RUNNER_ARCH=X64"}, "ok", "1.2.0", "1.2.0") + }) + + t.Run("the newest of a minor without a signature", func(t *testing.T) { + fx := newInstallFixture(t) + fx.add(t, "v1.3.0") + fx.add(t, "v1.2.5").noSig = true + fx.add(t, "v1.2.4") + fx.start(t) + runInstall(t, fx, []string{"GITHUB_ACTION_REF=v1.2"}, "ok", "1.2.4") + }) + + t.Run("a commit pin does not fall back", func(t *testing.T) { + fx := newInstallFixture(t) + fx.add(t, "v1.2.5").noSig = true + fx.add(t, "v1.2.4") + fx.start(t) + runInstall(t, fx, []string{"GITHUB_ACTION_REF=" + commitOf("v1.2.5")}, "fail", "could not download") + }) + + t.Run("the newest of a major without a signature", func(t *testing.T) { fx := newInstallFixture(t) fx.add(t, "v1.10.0").noSig = true fx.add(t, "v1.9.5") diff --git a/internal/selfupdate/sign/main.go b/internal/selfupdate/sign/main.go index e0fe45e..6077b11 100644 --- a/internal/selfupdate/sign/main.go +++ b/internal/selfupdate/sign/main.go @@ -1,10 +1,13 @@ -// Sign makes the release signing key and signs checksums.txt. +// Sign makes the release signing key and signs checksums.txt. It refuses a key +// whose public half is not the one built into tend, so a bad secret fails +// before anything is published. // // go run ./internal/selfupdate/sign -keygen // TEND_SIGNING_KEY= go run ./internal/selfupdate/sign -in checksums.txt > checksums.txt.sig package main import ( + "bytes" "crypto/ed25519" "crypto/rand" "crypto/x509" @@ -16,8 +19,12 @@ import ( "fmt" "io" "os" + + "github.com/mohsensc/tend-cli/internal/selfupdate" ) +var wantPublic = selfupdate.PublicKey + func main() { if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil { fmt.Fprintln(os.Stderr, "sign:", err) @@ -64,19 +71,24 @@ func sign(w io.Writer, keyHex, path string) error { if err != nil { return fmt.Errorf("key is not hex: %w", err) } - var priv ed25519.PrivateKey - switch len(b) { - case ed25519.SeedSize: - priv = ed25519.NewKeyFromSeed(b) - case ed25519.PrivateKeySize: - priv = b - default: + if len(b) != ed25519.SeedSize && len(b) != ed25519.PrivateKeySize { return fmt.Errorf("key is %d bytes, want %d or %d", len(b), ed25519.SeedSize, ed25519.PrivateKeySize) } + priv := ed25519.NewKeyFromSeed(b[:ed25519.SeedSize]) + if len(b) == ed25519.PrivateKeySize && !bytes.Equal(b[ed25519.SeedSize:], priv[ed25519.SeedSize:]) { + return errors.New("key's public half does not match its seed") + } + if pub := priv.Public().(ed25519.PublicKey); !pub.Equal(wantPublic) { + return fmt.Errorf("key's public half is %x, but key.go and action/pubkey.pem hold %x; releases signed with it would not install", []byte(pub), []byte(wantPublic)) + } data, err := os.ReadFile(path) if err != nil { return err } - _, err = fmt.Fprintln(w, base64.StdEncoding.EncodeToString(ed25519.Sign(priv, data))) + sig := ed25519.Sign(priv, data) + if !ed25519.Verify(wantPublic, data, sig) { + return errors.New("signature does not verify against the public key in key.go") + } + _, err = fmt.Fprintln(w, base64.StdEncoding.EncodeToString(sig)) return err } diff --git a/internal/selfupdate/sign/main_test.go b/internal/selfupdate/sign/main_test.go index 1fd68d4..be3101e 100644 --- a/internal/selfupdate/sign/main_test.go +++ b/internal/selfupdate/sign/main_test.go @@ -12,6 +12,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/mohsensc/tend-cli/internal/selfupdate" ) func keygen(t *testing.T) (priv string, pub ed25519.PublicKey, pemText string) { @@ -33,6 +35,13 @@ func keygen(t *testing.T) (priv string, pub ed25519.PublicKey, pemText string) { return priv, b, lines[2] } +func trust(t *testing.T, pub ed25519.PublicKey) { + t.Helper() + old := wantPublic + wantPublic = pub + t.Cleanup(func() { wantPublic = old }) +} + func TestKeygen(t *testing.T) { priv, pub, pemText := keygen(t) if len(priv) != 2*ed25519.SeedSize { @@ -61,6 +70,7 @@ func TestKeygen(t *testing.T) { func TestSign(t *testing.T) { priv, pub, pemText := keygen(t) + trust(t, pub) dir := t.TempDir() file := filepath.Join(dir, "checksums.txt") data := []byte("abc123 tend_1.0.0_linux_amd64.tar.gz\n") @@ -94,6 +104,9 @@ func TestSign(t *testing.T) { t.Log("openssl not found, skipping the cross-check") return } + if v, _ := exec.Command("openssl", "version").Output(); !strings.HasPrefix(string(v), "OpenSSL 3") && !strings.HasPrefix(string(v), "OpenSSL 1.1.1") { + t.Skip("openssl is " + strings.TrimSpace(string(v)) + ", ed25519 needs OpenSSL 1.1.1 or newer") + } pubFile, sigFile := filepath.Join(dir, "pub.pem"), filepath.Join(dir, "sig.bin") if err := os.WriteFile(pubFile, []byte(pemText), 0o644); err != nil { t.Fatal(err) @@ -113,6 +126,7 @@ func TestSign(t *testing.T) { func TestSignAcceptsFullPrivateKey(t *testing.T) { seed := bytes.Repeat([]byte{7}, ed25519.SeedSize) full := ed25519.NewKeyFromSeed(seed) + trust(t, full.Public().(ed25519.PublicKey)) file := filepath.Join(t.TempDir(), "f") if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { t.Fatal(err) @@ -130,6 +144,7 @@ func TestSignAcceptsFullPrivateKey(t *testing.T) { } func TestRunErrors(t *testing.T) { + trust(t, ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)).Public().(ed25519.PublicKey)) file := filepath.Join(t.TempDir(), "f") if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { t.Fatal(err) @@ -158,3 +173,55 @@ func TestRunErrors(t *testing.T) { }) } } + +func TestSignRefusesAKeyThatWouldNotVerify(t *testing.T) { + seed := bytes.Repeat([]byte{7}, ed25519.SeedSize) + full := ed25519.NewKeyFromSeed(seed) + trust(t, full.Public().(ed25519.PublicKey)) + file := filepath.Join(t.TempDir(), "checksums.txt") + if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{9}, ed25519.SeedSize)) + mismatched := append(append([]byte{}, seed...), other[ed25519.SeedSize:]...) + + tests := []struct { + name string + key []byte + want string + }{ + {"public half does not match the seed", mismatched, "does not match its seed"}, + {"another key's seed", other.Seed(), "key.go and action/pubkey.pem hold"}, + {"another full key", other, "key.go and action/pubkey.pem hold"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + err := run([]string{"-key", hex.EncodeToString(tc.key), "-in", file}, &out, os.Stderr) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("err = %v, want %q", err, tc.want) + } + if out.Len() != 0 { + t.Errorf("wrote a signature: %q", out.String()) + } + }) + } +} + +func TestSignTrustsTheShippedKey(t *testing.T) { + if !wantPublic.Equal(selfupdate.PublicKey) { + t.Fatal("sign checks keys against something other than key.go") + } + _, pub, _ := keygen(t) + if pub.Equal(wantPublic) { + t.Fatal("a fresh key matched the shipped one") + } + file := filepath.Join(t.TempDir(), "f") + if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + priv, _, _ := keygen(t) + if err := run([]string{"-key", priv, "-in", file}, &bytes.Buffer{}, os.Stderr); err == nil { + t.Fatal("signed with a key that is not the shipped one") + } +} diff --git a/internal/selfupdate/update.go b/internal/selfupdate/update.go index f502112..46a3732 100644 --- a/internal/selfupdate/update.go +++ b/internal/selfupdate/update.go @@ -15,12 +15,14 @@ import ( "errors" "fmt" "io" + "io/fs" "os" "path" "path/filepath" "regexp" "runtime" "strings" + "time" "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/ver" @@ -41,11 +43,12 @@ type ReleaseInfo struct { URL string } -var releaseRe = regexp.MustCompile(`^v?\d+\.\d+\.\d+$`) +var releaseRe = regexp.MustCompile(`^v?\d+\.\d+\.\d+(-(alpha|beta|rc)\.?\d+)?$`) // Latest asks GitHub for the latest release and compares it with current. A -// build that is not a release ("", "dev", a git describe string) never has a -// newer version and costs no request. +// build that is not a release or a prerelease the release workflow publishes +// ("", "dev", a git describe string, a pseudo-version, a +dirty build) never +// has a newer version and costs no request. func Latest(ctx context.Context, f core.Fetcher, current string) (*ReleaseInfo, error) { if !releaseRe.MatchString(current) { return &ReleaseInfo{Tag: "dev", Version: "dev"}, nil @@ -110,12 +113,15 @@ func apply(ctx context.Context, f core.Fetcher, r *ReleaseInfo, exe, goos, goarc if r == nil || r.Tag == "" || r.Version == "" { return errors.New("selfupdate: no release to apply") } + if err := writable(exe); err != nil { + return err + } base := assetsURL + "/" + r.Tag + "/" - sums, err := download(ctx, f, base+"checksums.txt") + sums, err := download(ctx, f, base+"checksums.txt", 0) if err != nil { return err } - sig, err := download(ctx, f, base+"checksums.txt.sig") + sig, err := download(ctx, f, base+"checksums.txt.sig", 0) if err != nil { return fmt.Errorf("%w (a release without a signature is refused)", err) } @@ -130,7 +136,7 @@ func apply(ctx context.Context, f core.Fetcher, r *ReleaseInfo, exe, goos, goarc if err != nil { return err } - archive, err := download(ctx, f, base+name) + archive, err := download(ctx, f, base+name, archiveTimeout) if err != nil { return err } @@ -144,8 +150,12 @@ func apply(ctx context.Context, f core.Fetcher, r *ReleaseInfo, exe, goos, goarc return replace(exe, bin, goos == "windows") } -func download(ctx context.Context, f core.Fetcher, url string) ([]byte, error) { - res, err := f.Get(ctx, url, func(o *core.FetchOpts) { o.NoCache = true }) +// archiveTimeout is how long the release archive, a few megabytes, may take +// to download on a slow link. +const archiveTimeout = 10 * time.Minute + +func download(ctx context.Context, f core.Fetcher, url string, timeout time.Duration) ([]byte, error) { + res, err := f.Get(ctx, url, func(o *core.FetchOpts) { o.NoCache, o.Timeout = true, timeout }) if err != nil { return nil, fmt.Errorf("selfupdate: %w", err) } @@ -198,7 +208,7 @@ func fromTar(archive []byte) ([]byte, error) { return nil, err } if h.Typeflag == tar.TypeReg && path.Base(h.Name) == "tend" { - return readLimited(tr) + return readLimited(tr, binMax) } } } @@ -217,29 +227,50 @@ func fromZip(archive []byte) ([]byte, error) { return nil, err } defer rc.Close() - return readLimited(rc) + return readLimited(rc, binMax) } return nil, errors.New("no tend.exe in the archive") } -func readLimited(r io.Reader) ([]byte, error) { - b, err := io.ReadAll(io.LimitReader(r, binMax+1)) - if err == nil && len(b) > binMax { +func readLimited(r io.Reader, limit int) ([]byte, error) { + b, err := io.ReadAll(io.LimitReader(r, int64(limit)+1)) + if err == nil && len(b) > limit { err = errors.New("binary is larger than the limit") } return b, err } +// writable fails early, before any download, when exe cannot be replaced. +func writable(exe string) error { + f, err := os.CreateTemp(filepath.Dir(exe), ".tend-update-*") + if err != nil { + return denied(exe, err) + } + f.Close() + return os.Remove(f.Name()) +} + +func denied(exe string, err error) error { + if errors.Is(err, fs.ErrPermission) { + return fmt.Errorf("selfupdate: cannot write to %s (%w); rerun as a user who can, e.g. sudo tend update, or reinstall tend into a directory you own", filepath.Dir(exe), err) + } + return fmt.Errorf("selfupdate: %w", err) +} + // replace swaps exe for bin. The new file is written beside exe so the final -// rename stays on one filesystem. Windows cannot overwrite a running image -// but can rename it, so the old one moves to exe.old first. +// rename stays on one filesystem, and synced so a crash cannot leave a +// truncated binary behind. Windows cannot overwrite a running image but can +// rename it, so the old one moves to exe.old first. func replace(exe string, bin []byte, windows bool) error { tmp, err := os.CreateTemp(filepath.Dir(exe), ".tend-update-*") if err != nil { - return fmt.Errorf("selfupdate: %w", err) + return denied(exe, err) } defer os.Remove(tmp.Name()) _, err = tmp.Write(bin) + if err == nil { + err = tmp.Sync() + } if cerr := tmp.Close(); err == nil { err = cerr } @@ -250,23 +281,23 @@ func replace(exe string, bin []byte, windows bool) error { return fmt.Errorf("selfupdate: %w", err) } if !windows { - return rename(tmp.Name(), exe) + return rename(exe, tmp.Name(), exe) } old := exe + ".old" os.Remove(old) - if err := rename(exe, old); err != nil { + if err := rename(exe, exe, old); err != nil { return err } - if err := rename(tmp.Name(), exe); err != nil { - _ = rename(old, exe) + if err := rename(exe, tmp.Name(), exe); err != nil { + _ = os.Rename(old, exe) return err } return nil } -func rename(from, to string) error { +func rename(exe, from, to string) error { if err := os.Rename(from, to); err != nil { - return fmt.Errorf("selfupdate: %w", err) + return denied(exe, err) } return nil } diff --git a/internal/selfupdate/update_test.go b/internal/selfupdate/update_test.go index ece1ed2..868a2a5 100644 --- a/internal/selfupdate/update_test.go +++ b/internal/selfupdate/update_test.go @@ -11,12 +11,17 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" "fmt" + "io/fs" "net/http" "net/http/httptest" "os" + "os/exec" "path/filepath" + "runtime" "strings" + "sync/atomic" "testing" "github.com/mohsensc/tend-cli/internal/fetch" @@ -255,6 +260,13 @@ func TestLatest(t *testing.T) { {"", "dev", "dev", false}, {"dev", "dev", "dev", false}, {"v1.3.9-4-gabc1234-dirty", "dev", "dev", false}, + {"v1.4.0-rc.1", "v1.4.0", "1.4.0", true}, + {"v1.4.0-beta2", "v1.4.0", "1.4.0", true}, + {"v1.5.0-rc.1", "v1.4.0", "1.4.0", false}, + {"v1.2.4-0.20261029120000-abcdef123456", "dev", "dev", false}, + {"v1.3.0+dirty", "dev", "dev", false}, + {"v1.3.0-rc.1+dirty", "dev", "dev", false}, + {"v1.3.0-rc.1-2-gabc1234", "dev", "dev", false}, } for _, tc := range tests { t.Run(tc.current, func(t *testing.T) { @@ -270,14 +282,25 @@ func TestLatest(t *testing.T) { } func TestLatestDevMakesNoRequest(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + reply(w, `{"tag_name": "v9.0.0"}`) + })) + defer srv.Close() old := latestURL - latestURL = "http://127.0.0.1:1/never" + latestURL = srv.URL defer func() { latestURL = old }() - if _, err := Latest(context.Background(), fetch.New("", "test"), "dev"); err != nil { - t.Fatal(err) + for _, v := range []string{"", "dev", "v1.2.4-0.20261029120000-abcdef123456", "v1.3.0+dirty"} { + if _, err := Latest(context.Background(), fetch.New("", "test"), v); err != nil { + t.Fatal(err) + } } - if _, err := Latest(context.Background(), fetch.New("", "test"), "1.0.0"); err == nil { - t.Fatal("a release build reached nothing and reported no error") + if n := hits.Load(); n != 0 { + t.Fatalf("development builds made %d requests", n) + } + if _, err := Latest(context.Background(), fetch.New("", "test"), "1.0.0"); err != nil || hits.Load() != 1 { + t.Fatalf("a release build made %d requests: %v", hits.Load(), err) } } @@ -345,3 +368,181 @@ func TestKeyMatchesActionPEM(t *testing.T) { t.Error("action/pubkey.pem and key.go hold different keys") } } + +func TestReadLimited(t *testing.T) { + if b, err := readLimited(bytes.NewReader(make([]byte, 64)), 64); err != nil || len(b) != 64 { + t.Errorf("a binary at the limit: %d bytes, %v", len(b), err) + } + if _, err := readLimited(bytes.NewReader(make([]byte, 65)), 64); err == nil || !strings.Contains(err.Error(), "larger than the limit") { + t.Errorf("a binary over the limit: %v", err) + } +} + +func TestReplaceInAReadOnlyDir(t *testing.T) { + if os.Geteuid() == 0 || runtime.GOOS == "windows" { + t.Skip("needs a directory this user cannot write") + } + dir := filepath.Join(t.TempDir(), "bin") + path := filepath.Join(dir, "tend") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("old binary"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + + for name, err := range map[string]error{ + "replace": replace(path, []byte("new"), false), + "writable": writable(path), + "apply": apply(context.Background(), fetch.New("", "test"), &ReleaseInfo{Tag: "v1.2.0", Version: "1.2.0"}, path, "linux", "amd64"), + } { + if err == nil || !strings.Contains(err.Error(), "cannot write to "+dir) || !strings.Contains(err.Error(), "sudo tend update") || !errors.Is(err, fs.ErrPermission) { + t.Errorf("%s: %v", name, err) + } + } + if got := read(t, path); got != "old binary" { + t.Errorf("binary = %q", got) + } +} + +func TestApplyThroughSymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks need privileges on Windows") + } + r := newRelease(t, "v1.2.0", map[string][]byte{ + "tend_1.2.0_linux_amd64.tar.gz": tarball(t, map[string]string{"tend": "new binary"}), + }) + r.serve(t) + dir := t.TempDir() + real := filepath.Join(dir, "opt", "tend") + link := filepath.Join(dir, "bin", "tend") + for _, d := range []string{filepath.Dir(real), filepath.Dir(link)} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(real, []byte("old binary"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(real, link); err != nil { + t.Fatal(err) + } + exe, err := filepath.EvalSymlinks(link) + if err != nil { + t.Fatal(err) + } + if err := apply(context.Background(), fetch.New("", "test"), &ReleaseInfo{Tag: "v1.2.0", Version: "1.2.0"}, exe, "linux", "amd64"); err != nil { + t.Fatal(err) + } + if got := read(t, real); got != "new binary" { + t.Errorf("real file = %q", got) + } + if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Errorf("the symlink was replaced: %v %v", fi, err) + } + if got := read(t, link); got != "new binary" { + t.Errorf("through the symlink = %q", got) + } +} + +const childEnv = "TEND_SELFUPDATE_CHILD" + +func TestSelfUpdateChild(t *testing.T) { + switch os.Getenv(childEnv) { + case "apply": + latestURL, assetsURL = os.Getenv("TEND_TEST_LATEST"), os.Getenv("TEND_TEST_ASSETS") + PublicKey, _ = hex.DecodeString(os.Getenv("TEND_TEST_KEY")) + if err := Apply(context.Background(), fetch.New("", "test"), &ReleaseInfo{Tag: "v1.2.0", Version: "1.2.0"}); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(3) + } + os.Exit(0) + case "cleanup": + Cleanup() + os.Exit(0) + } +} + +func runChild(t *testing.T, path, mode string, env ...string) { + t.Helper() + cmd := exec.Command(path, "-test.run=^TestSelfUpdateChild$") + cmd.Env = append(append(os.Environ(), childEnv+"="+mode), env...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%s: %v\n%s", mode, err, out) + } +} + +func TestApplyReplacesTheRunningBinary(t *testing.T) { + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + bin, err := os.ReadFile(self) + if err != nil { + t.Fatal(err) + } + name := fmt.Sprintf("tend_1.2.0_%s_%s.tar.gz", runtime.GOOS, runtime.GOARCH) + archive := tarball(t, map[string]string{"tend": string(bin)}) + exeName := "tend" + if runtime.GOOS == "windows" { + name = strings.TrimSuffix(name, ".tar.gz") + ".zip" + archive = zipfile(t, map[string]string{"tend.exe": string(bin)}) + exeName = "tend.exe" + } + r := newRelease(t, "v1.2.0", map[string][]byte{name: archive}) + r.serve(t) + + dir := t.TempDir() + real := filepath.Join(dir, "opt", exeName) + if err := os.MkdirAll(filepath.Dir(real), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(real, bin, 0o755); err != nil { + t.Fatal(err) + } + start := real + if runtime.GOOS != "windows" { + start = filepath.Join(dir, "bin", exeName) + if err := os.MkdirAll(filepath.Dir(start), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(real, start); err != nil { + t.Fatal(err) + } + } + before, err := os.Stat(real) + if err != nil { + t.Fatal(err) + } + + runChild(t, start, "apply", "TEND_TEST_LATEST="+latestURL, "TEND_TEST_ASSETS="+assetsURL, "TEND_TEST_KEY="+hex.EncodeToString(PublicKey)) + + after, err := os.Stat(real) + if err != nil { + t.Fatal(err) + } + if os.SameFile(before, after) { + t.Fatal("the binary was not replaced") + } + if got, _ := os.ReadFile(real); !bytes.Equal(got, bin) { + t.Fatal("the new binary differs from the release") + } + if start != real { + if fi, err := os.Lstat(start); err != nil || fi.Mode()&os.ModeSymlink == 0 { + t.Fatalf("the symlink the binary ran from was replaced: %v", err) + } + } + _, oldErr := os.Stat(real + ".old") + if (oldErr == nil) != (runtime.GOOS == "windows") { + t.Fatalf(".old present = %v on %s", oldErr == nil, runtime.GOOS) + } + + runChild(t, start, "cleanup") + if _, err := os.Stat(real + ".old"); !os.IsNotExist(err) { + t.Errorf("Cleanup left %s.old: %v", exeName, err) + } +} diff --git a/internal/source/eol.go b/internal/source/eol.go index 89338b3..fd9a4c8 100644 --- a/internal/source/eol.go +++ b/internal/source/eol.go @@ -29,6 +29,7 @@ var eolProducts = map[string]string{ "mysql": "mysql", "mariadb": "mariadb", "redis": "redis", + "mongo": "mongodb", "nginx": "nginx", "alpine": "alpine-linux", "debian": "debian", diff --git a/internal/source/notes.go b/internal/source/notes.go index 462a5a6..eeb6f17 100644 --- a/internal/source/notes.go +++ b/internal/source/notes.go @@ -3,6 +3,7 @@ package source import ( "context" "fmt" + "maps" "regexp" "slices" "strings" @@ -80,8 +81,13 @@ func releaseNotes(ctx context.Context, f core.Fetcher, owner, repo, pkg string, hits = append(hits, hit{v, r}) } slices.SortFunc(hits, func(a, b hit) int { return ver.Compare(b.v, a.v) }) + vs := make([]ver.V, len(hits)) + for i, h := range hits { + vs[i] = h.v + } var res []core.Evidence - for _, h := range hits[:min(len(hits), notesMax)] { + for _, i := range pickNotes(vs) { + h := hits[i] title := h.r.Tag if h.r.Name != "" && h.r.Name != h.r.Tag { title += " " + h.r.Name @@ -145,8 +151,13 @@ func changelogNotes(ctx context.Context, f core.Fetcher, owner, repo string, spa continue } slices.SortFunc(hits, func(a, b section) int { return ver.Compare(b.v, a.v) }) + vs := make([]ver.V, len(hits)) + for i, h := range hits { + vs[i] = h.v + } var res []core.Evidence - for _, s := range hits[:min(len(hits), notesMax)] { + for _, i := range pickNotes(vs) { + s := hits[i] res = append(res, core.Evidence{ Source: "changelog", Title: s.title, @@ -159,6 +170,36 @@ func changelogNotes(ctx context.Context, f core.Fetcher, owner, repo string, spa return nil, first } +// majorNotes caps how many first releases of a major the notes add past +// the newest notesMax. +const majorNotes = 4 + +// pickNotes picks, from versions newest first, which releases' notes to +// quote: the newest notesMax, and the first release of each major the range +// crosses, where a rewrite such as openai 1.0.0 says what breaks, however +// many releases came after it. It returns indexes, newest first. +func pickNotes(vs []ver.V) []int { + keep := map[int]bool{} + for i := range min(len(vs), notesMax) { + keep[i] = true + } + first := map[int]int{} + for i, v := range vs { + first[v.Major()] = i + } + if len(first) < 2 { + return slices.Sorted(maps.Keys(keep)) + } + added := 0 + for i := len(vs) - 1; i >= 0 && added < majorNotes; i-- { + if first[vs[i].Major()] == i && !keep[i] { + keep[i] = true + added++ + } + } + return slices.Sorted(maps.Keys(keep)) +} + type section struct { v ver.V title string diff --git a/internal/source/notes_test.go b/internal/source/notes_test.go index db4b3d8..22cf8a8 100644 --- a/internal/source/notes_test.go +++ b/internal/source/notes_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/ver" ) const ( @@ -375,3 +376,20 @@ func TestMentions(t *testing.T) { }) } } + +func TestPickNotesKeepsMajors(t *testing.T) { + names := []string{"3.37.0", "3.36.0", "3.35.0", "3.34.0", "3.33.0", "3.32.0", "3.31.0", "3.30.0", "3.0.0", "2.5.0", "2.0.0", "1.2.0", "1.0.0"} + var vs []ver.V + for _, s := range names { + v, _ := ver.Parse(s) + vs = append(vs, v) + } + var got []string + for _, i := range pickNotes(vs) { + got = append(got, names[i]) + } + want := []string{"3.37.0", "3.36.0", "3.35.0", "3.34.0", "3.33.0", "3.32.0", "3.31.0", "3.30.0", "3.0.0", "2.0.0", "1.0.0"} + if !reflect.DeepEqual(got, want) { + t.Errorf("picked %v, want %v", got, want) + } +} diff --git a/internal/source/osv.go b/internal/source/osv.go index e892b56..3869e7e 100644 --- a/internal/source/osv.go +++ b/internal/source/osv.go @@ -4,7 +4,9 @@ import ( "context" "encoding/json" "fmt" + "maps" "net/url" + "regexp" "slices" "strings" "time" @@ -12,6 +14,7 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/eco" "github.com/mohsensc/tend-cli/internal/fetch" + "github.com/mohsensc/tend-cli/internal/ver" ) const ( @@ -63,7 +66,10 @@ type osvEntry struct { } `json:"severity"` Affected []struct { Package osvPkg `json:"package"` - Ranges []struct { + DB struct { + Informational string `json:"informational"` + } `json:"database_specific"` + Ranges []struct { Type string `json:"type"` Events []map[string]string `json:"events"` } `json:"ranges"` @@ -88,31 +94,187 @@ func (s *OSV) Changes(ctx context.Context, inv *core.Inventory) ([]core.Change, if err != nil { return nil, err } - var res []core.Change + var hit []*hitDep for _, d := range inv.Deps { u := upstream(s.Upstream, d) q, ok := osvFor(u) if !ok { continue } - var advs []advisory - // One issue can come back under several ids, a GitHub advisory and - // its Go or PyPI twin among them; the first stands for the rest. - taken := map[string]bool{} - for _, id := range hits[q] { - e := entries[id] - if e == nil || e.Withdrawn != "" || taken[id] { + h := &hitDep{d: d, u: u, q: q, taken: map[string]bool{}} + h.take(hits[q], entries, q) + hit = append(hit, h) + } + if err := s.clear(ctx, hit, entries); err != nil { + return nil, err + } + var res []core.Change + for _, h := range hit { + res = append(res, securityChanges(h.d, h.advs)...) + if len(h.notices) > 0 { + res = append(res, notice(h.d, h.notices)) + } + } + return res, nil +} + +// hitDep is what OSV says of one dep: the advisories that hit it, the +// notices about it, and the ids already counted. +type hitDep struct { + d, u core.Dep + q osvQuery + advs []advisory + notices []core.Evidence + taken map[string]bool +} + +// take counts the advisories ids name against the version q asks about. One +// issue can come back under several ids, a GitHub advisory and its Go or +// PyPI twin among them; the first stands for the rest. +func (h *hitDep) take(ids []string, entries map[string]*osvEntry, q osvQuery) []advisory { + var res []advisory + for _, id := range ids { + e := entries[id] + if e == nil || e.Withdrawn != "" || h.taken[id] { + continue + } + h.taken[id] = true + for _, a := range e.Aliases { + h.taken[a] = true + } + a := e.advisory(h.u, q) + switch e.informational(h.u, q) { + case "unmaintained", "notice": + h.notices = append(h.notices, a.ev) + continue + case "unsound": + a.severity = "low" + } + h.advs = append(h.advs, a) + res = append(res, a) + } + return res +} + +// fix is the release that fixes every advisory h has a fix for, "" for none. +func (h *hitDep) fix() string { + res := "" + for _, a := range h.advs { + if a.fixed != "" && (res == "" || ver.Less(res, a.fixed)) { + res = a.fixed + } + } + return res +} + +// clearMax caps how many times a fix is checked against OSV for advisories +// of its own. +const clearMax = 5 + +// clear checks the release each dep's fix moves it to against OSV, since a +// release can fix the advisories on the version in use and be hit by +// others that never touched it: axios 0.21.1 moves to 0.33.0, which two +// advisories introduced since 0.27.2 still hit. Each fix rises to one +// those miss too, a round at a time, and the advisories that hit it are +// counted with the rest; merge then moves them all to the highest fix. +func (s *OSV) clear(ctx context.Context, hit []*hitDep, entries map[string]*osvEntry) error { + want := map[*hitDep]string{} + for _, h := range hit { + want[h] = h.fix() + } + for range clearMax { + at := map[osvQuery][]*hitDep{} + var qs []osvQuery + for _, h := range hit { + if want[h] == "" { continue } - taken[id] = true - for _, a := range e.Aliases { - taken[a] = true + q := h.q + q.Version = want[h] + if at[q] == nil { + qs = append(qs, q) } - advs = append(advs, e.advisory(u, q)) + at[q] = append(at[q], h) + } + if len(qs) == 0 { + break + } + hits, err := s.query(ctx, qs) + if err != nil { + return err + } + fresh := map[osvQuery][]string{} + for q, ids := range hits { + for _, id := range ids { + if _, ok := entries[id]; !ok { + fresh[q] = append(fresh[q], id) + } + } + } + more, err := s.entries(ctx, fresh) + if err != nil { + return err + } + maps.Copy(entries, more) + moved := false + for _, q := range qs { + for _, h := range at[q] { + next := want[h] + for _, a := range h.take(hits[q], entries, q) { + if a.fixed != "" && ver.Less(next, a.fixed) { + next = a.fixed + } + } + if next != want[h] { + want[h], moved = next, true + } else { + want[h] = "" + } + } + } + if !moved { + break } - res = append(res, securityChanges(d, advs)...) } - return res, nil + return nil +} + +// notice is what an informational advisory, such as RustSec's +// unmaintained, says of d: a deprecation with no fix, with the ways off it +// the catalog or the notice itself names. +func notice(d core.Dep, evs []core.Evidence) core.Change { + ch := core.Change{Kind: core.Deprecation, Deps: []core.Dep{d}, Evidence: evs} + if one, opts, ok := Replacement(d.Ecosystem, d.Name); ok { + if one != nil { + opts = []core.Option{*one} + } + ch.Options = opts + } else { + for _, ev := range evs { + if m := useInstead.FindStringSubmatch(ev.Title + "\n" + ev.Text); m != nil { + ch.Options = []core.Option{{Title: "Switch to " + m[1], Detail: ev.URL, ToName: m[1]}} + break + } + } + } + ch.ID = core.ChangeID(&ch) + return ch +} + +// useInstead finds the replacement a notice names: "use `terminal_size` +// instead", "Consider using [`nu-ansi-term`]". +var useInstead = regexp.MustCompile(`(?i)(?:use|consider using|switch to|migrate to)\s+\[?` + "`" + `([A-Za-z0-9_.:/-]+)` + "`") + +// informational is what kind of notice e is for d, as RustSec marks one in +// the affected entry: unmaintained, unsound or notice; "" for a +// vulnerability. +func (e *osvEntry) informational(d core.Dep, q osvQuery) string { + for _, a := range e.Affected { + if a.Package.Ecosystem == q.Package.Ecosystem && sameName(d.Ecosystem, a.Package.Name, d.Name) { + return a.DB.Informational + } + } + return "" } // upstream is d as its registry names it, d itself when there is no mapping. @@ -132,12 +294,43 @@ func osvFor(d core.Dep) (osvQuery, bool) { return osvQuery{}, false } v, ok := plainVersion(d) + if !ok && d.Version == "" { + v, ok = reqFloor(d.Req) + } if !ok { return osvQuery{}, false } return osvQuery{Package: osvPkg{Name: d.Name, Ecosystem: e.Traits().OSV}, Version: v}, true } +// reqFloor is the least version a requirement admits, for a dep no +// lockfile pins: "0.2.11" for cargo's 0.2.11 or ^0.2.11, 2.1 for >=2.1. A +// requirement with no floor, * or <3, or one that leaves the floor out, as +// >1.0 does, has none. The manifest allows that version, so an advisory on +// it is a real exposure, and raising the floor fixes it. +func reqFloor(req string) (string, bool) { + first := strings.TrimSpace(req) + if i := strings.IndexAny(first, ",|;"); i >= 0 { + first = strings.TrimSpace(first[:i]) + } + if f := strings.Fields(first); len(f) > 1 && !strings.ContainsAny(f[0], "0123456789") { + first = f[0] + f[1] + } else if len(f) > 0 { + first = f[0] + } + v := strings.TrimLeft(first, "^~=v ") + if strings.HasPrefix(first, ">=") { + v = strings.TrimPrefix(strings.TrimSpace(strings.TrimPrefix(first, ">=")), "v") + } + if v == "" || strings.ContainsAny(v, "<>*xX!") { + return "", false + } + if _, ok := ver.Parse(v); !ok { + return "", false + } + return v, true +} + // query returns the advisory ids per query, following page tokens until each // query is exhausted. func (s *OSV) query(ctx context.Context, qs []osvQuery) (map[osvQuery][]string, error) { diff --git a/internal/source/osv_test.go b/internal/source/osv_test.go index 548e9a8..05c3e08 100644 --- a/internal/source/osv_test.go +++ b/internal/source/osv_test.go @@ -148,6 +148,9 @@ func TestOSVPaging(t *testing.T) { if len(req.Queries) != 1 { return status(400) } + if req.Queries[0].Version != "1.0.0" { + return text(`{"results":[{"vulns":[]}]}`) + } tok := req.Queries[0].PageToken tokens = append(tokens, tok) switch tok { @@ -249,7 +252,10 @@ func TestOSVChanges(t *testing.T) { if len(merged.Evidence) != 2 { t.Fatalf("evidence = %+v, want both advisories", merged.Evidence) } - ev := merged.Evidence[0] + if merged.Evidence[0].Title != "A2 second" { + t.Errorf("evidence starts with %+v, want the critical advisory", merged.Evidence[0]) + } + ev := merged.Evidence[1] if ev.Source != "osv" || ev.Title != "A1 first" || ev.URL != "https://osv.dev/vulnerability/A1" { t.Errorf("evidence = %+v", ev) } @@ -521,3 +527,100 @@ func TestOSVUpstreamRenamed(t *testing.T) { t.Fatalf("changes = %+v", got) } } + +func TestReqFloor(t *testing.T) { + for req, want := range map[string]string{ + "0.2.11": "0.2.11", "^0.2.11": "0.2.11", "~1.4": "1.4", "=2.0.1": "2.0.1", ">= 2.1, < 3": "2.1", ">=1.0": "1.0", + "*": "", "<3": "", ">1.0": "", "1.x": "", "": "", + } { + got, ok := reqFloor(req) + if got != want || ok != (want != "") { + t.Errorf("reqFloor(%q) = %q, %v; want %q", req, got, ok, want) + } + } + q, ok := osvFor(core.Dep{Ecosystem: core.Cargo, Name: "atty", Req: "0.2.11"}) + if !ok || q.Version != "0.2.11" || q.Package.Ecosystem != "crates.io" { + t.Errorf("osvFor = %+v, %v", q, ok) + } +} + +// RustSec's informational notices are no vulnerabilities: unmaintained is a +// deprecation with the way off its title names, unsound a low one. +func TestOSVInformational(t *testing.T) { + info := func(name, kind string) map[string]any { + a := affected(name, "crates.io", introduced("0")) + a["database_specific"] = map[string]any{"informational": kind} + return a + } + hits := osvHits{"term_size@0.3.1": {"R1"}, "dirs-sys@0.3.4": {"R2"}, "lru@0.6.0": {"R3"}} + details := map[string]any{ + "R1": map[string]any{"id": "RUSTSEC-2020-0163", "summary": "`term_size` is unmaintained; use `terminal_size` instead", "affected": []any{info("term_size", "unmaintained")}}, + "R2": map[string]any{"id": "RUSTSEC-2020-0053", "summary": "dirs-sys is unmaintained, use `dirs-sys-next` instead", "affected": []any{info("dirs-sys", "unmaintained")}}, + "R3": map[string]any{"id": "RUSTSEC-2021-0130", "summary": "unsound IterMut", "database_specific": map[string]any{"severity": "HIGH"}, + "affected": []any{func() map[string]any { + a := affected("lru", "crates.io", introduced("0"), fixed("0.7.1")) + a["database_specific"] = map[string]any{"informational": "unsound"} + return a + }()}}, + } + inv := &core.Inventory{Deps: []core.Dep{dep(core.Cargo, "term_size", "0.3.1"), dep(core.Cargo, "dirs-sys", "0.3.4"), dep(core.Cargo, "lru", "0.6.0")}} + got, err := (&OSV{Fetch: osvServer(hits, details)}).Changes(context.Background(), inv) + if err != nil { + t.Fatal(err) + } + if len(got) != 3 { + t.Fatalf("changes = %+v", got) + } + by := map[string]core.Change{} + for _, ch := range got { + by[ch.Deps[0].Name] = ch + } + if c := by["term_size"]; c.Kind != core.Deprecation || len(c.Options) != 1 || c.Options[0].ToName != "terminal_size" { + t.Errorf("term_size = %+v", c) + } + if c := by["dirs-sys"]; c.Kind != core.Deprecation || len(c.Options) != 1 || c.Options[0].ToName != "dirs-sys-next" { + t.Errorf("dirs-sys = %+v", c) + } + if c := by["lru"]; c.Kind != core.Security || c.Severity != "low" || c.To != "0.7.1" { + t.Errorf("lru = %+v", c) + } +} + +// A fix that other advisories still hit is not where a security change +// stops: axios 0.21.1's fix to 0.33.0 rises to 0.34.0, then past an +// advisory of that release too, and one with no fix stays on the record. +func TestOSVClearsTheTarget(t *testing.T) { + hits := osvHits{ + "axios@0.21.1": {"A"}, + "axios@0.33.0": {"B", "C"}, + "axios@0.34.0": {"D", "N"}, + "axios@0.35.0": {"N"}, + } + details := map[string]any{ + "A": map[string]any{"id": "A", "summary": "a", "database_specific": map[string]any{"severity": "HIGH"}, "affected": []any{affected("axios", "npm", introduced("0"), fixed("0.33.0"))}}, + "B": map[string]any{"id": "B", "summary": "b", "database_specific": map[string]any{"severity": "HIGH"}, "affected": []any{affected("axios", "npm", introduced("0.27.2"), fixed("0.34.0"))}}, + "C": map[string]any{"id": "C", "summary": "c", "aliases": []string{"B"}, "affected": []any{affected("axios", "npm", introduced("0.28.0"), fixed("0.34.0"))}}, + "D": map[string]any{"id": "D", "summary": "d", "affected": []any{affected("axios", "npm", introduced("0.34.0"), fixed("0.35.0"))}}, + "N": map[string]any{"id": "N", "summary": "n", "affected": []any{affected("axios", "npm", introduced("0"))}}, + } + f := osvServer(hits, details) + got, err := (&OSV{Fetch: f}).Changes(context.Background(), &core.Inventory{Deps: []core.Dep{dep(core.Npm, "axios", "0.21.1")}}) + if err != nil { + t.Fatal(err) + } + var rows []string + for _, c := range got { + rows = append(rows, c.To+":"+strings.Join(tagsOf(c.Evidence), ",")) + } + if want := []string{"0.33.0:A", "0.34.0:B,C", "0.35.0:D", ":N"}; !reflect.DeepEqual(rows, want) { + t.Errorf("changes = %v, want %v", rows, want) + } +} + +func tagsOf(evs []core.Evidence) []string { + var res []string + for _, ev := range evs { + res = append(res, strings.Fields(ev.Title)[0]) + } + return res +} diff --git a/internal/source/replace.go b/internal/source/replace.go index c0d339f..7351ed7 100644 --- a/internal/source/replace.go +++ b/internal/source/replace.go @@ -9,6 +9,7 @@ import ( "gopkg.in/yaml.v3" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/eco" ) //go:embed replacements.yml @@ -18,12 +19,16 @@ type replacement struct { Eco string `yaml:"eco"` Name string `yaml:"name"` To string `yaml:"to"` + Safe bool `yaml:"safe"` Options []struct { To string `yaml:"to"` Why string `yaml:"why"` // what choosing it means, next to the others } `yaml:"options"` Note string `yaml:"note"` URL string `yaml:"url"` + // Instead is the way off a package that is no package to move to: a + // standard library call, or a plain run step in place of an Action. + Instead string `yaml:"instead"` } var table = sync.OnceValue(func() map[string]replacement { @@ -33,21 +38,26 @@ var table = sync.OnceValue(func() map[string]replacement { } res := make(map[string]replacement, len(rows)) for _, r := range rows { - res[r.Eco+"/"+r.Name] = r + res[r.Eco+"/"+eco.Canon(r.Eco, r.Name)] = r } return res }) -// Replacement returns the single mechanical replacement for a deprecated -// package, or the options when there is more than one way off it. -func Replacement(eco, name string) (*core.Option, []core.Option, bool) { - r, ok := table()[eco+"/"+name] +// Replacement returns the single replacement for a deprecated package, or the +// options when there is more than one way off it. Only a replacement that +// keeps the import name and API is Safe; the others need their call sites +// moved. +func Replacement(ecosystem, name string) (*core.Option, []core.Option, bool) { + r, ok := table()[ecosystem+"/"+eco.Canon(ecosystem, name)] if !ok { return nil, nil, false } detail := strings.TrimSpace(r.Note + " " + r.URL) if r.To != "" { - return &core.Option{Title: "Switch to " + r.To, Detail: detail, Safe: true, ToName: r.To}, nil, true + return &core.Option{Title: "Switch to " + r.To, Detail: detail, Safe: r.Safe, ToName: r.To}, nil, true + } + if len(r.Options) == 0 && r.Instead != "" { + return nil, []core.Option{{Title: r.Instead, Detail: detail}}, true } if len(r.Options) == 0 { return nil, nil, false diff --git a/internal/source/replace_test.go b/internal/source/replace_test.go index 18daff3..e52c420 100644 --- a/internal/source/replace_test.go +++ b/internal/source/replace_test.go @@ -52,18 +52,26 @@ func TestReplacement(t *testing.T) { tests := []struct { name, eco, pkg string one string + safe bool many []string found bool }{ - {"single", core.Npm, "node-sass", "sass", nil, true}, - {"single go", core.Go, "github.com/dgrijalva/jwt-go", "github.com/golang-jwt/jwt/v5", nil, true}, - {"several", core.Npm, "moment", "", []string{"dayjs", "luxon", "date-fns"}, true}, - {"several request", core.Npm, "request", "", []string{"undici", "node-fetch", "axios"}, true}, - {"other ecosystem same name", core.Pip, "request", "", nil, false}, - {"unknown", core.Npm, "left-pad", "", nil, false}, - {"glob row is never matched", core.Npm, "@types/*", "", nil, false}, - {"glob query", core.Npm, "@types/node", "", nil, false}, - {"note only", core.Nuget, "microsoft.aspnet.webapi.client", "", nil, false}, + {"single", core.Npm, "node-sass", "sass", false, nil, true}, + {"single go", core.Go, "github.com/dgrijalva/jwt-go", "github.com/golang-jwt/jwt/v5", false, nil, true}, + {"drop-in", core.Pip, "pycrypto", "pycryptodome", true, nil, true}, + {"pip name as written", core.Pip, "PyCrypto", "pycryptodome", true, nil, true}, + {"pip name in capitals", core.Pip, "SKLearn", "scikit-learn", true, nil, true}, + {"composer case", core.Composer, "Fzaninotto/Faker", "fakerphp/faker", true, nil, true}, + {"new api", core.Pip, "nose", "pytest", false, nil, true}, + {"npm is case sensitive", core.Npm, "Node-Sass", "", false, nil, false}, + {"several", core.Npm, "moment", "", false, []string{"dayjs", "luxon", "date-fns"}, true}, + {"several request", core.Npm, "request", "", false, []string{"undici", "node-fetch", "axios"}, true}, + {"other ecosystem same name", core.Pip, "request", "", false, nil, false}, + {"unknown", core.Npm, "left-pad", "", false, nil, false}, + {"glob row is never matched", core.Npm, "@types/*", "", false, nil, false}, + {"glob query", core.Npm, "@types/node", "", false, nil, false}, + {"note only", core.Nuget, "microsoft.aspnet.webapi.client", "", false, nil, false}, + {"note only as nuget writes it", core.Nuget, "Microsoft.AspNet.WebApi.Client", "", false, nil, false}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -73,8 +81,8 @@ func TestReplacement(t *testing.T) { } switch { case tc.one != "": - if one == nil || many != nil || one.ToName != tc.one || !one.Safe { - t.Fatalf("one = %+v, many = %+v; want a safe swap to %s", one, many, tc.one) + if one == nil || many != nil || one.ToName != tc.one || one.Safe != tc.safe { + t.Fatalf("one = %+v, many = %+v; want a swap to %s, safe %v", one, many, tc.one, tc.safe) } case tc.many != nil: var got []string @@ -96,6 +104,28 @@ func TestReplacement(t *testing.T) { } } +func TestSafeReplacementsKeepTheirImport(t *testing.T) { + sameImport := map[string]string{ + "pip/pycrypto": "Crypto", + "pip/sklearn": "sklearn", + "composer/fzaninotto/faker": `Faker\`, + "actions/actions/setup-ruby": "ruby-version input", + } + var rows []replacement + if err := yaml.Unmarshal(replacements, &rows); err != nil { + t.Fatal(err) + } + for _, r := range rows { + key := r.Eco + "/" + r.Name + if r.Safe && r.To == "" { + t.Errorf("%s is safe with nothing to switch to", key) + } + if _, ok := sameImport[key]; r.Safe != ok { + t.Errorf("%s: safe = %v; a swap is safe only when code keeps working unchanged", key, r.Safe) + } + } +} + func TestReplacementDetail(t *testing.T) { one, _, _ := Replacement(core.Npm, "node-sass") if one.Detail != "https://sass-lang.com/blog/libsass-is-deprecated/" || one.Title != "Switch to sass" { @@ -117,3 +147,19 @@ func TestReplacementDetail(t *testing.T) { t.Errorf("option = %+v", gone) } } + +// A way off that is no package is an option tend never takes itself. +func TestReplacementInstead(t *testing.T) { + for _, c := range []struct{ eco, name, title string }{ + {core.Actions, "actions-rs/toolchain", "Switch to dtolnay/rust-toolchain"}, + {core.Cargo, "atty", "Use std::io::IsTerminal"}, + } { + one, opts, ok := Replacement(c.eco, c.name) + if !ok || one != nil || len(opts) != 1 || opts[0].Title != c.title || opts[0].ToName != "" || opts[0].Safe { + t.Errorf("Replacement(%s) = %+v, %+v, %v", c.name, one, opts, ok) + } + } + if one, _, ok := Replacement(core.Cargo, "term_size"); !ok || one == nil || one.ToName != "terminal_size" { + t.Errorf("term_size = %+v", one) + } +} diff --git a/internal/source/replacements.yml b/internal/source/replacements.yml index 7169580..b4f1fbe 100644 --- a/internal/source/replacements.yml +++ b/internal/source/replacements.yml @@ -17,17 +17,29 @@ - {to: luxon, why: "from moment's maintainers; immutable, with time zones built in, but a different API"} - {to: date-fns, why: "plain functions over the native Date and tree-shakes well; every call site changes shape"} - {eco: npm, name: "@types/*", note: "follows its package"} # handled in plan grouping, listed for readers -- {eco: pip, name: pycrypto, to: pycryptodome, url: https://github.com/pycrypto/pycrypto/issues/173} +- {eco: pip, name: pycrypto, to: pycryptodome, safe: true, url: https://github.com/pycrypto/pycrypto/issues/173} - {eco: pip, name: nose, to: pytest, url: https://nose.readthedocs.io/en/latest/#note-to-users} -- {eco: pip, name: sklearn, to: scikit-learn, url: https://pypi.org/project/sklearn/} +- {eco: pip, name: sklearn, to: scikit-learn, safe: true, url: https://pypi.org/project/sklearn/} - {eco: go, name: github.com/golang/protobuf, to: google.golang.org/protobuf, url: https://go.dev/blog/protobuf-apiv2} - {eco: go, name: github.com/dgrijalva/jwt-go, to: github.com/golang-jwt/jwt/v5, url: https://github.com/dgrijalva/jwt-go/issues/462} - {eco: go, name: github.com/pkg/errors, to: errors, note: "stdlib errors since Go 1.13; archived", url: https://github.com/pkg/errors} -- {eco: go, name: golang.org/x/lint, to: honnef.co/go/tools/cmd/staticcheck, url: https://github.com/golang/lint} +- {eco: go, name: golang.org/x/lint, to: honnef.co/go/tools, note: "run its staticcheck command in place of golint", url: https://github.com/golang/lint} - {eco: go, name: github.com/satori/go.uuid, to: github.com/google/uuid, url: https://github.com/satori/go.uuid/issues/73} - {eco: actions, name: actions/create-release, to: softprops/action-gh-release, url: https://github.com/actions/create-release} - {eco: actions, name: actions/upload-release-asset, to: softprops/action-gh-release, url: https://github.com/actions/upload-release-asset} -- {eco: actions, name: actions/setup-ruby, to: ruby/setup-ruby, url: https://github.com/actions/setup-ruby} +- {eco: actions, name: actions/setup-ruby, to: ruby/setup-ruby, safe: true, url: https://github.com/actions/setup-ruby} - {eco: rubygems, name: therubyracer, to: mini_racer, url: https://github.com/rubyjs/therubyracer} -- {eco: composer, name: fzaninotto/faker, to: fakerphp/faker, url: https://github.com/fzaninotto/Faker} +- {eco: composer, name: fzaninotto/faker, to: fakerphp/faker, safe: true, url: https://github.com/fzaninotto/Faker} - {eco: nuget, name: microsoft.aspnet.webapi.client, note: "see alternatePackage from nuget", url: https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client} +- {eco: cargo, name: term_size, to: terminal_size, url: https://rustsec.org/advisories/RUSTSEC-2020-0163} +- {eco: cargo, name: atty, instead: "Use std::io::IsTerminal", note: "in the standard library since Rust 1.70", url: https://rustsec.org/advisories/RUSTSEC-2024-0375} +- eco: cargo + name: ansi_term + url: https://rustsec.org/advisories/RUSTSEC-2021-0139 + options: + - {to: nu-ansi-term, why: "a maintained fork with the same API, so most code carries over"} + - {to: owo-colors, why: "zero-allocation and no_std, with a different, trait-based API"} +- {eco: actions, name: actions-rs/toolchain, instead: "Switch to dtolnay/rust-toolchain", note: "pinned by a toolchain ref such as @stable or @1.80; its override, profile and default inputs have no equivalent, while components and targets carry over", url: https://github.com/actions-rs/toolchain} +- {eco: actions, name: actions-rs/cargo, instead: "Replace it with a plain `run: cargo ` step", note: "archived", url: https://github.com/actions-rs/cargo} +- {eco: actions, name: actions-rs/audit-check, instead: "Switch to rustsec/audit-check", note: "archived; the inputs carry over", url: https://github.com/actions-rs/audit-check} +- {eco: actions, name: actions-rs/clippy-check, instead: "Run `cargo clippy` in a step", note: "archived", url: https://github.com/actions-rs/clippy-check} diff --git a/internal/source/security.go b/internal/source/security.go index 55165cb..ebdad62 100644 --- a/internal/source/security.go +++ b/internal/source/security.go @@ -23,13 +23,15 @@ var severityRank = map[string]int{"": 0, "low": 1, "moderate": 2, "high": 3, "cr // securityChanges folds the advisories that hit dep d into one change per fixed version. func securityChanges(d core.Dep, advs []advisory) []core.Change { + advs = slices.Clone(advs) + slices.SortStableFunc(advs, func(x, y advisory) int { return severityRank[y.severity] - severityRank[x.severity] }) byTo := map[string]*core.Change{} var tos []string for _, a := range advs { to := asWritten(d.Version, a.fixed) c := byTo[to] if c == nil { - c = &core.Change{Kind: core.Security, Deps: []core.Dep{d}, To: to, Level: ver.Step(d.Version, to)} + c = &core.Change{Kind: core.Security, Deps: []core.Dep{d}, To: to, Level: ver.StepIn(d.Ecosystem, d.Version, to)} byTo[to] = c tos = append(tos, to) } diff --git a/internal/source/testdata/recorded/POST_api.osv.dev_cef841434851.json b/internal/source/testdata/recorded/POST_api.osv.dev_cef841434851.json new file mode 100644 index 0000000..70d1213 --- /dev/null +++ b/internal/source/testdata/recorded/POST_api.osv.dev_cef841434851.json @@ -0,0 +1,10 @@ +{ + "url": "https://api.osv.dev/v1/querybatch", + "status": 200, + "header": { + "Content-Type": [ + "application/json" + ] + }, + "body": "{\"results\":[{}]}" +} diff --git a/internal/source/util_test.go b/internal/source/util_test.go index b877541..8f1abcf 100644 --- a/internal/source/util_test.go +++ b/internal/source/util_test.go @@ -185,7 +185,7 @@ func TestSecurityChangesOrder(t *testing.T) { have = append(have, c.To+"/"+c.Severity+"/"+c.Level+"/"+strings.Join(tags(c.Evidence), ",")) } want := []string{ - "v1.9.0/critical/minor/nine,nine again", + "v1.9.0/critical/minor/nine again,nine", "v1.10.0//minor/ten", "v2.0.0//major/major", "/low//none", diff --git a/internal/state/lock_other.go b/internal/state/lock_other.go new file mode 100644 index 0000000..0ece602 --- /dev/null +++ b/internal/state/lock_other.go @@ -0,0 +1,54 @@ +//go:build !unix + +package state + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "time" +) + +// StaleAfter is how old a lock gets before another run may take it over. +const StaleAfter = 2 * time.Hour + +// Lock takes the run lock in dir. Where the system has no lock a process +// holds until it dies, a lock older than two hours is stale. Releasing it +// leaves alone a lock another run took over in the meantime. +func Lock(dir string) (release func(), err error) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + p := filepath.Join(dir, lockName) + for range 2 { + f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if err == nil { + mine := fmt.Sprintf("%d %d\n", os.Getpid(), now().Unix()) + _, err = f.WriteString(mine) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(p) + return nil, err + } + return func() { + if b, err := os.ReadFile(p); err == nil && string(b) == mine { + os.Remove(p) + } + }, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, err + } + held := readLock(p) + if now().Sub(held.At) < StaleAfter { + return nil, held + } + if err := os.Remove(p); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + } + return nil, fmt.Errorf("state: cannot take %s", p) +} diff --git a/internal/state/lock_other_test.go b/internal/state/lock_other_test.go new file mode 100644 index 0000000..27534fa --- /dev/null +++ b/internal/state/lock_other_test.go @@ -0,0 +1,66 @@ +//go:build !unix + +package state + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestLockStale(t *testing.T) { + dir := t.TempDir() + at := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) + defer func() { now = time.Now }() + p := filepath.Join(dir, "lock") + + write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter+time.Minute).Unix())) + now = func() time.Time { return at } + if _, err := Lock(dir); err == nil { + t.Fatal("took a fresh lock") + } + + write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter-time.Minute).Unix())) + release, err := Lock(dir) + if err != nil { + t.Fatalf("stale lock not taken over: %v", err) + } + b, _ := os.ReadFile(p) + if !strings.HasPrefix(string(b), fmt.Sprint(os.Getpid())+" ") { + t.Errorf("lock holds %q", b) + } + release() + + // A run that kept the lock past StaleAfter leaves the one that took it over alone. + write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter-time.Minute).Unix())) + old, err := Lock(dir) + if err != nil { + t.Fatal(err) + } + now = func() time.Time { return at.Add(StaleAfter + time.Minute) } + release, err = Lock(dir) + if err != nil { + t.Fatalf("stale lock of this pid not taken over: %v", err) + } + old() + if _, err := os.Stat(p); err != nil { + t.Fatalf("the old run's release removed the new lock: %v", err) + } + release() + if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("lock still there after release: %v", err) + } + now = func() time.Time { return at } + + write(t, p, "") + if err := os.Chtimes(p, at, at); err != nil { + t.Fatal(err) + } + if _, err := Lock(dir); err == nil { + t.Fatal("took a lock that is being written") + } +} diff --git a/internal/state/lock_unix.go b/internal/state/lock_unix.go new file mode 100644 index 0000000..26dfacb --- /dev/null +++ b/internal/state/lock_unix.go @@ -0,0 +1,47 @@ +//go:build unix + +package state + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "syscall" +) + +// Lock takes the run lock in dir: an advisory lock on dir/lock that the +// system holds for this process until it releases it or dies, SIGKILL and +// all. A lock file nobody holds, left by a killed run or restored from a +// cache, is taken at once; the file says which process holds it only so +// the error can. +func Lock(dir string) (release func(), err error) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + p := filepath.Join(dir, lockName) + f, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE, 0o644) + if err != nil { + return nil, err + } + for { + err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if !errors.Is(err, syscall.EINTR) { + break + } + } + if err != nil { + f.Close() + if errors.Is(err, syscall.EWOULDBLOCK) { + return nil, readLock(p) + } + return nil, err + } + if err := f.Truncate(0); err == nil { + _, _ = f.WriteAt(fmt.Appendf(nil, "%d %d\n", os.Getpid(), now().Unix()), 0) + } + return func() { + _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + f.Close() + }, nil +} diff --git a/internal/state/lock_unix_test.go b/internal/state/lock_unix_test.go new file mode 100644 index 0000000..5570593 --- /dev/null +++ b/internal/state/lock_unix_test.go @@ -0,0 +1,75 @@ +//go:build unix + +package state + +import ( + "bufio" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// A lock file no process holds, as a killed run or a restored cache leaves +// one, is no lock at all. +func TestLockLeftOver(t *testing.T) { + dir := t.TempDir() + write(t, filepath.Join(dir, "lock"), fmt.Sprintf("999999 %d\n", time.Now().Unix())) + release, err := Lock(dir) + if err != nil { + t.Fatalf("a lock nobody holds: %v", err) + } + release() + if _, err := os.Stat(filepath.Join(dir, "lock")); err != nil { + t.Errorf("release removed the lock file: %v", err) + } +} + +// TestLockChild is the child TestLockKilled starts: it takes the lock, says +// so and waits to be killed. +func TestLockChild(t *testing.T) { + dir := os.Getenv("TEND_LOCK_CHILD") + if dir == "" { + t.Skip("run by TestLockKilled") + } + if _, err := Lock(dir); err != nil { + t.Fatal(err) + } + fmt.Println("locked") + time.Sleep(time.Minute) +} + +// A run killed outright, which runs no deferred release, leaves the lock +// free for the next one. +func TestLockKilled(t *testing.T) { + dir := t.TempDir() + cmd := exec.Command(os.Args[0], "-test.run=^TestLockChild$", "-test.v") + cmd.Env = append(os.Environ(), "TEND_LOCK_CHILD="+dir) + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + sc := bufio.NewScanner(out) + for sc.Scan() && sc.Text() != "locked" { + } + _, err = Lock(dir) + var held *Locked + if !errors.As(err, &held) || held.PID != cmd.Process.Pid { + t.Fatalf("lock held by the child: %v", err) + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + _ = cmd.Wait() + release, err := Lock(dir) + if err != nil { + t.Fatalf("after the holder was killed: %v", err) + } + release() +} diff --git a/internal/state/state.go b/internal/state/state.go index 2100930..f5c1b88 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -38,6 +38,9 @@ type State struct { Stage int `json:",omitempty"` Issue Issue Updated time.Time + // Discarded says why the state on disk could not be used, when Open set + // it aside and started fresh; "" when it loaded. + Discarded string `json:"-"` path string } @@ -47,6 +50,10 @@ type Seen struct { Verdict string // noise|ignored|cooldown|parked|queued|delivered|unsupported Detail string `json:",omitempty"` Base string `json:",omitempty"` // unsupported: the base commit tend failed on + // Failed and FailedBase keep why the change could not be made, and on + // which base, while it waits to be tried again after the base moved. + Failed string `json:",omitempty"` + FailedBase string `json:",omitempty"` } // BaseRun is the project's own commands run on a base commit. @@ -155,18 +162,31 @@ func trimRepo(p string) string { func Dir(home, key string) string { return filepath.Join(home, "repos", key) } // Open loads the state of the repo with this key under home and returns it with -// the repo's directory. A missing or empty state is a fresh one. +// the repo's directory. A missing or empty state is a fresh one. The state +// is a cache of what the forge and a re-run can tell again, so one that +// cannot be read, or that a newer tend wrote, is set aside next to it and +// replaced by a fresh one, and Discarded says why. func Open(home, key string) (*State, string, error) { dir := Dir(home, key) - s := &State{path: filepath.Join(dir, "state.json")} - b, err := os.ReadFile(s.path) + path := filepath.Join(dir, "state.json") + s := &State{path: path} + b, err := os.ReadFile(path) switch { case errors.Is(err, os.ErrNotExist): case err != nil: - return nil, "", err + return nil, "", fmt.Errorf("state: %w; run with --reset to start over", err) case len(b) > 0: + aside, why := "", "" if err := json.Unmarshal(b, s); err != nil { - return nil, "", fmt.Errorf("state: %s: %w", s.path, err) + aside, why = path+".corrupt", err.Error() + } else if s.Version > 1 { + aside, why = fmt.Sprintf("%s.v%d", path, s.Version), fmt.Sprintf("a newer tend wrote it (version %d)", s.Version) + } + if aside != "" { + if err := os.Rename(path, aside); err != nil { + return nil, "", fmt.Errorf("state: %s: %s, and it cannot be set aside: %w; run with --reset to start over", path, why, err) + } + s = &State{path: path, Discarded: fmt.Sprintf("%s: %s; kept it as %s", path, why, filepath.Base(aside))} } } s.init() @@ -224,6 +244,12 @@ func (s *State) See(id, verdict, detail string, now time.Time) { if verdict == prev.Verdict { res.Base = prev.Base } + switch { + case verdict == "queued" && prev.Verdict == "unsupported": + res.Failed, res.FailedBase = prev.Detail, prev.Base + case verdict == "queued": + res.Failed, res.FailedBase = prev.Failed, prev.FailedBase + } s.Seen[id] = res } @@ -283,9 +309,6 @@ func writeFile(path string, b []byte) error { return err } -// StaleAfter is how old a lock gets before another run may take it over. -const StaleAfter = 2 * time.Hour - var now = time.Now // Locked is the error Lock returns when another run holds the lock. @@ -295,50 +318,14 @@ type Locked struct { } func (e *Locked) Error() string { + if e.PID == 0 { + return "another tend run holds the lock" + } return fmt.Sprintf("another tend run holds the lock (pid %d, since %s)", e.PID, e.At.UTC().Format(time.RFC3339)) } const lockName = "lock" -// Lock takes the run lock in dir. A lock older than two hours is stale. -// Releasing it leaves alone a lock another run took over in the meantime. -func Lock(dir string) (release func(), err error) { - if err := os.MkdirAll(dir, 0o755); err != nil { - return nil, err - } - p := filepath.Join(dir, lockName) - for range 2 { - f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) - if err == nil { - mine := fmt.Sprintf("%d %d\n", os.Getpid(), now().Unix()) - _, err = f.WriteString(mine) - if cerr := f.Close(); err == nil { - err = cerr - } - if err != nil { - os.Remove(p) - return nil, err - } - return func() { - if b, err := os.ReadFile(p); err == nil && string(b) == mine { - os.Remove(p) - } - }, nil - } - if !errors.Is(err, os.ErrExist) { - return nil, err - } - held := readLock(p) - if now().Sub(held.At) < StaleAfter { - return nil, held - } - if err := os.Remove(p); err != nil && !errors.Is(err, os.ErrNotExist) { - return nil, err - } - } - return nil, fmt.Errorf("state: cannot take %s", p) -} - // readLock falls back to the file's mtime when the lock has no readable // content yet: another run may be between creating and writing it. func readLock(p string) *Locked { diff --git a/internal/state/state_test.go b/internal/state/state_test.go index 271304b..3dddae7 100644 --- a/internal/state/state_test.go +++ b/internal/state/state_test.go @@ -130,15 +130,64 @@ func TestSaveKeepsOldFileOnFailure(t *testing.T) { } func TestOpenCorrupt(t *testing.T) { + tests := []struct{ name, body, why string }{ + {"truncated", `{"Version":1,"Seen":{"a":`, "unexpected end of JSON input"}, + {"zero-filled", "\x00\x00\x00\x00", "invalid character"}, + {"wrongly typed", `{"Version":1,"Seen":[1,2]}`, "cannot unmarshal array"}, + {"from a newer tend", `{"Version":7,"Seen":{"a":{"Verdict":"noise"}}}`, "newer tend"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + p := filepath.Join(Dir(home, "k"), "state.json") + write(t, p, tc.body) + write(t, p+".corrupt", "an older one") + s, _, err := Open(home, "k") + if err != nil { + t.Fatal(err) + } + if s.Version != 1 || len(s.Seen) != 0 || s.Seen == nil || s.Parked == nil || s.Open != nil { + t.Errorf("state = %+v, want a fresh one", s) + } + if !strings.Contains(s.Discarded, tc.why) { + t.Errorf("Discarded = %q, want it to say %q", s.Discarded, tc.why) + } + aside := p + ".corrupt" + if strings.Contains(tc.body, `"Version":7`) { + aside = p + ".v7" + } + if b, err := os.ReadFile(aside); err != nil || string(b) != tc.body { + t.Errorf("%s = %q, %v", filepath.Base(aside), b, err) + } + if _, err := os.Stat(p); !os.IsNotExist(err) { + t.Errorf("state.json is still there: %v", err) + } + if err := s.Save(); err != nil { + t.Fatal(err) + } + if again, _, err := Open(home, "k"); err != nil || again.Discarded != "" { + t.Errorf("the fresh state did not load: %q, %v", again.Discarded, err) + } + }) + } +} + +func TestOpenEmpty(t *testing.T) { home := t.TempDir() - p := filepath.Join(Dir(home, "k"), "state.json") - write(t, p, "{") - if _, _, err := Open(home, "k"); err == nil { - t.Fatal("corrupt state loaded") + write(t, filepath.Join(Dir(home, "k"), "state.json"), "") + s, _, err := Open(home, "k") + if err != nil || s.Discarded != "" { + t.Fatalf("empty state: %q, %v", s.Discarded, err) + } +} + +func TestOpenUnreadable(t *testing.T) { + home := t.TempDir() + if err := os.MkdirAll(filepath.Join(Dir(home, "k"), "state.json"), 0o755); err != nil { + t.Fatal(err) } - write(t, p, "") - if _, _, err := Open(home, "k"); err != nil { - t.Fatalf("empty state: %v", err) + if _, _, err := Open(home, "k"); err == nil || !strings.Contains(err.Error(), "--reset") { + t.Fatalf("err = %v, want it to point at --reset", err) } } @@ -203,59 +252,6 @@ func TestLock(t *testing.T) { release2() } -func TestLockStale(t *testing.T) { - dir := t.TempDir() - at := time.Date(2026, 10, 21, 12, 0, 0, 0, time.UTC) - defer func() { now = time.Now }() - p := filepath.Join(dir, "lock") - - write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter+time.Minute).Unix())) - now = func() time.Time { return at } - if _, err := Lock(dir); err == nil { - t.Fatal("took a fresh lock") - } - - write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter-time.Minute).Unix())) - release, err := Lock(dir) - if err != nil { - t.Fatalf("stale lock not taken over: %v", err) - } - b, _ := os.ReadFile(p) - if !strings.HasPrefix(string(b), fmt.Sprint(os.Getpid())+" ") { - t.Errorf("lock holds %q", b) - } - release() - - // A run that kept the lock past StaleAfter leaves the one that took it over alone. - write(t, p, fmt.Sprintf("4242 %d\n", at.Add(-StaleAfter-time.Minute).Unix())) - old, err := Lock(dir) - if err != nil { - t.Fatal(err) - } - now = func() time.Time { return at.Add(StaleAfter + time.Minute) } - release, err = Lock(dir) - if err != nil { - t.Fatalf("stale lock of this pid not taken over: %v", err) - } - old() - if _, err := os.Stat(p); err != nil { - t.Fatalf("the old run's release removed the new lock: %v", err) - } - release() - if _, err := os.Stat(p); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("lock still there after release: %v", err) - } - now = func() time.Time { return at } - - write(t, p, "") - if err := os.Chtimes(p, at, at); err != nil { - t.Fatal(err) - } - if _, err := Lock(dir); err == nil { - t.Fatal("took a lock that is being written") - } -} - func write(t *testing.T, p, body string) { t.Helper() if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { diff --git a/internal/ver/ver.go b/internal/ver/ver.go index c969562..7301330 100644 --- a/internal/ver/ver.go +++ b/internal/ver/ver.go @@ -42,7 +42,9 @@ var postWords = map[string]bool{"post": true, "rev": true} // Parse accepts "v1.2.3", "1.2", "1.2.3-rc.1", "1.0a1", "1.0.post1", "2024.1.2" and // docker-style "18-alpine". A suffix that is not a known pre-release word, such as -// "-alpine" or "-slim", is a variant and does not take part in ordering. +// "-alpine" or "-slim", is a variant and does not take part in ordering. A PEP 440 +// epoch ("1!2.0") outranks every version without one, so a version with one does +// not parse. func Parse(s string) (V, bool) { v := V{Raw: s} s = strings.TrimSpace(s) @@ -52,6 +54,9 @@ func Parse(s string) (V, bool) { if i := strings.IndexByte(s, '+'); i >= 0 { s = s[:i] } + if strings.Contains(s, "!") { + return V{Raw: v.Raw}, false + } for { n := digits(s) if n == 0 { @@ -228,12 +233,14 @@ func Less(a, b string) bool { return Compare(va, vb) < 0 } -// Level names the size of the step from one version to another: major, minor, patch or same. +// Level names the size of the step from one version to another: major, +// minor, patch or same. A step off v's compatibility line is major, as a +// caret range reads it: 0.1 to 0.2 is, and so is 0.0.1 to 0.0.2. func Level(from, to V) string { switch { case Compare(from, to) == 0: return "same" - case part(from.Nums, 0) != part(to.Nums, 0): + case from.Line() != to.Line(): return "major" case part(from.Nums, 1) != part(to.Nums, 1): return "minor" @@ -254,7 +261,39 @@ func Step(from, to string) string { return "" } +// StepIn is Step as ecosystem eco reads a version: a Go module keeps its +// import path across v0.x minors, which go get takes as routine upgrades, +// so v0.13 to v0.49 is minor there; everywhere else a caret range rules. +func StepIn(eco, from, to string) string { + if eco != "go" { + return Step(from, to) + } + a, okA := Parse(from) + b, okB := Parse(to) + switch { + case !okA || !okB || Compare(a, b) == 0: + return "" + case a.Major() != b.Major(): + return "major" + case part(a.Nums, 1) != part(b.Nums, 1): + return "minor" + } + return "patch" +} + func (v V) Major() int { return part(v.Nums, 0) } +// Line is the compatibility line v is on, what a caret range holds fixed: +// the major from 1 on, "0.3" for a 0.3.x, "0.0.4" for 0.0.4. +func (v V) Line() string { + switch { + case part(v.Nums, 0) > 0: + return strconv.Itoa(part(v.Nums, 0)) + case part(v.Nums, 1) > 0: + return "0." + strconv.Itoa(part(v.Nums, 1)) + } + return "0.0." + strconv.Itoa(part(v.Nums, 2)) +} + // GoLess orders Go module versions, which are strict semver with a v prefix. func GoLess(a, b string) bool { return semver.Compare(a, b) < 0 } diff --git a/internal/ver/ver_test.go b/internal/ver/ver_test.go index adf4886..b9d0464 100644 --- a/internal/ver/ver_test.go +++ b/internal/ver/ver_test.go @@ -105,6 +105,12 @@ func TestLessSorts(t *testing.T) { } } +func TestParseEpoch(t *testing.T) { + if v, ok := Parse("1!2.0"); ok { + t.Errorf("Parse(1!2.0) = %v", v) + } +} + func TestLevel(t *testing.T) { tests := []struct{ from, to, want string }{ {"1.2.3", "2.0.0", "major"}, @@ -114,7 +120,12 @@ func TestLevel(t *testing.T) { {"1.0.0-rc.1", "1.0.0", "patch"}, {"1.0", "1.0.post1", "patch"}, {"16-alpine", "22-alpine", "major"}, - {"0.1.0", "0.2.0", "minor"}, + {"0.1.0", "0.2.0", "major"}, + {"0.11.27", "0.12.0", "major"}, + {"0.1.0", "0.1.5", "patch"}, + {"0.0.1", "0.0.2", "major"}, + {"0.9.3", "1.0.0", "major"}, + {"1.2", "1.3", "minor"}, } for _, tt := range tests { a, _ := Parse(tt.from) @@ -138,6 +149,22 @@ func TestStep(t *testing.T) { } } +func TestStepIn(t *testing.T) { + tests := []struct{ eco, from, to, want string }{ + {"go", "v0.13.0", "v0.49.0", "minor"}, + {"go", "v0.0.0-20191026070338-33540a1f6037", "v0.49.0", "minor"}, + {"go", "v1.2.0", "v2.0.0", "major"}, + {"go", "v0.13.0", "v0.13.1", "patch"}, + {"cargo", "0.1.0", "0.2.0", "major"}, + {"npm", "0.13.0", "0.49.0", "major"}, + } + for _, tt := range tests { + if got := StepIn(tt.eco, tt.from, tt.to); got != tt.want { + t.Errorf("StepIn(%s, %q, %q) = %q, want %q", tt.eco, tt.from, tt.to, got, tt.want) + } + } +} + func TestMajor(t *testing.T) { for in, want := range map[string]int{"v14.2.0": 14, "22-alpine": 22, "0.3": 0} { v, _ := Parse(in) diff --git a/internal/verify/detect.go b/internal/verify/detect.go index 6b40bdc..f4350fc 100644 --- a/internal/verify/detect.go +++ b/internal/verify/detect.go @@ -12,9 +12,10 @@ import ( // Detect merges the commands in config with each ecosystem's defaults. A // non-empty install, build or test list in config replaces that list entirely. -// Each ecosystem runs its lines from the right directory itself; installs that -// a manifest higher up already covers (npm workspaces, a nested requirements -// file without a lock of its own) are left out. +// Each ecosystem runs its lines from the right directory itself. A nested +// install is left out when a manifest higher up installs for it, as a +// workspace root does for its members, or when nothing runs in its +// directory, as with a requirements file another one pulls in. func Detect(root string, manifests []core.Manifest, ecos map[string]core.Ecosystem, cfg config.Verify) core.Commands { var res core.Commands for _, e := range eco.All() { @@ -26,7 +27,7 @@ func Detect(root string, manifests []core.Manifest, ecos map[string]core.Ecosyst ms := byDepth(manifests, name) for _, m := range ms { c := ec.Commands(root, m) - if !covered(ms, m) { + if !covered(ms, m) && (path.Dir(m.Path) == "." || len(c.Build)+len(c.Test) > 0) { res.Install = append(res.Install, c.Install...) } res.Build = append(res.Build, c.Build...) @@ -55,19 +56,20 @@ func byDepth(manifests []core.Manifest, name string) []core.Manifest { return res } -// covered reports whether a manifest in a parent directory installs for m. +// covered reports whether a manifest higher up installs for m: m's lock +// sits in an ancestor directory that has a manifest of its own, as with an +// npm, pnpm, yarn or cargo workspace member. A nested manifest with no lock, +// or a lock of its own, installs for itself. func covered(ms []core.Manifest, m core.Manifest) bool { dir := path.Dir(m.Path) - if dir == "." || m.Lock != "" && path.Dir(m.Lock) == dir { + if dir == "." || m.Lock == "" { return false } - for _, n := range ms { - up := path.Dir(n.Path) - if up != dir && (up == "." || strings.HasPrefix(dir, up+"/")) { - return true - } + up := path.Dir(m.Lock) + if up == dir || up != "." && !strings.HasPrefix(dir, up+"/") { + return false } - return false + return slices.ContainsFunc(ms, func(n core.Manifest) bool { return path.Dir(n.Path) == up }) } func pick(override, detected []string) []string { diff --git a/internal/verify/detect_test.go b/internal/verify/detect_test.go index 215cdd7..5451002 100644 --- a/internal/verify/detect_test.go +++ b/internal/verify/detect_test.go @@ -39,14 +39,17 @@ func TestDetect(t *testing.T) { "packages/a/package.json": {Install: []string{"npm ci"}, Test: []string{"cd packages/a && npm test"}}, "web/package.json": {Install: []string{"cd web && npm ci"}, Build: []string{"cd web && npm run build"}, Test: []string{"cd web && npm test"}}, "site docs/package.json": {Test: []string{"cd 'site docs' && npm test"}}, + "docs/package.json": {Install: []string{"cd docs && npm install"}, Build: []string{"cd docs && npm run build"}}, }}, core.Go: fakeEco{core.Go, map[string]core.Commands{ "go.mod": goCmds, "tools/gen/go.mod": {Build: []string{"cd tools/gen && go build ./..."}, Test: []string{"cd tools/gen && go vet ./... && go test ./..."}}, }}, core.Pip: fakeEco{core.Pip, map[string]core.Commands{ - "requirements.txt": {Install: []string{"python -m venv .venv && .venv/bin/pip install -r requirements.txt"}, Test: []string{"python -m unittest"}}, - "requirements-dev.txt": {Install: []string{"python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt"}, Test: []string{"python -m unittest"}}, + "requirements.txt": {Install: []string{"python -m venv .venv && .venv/bin/pip install -r requirements.txt"}, Test: []string{"python -m unittest"}}, + "requirements-dev.txt": {Install: []string{"python -m venv .venv && .venv/bin/pip install -r requirements-dev.txt"}, Test: []string{"python -m unittest"}}, + "svc/requirements.txt": {Install: []string{"cd svc && python3 -m venv .venv && .venv/bin/pip install -r requirements.txt"}, Test: []string{"cd svc && .venv/bin/python -m unittest"}}, + "requirements/base.txt": {Install: []string{"cd requirements && python3 -m venv .venv && .venv/bin/pip install -r base.txt"}}, }}, core.Docker: eco.ByName(core.Docker), core.Actions: eco.ByName(core.Actions), @@ -104,6 +107,37 @@ func TestDetect(t *testing.T) { Test: []string{"npm test", "cd web && npm test"}, }, }, + { + "nested package without a lock of its own is no workspace member, and installs itself", + []core.Manifest{npmRoot, {Ecosystem: core.Npm, Path: "docs/package.json"}}, + config.Verify{}, + core.Commands{ + Install: []string{"npm ci", "cd docs && npm install"}, + Build: []string{"npm run build", "cd docs && npm run build"}, + Test: []string{"npm test"}, + }, + }, + { + "nested requirements with tests of their own install themselves", + []core.Manifest{{Ecosystem: core.Pip, Path: "requirements.txt"}, {Ecosystem: core.Pip, Path: "svc/requirements.txt"}}, + config.Verify{}, + core.Commands{ + Install: []string{ + "python -m venv .venv && .venv/bin/pip install -r requirements.txt", + "cd svc && python3 -m venv .venv && .venv/bin/pip install -r requirements.txt", + }, + Test: []string{"python -m unittest", "cd svc && .venv/bin/python -m unittest"}, + }, + }, + { + "nested requirements with nothing to run there are pulled in by another", + []core.Manifest{{Ecosystem: core.Pip, Path: "requirements.txt"}, {Ecosystem: core.Pip, Path: "requirements/base.txt"}}, + config.Verify{}, + core.Commands{ + Install: []string{"python -m venv .venv && .venv/bin/pip install -r requirements.txt"}, + Test: []string{"python -m unittest"}, + }, + }, { "two manifests in one dir, identical lines once", []core.Manifest{{Ecosystem: core.Pip, Path: "requirements.txt"}, {Ecosystem: core.Pip, Path: "requirements-dev.txt"}}, diff --git a/internal/verify/env.go b/internal/verify/env.go index 1d9135f..e97f47d 100644 --- a/internal/verify/env.go +++ b/internal/verify/env.go @@ -1,17 +1,12 @@ package verify import ( - "regexp" "slices" "strings" "github.com/mohsensc/tend-cli/internal/core" ) -// secretShape catches credentials by the shape of their name, beyond what -// core.Scrub drops: STRIPE_KEY, GH_PAT, VAULT_ROOT_TOKEN and the like. -var secretShape = regexp.MustCompile(`(?i)(_KEY|_TOKEN|_SECRET|_PAT|_CREDENTIALS)$|PASSWORD`) - // Filter returns the environment the project's commands see: env without // anything that looks like a secret and without tend's own variables, plus the // names in keep (verify.env), plus the settings that make installs quiet and @@ -22,14 +17,12 @@ func Filter(env []string, keep []string) []string { "TEND": "1", "npm_config_fund": "false", "npm_config_audit": "false", + "HUSKY": "0", "GOFLAGS": "-mod=mod", } var res []string for _, kv := range core.Scrub(env, keep) { name, val, _ := strings.Cut(kv, "=") - if secretShape.MatchString(name) && !slices.Contains(keep, name) { - continue - } if name == "GOFLAGS" { if !strings.Contains(val, "-mod=") { val = strings.TrimSpace(val + " -mod=mod") diff --git a/internal/verify/env_test.go b/internal/verify/env_test.go index 3f0c45a..429aa6e 100644 --- a/internal/verify/env_test.go +++ b/internal/verify/env_test.go @@ -8,7 +8,7 @@ import ( func TestFilter(t *testing.T) { with := func(gofl string, kv ...string) []string { res := slices.Clone(kv) - res = append(res, "CI=1", "GOFLAGS="+gofl, "TEND=1", "npm_config_audit=false", "npm_config_fund=false") + res = append(res, "CI=1", "GOFLAGS="+gofl, "HUSKY=0", "TEND=1", "npm_config_audit=false", "npm_config_fund=false") return res } tests := []struct { diff --git a/internal/verify/proc_other.go b/internal/verify/proc_other.go deleted file mode 100644 index 31fe29e..0000000 --- a/internal/verify/proc_other.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !unix - -package verify - -import "os/exec" - -// On Windows there are no process groups to signal: a timeout kills the shell -// only, and children it started may outlive the step. Use verify.container -// there when that matters. -func group(cmd *exec.Cmd) {} - -func reap(cmd *exec.Cmd) {} diff --git a/internal/verify/proc_unix.go b/internal/verify/proc_unix.go deleted file mode 100644 index 6288026..0000000 --- a/internal/verify/proc_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build unix - -package verify - -import ( - "os/exec" - "syscall" -) - -// group puts the command in its own process group so a timeout kills the -// whole tree (a test runner and its workers), not just the shell. -func group(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } -} - -// reap kills whatever the command left behind in its group after it exited. -func reap(cmd *exec.Cmd) { - if cmd.Process != nil { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - } -} diff --git a/internal/verify/run.go b/internal/verify/run.go index d6f4768..e938ead 100644 --- a/internal/verify/run.go +++ b/internal/verify/run.go @@ -16,6 +16,7 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/gitx" + "github.com/mohsensc/tend-cli/internal/proc" ) const defaultTimeout = 20 * time.Minute @@ -45,16 +46,25 @@ func Run(ctx context.Context, w *Worktree, o Options) (*core.Run, error) { start := time.Now() res := &core.Run{} res.Commit, _ = gitx.Run(ctx, w.Dir, "rev-parse", "HEAD") - var lines []string - lines = append(lines, o.Commands.Install...) - lines = append(lines, o.Commands.Build...) - lines = append(lines, o.Commands.Test...) + var lines, phases []string + for _, ph := range []struct { + name string + lines []string + }{{core.PhaseInstall, o.Commands.Install}, {core.PhaseBuild, o.Commands.Build}, {core.PhaseTest, o.Commands.Test}} { + lines = append(lines, ph.lines...) + for range ph.lines { + phases = append(phases, ph.name) + } + } if len(lines) == 0 { res.Pass = true return res, nil } env := Filter(os.Environ(), o.Env) + if o.Container == "" { + defer guardConfig(ctx, w)() + } if o.Warnings { env = warningsOn(env) } @@ -82,13 +92,14 @@ func Run(ctx context.Context, w *Worktree, o Options) (*core.Run, error) { why := "" for i, s := range steps { if why != "" { - res.Steps = append(res.Steps, core.Step{Cmd: s.cmd, Skipped: why}) + res.Steps = append(res.Steps, core.Step{Cmd: s.cmd, Phase: phases[i], Skipped: why}) continue } st, err := runStep(runCtx, w.Dir, env, i+1, s, o, timeout) if err != nil { return nil, err } + st.Phase = phases[i] res.Steps = append(res.Steps, st) switch { case ctx.Err() != nil: @@ -115,6 +126,27 @@ func Run(ctx context.Context, w *Worktree, o Options) (*core.Run, error) { return res, ctx.Err() } +// guardConfig keeps the repository's git config as it was while the +// project's commands run in a linked worktree, which shares that config: a +// husky prepare script, or any step that calls git config, would otherwise +// write the user's .git/config. The returned func puts it back. +func guardConfig(ctx context.Context, w *Worktree) func() { + dir, err := gitx.Run(ctx, w.Dir, "rev-parse", "--path-format=absolute", "--git-common-dir") + if err != nil || dir == "" { + return func() {} + } + p := filepath.Join(dir, "config") + was, err := os.ReadFile(p) + if err != nil { + return func() {} + } + return func() { + if now, err := os.ReadFile(p); err != nil || !bytes.Equal(now, was) { + _ = os.WriteFile(p, was, 0o644) + } + } +} + func hostSteps(lines []string) []step { res := make([]step, len(lines)) for i, l := range lines { @@ -200,11 +232,11 @@ func execute(ctx context.Context, dir string, env []string, s step, out io.Write cmd := exec.CommandContext(ctx, s.argv[0], s.argv[1:]...) cmd.Dir, cmd.Env = dir, env cmd.Stdout, cmd.Stderr = w, w - group(cmd) + proc.Group(cmd) err = cmd.Start() if err == nil { err = cmd.Wait() - reap(cmd) + proc.Reap(cmd) } if ctx.Err() != nil && s.stop != nil { s.stop() diff --git a/internal/verify/run_test.go b/internal/verify/run_test.go index 1b47c44..4c75c20 100644 --- a/internal/verify/run_test.go +++ b/internal/verify/run_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -63,10 +64,10 @@ func TestRunStopsAtFailure(t *testing.T) { t.Error("Pass after a failing step") } want := []core.Step{ - {Cmd: "true"}, - {Cmd: "echo broken; exit 3", Exit: 3, Tail: "broken"}, - {Cmd: "echo never > ran", Skipped: "previous step failed"}, - {Cmd: "true", Skipped: "previous step failed"}, + {Cmd: "true", Phase: core.PhaseInstall}, + {Cmd: "echo broken; exit 3", Phase: core.PhaseBuild, Exit: 3, Tail: "broken"}, + {Cmd: "echo never > ran", Phase: core.PhaseTest, Skipped: "previous step failed"}, + {Cmd: "true", Phase: core.PhaseTest, Skipped: "previous step failed"}, } for i, st := range res.Steps { st.Took = 0 @@ -211,3 +212,35 @@ func TestLocalPaths(t *testing.T) { t.Errorf("local =\n%s\nwant\n%s", got, want) } } + +// A step that writes git config in the worktree, as husky install does, +// leaves the repository's own config as it was. +func TestRunKeepsGitConfig(t *testing.T) { + repo := t.TempDir() + for _, args := range [][]string{{"init", "--quiet", "-b", "main"}, {"commit", "--quiet", "--allow-empty", "-m", "x"}} { + cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@t"}, args...)...) + cmd.Dir = repo + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + cfg := filepath.Join(repo, ".git", "config") + was, err := os.ReadFile(cfg) + if err != nil { + t.Fatal(err) + } + wt, err := Checkout(context.Background(), repo, filepath.Join(t.TempDir(), "wt"), "HEAD") + if err != nil { + t.Fatal(err) + } + res, err := Run(context.Background(), wt, Options{Commands: core.Commands{Install: []string{"git config core.hooksPath .husky && echo $HUSKY"}}}) + if err != nil || !res.Pass { + t.Fatalf("run = %+v, %v", res, err) + } + if now, _ := os.ReadFile(cfg); string(now) != string(was) { + t.Errorf("the repository's config changed:\n%s", now) + } + if !strings.Contains(res.Steps[0].Tail, "0") { + t.Errorf("HUSKY is not 0: %q", res.Steps[0].Tail) + } +} diff --git a/internal/verify/worktree.go b/internal/verify/worktree.go index 95ba938..2738fe7 100644 --- a/internal/verify/worktree.go +++ b/internal/verify/worktree.go @@ -5,6 +5,8 @@ import ( "context" "os" "path/filepath" + "slices" + "strings" "github.com/mohsensc/tend-cli/internal/gitx" ) @@ -58,10 +60,93 @@ func Checkout(ctx context.Context, repo, dir, base string) (*Worktree, error) { if err != nil { return nil, err } - gitx.Pin(dir, gitDir) + exclude, err := excludes(ctx, dir, gitDir) + if err != nil { + return nil, err + } + gitx.Pin(dir, gitDir, exclude) return &Worktree{Dir: dir, Repo: repo, Base: sha, GitDir: gitDir}, nil } +// installed are the directories installs fill that no project commits. +var installed = []string{"node_modules", ".venv", "venv", "__pycache__", ".gradle"} + +// excludes writes the excludes file git reads in the worktree at dir: the +// user's own, plus the install directories the project does not track. Its +// .gitignore may not list them, and a clean between commands must not take +// an install away, nor an add -A put one in the patch. It lives in the +// worktree's own git dir, so the user's repository is never written. +func excludes(ctx context.Context, dir, gitDir string) (string, error) { + var b strings.Builder + if own := userExcludes(ctx, dir); own != "" { + if data, err := os.ReadFile(own); err == nil { + b.Write(data) + b.WriteString("\n") + } + } + var specs []string + for _, d := range installed { + specs = append(specs, ":(glob)**/"+d+"/**") + } + tracked, err := gitx.Raw(ctx, dir, append([]string{"ls-files", "-z", "--"}, specs...)...) + if err != nil { + return "", err + } + for _, d := range installed { + if !slices.ContainsFunc(strings.Split(tracked, "\x00"), func(f string) bool { + return slices.Contains(strings.Split(f, "/"), d) + }) { + b.WriteString(d + "/\n") + } + } + p := filepath.Join(gitDir, "tend-exclude") + return p, os.WriteFile(p, []byte(b.String()), 0o644) +} + +// userExcludes is the excludes file git would read in dir by itself. +func userExcludes(ctx context.Context, dir string) string { + if p, err := gitx.Run(ctx, dir, "config", "--path", "--get", "core.excludesFile"); err == nil && p != "" { + return p + } + if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { + return filepath.Join(x, "git", "ignore") + } + if h, err := os.UserHomeDir(); err == nil { + return filepath.Join(h, ".config", "git", "ignore") + } + return "" +} + +// Sweep removes the worktrees under parent, all but keep: those a dry +// run, --keep or a killed run left in the repo. +func Sweep(ctx context.Context, repo, parent, keep string) error { + ents, err := os.ReadDir(parent) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + swept := false + for _, e := range ents { + dir := filepath.Join(parent, e.Name()) + if !e.IsDir() || filepath.Clean(dir) == filepath.Clean(keep) { + continue + } + gitx.Unpin(dir) + _, _ = gitx.Run(ctx, repo, "worktree", "remove", "--force", dir) + if err := os.RemoveAll(dir); err != nil { + return err + } + swept = true + } + if !swept { + return nil + } + _, err = gitx.Run(ctx, repo, "worktree", "prune") + return err +} + func (w *Worktree) Remove(ctx context.Context) error { gitx.Unpin(w.Dir) if _, err := gitx.Run(ctx, w.Repo, "worktree", "remove", "--force", w.Dir); err != nil { diff --git a/internal/verify/worktree_test.go b/internal/verify/worktree_test.go index 1364c03..fc387c0 100644 --- a/internal/verify/worktree_test.go +++ b/internal/verify/worktree_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/gitx" ) // isolate keeps the developer's git config (hooks, signing, identity) out of tests. @@ -238,3 +239,43 @@ echo changed >> main.go t.Fatal("a command from the rewritten git dir ran") } } + +// A project whose .gitignore does not list node_modules keeps its install +// across a clean, and never stages it, while a vendor dir it tracks stays +// tracked. +func TestWorktreeKeepsInstalls(t *testing.T) { + repo := newRepo(t, map[string]string{"package.json": "{}\n", "vendor/venv/a.txt": "a\n"}) + ctx := context.Background() + wt, err := Checkout(ctx, repo, filepath.Join(t.TempDir(), "wt"), "HEAD") + if err != nil { + t.Fatal(err) + } + defer func() { _ = wt.Remove(ctx) }() + write(t, wt.Dir, map[string]string{"node_modules/lodash/index.js": "x\n", "src/__pycache__/a.pyc": "x", "vendor/venv/b.txt": "b\n", "built.txt": "x\n"}) + if _, err := gitx.Run(ctx, wt.Dir, "clean", "--quiet", "--force", "-d"); err != nil { + t.Fatal(err) + } + for _, p := range []string{"node_modules/lodash/index.js", "src/__pycache__/a.pyc"} { + if _, err := os.Stat(filepath.Join(wt.Dir, p)); err != nil { + t.Errorf("clean took %s away: %v", p, err) + } + } + for _, p := range []string{"built.txt", "vendor/venv/b.txt"} { + if _, err := os.Stat(filepath.Join(wt.Dir, p)); err == nil { + t.Errorf("clean left %s", p) + } + } + write(t, wt.Dir, map[string]string{"vendor/venv/b.txt": "b\n"}) + if _, err := gitx.Run(ctx, wt.Dir, "add", "-A"); err != nil { + t.Fatal(err) + } + staged, _ := gitx.Run(ctx, wt.Dir, "diff", "--cached", "--name-only") + if staged != "vendor/venv/b.txt" { + t.Errorf("staged %q, want only vendor/venv/b.txt", staged) + } + if _, err := os.Stat(filepath.Join(repo, ".git", "info", "exclude")); err == nil { + if data, _ := os.ReadFile(filepath.Join(repo, ".git", "info", "exclude")); strings.Contains(string(data), "node_modules") { + t.Error("the user's info/exclude was written") + } + } +} diff --git a/internal/vet/helpers_test.go b/internal/vet/helpers_test.go index e336a54..23f1cc9 100644 --- a/internal/vet/helpers_test.go +++ b/internal/vet/helpers_test.go @@ -104,8 +104,11 @@ type index struct { dir string imports []core.Import endpoints []core.URLUse + reach map[string][]string // the files each test reaches } +func (x *index) Reaches(test, p string) bool { return slices.Contains(x.reach[test], p) } + var chainRe = regexp.MustCompile(`[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*`) func (x *index) Uses(names []string) []core.Site { diff --git a/internal/vet/lang.go b/internal/vet/lang.go index ae1ceee..1416a9b 100644 --- a/internal/vet/lang.go +++ b/internal/vet/lang.go @@ -1,6 +1,7 @@ package vet import ( + "bytes" "path" "strings" ) @@ -42,7 +43,7 @@ func blockComments(lang string) bool { // numbers still hold. It is a lexer for this purpose only: regex literals and // heredocs are not understood. func blank(lang string, src []byte) []byte { - res := []byte(string(src)) + res := bytes.Clone(src) starts := lineComments(lang) block := blockComments(lang) wipe := func(from, to int) { @@ -55,8 +56,8 @@ func blank(lang string, src []byte) []byte { for i := 0; i < len(src); { c := src[i] switch { - case block && strings.HasPrefix(string(src[i:min(i+2, len(src))]), "/*"): - end := strings.Index(string(src[i+2:]), "*/") + case block && bytes.HasPrefix(src[i:], []byte("/*")): + end := bytes.Index(src[i+2:], []byte("*/")) if end < 0 { end = len(src) } else { @@ -71,9 +72,9 @@ func blank(lang string, src []byte) []byte { } wipe(i, end) i = end - case lang == "python" && (strings.HasPrefix(string(src[i:min(i+3, len(src))]), `"""`) || strings.HasPrefix(string(src[i:min(i+3, len(src))]), `'''`)): - q := string(src[i : i+3]) - end := strings.Index(string(src[i+3:]), q) + case lang == "python" && (bytes.HasPrefix(src[i:], []byte(`"""`)) || bytes.HasPrefix(src[i:], []byte(`'''`))): + q := src[i : i+3] + end := bytes.Index(src[i+3:], q) if end < 0 { end = len(src) } else { @@ -112,7 +113,7 @@ func blank(lang string, src []byte) []byte { func hasAny(b []byte, prefixes []string) bool { for _, p := range prefixes { - if strings.HasPrefix(string(b[:min(len(p), len(b))]), p) { + if bytes.HasPrefix(b, []byte(p)) { return true } } diff --git a/internal/vet/lang_test.go b/internal/vet/lang_test.go index ad30a13..6210174 100644 --- a/internal/vet/lang_test.go +++ b/internal/vet/lang_test.go @@ -1,6 +1,10 @@ package vet -import "testing" +import ( + "strings" + "testing" + "time" +) func TestBlank(t *testing.T) { tests := []struct { @@ -34,6 +38,23 @@ func TestBlank(t *testing.T) { } } +func TestBlankLinear(t *testing.T) { + for _, tt := range []struct{ lang, line, want string }{ + {"js", "/*a*/x;\n", " x;\n"}, + {"python", "\"\"\"a\"\"\"\n", "\"\"\" \"\"\"\n"}, + } { + src := []byte(strings.Repeat(tt.line, 2<<20/len(tt.line))) + start := time.Now() + got := blank(tt.lang, src) + if d := time.Since(start); d > 2*time.Second { + t.Errorf("%s: blank took %s on %d bytes", tt.lang, d, len(src)) + } + if want := strings.Repeat(tt.want, len(src)/len(tt.line)); string(got) != want { + t.Errorf("%s: blank changed the output", tt.lang) + } + } +} + func TestHasWord(t *testing.T) { tests := []struct { s, name string diff --git a/internal/vet/lockfile.go b/internal/vet/lockfile.go index d21c431..6a96f5e 100644 --- a/internal/vet/lockfile.go +++ b/internal/vet/lockfile.go @@ -60,31 +60,44 @@ func lockfile(ctx context.Context, p *pass) ([]core.Finding, string) { } // moves says which packages a clean lockfile change moved: only the bumped -// ones, or those and so many of their dependencies. +// ones the lockfile names, or those and so many of their dependencies. func moves(ch *core.Change, moved []string) string { + in := func(n string) bool { + return len(moved) == 0 || slices.ContainsFunc(moved, func(m string) bool { return strings.EqualFold(m, n) }) + } var roots []string for _, d := range ch.Deps { - if !slices.Contains(roots, d.Name) { + if !slices.Contains(roots, d.Name) && in(d.Name) { roots = append(roots, d.Name) } } - if ch.ToName != "" { + if ch.ToName != "" && in(ch.ToName) { roots = append(roots, ch.ToName) } + if len(roots) == 0 { + return "only the bumped packages and their dependencies changed" + } rest := 0 for _, n := range moved { if !slices.ContainsFunc(roots, func(r string) bool { return strings.EqualFold(r, n) }) { rest++ } } - res := "only " + strings.Join(roots, ", ") + " changed" + names := strings.Join(roots, ", ") + if len(roots) > 8 { + names = fmt.Sprintf("the %d bumped packages", len(roots)) + } + its := "its" + if len(roots) > 1 { + its = "their" + } switch { case rest == 1: - res = "only " + strings.Join(roots, ", ") + " and 1 of its dependencies changed" + return fmt.Sprintf("only %s and 1 of %s dependencies changed", names, its) case rest > 1: - res = fmt.Sprintf("only %s and %d of its dependencies changed", strings.Join(roots, ", "), rest) + return fmt.Sprintf("only %s and %d of %s dependencies changed", names, rest, its) } - return res + return "only " + names + " changed" } // checkLock compares one lockfile before and after the patch. It returns the @@ -216,11 +229,12 @@ var relock = func(ctx context.Context, dir string, m core.Manifest, deps []core. if _, err := exec.LookPath(tool); err != nil { return core.ToolMissing{Tool: tool} } - cmd := exec.CommandContext(ctx, "sh", "-c", line) - cmd.Dir = filepath.Join(dir, filepath.FromSlash(path.Dir(m.Path))) - out, err := cmd.CombinedOutput() + out, err := eco.Run(ctx, filepath.Join(dir, filepath.FromSlash(path.Dir(m.Path))), line) if err != nil { - msg := strings.TrimSpace(string(out)) + msg := strings.TrimSpace(out) + if msg == "" { + msg = err.Error() + } if i := strings.LastIndexByte(msg, '\n'); i >= 0 { msg = msg[i+1:] } diff --git a/internal/vet/scope.go b/internal/vet/scope.go index 174e764..9b6b4aa 100644 --- a/internal/vet/scope.go +++ b/internal/vet/scope.go @@ -8,30 +8,28 @@ import ( "github.com/mohsensc/tend-cli/internal/core" "github.com/mohsensc/tend-cli/internal/gitx" + "github.com/mohsensc/tend-cli/internal/scan" ) // scope: does the diff touch only files this change explains? Those are the // manifests and lockfiles of the deps, files with affected call sites, files -// the patch's own steps name, and files the model was given to edit. +// the patch's own steps name, the code files the model was given to edit, +// and the tests the model edited that reach a site file. Any other test the +// model edited is left to the tests check, which flags it: reverting it would +// break the proof that ran with it. func scope(ctx context.Context, p *pass) ([]core.Finding, string) { - ok := p.depFiles() - for _, s := range p.in.Change.Sites { - ok[s.File] = true - } - for _, f := range mentioned(p.in.Patch.Applied) { - ok[f] = true - } - for f := range p.model { - ok[f] = true - } + ok := p.explained() var res []core.Finding kept := 0 for _, f := range p.files { file := f.Path() - if ok[file] { + if ok[file] || p.model[file] && scan.IsTest(file) && p.reachesSite(file) { kept++ continue } + if p.model[file] && scan.IsTest(file) { + continue + } if err := revert(ctx, p, f); err != nil { res = append(res, finding("scope", file, 0, "flagged", "not explained by this change, and reverting failed: %v", err)) continue diff --git a/internal/vet/section.go b/internal/vet/section.go index 3426d4d..f5647b8 100644 --- a/internal/vet/section.go +++ b/internal/vet/section.go @@ -8,9 +8,10 @@ import ( ) // Verdict is reject when symbols, fields or scope found something left -// unresolved and the patched proof fails; draft when symbols, fields, -// leftovers, lockfile or commands left a flag, or the baseline already -// fails; else pass. +// unresolved and the patched proof fails where the base does not; draft when symbols, fields, scope, +// leftovers, lockfile, commands or tests left a flag, or the baseline +// already fails; else pass. Flags from dead, debug and question are +// advisory: the PR lists them for the reviewer without holding it back. // Call it again after re-running the proof on a worktree that vetting changed. func Verdict(v *core.Vetting, proof *core.Proof) string { hard, soft := false, false @@ -23,13 +24,13 @@ func Verdict(v *core.Vetting, proof *core.Proof) string { hard = true } switch f.Check { - case "symbols", "fields", "leftovers", "lockfile", "commands": + case "symbols", "fields", "scope", "leftovers", "lockfile", "commands", "tests": soft = true } } failing := func(r *core.Run) bool { return r != nil && !r.Pass } switch { - case hard && proof != nil && failing(proof.Patched): + case hard && proof != nil && failing(proof.Patched) && (!failing(proof.Base) || !proof.Proven()): return "reject" case soft || proof != nil && failing(proof.Base): return "draft" @@ -47,6 +48,7 @@ var clean = map[string]string{ "dead": "nothing left unreferenced", "scope": "every changed file is explained by this change", "question": "nothing to note", + "tests": "no test weakened", } // Section renders the list under the PR body's Vetting heading: one line per diff --git a/internal/vet/symbols.go b/internal/vet/symbols.go index 681ae68..e78352e 100644 --- a/internal/vet/symbols.go +++ b/internal/vet/symbols.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "go/build" "go/parser" "go/token" "io/fs" @@ -19,6 +20,7 @@ import ( "time" "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/proc" ) type status int @@ -43,6 +45,7 @@ func symbols(ctx context.Context, p *pass) ([]core.Finding, string) { return nil, "no scan index" } r := &resolver{p: p, js: map[string]*jsPkg{}, added: map[string]map[int]string{}, docs: map[string]docResult{}} + major := ch.Level == "major" var res []core.Finding var where []string seen := map[string]bool{} @@ -61,7 +64,7 @@ func symbols(ctx context.Context, p *pass) ([]core.Finding, string) { seen[key] = true st, why, in := r.resolve(ctx, d, names, s) touched := r.touched(s) - if st == none || st == unknown && !touched { + if st == none || st == unknown && !touched && !major { continue } checked++ @@ -81,7 +84,11 @@ func symbols(ctx context.Context, p *pass) ([]core.Finding, string) { case missing: res = append(res, finding("symbols", s.File, s.Line, "flagged", "%s: %s", call, why)) case unknown: - res = append(res, finding("symbols", s.File, s.Line, "flagged", "%s not verified: %s", call, why)) + across := "" + if !touched { + across = " across the major release" + } + res = append(res, finding("symbols", s.File, s.Line, "flagged", "%s not verified%s: %s", call, across, why)) } } } @@ -152,28 +159,33 @@ func (r *resolver) resolve(ctx context.Context, d core.Dep, names []string, s co } // importOf finds the import the site's root binds to and returns the package -// and the chain as names inside that package. -func (r *resolver) importOf(names []string, s core.Site) (string, []string, bool) { +// and the chain as names inside that package. bound says the root is the +// module itself, as a require, a default or a namespace import binds it, +// rather than one name imported from it. +func (r *resolver) importOf(names []string, s core.Site) (pkg string, chain []string, bound, ok bool) { for _, n := range names { for _, imp := range r.p.in.Index.Imports(n) { if imp.File != s.File { continue } if imp.Binding == s.Chain[0] { - return imp.Package, s.Chain[1:], true + return imp.Package, s.Chain[1:], true, true } if slices.Contains(imp.Names, s.Chain[0]) { - return imp.Package, s.Chain, true + return imp.Package, s.Chain, false, true } } } - return "", nil, false + return "", nil, false, false } type jsPkg struct { label string // name@version text string // every .d.ts file and the entry file exports map[string]bool + typed bool // it ships typings, or @types has them + value string // what the module itself is, when it is one named thing: axios for export default axios + partial bool // module.exports is a value whose members a scan of the code cannot read members map[string]status // member answers by "name.m" decls map[string]string // the line declaring "name.m", when found } @@ -183,14 +195,15 @@ var ( jsList = regexp.MustCompile(`\bexport\s+(?:type\s+)?\{([^}]*)\}`) cjsProp = regexp.MustCompile(`\b(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*=`) cjsObj = regexp.MustCompile(`\bmodule\.exports\s*=\s*\{`) + cjsVal = regexp.MustCompile(`\bmodule\.exports\s*=\s*(?:new\s+)?([^\s{;=][^\s;(]*)`) + jsDflt = regexp.MustCompile(`\bexport\s+default\s+(?:(?:abstract\s+)?class\s+|(?:async\s+)?function\*?\s+)?([A-Za-z_$][\w$]*)`) + tsEq = regexp.MustCompile(`\bexport\s*=\s*([A-Za-z_$][\w$]*)`) jsKey = regexp.MustCompile(`^\s*(?:async\s+|get\s+|set\s+|\*\s*)?['"]?([A-Za-z_$][\w$]*)`) ) func (r *resolver) npm(names []string, s core.Site) (status, string, string) { - pkg, chain, ok := r.importOf(names, s) + pkg, chain, bound, ok := r.importOf(names, s) if !ok { - // The call goes through a value the code made, such as an app a - // factory returned, whose members no export declares. return none, "", "" } if len(chain) == 0 { @@ -202,7 +215,16 @@ func (r *resolver) npm(names []string, s core.Site) (status, string, string) { return unknown, name + " is not installed", "" } in := "in " + js.label + " typings" + if !js.typed && len(js.exports) == 0 { + return unknown, fmt.Sprintf("%s ships no typings, and its exports cannot be read", js.label), "" + } if !js.exports[chain[0]] { + if bound && (js.value != "" || js.partial) { + return js.ofValue(chain, in) + } + if !js.typed && js.partial { + return unknown, fmt.Sprintf("%s's module.exports is a value whose members cannot be read", js.label), "" + } return missing, fmt.Sprintf("`%s` is not exported by %s", chain[0], js.label), in } if len(chain) == 1 { @@ -220,10 +242,32 @@ func (r *resolver) npm(names []string, s core.Site) (status, string, string) { return resolved, "", in } +// ofValue resolves chain as members of what the module itself is: get on +// axios's default export, whose type extends the class that declares it. +func (js *jsPkg) ofValue(chain []string, in string) (status, string, string) { + opaque := fmt.Sprintf("%s's module.exports is a value whose members cannot be read", js.label) + if js.value == "" || js.value == "function" || js.value == "class" { + return unknown, opaque, "" + } + switch js.member(js.value, chain[0]) { + case missing: + return missing, fmt.Sprintf("`%s` is neither exported by %s nor a member of what it exports", chain[0], js.label), in + case unknown: + if !js.typed { + return unknown, opaque, "" + } + return unknown, fmt.Sprintf("no declaration of what %s exports to look `%s` up in", js.label, chain[0]), "" + } + if len(chain) > 1 { + return unknown, fmt.Sprintf("checked as far as `%s`", chain[0]), in + } + return resolved, "", in +} + // declare keeps the line of the new typings that declares a call the patch // wrote, for the question check to show. func (r *resolver) declare(names []string, s core.Site) { - pkg, chain, ok := r.importOf(names, s) + pkg, chain, _, ok := r.importOf(names, s) if !ok || len(chain) != 2 { return } @@ -265,6 +309,9 @@ func (r *resolver) jsPackage(file, name string) *jsPkg { } if fi, err := os.Stat(cand); err == nil && fi.IsDir() { js := loadJS(cand, name) + if js != nil && !js.typed { + js.with(filepath.Join(dir, "node_modules", "@types", typesName(name))) + } r.js[cand] = js return js } @@ -275,18 +322,35 @@ func (r *resolver) jsPackage(file, name string) *jsPkg { } } +// typesName is where DefinitelyTyped keeps a package's typings under @types: +// passport, or scope__pkg for @scope/pkg. +func typesName(name string) string { + if s, p, ok := strings.Cut(strings.TrimPrefix(name, "@"), "/"); ok && strings.HasPrefix(name, "@") { + return s + "__" + p + } + return name +} + +// with reads the typings in dir, @types for a package that ships none, into js. +func (js *jsPkg) with(dir string) { + text, typed := dtsIn(dir) + if !typed { + return + } + js.text += "\n" + text + js.typed = true + js.read() +} + const ( jsMax = 16 << 20 declMax = 300 ) -func loadJS(dir, name string) *jsPkg { - var meta struct{ Version, Main string } - label := name - if b, err := os.ReadFile(filepath.Join(dir, "package.json")); err == nil && json.Unmarshal(b, &meta) == nil && meta.Version != "" { - label += "@" + meta.Version - } +// dtsIn is every typings file under dir, and whether there was one. +func dtsIn(dir string) (string, bool) { var text strings.Builder + typed := false err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err != nil || text.Len() > jsMax { return filepath.SkipDir @@ -299,13 +363,29 @@ func loadJS(dir, name string) *jsPkg { if b, err := os.ReadFile(p); err == nil { text.Write(b) text.WriteByte('\n') + typed = true } } return nil }) if err != nil { + return "", false + } + return text.String(), typed +} + +func loadJS(dir, name string) *jsPkg { + var meta struct{ Version, Main string } + label := name + if b, err := os.ReadFile(filepath.Join(dir, "package.json")); err == nil && json.Unmarshal(b, &meta) == nil && meta.Version != "" { + label += "@" + meta.Version + } + if _, err := os.Stat(dir); err != nil { return nil } + dts, typed := dtsIn(dir) + var text strings.Builder + text.WriteString(dts) entry := meta.Main if entry == "" { entry = "index.js" @@ -316,7 +396,15 @@ func loadJS(dir, name string) *jsPkg { break } } - js := &jsPkg{label: label, text: text.String(), exports: map[string]bool{}} + js := &jsPkg{label: label, text: text.String(), typed: typed} + js.read() + return js +} + +// read finds what js exports in its text: the names, and what the module +// itself is when it is one value. +func (js *jsPkg) read() { + js.exports, js.members, js.decls = map[string]bool{}, nil, nil for _, m := range jsDecl.FindAllStringSubmatch(js.text, -1) { js.exports[m[1]] = true } @@ -336,7 +424,22 @@ func loadJS(dir, name string) *jsPkg { js.exports[k] = true } } - return js + js.value, js.partial = "", false + for _, re := range []*regexp.Regexp{tsEq, jsDflt} { + if m := re.FindStringSubmatch(js.text); m != nil { + js.value = m[1] + return + } + } + for _, m := range cjsVal.FindAllStringSubmatch(js.text, -1) { + if m[1] == "exports" || strings.HasPrefix(m[1], "require") { + continue + } + js.partial = true + if v := m[1]; regexp.MustCompile(`^[A-Za-z_$][\w$]*$`).MatchString(v) { + js.value = v + } + } } // member looks for m inside the declarations of name and inside the type name @@ -369,27 +472,180 @@ func (js *jsPkg) lookup(name, m string) (status, string) { if res == resolved { return res, decl } - typed := regexp.MustCompile(`\b` + q + `\s*\??\s*:\s*(?:[A-Za-z_$][\w$]*\.)*([A-Za-z_$][\w$]*)\s*[;,\n]`) - if t := typed.FindStringSubmatch(js.text); t != nil { - head := regexp.MustCompile(`\b(?:class|interface)\s+` + regexp.QuoteMeta(t[1]) + `\b[^{;]*\{`) - if st, decl := js.lookIn([]*regexp.Regexp{head}, m); st != unknown { + if t := js.declType(name); t != "" { + if st, decl := js.inType(t, m, map[string]bool{}); st != unknown { return st, decl } } return res, "" } +// declType is the type name is declared with, as written: "AxiosStatic" for +// `declare const axios: AxiosStatic;`, "" when there is none. +func (js *jsPkg) declType(name string) string { + q := regexp.QuoteMeta(name) + for _, re := range []*regexp.Regexp{ + regexp.MustCompile(`\b(?:const|let|var)\s+` + q + `\s*:\s*`), + regexp.MustCompile(`(?:^|[\s;{,])` + q + `\s*\??\s*:\s*`), + } { + if loc := re.FindStringIndex(js.text); loc != nil { + if t := typeExpr(js.text[loc[1]:]); t != "" && !strings.HasPrefix(t, "{") { + return t + } + } + } + return "" +} + +// typeExpr is the type written at the start of s: up to the semicolon, +// comma or end of line that ends it outside any brackets. +func typeExpr(s string) string { + depth := 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; c { + case '{', '(', '[', '<': + depth++ + case '}', ')', ']', '>': + if depth == 0 { + return strings.TrimSpace(s[:i]) + } + depth-- + case ';', ',', '=': + if depth == 0 { + return strings.TrimSpace(s[:i]) + } + case '\n': + rest := strings.TrimSpace(s[i:]) + if depth == 0 && !strings.HasPrefix(rest, "&") && !strings.HasPrefix(rest, "|") && !strings.HasSuffix(strings.TrimSpace(s[:i]), "&") && !strings.HasSuffix(strings.TrimSpace(s[:i]), "|") { + return strings.TrimSpace(s[:i]) + } + } + } + return strings.TrimSpace(s) +} + +// splitTop splits s at sep where no bracket is open. +func splitTop(s string, sep ...byte) []string { + var res []string + depth, start := 0, 0 + for i := 0; i < len(s); i++ { + switch c := s[i]; { + case c == '{' || c == '(' || c == '[' || c == '<': + depth++ + case c == '}' || c == ')' || c == ']' || c == '>': + depth-- + case depth == 0 && slices.Contains(sep, c): + res = append(res, strings.TrimSpace(s[start:i])) + start = i + 1 + } + } + return append(res, strings.TrimSpace(s[start:])) +} + +// inType looks for m in a type expression: each part of an intersection or +// union, an object literal, or a named type, with what it extends. It is +// missing only when every part was found and none declares m. +func (js *jsPkg) inType(expr, m string, seen map[string]bool) (status, string) { + res := missing + for _, part := range splitTop(expr, '&', '|') { + var st status + var decl string + switch { + case part == "": + continue + case strings.HasPrefix(part, "{"): + st, decl = blockHas(braceBlock(part, 0), m) + case strings.HasPrefix(part, "typeof "): + st, decl = js.lookup(strings.TrimSpace(strings.TrimPrefix(part, "typeof ")), m) + default: + st, decl = js.typeHas(typeName(part), m, seen) + } + switch st { + case resolved: + return resolved, decl + case unknown: + res = unknown + } + } + return res, "" +} + +// typeName is the bare name of a type reference: Chalk for chalk.Chalk. +func typeName(ref string) string { + ref, _, _ = strings.Cut(ref, "<") + ref = strings.TrimSpace(ref) + return ref[strings.LastIndexByte(ref, '.')+1:] +} + +// typeHas looks for m in the classes, interfaces and type aliases named t, +// and in what they extend. +func (js *jsPkg) typeHas(t, m string, seen map[string]bool) (status, string) { + if seen[t] || len(seen) > 32 || !regexp.MustCompile(`^[A-Za-z_$][\w$]*$`).MatchString(t) { + return unknown, "" + } + seen[t] = true + q := regexp.QuoteMeta(t) + found := false + var bases []string + head := regexp.MustCompile(`\b(?:class|interface)\s+` + q + `\b([^{;]*)\{`) + for _, loc := range head.FindAllStringSubmatchIndex(js.text, -1) { + found = true + if st, decl := blockHas(braceBlock(js.text, loc[1]-1), m); st == resolved { + return st, decl + } + h := js.text[loc[2]:loc[3]] + if _, ext, ok := strings.Cut(h, "extends"); ok { + ext, _, _ = strings.Cut(ext, "implements") + bases = append(bases, splitTop(ext, ',')...) + } + } + alias := regexp.MustCompile(`\btype\s+` + q + `\s*(?:<[^=]*>)?\s*=\s*`) + for _, loc := range alias.FindAllStringIndex(js.text, -1) { + found = true + st, decl := js.inType(typeExpr(js.text[loc[1]:]), m, seen) + if st == resolved { + return st, decl + } + if st == unknown { + return unknown, "" + } + } + if !found { + return unknown, "" + } + res := missing + for _, b := range bases { + switch st, decl := js.typeHas(typeName(b), m, seen); st { + case resolved: + return st, decl + case unknown: + res = unknown + } + } + return res, "" +} + +// blockHas looks for a member m declared in a type or object body. +func blockHas(block, m string) (status, string) { + if at := memberOf(m).FindStringIndex(block); at != nil { + start := strings.LastIndexByte(block[:at[1]], '\n') + 1 + line, _, _ := strings.Cut(block[start:], "\n") + return resolved, core.Clip(strings.TrimSpace(line), declMax) + } + return missing, "" +} + +func memberOf(m string) *regexp.Regexp { + return regexp.MustCompile(`(?:^|[\s;{,(])(?:(?:readonly|static|public|async|get|set|declare|export|function|const|let|var|abstract)\s+)*` + regexp.QuoteMeta(m) + `\s*\??\s*[(:<=,;}]`) +} + // lookIn also returns the line that declares m, when it is found. func (js *jsPkg) lookIn(heads []*regexp.Regexp, m string) (status, string) { - member := regexp.MustCompile(`(?:^|[\s;{,(])(?:(?:readonly|static|public|async|get|set|declare|export|function|const|let|var|abstract)\s+)*` + regexp.QuoteMeta(m) + `\s*\??\s*[(:<=,;}]`) res := unknown for _, h := range heads { for _, loc := range h.FindAllStringIndex(js.text, -1) { - block := braceBlock(js.text, loc[1]-1) - if at := member.FindStringIndex(block); at != nil { - start := strings.LastIndexByte(block[:at[1]], '\n') + 1 - line, _, _ := strings.Cut(block[start:], "\n") - return resolved, core.Clip(strings.TrimSpace(line), declMax) + if st, decl := blockHas(braceBlock(js.text, loc[1]-1), m); st == resolved { + return st, decl } if strings.Contains(js.text[loc[0]:loc[1]], "extends") { continue @@ -463,10 +719,14 @@ func (r *resolver) golang(ctx context.Context, s core.Site) (status, string) { if len(s.Chain) > 2 { sym += "." + s.Chain[2] } - k := pkg + " " + sym + target, ok := goTarget(filepath.Join(r.p.in.Dir, filepath.FromSlash(s.File))) + if !ok { + return unknown, "the file builds only under build tags no platform sets" + } + k := pkg + " " + sym + " " + target res, ok := r.docs[k] if !ok { - res.st, res.why = goDoc(ctx, r.p.in.Dir, pkg, sym) + res.st, res.why = goDoc(ctx, r.p.in.Dir, pkg, sym, target) r.docs[k] = res } if res.st == resolved && len(s.Chain) > 3 { @@ -477,12 +737,18 @@ func (r *resolver) golang(ctx context.Context, s core.Site) (status, string) { // goDoc asks go doc whether pkg has sym, from the worktree's module. go.mod is // read only: a change go doc made to it would be committed without being vetted. -func goDoc(ctx context.Context, dir, pkg, sym string) (status, string) { +func goDoc(ctx context.Context, dir, pkg, sym, target string) (status, string) { ctx, cancel := context.WithTimeout(ctx, goDocTimeout) defer cancel() cmd := exec.CommandContext(ctx, "go", "doc", pkg, sym) cmd.Dir = dir - cmd.Env = append(os.Environ(), "GOFLAGS=-mod=readonly") + env := []string{"GOFLAGS=-mod=readonly"} + if goos, goarch, ok := strings.Cut(target, "/"); ok { + env = append(env, "GOOS="+goos, "GOARCH="+goarch) + } + cmd.Env = core.Environ(env...) + proc.Group(cmd) + cmd.WaitDelay = time.Second out, err := cmd.CombinedOutput() if err == nil { return resolved, "" @@ -500,6 +766,34 @@ func goDoc(ctx context.Context, dir, pkg, sym string) (status, string) { return unknown, strings.TrimPrefix(msg, "doc: ") } +// goTargets are the platforms a file that does not build on this one is +// looked up for, the common ones first. +var goTargets = []string{ + "linux/amd64", "darwin/arm64", "windows/amd64", "freebsd/amd64", "openbsd/amd64", "netbsd/amd64", + "dragonfly/amd64", "solaris/amd64", "illumos/amd64", "aix/ppc64", "zos/s390x", "plan9/amd64", + "android/arm64", "ios/arm64", "js/wasm", "wasip1/wasm", "linux/arm64", "linux/386", "linux/arm", + "linux/s390x", "linux/ppc64le", "linux/riscv64", "linux/mips64", "linux/loong64", "windows/arm64", +} + +// goTarget is the platform the file at p builds for, as GOOS/GOARCH: "" +// for this one, or the first of goTargets its build constraints and name +// allow. ok is false when none does, for a file behind a custom tag. +func goTarget(p string) (string, bool) { + dir, name := filepath.Split(p) + if ok, err := build.Default.MatchFile(dir, name); err != nil || ok { + return "", true + } + for _, t := range goTargets { + c := build.Default + c.GOOS, c.GOARCH, _ = strings.Cut(t, "/") + c.CgoEnabled = true + if ok, err := c.MatchFile(dir, name); err == nil && ok { + return t, true + } + } + return "", false +} + var goMajor = regexp.MustCompile(`^v[0-9]+$`) // goImports maps the names a Go file binds its imports to onto import paths. @@ -536,7 +830,7 @@ func goImports(file string) map[string]string { } func (r *resolver) pip(names []string, s core.Site) (status, string, string) { - mod, chain, ok := r.importOf(names, s) + mod, chain, _, ok := r.importOf(names, s) if !ok { return none, "", "" } diff --git a/internal/vet/symbols_test.go b/internal/vet/symbols_test.go index 55c65d7..282d4e0 100644 --- a/internal/vet/symbols_test.go +++ b/internal/vet/symbols_test.go @@ -2,8 +2,12 @@ package vet import ( "context" + "os" "os/exec" + "path/filepath" + "runtime" "slices" + "strings" "testing" "github.com/mohsensc/tend-cli/internal/core" @@ -85,6 +89,31 @@ export declare class Client {} } } +// A package with no typings whose exports a scan cannot read, as lodash's +// module.exports = require('./lodash'), says nothing is missing from it. +func TestSymbolsUntyped(t *testing.T) { + base := map[string]string{".gitignore": "node_modules/\n", "src/a.js": "const _ = require('lodash')\n_.chunk([])\n"} + patched := map[string]string{ + "src/a.js": "const _ = require('lodash')\n_.chunk([1])\n", + "node_modules/lodash/package.json": `{"name": "lodash", "version": "4.18.1", "main": "lodash.js"}`, + "node_modules/lodash/lodash.js": "lodash.chunk = chunk;\nmodule.exports = lodash;\n", + } + dir, sha, diff := worktree(t, base, patched) + p := newPass(Input{ + Dir: dir, Base: sha, + Change: &core.Change{Deps: []core.Dep{{Ecosystem: core.Npm, Name: "lodash"}}, To: "4.18.1"}, + Patch: &core.Patch{Diff: diff}, + Ecos: ecos(core.Npm), + Index: &index{dir: dir, imports: []core.Import{{File: "src/a.js", Line: 1, Package: "lodash", Binding: "_"}}}, + }) + got, _ := symbols(context.Background(), p) + for _, f := range got { + if strings.Contains(f.Msg, "is not exported") { + t.Errorf("flagged %+v", f) + } + } +} + func TestSymbolsCommonJS(t *testing.T) { js := &jsPkg{text: `exports.e = 1; module.exports = { @@ -165,7 +194,7 @@ func TestGoDocLeavesGoModAlone(t *testing.T) { "go.mod": mod, "lib/lib.go": "package lib\n\nfunc Hello() {}\n", }) - if st, why := goDoc(context.Background(), dir, "example.com/m/lib", "Hello"); st != resolved { + if st, why := goDoc(context.Background(), dir, "example.com/m/lib", "Hello", ""); st != resolved { t.Errorf("goDoc = %v %q, want resolved", st, why) } if got := read(t, dir, "go.mod"); got != mod { @@ -275,3 +304,194 @@ func TestSymbolsSkips(t *testing.T) { t.Errorf("skip = %q", skip) } } + +// A require or default import binds what the module itself is, so a member +// of it resolves through the default export's type, what it extends among it. +func TestSymbolsDefaultExport(t *testing.T) { + pkgs := map[string]map[string]string{ + "axios": { + "package.json": `{"name": "axios", "version": "1.20.0", "main": "index.js", "types": "index.d.ts"}`, + "index.d.ts": `export class Axios { + constructor(config?: AxiosRequestConfig); + get, D = any>(url: string, config?: AxiosRequestConfig): Promise; +} +export interface AxiosInstance extends Axios { + (config: AxiosRequestConfig): Promise; + defaults: object; +} +export interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; +} +declare const axios: AxiosStatic; +export default axios; +`, + "index.js": "module.exports = require('./lib/axios')\n", + }, + "chalk": { + "package.json": `{"name": "chalk", "version": "4.1.2", "main": "source", "types": "index.d.ts"}`, + "index.d.ts": `declare namespace chalk { + interface ChalkFunction { + (text: TemplateStringsArray, ...placeholders: unknown[]): string; + } + interface Chalk extends ChalkFunction { + readonly green: Chalk; + } +} +declare const chalk: chalk.Chalk & chalk.ChalkFunction & { + supportsColor: chalk.ColorSupport | false; +}; +export = chalk; +`, + }, + "kleur": { + "package.json": `{"name": "kleur", "version": "5.0.0", "types": "index.d.ts"}`, + "index.d.ts": `export interface ChalkInstance { + red: ChalkInstance; +} +declare const kleur: ChalkInstance; +export default kleur; +`, + }, + "passport": { + "package.json": `{"name": "passport", "version": "0.6.0", "main": "./lib"}`, + "lib/index.js": `var Passport = require('./authenticator') + , SessionStrategy = require('./strategies/session'); + +exports = module.exports = new Passport(); +exports.Passport = +exports.Authenticator = Passport; +exports.Strategy = require('passport-strategy'); +`, + }, + } + base := map[string]string{".gitignore": "node_modules/\n", "src/a.js": "const axios = require('axios')\n"} + src := `const axios = require('axios') +const chalk = require('chalk') +import kleur from 'kleur' +const passport = require('passport') +axios.get(url) +chalk.green('ok') +kleur.red('x') +kleur.blue('x') +passport.initialize() +` + patched := map[string]string{"src/a.js": src} + var imports []core.Import + for i, name := range []string{"axios", "chalk", "kleur", "passport"} { + imports = append(imports, core.Import{File: "src/a.js", Line: i + 1, Package: name, Binding: name}) + for f, body := range pkgs[name] { + patched["node_modules/"+name+"/"+f] = body + } + } + dir, sha, diff := worktree(t, base, patched) + var deps []core.Dep + for _, name := range []string{"axios", "chalk", "kleur", "passport"} { + deps = append(deps, core.Dep{Ecosystem: core.Npm, Name: name}) + } + p := newPass(Input{ + Dir: dir, Base: sha, + Change: &core.Change{Deps: deps, To: "1.0.0"}, + Patch: &core.Patch{Diff: diff}, + Ecos: ecos(core.Npm), + Index: &index{dir: dir, imports: imports}, + }) + got, _ := symbols(context.Background(), p) + eq(t, got, + "flagged src/a.js:8 `kleur.blue`: `blue` is neither exported by kleur@5.0.0 nor a member of what it exports", + "flagged src/a.js:9 `passport.initialize` not verified: passport@0.6.0's module.exports is a value whose members cannot be read", + ) +} + +// Typings from @types count for a package that ships none. +func TestSymbolsAtTypes(t *testing.T) { + base := map[string]string{".gitignore": "node_modules/\n", "src/a.js": "const passport = require('passport')\n"} + patched := map[string]string{ + "src/a.js": "const passport = require('passport')\npassport.use(s)\npassport.authenticate('x')\npassport.gone()\n", + "node_modules/passport/package.json": `{"name": "passport", "version": "0.6.0", "main": "./lib"}`, + "node_modules/passport/lib/index.js": "exports = module.exports = new Passport();\nexports.Passport = Passport;\n", + "node_modules/@types/passport/package.json": `{"name": "@types/passport", "version": "1.0.16"}`, + "node_modules/@types/passport/index.d.ts": `declare namespace passport { + interface Authenticator { + use(strategy: Strategy): this; + authenticate(strategy: string | string[]): any; + } + interface PassportStatic extends Authenticator { + Authenticator: { new (): Authenticator }; + } +} +declare const passport: passport.PassportStatic; +export = passport; +`, + } + dir, sha, diff := worktree(t, base, patched) + p := newPass(Input{ + Dir: dir, Base: sha, + Change: &core.Change{Deps: []core.Dep{{Ecosystem: core.Npm, Name: "passport"}}, To: "0.6.0"}, + Patch: &core.Patch{Diff: diff}, + Ecos: ecos(core.Npm), + Index: &index{dir: dir, imports: []core.Import{{File: "src/a.js", Line: 1, Package: "passport", Binding: "passport"}}}, + }) + got, _ := symbols(context.Background(), p) + eq(t, got, "flagged src/a.js:4 `passport.gone`: `gone` is neither exported by passport@0.6.0 nor a member of what it exports") + if typesName("@scope/pkg") != "scope__pkg" || typesName("passport") != "passport" { + t.Error("typesName") + } +} + +// A file behind build constraints is looked up for a platform it builds on. +func TestGoTarget(t *testing.T) { + dir := t.TempDir() + other := "linux" + if runtime.GOOS == "linux" { + other = "darwin" + } + files := map[string]string{ + "plain.go": "package x\n", + "only.go": "//go:build " + other + "\n\npackage x\n", + "term_solaris.go": "package x\n", + "tagged.go": "//go:build integration\n\npackage x\n", + "terminal_check_notappengine.go": "//go:build !appengine && !js && !windows && !nacl && !plan9\n\npackage x\n", + } + for name, body := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + for name, want := range map[string]string{"plain.go": "", "only.go": other + "/", "term_solaris.go": "solaris/amd64"} { + got, ok := goTarget(filepath.Join(dir, name)) + if !ok || !strings.HasPrefix(got, want) || want == "" && got != "" { + t.Errorf("goTarget(%s) = %q, %v; want %q", name, got, ok, want) + } + } + if got, ok := goTarget(filepath.Join(dir, "tagged.go")); ok { + t.Errorf("a custom tag builds for %q", got) + } +} + +// A call the patch left alone that tend cannot look into is said on a major +// bump, so the PR does not read as fully checked. +func TestSymbolsMajorUnverified(t *testing.T) { + base := map[string]string{".gitignore": "node_modules/\n", "src/a.js": "const _ = require('lodash')\n_.chunk([])\n", "package.json": "{}\n"} + patched := map[string]string{ + "package.json": "{\"x\": 1}\n", + "node_modules/lodash/package.json": `{"name": "lodash", "version": "5.0.0", "main": "lodash.js"}`, + "node_modules/lodash/lodash.js": "module.exports = lodash;\n", + } + dir, sha, diff := worktree(t, base, patched) + in := func(level string) *pass { + return newPass(Input{ + Dir: dir, Base: sha, + Change: &core.Change{Level: level, Deps: []core.Dep{{Ecosystem: core.Npm, Name: "lodash"}}, To: "5.0.0"}, + Patch: &core.Patch{Diff: diff}, + Ecos: ecos(core.Npm), + Index: &index{dir: dir, imports: []core.Import{{File: "src/a.js", Line: 1, Package: "lodash", Binding: "_"}}}, + }) + } + got, _ := symbols(context.Background(), in("major")) + if len(got) != 1 || !strings.Contains(got[0].Msg, "not verified across the major release") { + t.Errorf("major: %+v", got) + } + if got, skip := symbols(context.Background(), in("minor")); len(got) != 0 || skip != na { + t.Errorf("minor: %+v, %q", got, skip) + } +} diff --git a/internal/vet/tests.go b/internal/vet/tests.go new file mode 100644 index 0000000..397b14b --- /dev/null +++ b/internal/vet/tests.go @@ -0,0 +1,109 @@ +package vet + +import ( + "context" + "regexp" + "slices" + + "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/scan" +) + +var ( + assertPat = regexp.MustCompile(`\b(assert\w*|expect\w*|should|require\.\w+|t\.(Error|Errorf|Fatal|Fatalf|Fail|FailNow))\b`) + trivialPat = regexp.MustCompile(`\b(assert\w*|expect\w*)(\.\w+)*\s*(\(\s*(true|True|1|!0)\s*\)|\s+(true|True|1)\s*$)`) + casePat = regexp.MustCompile(`(^|[^.\w])(it|test|describe|context)\s*(\.\w+\s*)?\(|\bit\s+["']|^\s*func\s+Test\w*\s*\(|^\s*(async\s+)?def\s+test\w*\s*\(|@Test\b|#\[test\]|\bt\.Run\s*\(`) + skipPat = regexp.MustCompile(`(^|[^\w])(xit|xdescribe|xtest)\s*\(|\.(skip|todo)\s*\(|\bt\.Skip\w*\s*\(|@(pytest\.mark\.skip\w*|unittest\.skip\w*|Disabled|Ignore)\b|#\[ignore\]|\bskip\s*\(`) +) + +// tests: did a model weaken a test, or edit one that reaches none of the +// files this change explains? A test edit is never reverted, since the +// proof ran with it; the flag makes the PR a draft. +func tests(ctx context.Context, p *pass) ([]core.Finding, string) { + if !p.in.Patch.Model { + return nil, na + } + ok := p.explained() + var res []core.Finding + for _, f := range p.files { + file := f.Path() + if !scan.IsTest(file) || !slices.ContainsFunc(f.Hunks, func(h *hunk) bool { return h.Model }) { + continue + } + if !ok[file] && !p.reachesSite(file) { + res = append(res, finding("tests", file, 0, "flagged", "a model edited this test, which reaches none of the files this change explains")) + } + if f.New == "" { + res = append(res, finding("tests", file, 0, "flagged", "a model deleted this test")) + continue + } + lang := langOf(file) + asserts, cases, skips := 0, 0, 0 + for _, h := range f.Hunks { + if !h.Model { + continue + } + for _, l := range h.Lines { + code := l.Text + if lang != "" { + code = codeOf(lang, l.Text) + } + n := 0 + switch l.Op { + case '-': + n = 1 + case '+': + n = -1 + if skipPat.MatchString(code) { + skips++ + } + default: + continue + } + if assertPat.MatchString(code) && (n > 0 || !trivialPat.MatchString(code)) { + asserts += n + } + if casePat.MatchString(code) { + cases += n + } + } + } + switch { + case cases > 0: + res = append(res, finding("tests", file, 0, "flagged", "a model removed %s from this test", count(cases, "test case"))) + case asserts > 0: + res = append(res, finding("tests", file, 0, "flagged", "a model removed %s from this test without adding as many back", count(asserts, "assertion"))) + } + if skips > 0 { + res = append(res, finding("tests", file, 0, "flagged", "a model skipped %s in this test", count(skips, "test"))) + } + } + sortFindings(res) + return res, "" +} + +// explained are the files this change explains: the manifests and lockfiles +// of the deps, files with affected call sites, files the patch's own steps +// name, and the code files a model was given to edit. A test the model +// edited is not explained by that alone. +func (p *pass) explained() map[string]bool { + ok := p.depFiles() + for _, s := range p.in.Change.Sites { + ok[s.File] = true + } + for _, f := range mentioned(p.in.Patch.Applied) { + ok[f] = true + } + for f := range p.model { + if !scan.IsTest(f) { + ok[f] = true + } + } + return ok +} + +// reachesSite reports whether the test file test reaches a file with one of +// the change's call sites. +func (p *pass) reachesSite(test string) bool { + return slices.ContainsFunc(p.in.Change.Sites, func(s core.Site) bool { return core.Reaches(p.in.Index, test, s.File) }) +} diff --git a/internal/vet/tests_test.go b/internal/vet/tests_test.go new file mode 100644 index 0000000..4a69549 --- /dev/null +++ b/internal/vet/tests_test.go @@ -0,0 +1,75 @@ +package vet + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/mohsensc/tend-cli/internal/core" + "github.com/mohsensc/tend-cli/internal/gitx" +) + +func TestTests(t *testing.T) { + base := map[string]string{ + "package.json": "{\"a\": 1}\n", + "src/billing.js": "pay.charges.create()\n", + "test/billing.test.js": "test('total', () => {\n assert.equal(total(), 42)\n})\n", + "test/refund.test.js": "test('refund', () => {\n assert.equal(refund(), 1)\n})\ntest('void', () => {\n assert.ok(voided())\n})\n", + "test/unrelated.test.js": "test('other', () => {\n assert.equal(other(), 1)\n})\n", + "test/skipped.test.js": "test('slow', () => {\n expect(slow()).toBe(2)\n})\n", + "test/tend/characterization.js": "test('pins', () => {\n assert.equal(total(), 42)\n})\n", + } + patched := map[string]string{ + "package.json": "{\"a\": 2}\n", + "src/billing.js": "pay.paymentIntents.create()\n", + "test/billing.test.js": "test('total', () => {\n assert.ok(true)\n})\n", + "test/refund.test.js": "test('refund', () => {\n assert.equal(refund(), 1)\n assert.ok(refunded())\n})\n", + "test/unrelated.test.js": "test('other', () => {\n assert.equal(other(), 2)\n})\n", + "test/skipped.test.js": "test.skip('slow', () => {\n expect(slow()).toBe(3)\n})\n", + } + dir, sha, _ := worktree(t, base, patched) + if err := os.Remove(filepath.Join(dir, "test", "tend", "characterization.js")); err != nil { + t.Fatal(err) + } + sh(t, dir, "git", "add", "-A") + diff, err := gitx.Raw(context.Background(), dir, "diff", "--no-color", "--no-renames", sha) + if err != nil { + t.Fatal(err) + } + ch := &core.Change{ + Deps: []core.Dep{{Ecosystem: core.Npm, Name: "pay", Manifest: core.Manifest{Path: "package.json"}}}, + Sites: []core.Site{{File: "src/billing.js", Line: 1}}, + } + edited := []string{"src/billing.js", "test/billing.test.js", "test/refund.test.js", "test/unrelated.test.js", "test/skipped.test.js", "test/tend/characterization.js"} + idx := &index{dir: dir, reach: map[string][]string{}} + for _, f := range edited[1:] { + if f != "test/unrelated.test.js" { + idx.reach[f] = []string{"src/billing.js"} + } + } + patch := &core.Patch{Diff: diff, Model: true, Edited: edited} + p := newPass(Input{Dir: dir, Base: sha, Change: ch, Patch: patch, Index: idx}) + got, skip := tests(context.Background(), p) + if skip != "" { + t.Fatalf("skipped: %s", skip) + } + eq(t, got, + "flagged test/billing.test.js:0 a model removed 1 assertion from this test without adding as many back", + "flagged test/refund.test.js:0 a model removed 1 test case from this test", + "flagged test/skipped.test.js:0 a model skipped 1 test in this test", + "flagged test/tend/characterization.js:0 a model deleted this test", + "flagged test/unrelated.test.js:0 a model edited this test, which reaches none of the files this change explains", + ) + + got, _ = scope(context.Background(), p) + eq(t, got) + if p.note != "6 files, all explained by this change" { + t.Errorf("scope note = %q", p.note) + } + + p = newPass(Input{Dir: dir, Base: sha, Change: ch, Patch: &core.Patch{Diff: diff, Edited: edited}, Index: idx}) + if _, skip := tests(context.Background(), p); skip != na { + t.Errorf("a patch no model wrote: skip = %q", skip) + } +} diff --git a/internal/vet/vet.go b/internal/vet/vet.go index 3ec7a9b..c5f82de 100644 --- a/internal/vet/vet.go +++ b/internal/vet/vet.go @@ -67,6 +67,7 @@ var checks = []check{ {name: "debug", fn: debug}, {name: "comments", fn: comments}, {name: "commands", fn: commands, quiet: true}, + {name: "tests", fn: tests, quiet: true}, {name: "dead", fn: dead}, {name: "question", fn: questions}, } diff --git a/internal/vet/vet_test.go b/internal/vet/vet_test.go index 078b48b..a73a110 100644 --- a/internal/vet/vet_test.go +++ b/internal/vet/vet_test.go @@ -10,6 +10,16 @@ import ( "github.com/mohsensc/tend-cli/internal/core" ) +// redAt is a run of a build and a test step that fails at step i. +func redAt(i int) *core.Run { + steps := []core.Step{{Cmd: "go vet ./...", Phase: core.PhaseBuild}, {Cmd: "go test ./...", Phase: core.PhaseTest}} + steps[i].Exit = 1 + for j := i + 1; j < len(steps); j++ { + steps[j].Skipped = "previous step failed" + } + return &core.Run{Steps: steps} +} + func TestVerdict(t *testing.T) { pass := &core.Run{Pass: true} fail := &core.Run{Pass: false} @@ -23,7 +33,7 @@ func TestVerdict(t *testing.T) { {"clean", nil, &core.Proof{Base: pass, Patched: pass}, "pass"}, {"no proof at all", nil, nil, "pass"}, {"fixed and dropped do not count", []core.Finding{f("lockfile", "fixed"), f("scope", "dropped"), f("debug", "dropped")}, &core.Proof{Patched: pass}, "pass"}, - {"flags outside 1-4 do not count", []core.Finding{f("dead", "flagged"), f("question", "flagged"), f("debug", "flagged")}, &core.Proof{Patched: pass}, "pass"}, + {"dead, question and debug flags are advisory", []core.Finding{f("dead", "flagged"), f("question", "flagged"), f("debug", "flagged")}, &core.Proof{Patched: pass}, "pass"}, {"symbol flag drafts", []core.Finding{f("symbols", "flagged")}, &core.Proof{Patched: pass}, "draft"}, {"leftover flag drafts", []core.Finding{f("leftovers", "flagged")}, &core.Proof{Patched: fail}, "draft"}, {"lockfile flag drafts", []core.Finding{f("lockfile", "flagged")}, &core.Proof{Patched: pass}, "draft"}, @@ -31,8 +41,11 @@ func TestVerdict(t *testing.T) { {"symbol flag and failing proof rejects", []core.Finding{f("symbols", "flagged")}, &core.Proof{Base: pass, Patched: fail}, "reject"}, {"field flag and failing proof rejects", []core.Finding{f("fields", "flagged")}, &core.Proof{Patched: fail}, "reject"}, {"scope revert failure and failing proof rejects", []core.Finding{f("scope", "flagged")}, &core.Proof{Patched: fail}, "reject"}, - {"scope revert failure alone passes", []core.Finding{f("scope", "flagged")}, &core.Proof{Patched: pass}, "pass"}, + {"scope revert failure alone drafts", []core.Finding{f("scope", "flagged")}, &core.Proof{Patched: pass}, "draft"}, + {"weakened test drafts", []core.Finding{f("tests", "flagged")}, &core.Proof{Patched: pass}, "draft"}, {"failing proof alone is not vetting's call", nil, &core.Proof{Patched: fail}, "pass"}, + {"symbol flag where the base fails the same way drafts", []core.Finding{f("symbols", "flagged")}, &core.Proof{Base: redAt(1), Patched: redAt(1)}, "draft"}, + {"symbol flag where the patch fails earlier rejects", []core.Finding{f("symbols", "flagged")}, &core.Proof{Base: redAt(1), Patched: redAt(0)}, "reject"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -142,3 +155,14 @@ func TestCheckNeedsChange(t *testing.T) { t.Error("Check without a change succeeded") } } + +func TestLockfileMoves(t *testing.T) { + ch := &core.Change{Deps: []core.Dep{{Name: "axios"}, {Name: "nodejs"}, {Name: "actions/checkout"}}} + if got := moves(ch, []string{"axios", "follow-redirects"}); got != "only axios and 1 of its dependencies changed" { + t.Errorf("moves = %q", got) + } + two := &core.Change{Deps: []core.Dep{{Name: "a"}, {Name: "b"}}} + if got := moves(two, []string{"a", "b", "c", "d"}); got != "only a, b and 2 of their dependencies changed" { + t.Errorf("moves = %q", got) + } +} From 2449bb0e99b732a215aadea7bc173160e1e9d106 Mon Sep 17 00:00:00 2001 From: Mohsen Sarrafan Date: Thu, 29 Oct 2026 10:51:43 -0400 Subject: [PATCH 2/2] Make self-update tests portable to Windows --- internal/selfupdate/sign/main_test.go | 2 +- internal/selfupdate/update_test.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/selfupdate/sign/main_test.go b/internal/selfupdate/sign/main_test.go index be3101e..5187ad7 100644 --- a/internal/selfupdate/sign/main_test.go +++ b/internal/selfupdate/sign/main_test.go @@ -158,7 +158,7 @@ func TestRunErrors(t *testing.T) { {"key without file", []string{"-key", "00"}, "usage"}, {"not hex", []string{"-key", "zz", "-in", file}, "not hex"}, {"short key", []string{"-key", "0011", "-in", file}, "2 bytes"}, - {"missing file", []string{"-key", strings.Repeat("00", 32), "-in", file + ".nope"}, "no such file"}, + {"missing file", []string{"-key", strings.Repeat("00", 32), "-in", file + ".nope"}, "f.nope"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/selfupdate/update_test.go b/internal/selfupdate/update_test.go index 868a2a5..4a30944 100644 --- a/internal/selfupdate/update_test.go +++ b/internal/selfupdate/update_test.go @@ -220,7 +220,7 @@ func TestApply(t *testing.T) { t.Errorf("binary = %q, want %q", got, tc.want) } fi, _ := os.Stat(path) - if fi.Mode().Perm() != 0o755 { + if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o755 { t.Errorf("mode = %v", fi.Mode()) } _, oldErr := os.Stat(path + ".old") @@ -518,6 +518,7 @@ func TestApplyReplacesTheRunningBinary(t *testing.T) { if err != nil { t.Fatal(err) } + os.SameFile(before, before) runChild(t, start, "apply", "TEND_TEST_LATEST="+latestURL, "TEND_TEST_ASSETS="+assetsURL, "TEND_TEST_KEY="+hex.EncodeToString(PublicKey))