diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml new file mode 100644 index 0000000..c2caf0d --- /dev/null +++ b/.github/workflows/release-assets.yml @@ -0,0 +1,169 @@ +name: Release Assets + +run-name: Release Assets (${{ inputs.tag }}) + +on: + workflow_dispatch: + inputs: + tag: + description: "Existing release tag to build and upload assets for" + required: true + type: string + source_run_id: + description: "Optional parent release workflow run id" + required: false + type: string + source_run_url: + description: "Optional parent release workflow run URL" + required: false + type: string + +permissions: + contents: write + +env: + CARGO_TERM_COLOR: always + +jobs: + build-release-assets: + name: ${{ matrix.name }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - name: Linux arm64 + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu + asset_target: unknown-linux-gnu-aarch64 + archive_ext: gz + binary_name: commitbot + install_cmd: "" + linker: "" + - name: Linux x86_64 + runner: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + asset_target: unknown-linux-gnu-x86_64 + archive_ext: gz + binary_name: commitbot + install_cmd: "" + linker: "" + - name: Amazon Linux / CentOS / RHEL arm64 + runner: ubuntu-24.04-arm + target: aarch64-unknown-linux-musl + asset_target: unknown-linux-musl-aarch64 + archive_ext: gz + binary_name: commitbot + install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools + linker: musl-gcc + - name: Amazon Linux / CentOS / RHEL x86_64 + runner: ubuntu-24.04 + target: x86_64-unknown-linux-musl + asset_target: unknown-linux-musl-x86_64 + archive_ext: gz + binary_name: commitbot + install_cmd: sudo apt-get update && sudo apt-get install -y musl-tools + linker: musl-gcc + - name: Windows x86_64 + runner: ubuntu-24.04 + target: x86_64-pc-windows-gnu + asset_target: pc-windows-gnu-x86_64 + archive_ext: zip + binary_name: commitbot.exe + install_cmd: sudo apt-get update && sudo apt-get install -y mingw-w64 + linker: "" + + steps: + - name: Resolve release tag + id: meta + shell: bash + run: | + set -euo pipefail + + if [ -n "${{ inputs.tag || '' }}" ]; then + echo "tag=${{ inputs.tag }}" >> "$GITHUB_OUTPUT" + else + echo "No release tag was provided." >&2 + exit 1 + fi + + - name: Check out tagged source + uses: actions/checkout@v7 + with: + ref: ${{ steps.meta.outputs.tag }} + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + + - name: Install target-specific build tooling + if: matrix.install_cmd != '' + shell: bash + run: ${{ matrix.install_cmd }} + + - name: Run tests + if: matrix.target == 'x86_64-unknown-linux-gnu' + run: cargo test --locked --all-features + + - name: Build release binary + shell: bash + env: + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: ${{ matrix.target == 'aarch64-unknown-linux-musl' && matrix.linker || '' }} + CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER: ${{ matrix.target == 'x86_64-unknown-linux-musl' && matrix.linker || '' }} + run: cargo build --locked --release --target ${{ matrix.target }} + + - name: Compress release binary + if: matrix.archive_ext == 'gz' + shell: bash + run: | + set -euo pipefail + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.gz" + gzip -n -c "target/${{ matrix.target }}/release/${{ matrix.binary_name }}" > "$asset" + echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" + + - name: Package zip archive + if: matrix.archive_ext == 'zip' + shell: bash + run: | + set -euo pipefail + asset="commitbot-${{ steps.meta.outputs.tag }}-${{ matrix.asset_target }}.zip" + cd "target/${{ matrix.target }}/release" + zip "../../../${asset}" "${{ matrix.binary_name }}" + cd - + echo "ASSET_PATH=$asset" >> "$GITHUB_ENV" + + - name: Upload asset to GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "${{ steps.meta.outputs.tag }}" "$ASSET_PATH" --clobber + + - name: Add run summary + shell: bash + run: | + { + echo "## Release Assets" + echo + echo "- Tag: \`${{ steps.meta.outputs.tag }}\`" + echo "- Target: \`${{ matrix.target }}\`" + if [[ -n "${{ inputs.source_run_url }}" ]]; then + echo "- Triggered by: ${{ inputs.source_run_url }}" + fi + } >> "$GITHUB_STEP_SUMMARY" + + publish-release: + name: Publish release + needs: build-release-assets + runs-on: ubuntu-24.04 + steps: + - name: Check out source + uses: actions/checkout@v7 + with: + ref: ${{ inputs.tag }} + + - name: Publish release and trigger Homebrew tap update + env: + GH_TOKEN: ${{ github.token }} + HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} + shell: bash + run: bash devops/publish-if-complete.sh "${{ inputs.tag }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..e76d072 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,213 @@ +name: Release + +on: + workflow_dispatch: + inputs: + target_branch: + description: Release branch + required: true + type: choice + options: + - develop + - main + version: + description: Release version (X.Y.Z) + required: true + type: string + +permissions: + actions: write + contents: write + +concurrency: + group: release-${{ inputs.target_branch }} + cancel-in-progress: false + +env: + CARGO_TERM_COLOR: always + +jobs: + plan: + runs-on: ubuntu-latest + outputs: + previous_version: ${{ steps.plan.outputs.previous_version }} + version: ${{ steps.plan.outputs.version }} + target_branch: ${{ steps.plan.outputs.target_branch }} + steps: + - name: Checkout selected branch + uses: actions/checkout@v4 + with: + ref: ${{ inputs.target_branch }} + fetch-depth: 0 + + - name: Fetch tags + run: git fetch --force --tags + + - name: Plan release + id: plan + env: + TARGET_BRANCH: ${{ inputs.target_branch }} + RELEASE_VERSION: ${{ inputs.version }} + run: devops/ga-release-plan.sh + + prepare_release: + needs: plan + runs-on: ubuntu-latest + outputs: + release_sha: ${{ steps.release_commit.outputs.release_sha }} + steps: + - name: Checkout target branch + uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.target_branch }} + fetch-depth: 0 + + - name: Fetch tags + run: git fetch --force --tags + + - name: Verify tag does not already exist + shell: bash + run: | + if git rev-parse "refs/tags/${{ needs.plan.outputs.version }}" >/dev/null 2>&1; then + echo "Tag ${{ needs.plan.outputs.version }} already exists." + exit 1 + fi + + - name: Configure git author + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Create release commit + id: release_commit + shell: bash + run: | + set -euo pipefail + + version="${{ needs.plan.outputs.version }}" + + perl -pi -e 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"/version = "'"$version"'"/' Cargo.toml + perl -0pi -e 's/name = "commitbot"\nversion = "[0-9]+\.[0-9]+\.[0-9]+"/name = "commitbot"\nversion = "'"$version"'"/m' Cargo.lock + + if git diff --quiet -- Cargo.toml Cargo.lock; then + echo "Release version ${version} is already present in Cargo metadata." >&2 + exit 1 + fi + + git add Cargo.toml Cargo.lock + git commit -m "Release ${version}" + git tag "${version}" + + echo "release_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + - name: Push release commit and tag + shell: bash + run: | + set -euo pipefail + git push origin "HEAD:${{ needs.plan.outputs.target_branch }}" + git push origin "refs/tags/${{ needs.plan.outputs.version }}" + + create_release: + needs: [plan, prepare_release] + runs-on: ubuntu-latest + steps: + - name: Check out release commit + uses: actions/checkout@v4 + with: + ref: ${{ needs.prepare_release.outputs.release_sha }} + + - name: Generate release notes + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + NOTES_ARGS=() + if [[ -n "${{ needs.plan.outputs.previous_version }}" ]]; then + NOTES_ARGS+=(-f previous_tag_name="${{ needs.plan.outputs.previous_version }}") + fi + + gh api \ + -H "Accept: application/vnd.github+json" \ + "/repos/${{ github.repository }}/releases/generate-notes" \ + -f tag_name="${{ needs.plan.outputs.version }}" \ + -f target_commitish="${{ needs.prepare_release.outputs.release_sha }}" \ + "${NOTES_ARGS[@]}" \ + --jq .body > generated-release-notes.md + + bash devops/render-release-notes.sh \ + "${{ needs.plan.outputs.version }}" \ + "${{ github.repository }}" \ + generated-release-notes.md > release-notes.md + + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + gh release create "${{ needs.plan.outputs.version }}" \ + --draft \ + --verify-tag \ + --target "${{ needs.prepare_release.outputs.release_sha }}" \ + --title "${{ needs.plan.outputs.version }}" \ + --notes-file release-notes.md + + - name: Dispatch release-assets workflow + id: dispatch_assets + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + + dispatch_started_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + source_run_url="https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + gh workflow run release-assets.yml \ + --ref "${{ needs.plan.outputs.target_branch }}" \ + -f tag="${{ needs.plan.outputs.version }}" \ + -f source_run_id="${{ github.run_id }}" \ + -f source_run_url="${source_run_url}" + + assets_run_url="" + for _ in {1..12}; do + sleep 5 + + assets_run_url="$( + gh api "/repos/${{ github.repository }}/actions/workflows/release-assets.yml/runs?event=workflow_dispatch&branch=${{ needs.plan.outputs.target_branch }}&per_page=20" \ + --jq '.workflow_runs + | map(select(.head_sha == "${{ needs.prepare_release.outputs.release_sha }}" and .status != null)) + | sort_by(.created_at) + | reverse + | .[0].html_url // ""' + )" + + if [[ -n "${assets_run_url}" ]]; then + break + fi + done + + echo "dispatch_started_at=${dispatch_started_at}" >> "$GITHUB_OUTPUT" + echo "assets_run_url=${assets_run_url}" >> "$GITHUB_OUTPUT" + + - name: Add release summary + shell: bash + run: | + release_url="https://github.com/${{ github.repository }}/releases/tag/${{ needs.plan.outputs.version }}" + assets_url="${{ steps.dispatch_assets.outputs.assets_run_url }}" + + { + echo "## Release" + echo + echo "- Version: \`${{ needs.plan.outputs.version }}\`" + echo "- Release: [${{ needs.plan.outputs.version }}](${release_url})" + if [[ -n "${assets_url}" ]]; then + echo "- Release assets workflow: [Open run](${assets_url})" + else + echo "- Release assets workflow: dispatched, but the run URL was not discovered yet." + echo "- Release assets workflow page: [Open workflow](https://github.com/${{ github.repository }}/actions/workflows/release-assets.yml)" + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..434d21b --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,39 @@ +name: Test Rust + +on: + push: + branches: [ "main", "develop" ] + pull_request: + branches: [ "main", "develop" ] + +permissions: + contents: read + +jobs: + test: + name: Test and Coverage + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + + - name: Set up Rust + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - name: Lint + run: cargo clippy --all-targets --all-features -- -D warnings + + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@cargo-llvm-cov + + - name: Generate coverage + run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + files: lcov.info + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: true diff --git a/Cargo.lock b/Cargo.lock index 80fa603..1c2eb2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,9 +13,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.21" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" dependencies = [ "anstyle", "anstyle-parse", @@ -28,50 +28,50 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anstyle-parse" -version = "0.2.7" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "anstyle-wincon" -version = "3.0.10" +version = "3.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "anyhow" -version = "1.0.100" +version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "assert_cmd" -version = "2.1.1" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcbb6924530aa9e0432442af08bbcafdad182db80d2e560da42a6d442535bf85" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" dependencies = [ "anstyle", "bstr", @@ -90,9 +90,31 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] [[package]] name = "base64" @@ -102,9 +124,15 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bitflags" -version = "2.10.0" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" [[package]] name = "bstr" @@ -119,23 +147,25 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.19.0" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "bytes" -version = "1.10.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" [[package]] name = "cc" -version = "1.2.44" +version = "1.2.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37521ac7aabe3d13122dc382493e20c9416f299d2ccd5b3a5340a2570cdeb0f3" +checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -145,11 +175,17 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + [[package]] name = "clap" -version = "4.5.51" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" dependencies = [ "clap_builder", "clap_derive", @@ -157,9 +193,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.51" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ "anstream", "anstyle", @@ -169,9 +205,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.49" +version = "4.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" dependencies = [ "heck", "proc-macro2", @@ -181,28 +217,47 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.6" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] [[package]] name = "colorchoice" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "colored" -version = "3.0.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", ] [[package]] name = "commitbot" -version = "0.3.0" +version = "0.8.0" dependencies = [ "anyhow", "assert_cmd", @@ -218,27 +273,27 @@ dependencies = [ "reqwest", "serde", "serde_json", + "tempfile", "toml", ] [[package]] name = "console" -version = "0.16.1" +version = "0.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b430743a6eb14e9764d4260d4c0d8123087d504eeb9c48f2b2a5e810dd369df4" +checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87" dependencies = [ "encode_unicode", "libc", - "once_cell", "unicode-width", "windows-sys 0.61.2", ] [[package]] name = "convert_case" -version = "0.7.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb402b8d4c85569410425650ce3eddc7d698ed96d39a73f941b08fb63082f1e7" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" dependencies = [ "unicode-segmentation", ] @@ -253,6 +308,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -265,7 +330,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags", + "bitflags 2.13.0", "crossterm_winapi", "derive_more", "document-features", @@ -286,24 +351,57 @@ dependencies = [ "winapi", ] +[[package]] +name = "defmt" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6e524506490a1953d237cb87b1cfc1e46f88c18f10a22dfe0f507dc6bfc7f7f" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a27770e9c8f719a79d8b638281f4d828f77d8fd61e0bd94451b9b85e576a0b" +dependencies = [ + "defmt-parser", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] + [[package]] name = "derive_more" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ "convert_case", "proc-macro2", "quote", + "rustc_version", "syn", ] @@ -336,9 +434,9 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", @@ -354,6 +452,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "encode_unicode" version = "1.0.0" @@ -371,9 +475,9 @@ dependencies = [ [[package]] name = "env_filter" -version = "0.1.4" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" dependencies = [ "log", "regex", @@ -381,9 +485,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.11.8" +version = "0.11.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" +checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" dependencies = [ "anstream", "anstyle", @@ -410,15 +514,15 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.3.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" [[package]] name = "find-msvc-tools" -version = "0.1.4" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" [[package]] name = "float-cmp" @@ -435,21 +539,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -459,11 +548,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures-channel" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", "futures-sink", @@ -471,33 +566,33 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" [[package]] name = "futures-io" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" [[package]] name = "futures-sink" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" [[package]] name = "futures-task" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" [[package]] name = "futures-util" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ "futures-core", "futures-io", @@ -505,33 +600,35 @@ dependencies = [ "futures-task", "memchr", "pin-project-lite", - "pin-utils", "slab", ] [[package]] name = "generator" -version = "0.8.7" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "605183a538e3e2a9c1038635cc5c2d194e2ee8fd0d1b66b8349fad7dbacce5a2" +checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae" dependencies = [ "cc", "cfg-if", "libc", "log", "rustversion", - "windows", + "windows-link", + "windows-result", ] [[package]] name = "getrandom" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -541,16 +638,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", "wasip2", + "wasm-bindgen", ] [[package]] name = "h2" -version = "0.4.12" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" dependencies = [ "atomic-waker", "bytes", @@ -567,9 +666,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.16.0" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "heck" @@ -579,12 +678,11 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "http" -version = "1.3.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" dependencies = [ "bytes", - "fnv", "itoa", ] @@ -619,9 +717,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" -version = "1.7.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" dependencies = [ "atomic-waker", "bytes", @@ -633,7 +731,6 @@ dependencies = [ "httparse", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -641,46 +738,28 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.7" +version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http", "hyper", "hyper-util", "rustls", - "rustls-pki-types", "tokio", "tokio-rustls", "tower-service", ] -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" -version = "0.1.17" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ "base64", "bytes", "futures-channel", - "futures-core", "futures-util", "http", "http-body", @@ -699,12 +778,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -712,9 +792,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" dependencies = [ "displaydoc", "litemap", @@ -725,9 +805,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -739,15 +819,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" [[package]] name = "icu_properties" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" dependencies = [ "icu_collections", "icu_locale_core", @@ -759,15 +839,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" dependencies = [ "displaydoc", "icu_locale_core", @@ -791,9 +871,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -801,9 +881,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.12.0" +version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown", @@ -811,9 +891,9 @@ dependencies = [ [[package]] name = "indicatif" -version = "0.18.2" +version = "0.18.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade6dfcba0dfb62ad59e59e7241ec8912af34fd29e0e743e3db992bd278e8b65" +checksum = "25470f23803092da7d239834776d653104d551bc4d7eacaf31e6837854b8e9eb" dependencies = [ "console", "portable-atomic", @@ -824,19 +904,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.8" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" -dependencies = [ - "memchr", - "serde", -] +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" [[package]] name = "is_terminal_polyfill" @@ -846,16 +916,17 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" -version = "1.0.15" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.16" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35" +checksum = "34f877a98676d2fb664698d74cc6a51ce6c484ce8c770f05d0108ec9090aeb46" dependencies = [ + "defmt", "jiff-static", "log", "portable-atomic", @@ -865,22 +936,82 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.16" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0666b5ab5ecaca213fc2a85b8c0083d9004e84ee2d5f9a7e0017aaf50986f25f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" dependencies = [ "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ "quote", "syn", ] +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + [[package]] name = "js-sys" -version = "0.3.82" +version = "0.3.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" +checksum = "03d04c30968dffe80775bd4d7fb676131cd04a1fb46d2686dbffbaec2d9dfd31" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -892,31 +1023,30 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.177" +version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" [[package]] name = "libredox" -version = "0.1.10" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" dependencies = [ - "bitflags", "libc", ] [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "litrs" @@ -935,9 +1065,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.28" +version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "loom" @@ -952,6 +1082,12 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "matchers" version = "0.2.0" @@ -963,9 +1099,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.6" +version = "2.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" [[package]] name = "mime" @@ -975,9 +1111,9 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "mio" -version = "1.1.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", "log", @@ -1019,23 +1155,6 @@ dependencies = [ "syn", ] -[[package]] -name = "native-tls" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - [[package]] name = "normalize-line-endings" version = "0.3.0" @@ -1062,9 +1181,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.3" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "once_cell_polyfill" @@ -1072,49 +1191,11 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" -[[package]] -name = "openssl" -version = "0.10.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24ad14dd45412269e1a30f52ad8f0664f0f4f4a89ee8fe28c3b3527021ebb654" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - -[[package]] -name = "openssl-sys" -version = "0.9.110" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a9f0075ba3c21b09f8e8b2026584b1d18d49388648f2fbbf3c97ea8deced8e2" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "option-ext" @@ -1142,7 +1223,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -1153,107 +1234,211 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] -name = "pin-utils" -version = "0.1.0" +name = "portable-atomic" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] -name = "pkg-config" -version = "0.3.32" +name = "portable-atomic-util" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] [[package]] -name = "portable-atomic" -version = "1.11.1" +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] [[package]] -name = "portable-atomic-util" -version = "0.2.4" +name = "quinn-proto" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e" dependencies = [ - "portable-atomic", + "aws-lc-rs", + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", ] [[package]] -name = "potential_utf" -version = "0.1.4" +name = "quinn-udp" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" dependencies = [ - "zerovec", + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", ] [[package]] -name = "predicates" -version = "3.1.3" +name = "quote" +version = "1.0.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d19ee57562043d37e82899fade9a22ebab7be9cef5026b07fda9cdd4293573" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" dependencies = [ - "anstyle", - "difflib", - "float-cmp", - "normalize-line-endings", - "predicates-core", - "regex", + "proc-macro2", ] [[package]] -name = "predicates-core" -version = "1.0.9" +name = "r-efi" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "727e462b119fe9c93fd0eb1429a5f7647394014cf3c04ab2c0350eeb09095ffa" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] -name = "predicates-tree" -version = "1.0.12" +name = "rand" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72dd2d6d381dfb73a193c7fca536518d7caee39fc8503f74e7dc0be0531b425c" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" dependencies = [ - "predicates-core", - "termtree", + "rand_chacha", + "rand_core", ] [[package]] -name = "proc-macro2" -version = "1.0.103" +name = "rand_chacha" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ - "unicode-ident", + "ppv-lite86", + "rand_core", ] [[package]] -name = "quote" -version = "1.0.41" +name = "rand_core" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ - "proc-macro2", + "getrandom 0.3.4", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "redox_syscall" version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.0", ] [[package]] @@ -1262,16 +1447,16 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ - "getrandom 0.2.16", + "getrandom 0.2.17", "libredox", "thiserror", ] [[package]] name = "regex" -version = "1.12.2" +version = "1.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" dependencies = [ "aho-corasick", "memchr", @@ -1281,9 +1466,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" dependencies = [ "aho-corasick", "memchr", @@ -1292,15 +1477,15 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.8" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "reqwest" -version = "0.12.24" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" dependencies = [ "base64", "bytes", @@ -1314,21 +1499,21 @@ dependencies = [ "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", "mime", - "native-tls", "percent-encoding", "pin-project-lite", + "quinn", + "rustls", "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", - "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", + "tokio-rustls", "tower", "tower-http", "tower-service", @@ -1346,19 +1531,34 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", - "getrandom 0.2.16", + "getrandom 0.2.17", "libc", "untrusted", "windows-sys 0.52.0", ] +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" -version = "1.1.2" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags", + "bitflags 2.13.0", "errno", "libc", "linux-raw-sys", @@ -1367,10 +1567,11 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.34" +version = "0.23.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9586e9ee2b4f8fab52a0048ca7334d7024eef48e2cb9407e3497bb7cab7fa7" +checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ + "aws-lc-rs", "once_cell", "rustls-pki-types", "rustls-webpki", @@ -1378,21 +1579,62 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" -version = "1.13.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" dependencies = [ + "web-time", "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + [[package]] name = "rustls-webpki" -version = "0.103.8" +version = "0.103.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -1406,15 +1648,24 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" -version = "1.0.20" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] [[package]] name = "schannel" -version = "0.1.28" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ "windows-sys 0.61.2", ] @@ -1433,12 +1684,12 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "security-framework" -version = "2.11.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", - "core-foundation", + "bitflags 2.13.0", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -1446,14 +1697,20 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.15.0" +version = "2.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" dependencies = [ "core-foundation-sys", "libc", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.228" @@ -1486,38 +1743,26 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.145" +version = "1.0.150" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" dependencies = [ "itoa", "memchr", - "ryu", "serde", "serde_core", + "zmij", ] [[package]] name = "serde_spanned" -version = "1.0.3" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" dependencies = [ "serde_core", ] -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - [[package]] name = "sharded-slab" version = "0.1.7" @@ -1529,9 +1774,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.3.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "signal-hook" @@ -1556,13 +1801,24 @@ dependencies = [ [[package]] name = "signal-hook-registry" -version = "1.4.6" +version = "1.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" dependencies = [ + "errno", "libc", ] +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -1571,24 +1827,24 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "slab" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" [[package]] name = "socket2" -version = "0.6.1" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1611,9 +1867,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.108" +version = "2.0.118" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" dependencies = [ "proc-macro2", "quote", @@ -1642,12 +1898,12 @@ dependencies = [ [[package]] name = "system-configuration" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags", - "core-foundation", + "bitflags 2.13.0", + "core-foundation 0.9.4", "system-configuration-sys", ] @@ -1663,9 +1919,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.23.0" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", "getrandom 0.3.4", @@ -1682,18 +1938,18 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "thiserror" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", @@ -1711,19 +1967,34 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" dependencies = [ "displaydoc", "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" -version = "1.48.0" +version = "1.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" dependencies = [ "bytes", "libc", @@ -1733,16 +2004,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.4" @@ -1755,9 +2016,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.17" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" dependencies = [ "bytes", "futures-core", @@ -1768,9 +2029,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.9.8" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" +checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee" dependencies = [ "indexmap", "serde_core", @@ -1783,33 +2044,33 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.7.3" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" -version = "1.0.4" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.0.4" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tower" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", @@ -1822,20 +2083,20 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.6" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.13.0", "bytes", "futures-util", "http", "http-body", - "iri-string", "pin-project-lite", "tower", "tower-layer", "tower-service", + "url", ] [[package]] @@ -1852,9 +2113,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.41" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", "tracing-core", @@ -1862,9 +2123,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.34" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", "valuable", @@ -1883,9 +2144,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.20" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2054a14f5307d601f88daf0553e1cbf472acc4f2c51afab632431cdcd72124d5" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" dependencies = [ "matchers", "nu-ansi-term", @@ -1907,15 +2168,15 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "unicode-ident" -version = "1.0.22" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-segmentation" -version = "1.12.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" @@ -1925,9 +2186,9 @@ checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" [[package]] name = "unit-prefix" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "323402cff2dd658f39ca17c789b502021b3f18707c91cdf22e3838e1b4023817" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" [[package]] name = "untrusted" @@ -1937,9 +2198,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.7" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", @@ -1965,12 +2226,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - [[package]] name = "wait-timeout" version = "0.2.1" @@ -1980,6 +2235,16 @@ dependencies = [ "libc", ] +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "want" version = "0.3.1" @@ -1997,18 +2262,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.1+wasi-0.2.4" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.105" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" +checksum = "8ddb3f79143bced6de84270411622a2699cee572fc0875aeaf1e7867cf9fca1a" dependencies = [ "cfg-if", "once_cell", @@ -2019,22 +2284,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.55" +version = "0.4.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" +checksum = "503b14d284f2c8dac03b819967e155ea753f573586193b2b2c95990cb5d69280" dependencies = [ - "cfg-if", "js-sys", - "once_cell", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.105" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" +checksum = "4e21a184b13fb19e157296e2c46056aec9092264fab83e4ba59e68c61b323c3d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2042,9 +2304,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.105" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" +checksum = "fecefd9c35bd935a20fc3fc344b5f29138961e4f47fb03297d88f2587afb5ebd" dependencies = [ "bumpalo", "proc-macro2", @@ -2055,18 +2317,18 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.105" +version = "0.2.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" +checksum = "23939e44bb9a5d7576fa2b563dc2e136628f1224e88a8deed09e04858b77871f" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.82" +version = "0.3.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" +checksum = "a6430a72df5eb332242960fe84b3002a241163998241eb596d4f739b9757061d" dependencies = [ "js-sys", "wasm-bindgen", @@ -2082,6 +2344,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" @@ -2099,84 +2370,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.61.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" -dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-link 0.1.3", - "windows-numerics", -] - -[[package]] -name = "windows-collections" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" -dependencies = [ - "windows-core", -] - -[[package]] -name = "windows-core" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link 0.1.3", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-future" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" -dependencies = [ - "windows-core", - "windows-link 0.1.3", - "windows-threading", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" +name = "winapi-util" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "proc-macro2", - "quote", - "syn", + "windows-sys 0.61.2", ] [[package]] -name = "windows-link" -version = "0.1.3" +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-link" @@ -2184,43 +2390,33 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-numerics" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" -dependencies = [ - "windows-core", - "windows-link 0.1.3", -] - [[package]] name = "windows-registry" -version = "0.5.3" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-link 0.1.3", + "windows-link", "windows-result", "windows-strings", ] [[package]] name = "windows-result" -version = "0.3.4" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link 0.1.3", + "windows-link", ] [[package]] name = "windows-strings" -version = "0.4.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link 0.1.3", + "windows-link", ] [[package]] @@ -2247,7 +2443,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -2272,7 +2468,7 @@ version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows-link 0.2.1", + "windows-link", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", @@ -2283,15 +2479,6 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] -[[package]] -name = "windows-threading" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" -dependencies = [ - "windows-link 0.1.3", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -2390,27 +2577,27 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.7.13" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" [[package]] name = "wit-bindgen" -version = "0.46.0" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2419,9 +2606,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", @@ -2429,20 +2616,40 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", @@ -2452,15 +2659,15 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" dependencies = [ "displaydoc", "yoke", @@ -2469,9 +2676,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" dependencies = [ "yoke", "zerofrom", @@ -2480,11 +2687,17 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", "syn", ] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml index dec6007..84b777d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "commitbot" -version = "0.3.0" +version = "0.8.0" edition = "2024" description = "A CLI assistant that generates commit and PR messages from your diffs using LLMs." @@ -13,23 +13,24 @@ keywords = ["git", "commit", "cli", "llm", "chatgpt"] categories = ["command-line-utilities", "development-tools", "text-processing"] [dependencies] -anyhow = "1.0" -clap = { version = "4.5", features = ["derive", "env"] } -colored = "3" -crossterm = "0.29" -dirs = "6.0.0" -env_logger = "0.11" -indicatif = "0.18.2" -log = "0.4" -musli = { version = "0.0.149", features = ["json", "alloc"] } -reqwest = { version = "0.12", features = ["json", "blocking"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -toml = "0.9.8" +anyhow = "^1.0" +clap = { version = "^4.5", features = ["derive", "env"] } +colored = "^3" +crossterm = "^0.29" +dirs = "^6.0.0" +env_logger = "^0.11" +indicatif = "^0.18.2" +log = "^0.4" +musli = { version = "^0.0.149", features = ["json", "alloc"] } +reqwest = { version = "^0.13", features = ["json", "blocking"] } +serde = { version = "^1", features = ["derive"] } +serde_json = "^1" +toml = "^1.0" [dev-dependencies] -assert_cmd = "2.1.1" -predicates = "3.1.3" +assert_cmd = "^2.1.1" +predicates = "^3.1.3" +tempfile = "^3.10" [profile.release] opt-level = 3 @@ -37,3 +38,7 @@ lto = true codegen-units = 1 panic = "abort" strip = "symbols" + +[profile.dev] +debug = 2 +opt-level = 0 diff --git a/README.md b/README.md index 7e68128..874aa8a 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,9 @@ A Rust-powered CLI that writes meaningful, structured Git commit messages using LLMs. -[![Version](https://img.shields.io/github/v/release/MikeGarde/commitbot?color=brightgreen&label=release)](https://github.com/MikeGarde/commitbot/releases) -[![Version](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](https://github.com/MikeGarde/commitbot/blob/main/LICENSE) +[![Version](https://img.shields.io/github/v/release/MikeGarde/commitbot?color=blue&label=release)](https://github.com/MikeGarde/commitbot/releases) +[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](https://github.com/MikeGarde/commitbot/blob/main/LICENSE) +[![Downloads](https://img.shields.io/github/downloads/MikeGarde/commitbot/total.svg?color=blue)](https://GitHub.com/MikeGarde/commitbot/releases/) --- @@ -17,7 +18,7 @@ It can summarize diffs, ask you how each file relates to the purpose of the comm - **Interactive “ask” mode** – Classify each file as main, supporting, or consequential. - **Quick mode** – Instantly summarize staged diffs into a commit message. -- **LLM-powered** – Uses OpenAI’s GPT models to generate concise and structured messages. +- **LLM-powered** – Uses OpenAI, or a local model via [Ollama](#providers) or [LM Studio](#providers). - **Configurable** – Choose models, tweak behavior, and set defaults in a config file. - **Pull request summaries** – Generate clean, readable PR descriptions from your commit history. @@ -25,7 +26,7 @@ It can summarize diffs, ask you how each file relates to the purpose of the comm ## Installation -You’ll need an OpenAI API key set as an environment variable: +To use OpenAI (the default provider) you’ll need an API key set as an environment variable: ```bash export OPENAI_API_KEY="sk-..." @@ -34,8 +35,7 @@ export OPENAI_API_KEY="sk-..." ### Homebrew ```bash -brew tap mikegarde/tap -brew install commitbot +brew install mikegarde/tap/commitbot ``` --- @@ -73,6 +73,32 @@ After all files are classified, Commitbot summarizes and generates the full comm --- +### Using External Diffs + +Generate commit messages from a saved diff file instead of git staged changes: + +```bash +# From a diff file +commitbot --diff my-changes.diff + +# With a custom branch name for context +commitbot --diff my-changes.diff --branch feature/ISSUE-123-auth + +# From stdin (pipe a diff)task : +git diff HEAD~3 | commitbot --diff - + +# From a commit hash (looked up in git history automatically) +commitbot --diff aabcf3b6ce03e4f1503c7a0fdda7c120bf73c8bc +``` + +When `--diff` looks like a commit hash, Commitbot first checks whether it +exists in the current repo's history and, if so, summarizes the diff +introduced by that commit. If it doesn't match a commit, Commitbot falls +back to treating the value as a file path; if neither a matching commit nor +a file is found, it reports an error instead of guessing. + +--- + ### Pull Request Summaries Generate high-level PR descriptions by summarizing commit messages instead of diffs: @@ -96,20 +122,42 @@ Commitbot automatically loads its configuration from [~/.config/commitbot.toml]( Settings can be defined globally in this file, overridden by environment variables, or specified directly through CLI flags. Per-project configurations are also supported for repository-specific overrides. +> Note: Repository names are case-sensitive. + Example: ```toml model = "gpt-4o-mini" -["mikegarde/commitbot"] +["MikeGarde/commitbot"] model = "gpt-5-nano" ``` --- +## Providers + +Set `provider` to choose a backend. Any of them can be overridden per repository. + +| Provider | Default `url` | API key | +|------------|--------------------------|----------| +| `openai` | `https://api.openai.com` | required | +| `ollama` | `http://localhost:11434` | not used | +| `lmstudio` | `http://localhost:1234` | optional | + +```toml +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +url = "http://192.168.1.16:1234/v1" +``` + +--- + ## Roadmap - [x] Support for local/offline LLMs (Ollama, LM Studio). +- [ ] Support for Anthropic's Claude. - [ ] Model auto-detection and fallback. - [ ] Configurable commit message templates. - [ ] Integration with GitHub Actions or CI pipelines. diff --git a/Taskfile.yaml b/Taskfile.yaml index 3f476b0..120a8cc 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -17,10 +17,21 @@ tasks: - cargo clippy --all-targets --all-features -- -D warnings - cargo test --all-features + test:simple: + desc: "Run simple unit tests" + cmds: + - cargo clippy --all-targets --all-features -- -D warnings + - cargo test -- --nocapture + + test:prompts: + desc: "Run prompt tests" + cmds: + - cargo test --test prompt_live -- --ignored --nocapture + run:simple: - desc: "Run commitbot in simple mode (no model, debug) using cargo run" + desc: "Run commitbot in simple mode (no model, info verbosity) using cargo run" cmds: - - cargo run -- -vv + - cargo run -- -v run:ask: desc: "Run commitbot in interactive ask mode (no model, debug)" @@ -42,7 +53,22 @@ tasks: install: desc: "Install commitbot binary locally via cargo install --path ." cmds: - - cargo install --path . --force + - brew uninstall mikegarde/tap/commitbot || true + - cargo install --path . --force --locked + + install:brew: + desc: "Install commitbot via Homebrew (macOS)" + cmds: + - cargo uninstall commitbot || true + - brew uninstall mikegarde/tap/commitbot || true + - brew install mikegarde/tap/commitbot + + build: + desc: "Build debug binary for the host" + silent: true + cmds: + - cargo build 2>$1 + - du -h target/debug/commitbot build:release: desc: "Build optimized release binary for the host" @@ -58,11 +84,11 @@ tasks: silent: true cmds: - mkdir -p dist - - rm -f dist/commitbot-*.tar.gz + - rm -f dist/commitbot-*.gz - | set -euo pipefail - echo "Building release binaries..." + echo "Building Mac release binaries..." cargo build --release --target aarch64-apple-darwin cargo build --release --target x86_64-apple-darwin @@ -71,13 +97,11 @@ tasks: echo "Packaging into dist with version {{.VERSION}}..." - tar -C target/aarch64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-aarch64-apple-darwin.tar.gz \ - commitbot + gzip -n -c target/aarch64-apple-darwin/release/commitbot \ + > dist/commitbot-{{.VERSION}}-apple-darwin-aarch64.gz - tar -C target/x86_64-apple-darwin/release \ - -czf dist/commitbot-{{.VERSION}}-x86_64-apple-darwin.tar.gz \ - commitbot + gzip -n -c target/x86_64-apple-darwin/release/commitbot \ + > dist/commitbot-{{.VERSION}}-apple-darwin-x86_64.gz echo "Artifacts created:" ls -lh dist @@ -88,11 +112,11 @@ tasks: VERSION: '{{index .MATCH 0}}' interactive: true cmds: - - task: test + - task: test:simple - sh devops/release.sh {{.VERSION}} - task: publish:dry - task: publish - - cd ../homebrew-tap && gh workflow run update-formula.yml -f formula=commitbot -f repo=mikegarde/commitbot -f version={{.VERSION}} + - task: install publish:dry: desc: "Dry-run crates.io publish to verify packaging" diff --git a/commitbot.toml b/commitbot.toml index 17c2a88..e817015 100644 --- a/commitbot.toml +++ b/commitbot.toml @@ -7,14 +7,14 @@ model = "gpt-5-nano" # Optional: OpenAI-style API key (falls back to env OPENAI_API_KEY) openai_api_key = "your api key here" -# Optional: provider base URL (e.g. http://localhost:11434 for Ollama) +# Optional: provider base URL (e.g. http://localhost:11434 for local LLM) url = "https://api.openai.com" # 1 = fully serial, >1 = parallel API calls max_concurrent_requests = 4 -["mikegarde/commitbot"] +["company/repo"] provider = "openai" stream = false model = "gpt-4o-mini" @@ -22,6 +22,14 @@ openai_api_key = "alternative for spend identification" max_concurrent_requests = 8 +["MikeGarde/commitbot"] +provider = "lmstudio" +model = "google/gemma-4-12b-qat" +url = "http://gpu.garde.one:1234/v1" +# Fallback / direct IP: url = "http://192.168.1.16:1234/v1" +max_concurrent_requests = 2 + + ["company/enterprise"] # Enterprise / self-hosted style config base_url = "https://enterprise.api.endpoint" diff --git a/devops/ga-release-plan.sh b/devops/ga-release-plan.sh new file mode 100755 index 0000000..f849235 --- /dev/null +++ b/devops/ga-release-plan.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash + +set -euo pipefail + +TARGET_BRANCH="${TARGET_BRANCH:-${1:-}}" +RELEASE_VERSION="${RELEASE_VERSION:-${2:-}}" + +if [[ -z "${TARGET_BRANCH}" ]]; then + echo "usage: TARGET_BRANCH= RELEASE_VERSION=X.Y.Z $0" >&2 + exit 1 +fi + +case "${TARGET_BRANCH}" in + main|develop) ;; + *) + echo "Unsupported target branch: ${TARGET_BRANCH}" >&2 + exit 1 + ;; +esac + +semver_pattern='^[0-9]+\.[0-9]+\.[0-9]+$' + +if [[ ! "${RELEASE_VERSION}" =~ ${semver_pattern} ]]; then + echo "RELEASE_VERSION must be a semantic version like 1.0.0" >&2 + exit 1 +fi + +# Newest released version (empty when no semver tags exist yet). +PREVIOUS_VERSION="$( + git tag --list \ + | grep -E "${semver_pattern}" || true +)" +PREVIOUS_VERSION="$( + printf '%s\n' "${PREVIOUS_VERSION}" \ + | sort -V \ + | tail -n 1 +)" + +# Baseline for the next version: the newest of the latest tag and the version +# currently in Cargo.toml, so the requested version can never move backwards. +CARGO_VERSION="$( + sed -nE 's/^version = "([0-9]+\.[0-9]+\.[0-9]+)"/\1/p' Cargo.toml | head -n1 +)" + +CURRENT_VERSION="$( + printf '%s\n%s\n' "${PREVIOUS_VERSION}" "${CARGO_VERSION}" \ + | sort -V \ + | tail -n 1 +)" + +newest="$(printf '%s\n%s\n' "${CURRENT_VERSION}" "${RELEASE_VERSION}" | sort -V | tail -n 1)" +if [[ "${newest}" != "${RELEASE_VERSION}" ]] || [[ "${RELEASE_VERSION}" == "${CURRENT_VERSION}" ]]; then + echo "RELEASE_VERSION ${RELEASE_VERSION} must be newer than ${CURRENT_VERSION}" >&2 + exit 1 +fi + +VERSION="${RELEASE_VERSION}" + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + { + echo "previous_version=${PREVIOUS_VERSION}" + echo "version=${VERSION}" + echo "target_branch=${TARGET_BRANCH}" + } >> "${GITHUB_OUTPUT}" +fi + +echo "previous_version=${PREVIOUS_VERSION}" +echo "version=${VERSION}" diff --git a/devops/publish-if-complete.sh b/devops/publish-if-complete.sh new file mode 100755 index 0000000..c045eb6 --- /dev/null +++ b/devops/publish-if-complete.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +set -euo pipefail + +TAG="${1:?usage: publish-if-complete.sh }" + +EXPECTED=( + "commitbot-${TAG}-apple-darwin-aarch64.gz" + "commitbot-${TAG}-apple-darwin-x86_64.gz" + "commitbot-${TAG}-unknown-linux-gnu-aarch64.gz" + "commitbot-${TAG}-unknown-linux-gnu-x86_64.gz" + "commitbot-${TAG}-unknown-linux-musl-aarch64.gz" + "commitbot-${TAG}-unknown-linux-musl-x86_64.gz" + "commitbot-${TAG}-pc-windows-gnu-x86_64.zip" +) + +ACTUAL="$(gh release view "${TAG}" --json assets --jq '[.assets[].name]')" + +for asset in "${EXPECTED[@]}"; do + if ! printf '%s' "${ACTUAL}" | jq -e --arg n "${asset}" 'any(.[]; . == $n)' > /dev/null 2>&1; then + echo "Release not yet complete (missing: ${asset}). Skipping publish." + exit 0 + fi +done + +echo "All expected assets present. Publishing release ${TAG}..." +gh release edit "${TAG}" --draft=false +echo "Published." + +echo "Triggering Homebrew tap formula update..." +if GH_TOKEN="${HOMEBREW_TAP_TOKEN:-}" gh workflow run update-formula.yml \ + --repo MikeGarde/homebrew-tap \ + -f formula=commitbot \ + -f repo=MikeGarde/commitbot \ + -f tag="${TAG}"; then + echo "Homebrew tap update dispatched." +else + echo "Warning: could not dispatch Homebrew tap update. Trigger it manually with:" + echo " gh workflow run update-formula.yml --repo MikeGarde/homebrew-tap -f formula=commitbot -f repo=MikeGarde/commitbot -f tag=${TAG}" +fi diff --git a/devops/release.sh b/devops/release.sh index d4ea765..aaf725f 100644 --- a/devops/release.sh +++ b/devops/release.sh @@ -1,16 +1,16 @@ #!/bin/zsh set -euo pipefail -# --------------------------------------------------------- +# # Config -# --------------------------------------------------------- +# DIST_DIR="dist" STEP=${1:?usage: release.sh [major|minor|patch|X.Y.Z]} -# --------------------------------------------------------- +# # Pre-flight checks -# --------------------------------------------------------- +# if ! command -v task >/dev/null 2>&1; then echo "Error: 'task' command not found. Install Taskfile runner first." exit 1 @@ -21,6 +21,13 @@ if ! command -v gh >/dev/null 2>&1; then exit 1 fi +if ! command -v jq >/dev/null 2>&1; then + echo "Error: 'jq' not found. Install jq first." + exit 1 +fi + +REPO_SLUG=$(gh repo view --json nameWithOwner -q .nameWithOwner) + BRANCH=$(git rev-parse --abbrev-ref HEAD) if [ "$BRANCH" != "main" ]; then echo "Error: releases may only be created from 'main' (current: $BRANCH)." @@ -33,9 +40,9 @@ if ! git diff --quiet || ! git diff --cached --quiet; then exit 1 fi -# --------------------------------------------------------- +# # Read current version from Cargo.toml -# --------------------------------------------------------- +# CURRENT_VERSION=$( grep -E '^version = "[0-9]+\.[0-9]+\.[0-9]+"' Cargo.toml \ | head -n1 \ @@ -52,9 +59,9 @@ MINOR=$(echo "$CURRENT_VERSION" | cut -d. -f2) PATCH=$(echo "$CURRENT_VERSION" | cut -d. -f3) LATEST=true -# --------------------------------------------------------- +# # Compute new version -# --------------------------------------------------------- +# case "$STEP" in major) MAJOR=$((MAJOR+1)) @@ -84,12 +91,57 @@ esac NEW_VERSION="$MAJOR.$MINOR.$PATCH" -# Check that tag does not already exist +# +# Join mode: tag already exists (e.g. GA created the release first) +# if git rev-parse -q --verify "refs/tags/$NEW_VERSION" >/dev/null 2>&1; then - echo "Error: git tag $NEW_VERSION already exists." - exit 1 + echo "Tag $NEW_VERSION already exists. Joining existing draft release to upload Mac assets..." + echo + + RELEASE_IS_DRAFT=$(gh release view "$NEW_VERSION" --json isDraft --jq .isDraft 2>/dev/null || echo "not_found") + if [ "$RELEASE_IS_DRAFT" = "false" ]; then + echo "Release $NEW_VERSION is already published. Nothing to do." + exit 0 + fi + if [ "$RELEASE_IS_DRAFT" = "not_found" ]; then + echo "Error: tag $NEW_VERSION exists in git but no GitHub release was found." + exit 1 + fi + + CARGO_VERSION=$( + grep -E '^version = "[0-9]+\.[0-9]+\.[0-9]+"' Cargo.toml \ + | head -n1 \ + | sed -E 's/version = "([^"]+)"/\1/' + ) + if [ "$CARGO_VERSION" != "$NEW_VERSION" ]; then + echo "Error: Cargo.toml version ($CARGO_VERSION) does not match release version ($NEW_VERSION)." + echo "Run 'git pull' to sync the release commit, then retry." + exit 1 + fi + + echo "Building Mac binaries for $NEW_VERSION..." + task setup + task "build:release:${NEW_VERSION}" + + MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.gz) + if [ ${#MAC_ASSETS[@]} -eq 0 ]; then + echo "Error: no Mac assets found in $DIST_DIR after build." + exit 1 + fi + + echo "Uploading Mac assets to existing draft release $NEW_VERSION:" + for a in "${MAC_ASSETS[@]}"; do + echo " - $a" + done + gh release upload "$NEW_VERSION" "${MAC_ASSETS[@]}" --clobber + + bash devops/publish-if-complete.sh "$NEW_VERSION" + exit 0 fi +# +# Full release flow +# echo "Current version: $CURRENT_VERSION" echo "New version: $NEW_VERSION" echo "Branch: $BRANCH" @@ -101,9 +153,9 @@ if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then exit 1 fi -# --------------------------------------------------------- +# # Bump Cargo.toml with rollback on failure -# --------------------------------------------------------- +# CARGO_BAK="Cargo.toml.bak.$$" cp Cargo.toml "$CARGO_BAK" @@ -120,25 +172,22 @@ trap cleanup_on_error INT TERM ERR echo "Updating Cargo.toml to version $NEW_VERSION..." perl -pi -e 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"/version = "'"$NEW_VERSION"'"/' Cargo.toml -# --------------------------------------------------------- +# # Run tasks: setup, test, build -# --------------------------------------------------------- +# echo "Running task setup..." task setup -echo "Running task test..." -task test - -echo "Running task build:release:all..." +echo "Running task build:release:${NEW_VERSION}..." task "build:release:${NEW_VERSION}" # If we got here, tasks succeeded – stop rollback trap trap - INT TERM ERR rm -f "$CARGO_BAK" -# --------------------------------------------------------- +# # Commit, tag, push -# --------------------------------------------------------- +# if git diff --quiet -- Cargo.toml; then echo "Warning: Cargo.toml did not change; nothing to commit." else @@ -154,37 +203,77 @@ echo "Pushing main and tag..." git push origin main git push origin "refs/tags/$NEW_VERSION" -# --------------------------------------------------------- -# Create GitHub release from artifacts in DIST_DIR -# --------------------------------------------------------- +# +# Create draft GitHub release with Mac assets +# if [ ! -d "$DIST_DIR" ]; then echo "Error: build artifacts directory '$DIST_DIR' not found." echo "Check task build:release:all" exit 1 fi -ASSETS=("$DIST_DIR"/*) -if [ ${#ASSETS[@]} -eq 0 ]; then - echo "Error: no build artifacts found in '$DIST_DIR'." +MAC_ASSETS=("$DIST_DIR"/commitbot-"$NEW_VERSION"-*apple-darwin*.gz) +if [ ${#MAC_ASSETS[@]} -eq 0 ]; then + echo "Error: no Mac assets found in '$DIST_DIR'." exit 1 fi -LATEST_FLAG="" -if [ "$LATEST" = true ]; then - LATEST_FLAG="--latest" -fi - -echo "Creating GitHub release $NEW_VERSION with assets:" -for a in "${ASSETS[@]}"; do +echo "Creating draft GitHub release $NEW_VERSION with Mac assets:" +for a in "${MAC_ASSETS[@]}"; do echo " - $a" done +NOTES_FILE="$(mktemp)" +COMBINED_NOTES_FILE="$(mktemp)" + +cleanup_notes() { + rm -f "$NOTES_FILE" "$COMBINED_NOTES_FILE" +} +trap cleanup_notes EXIT + +gh api \ + -H "Accept: application/vnd.github+json" \ + "/repos/$REPO_SLUG/releases/generate-notes" \ + -f tag_name="$NEW_VERSION" \ + -f target_commitish="$HASH" \ + --jq .body > "$NOTES_FILE" + +bash devops/render-release-notes.sh "$NEW_VERSION" "$REPO_SLUG" "$NOTES_FILE" > "$COMBINED_NOTES_FILE" + +LATEST_ARGS=() +if [ "$LATEST" = true ]; then + LATEST_ARGS+=(--latest) +fi + gh release create "$NEW_VERSION" \ + --draft \ --fail-on-no-commits \ - --generate-notes \ - $LATEST_FLAG \ + "${LATEST_ARGS[@]}" \ + --notes-file "$COMBINED_NOTES_FILE" \ --target "$HASH" \ - "${ASSETS[@]}" + "${MAC_ASSETS[@]}" + +# +# Dispatch release-assets workflow for Linux + Windows +# +echo +echo "Dispatching release-assets workflow for Linux and Windows builds..." + +SOURCE_RUN_URL="local:$(hostname)" + +gh workflow run release-assets.yml \ + --ref main \ + -f tag="$NEW_VERSION" \ + -f source_run_url="${SOURCE_RUN_URL}" + +echo "Dispatched. Linux and Windows assets will be uploaded by GitHub Actions." +echo "The release will be published automatically once all assets are present." +echo + +# +# Check if all assets happen to already be present (rare but possible) +# +bash devops/publish-if-complete.sh "$NEW_VERSION" -echo "Release $NEW_VERSION created successfully." +echo "Release $NEW_VERSION draft created successfully." exit 0 diff --git a/devops/render-release-notes.sh b/devops/render-release-notes.sh new file mode 100644 index 0000000..802946f --- /dev/null +++ b/devops/render-release-notes.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash + +set -euo pipefail + +VERSION="${1:?usage: render-release-notes.sh [notes-file]}" +REPO="${2:?usage: render-release-notes.sh [notes-file]}" +NOTES_FILE="${3:-}" + +asset_url() { + local filename="$1" + printf 'https://github.com/%s/releases/download/%s/%s' "${REPO}" "${VERSION}" "${filename}" +} + +cat < /dev/null +sudo chmod +x /usr/local/bin/commitbot +~~~ + +EOF + +if [[ -n "${NOTES_FILE}" && -f "${NOTES_FILE}" ]]; then + cat "${NOTES_FILE}" +fi diff --git a/src/cli_args.rs b/src/cli_args.rs index 5cb5eed..5b0ab9f 100644 --- a/src/cli_args.rs +++ b/src/cli_args.rs @@ -1,10 +1,10 @@ -use clap::{Parser, Subcommand, ArgAction}; +use clap::{ArgAction, Parser, Subcommand}; /// CLI options #[derive(Parser, Debug)] #[command( name = "commitbot", - version, + disable_version_flag = true, about = "LLM-assisted Git commit message generator" )] pub struct Cli { @@ -12,10 +12,6 @@ pub struct Cli { #[arg(long, global = true)] pub ask: bool, - /// If set, write the generated message into .git/COMMIT_EDITMSG (no commit is created) - #[arg(short = 'w', long, global = true)] - pub apply: bool, - /// Stage all changes before generating the commit message #[arg(short, long, global = true)] pub stage: bool, @@ -32,7 +28,7 @@ pub struct Cli { #[arg(short = 'k', long, global = true)] pub api_key: Option, - /// LLM provider / API style (openai or ollama) + /// LLM provider / API style (openai, ollama, or lmstudio) #[arg(long, global = true)] pub provider: Option, @@ -40,29 +36,60 @@ pub struct Cli { #[arg(long, global = true)] pub url: Option, - /// Stream responses as they are generated (use `--stream=false` to disable) + /// Read diff from a file instead of git staged changes (use "-" for stdin). + /// Cannot be used with --ask mode. + #[arg(long, global = true, value_name = "FILE")] + pub diff: Option, + + /// Branch name to use in the commit message context (used with --diff). + /// If not specified when using --diff, defaults to the current branch. + #[arg(long, global = true)] + pub branch: Option, + + /// Disable streaming responses (streaming is on by default) + #[arg(long, global = true)] + pub no_stream: bool, + + /// Also emit a single-line version of the generated message (with the + /// LLM stats appended), suitable for worktree/scripted commits. + /// + /// Pass with no value to keep the normal readable output and print the + /// one-line summary afterward. Pass `--oneline quiet` to suppress the + /// normal readable output entirely and print only the one-line summary. #[arg( long, global = true, - default_missing_value = "true", + value_name = "MODE", num_args = 0..=1, - value_parser = clap::value_parser!(bool) + default_missing_value = "readable" )] - pub stream: Option, + pub oneline: Option, /// Increase verbosity (-v, -vv, -vvv) #[arg(short = 'v', long = "verbose", action = ArgAction::Count)] pub verbose: u8, + /// Define config file (default: ~/.config/commitbot.toml) + #[arg(long, global = true, value_name = "FILE")] + pub config: Option, + /// Subcommand (e.g. 'pr') #[command(subcommand)] pub command: Option, + + /// Print only the version number (e.g. "0.5.1"). This replaces clap's auto --version output. + #[arg(long, global = true, action = ArgAction::SetTrue)] + pub version: bool, } /// Subcommands, e.g. `commitbot pr develop` #[derive(Subcommand, Debug)] pub enum Command { /// Generate a Pull Request description by summarizing commit or PR messages + /// + /// This command analyzes a commit range and generates a PR summary. + /// Example: + /// commitbot pr --base main --from feature-branch Pr { /// Base branch to compare against (e.g. main or develop) base: String, @@ -80,6 +107,9 @@ pub enum Command { }, /// Freeform summary provided at the end of the command. + /// + /// Example: + /// commitbot summary "fix: correct typo in documentation" #[command(external_subcommand)] Summary(Vec), } diff --git a/src/config.rs b/src/config.rs index 17a6e86..f5d2404 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,142 +1,124 @@ -use crate::{git, Cli}; +use crate::{Cli, git}; +use anyhow::{anyhow, Result}; +use git::detect_repo_id; use serde::Deserialize; use std::collections::HashMap; use std::env; use std::fs; -use std::path::PathBuf; -use git::detect_repo_id; +use std::path::{Path, PathBuf}; /// Final resolved configuration for commitbot. #[derive(Debug, Clone)] pub struct Config { + /// LLM provider (openai, ollama, lmstudio) pub provider: String, + /// OpenAI API key for authentication (sensitive – redacted in logs) pub openai_api_key: Option, + /// Base URL for the LLM provider pub base_url: Option, + /// Model name to use for LLM calls pub model: String, + /// Maximum concurrent requests to the LLM API pub max_concurrent_requests: usize, + /// Whether to stream responses from the LLM pub stream: bool, + /// HTTP request timeout in seconds for LLM calls + pub request_timeout_secs: u64, + /// Maximum size (in bytes) of a single file's diff sent to the LLM. + /// Larger diffs (e.g. notebooks with embedded base64 output, minified + /// bundles) are truncated to avoid exceeding the model's context window. + pub max_diff_bytes: usize, + /// `--oneline` was passed (in either mode): emit a one-line summary + /// (message + LLM stats, newlines escaped as `\n`) after generation. + pub oneline: bool, + /// `--oneline quiet`: suppress the normal readable output (including + /// live streaming) and only emit the one-line summary. + pub oneline_quiet: bool, } impl Config { + /// Returns the names of fields that contain sensitive data (e.g. API keys). + /// These are redacted in debug/verbose log output. + pub fn sensitive_field_names() -> &'static [&'static str] { + &["openai_api_key"] + } + /// Build the final config from CLI flags, environment, TOML file, and defaults. /// /// Precedence (highest to lowest): - /// 1. CLI flags (`--provider`, `--model`, `--api-key`, `--base-url`, `--max`, `--stream`) - /// 2. Env vars (`COMMITBOT_PROVIDER`, `COMMITBOT_MODEL`, `OPENAI_API_KEY`, `COMMITBOT_BASE_URL`, `COMMITBOT_MAX_CONCURRENT_REQUESTS`, `COMMITBOT_STREAM`) - /// 3. Per-repo table in `~/.config/commitbot.toml` (e.g. ["mikegarde/commitbot"]) - /// 4. [default] table in `~/.config/commitbot.toml` - /// 5. Hardcoded defaults (model = "gpt-5-nano", max_concurrent_requests = 4) - pub fn from_sources(cli: &Cli) -> Self { - let file_cfg_root = load_file_config().unwrap_or_default(); - let repo_id = detect_repo_id(); + /// 1. CLI flags + /// 2. Env vars + /// 3. Per-repo table in config file (e.g. ["mikegarde/commitbot"]) + /// 4. [default] table in config file + /// 5. Hardcoded defaults + pub fn from_sources(cli: &Cli) -> Result { + let r = ConfigResolver::new(cli); - // Split file config into [default] and repo-specific override (if any). - let default_file_cfg = file_cfg_root.default.unwrap_or_default(); - let repo_file_cfg = repo_id - .as_deref() - .and_then(|id| file_cfg_root.repos.get(id)) - .cloned() - .unwrap_or_default(); + let provider = r.get_string("provider", "openai").to_lowercase(); + let model = r.get_string("model", "gpt-5-nano"); + + // secrets: logged as / + let openai_api_key = r.get_secret_opt_string("openai_api_key"); - // CLI values - let provider_cli = cli.provider.clone(); - let model_cli = cli.model.clone(); - let api_key_cli = cli.api_key.clone(); - let base_url_cli = cli.url.clone(); - let max_cli = cli.max; - let stream_cli = cli.stream; - - // Env values - let provider_env = env::var("COMMITBOT_PROVIDER").ok(); - let model_env = env::var("COMMITBOT_MODEL").ok(); - let api_key_env = env::var("OPENAI_API_KEY").ok(); - let base_url_env = env::var("COMMITBOT_BASE_URL").ok(); - let max_env = env::var("COMMITBOT_MAX_CONCURRENT_REQUESTS") - .ok() - .and_then(|s| s.parse::().ok()); - let stream_env = env::var("COMMITBOT_STREAM") - .ok() - .and_then(|s| s.parse::().ok()); - - // Resolve provider - let provider = provider_cli - .or(provider_env) - .or(repo_file_cfg.provider) - .or(default_file_cfg.provider) - .unwrap_or_else(|| "openai".to_string()) - .to_lowercase(); - - // Resolve model - let model = model_cli - .or(model_env) - .or(repo_file_cfg.model) - .or(default_file_cfg.model) - .unwrap_or_else(|| "gpt-5-nano".to_string()); - - // Resolve API key (only required for OpenAI-style providers) - let openai_api_key = api_key_cli - .or(api_key_env) - .or(repo_file_cfg.openai_api_key) - .or(default_file_cfg.openai_api_key); - - // Resolve base URL (used for ollama or openai-compatible endpoints) - let base_url = base_url_cli - .or(base_url_env) - .or(repo_file_cfg.base_url) - .or(default_file_cfg.base_url); - - // Resolve max concurrency; default to 4 if not specified anywhere - let max_concurrent_requests = max_cli - .or(max_env) - .or(repo_file_cfg.max_concurrent_requests) - .or(default_file_cfg.max_concurrent_requests) - .unwrap_or(4); - - let stream = stream_cli - .or(stream_env) - .or(repo_file_cfg.stream) - .or(default_file_cfg.stream) - .unwrap_or(true); + // optional + let base_url = r.get_opt_string("base_url"); + let max_concurrent_requests = r.get_usize("max_concurrent_requests", 4); + let stream = r.get_bool("stream", true); + let request_timeout_secs = r.get_u64("request_timeout_secs", 300); + let max_diff_bytes = r.get_usize("max_diff_bytes", 20_000); + + // CLI-only: not sourced from env/file, since it controls this + // process's own stdout shape rather than provider behavior. + let oneline = cli.oneline.is_some(); + let oneline_quiet = cli.oneline.as_deref() == Some("quiet"); + + // Cleanup: trim stray quotes if any upstream included them let provider = provider.trim_matches('"').to_string(); let model = model.trim_matches('"').to_string(); let openai_api_key = openai_api_key.map(|s| s.trim_matches('"').to_string()); - let base_url = base_url.map(|s| s.trim_matches('"').to_string()); + // A blank url is the same as no url + let base_url = base_url + .map(|s| s.trim_matches('"').trim().to_string()) + .filter(|s| !s.is_empty()); - let url = base_url.clone().unwrap_or_default(); - - log::debug!("Provider: {}", provider); - log::debug!("Model: {}", model); - log::debug!("API key: {}", openai_api_key.is_some()); - log::debug!("URL: {}", url); - log::debug!("Max Req: {}", max_concurrent_requests); - log::debug!("Stream: {}", stream); + let is_custom_endpoint = base_url + .as_deref() + .map(|u| !u.starts_with("https://api.openai.com")) + .unwrap_or(false); - if provider == "openai" && openai_api_key.is_none() { - panic!("OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai"); + if provider == "openai" && openai_api_key.is_none() && !is_custom_endpoint { + return Err(anyhow!( + "OPENAI_API_KEY must be set via CLI, env var, or config file for provider=openai" + )); } - Config { + Ok(Config { provider, model, openai_api_key, base_url, max_concurrent_requests, stream, - } + request_timeout_secs, + max_diff_bytes, + oneline, + oneline_quiet, + }) } } #[derive(Debug, Default, Deserialize, Clone)] struct FileConfig { - /// LLM provider / API style (openai or ollama). pub provider: Option, - /// Default model to use when not provided via CLI or env. pub model: Option, pub openai_api_key: Option, + #[serde(alias = "url")] pub base_url: Option, pub max_concurrent_requests: Option, pub stream: Option, + pub request_timeout_secs: Option, + pub max_diff_bytes: Option, } /// Root of the TOML file: @@ -150,18 +132,436 @@ struct FileConfigRoot { pub repos: HashMap, } -/// Return `~/.config/commitbot.toml` -fn config_path() -> Option { - let home = dirs::home_dir()?; - Some(home.join(".config").join("commitbot.toml")) +#[derive(Debug, Clone, Copy)] +enum ValueSource { + Hardcoded, + FileDefault, + FileRepo, + Env, + Cli, +} + +fn source_label(s: ValueSource) -> &'static str { + match s { + ValueSource::Cli => "cli", + ValueSource::Env => "env", + ValueSource::FileRepo => "file:[repo]", + ValueSource::FileDefault => "file:[default]", + ValueSource::Hardcoded => "hardcoded", + } +} + +struct ConfigResolver<'a> { + cli: &'a Cli, + repo_id: Option, + file_default: FileConfig, + file_repo: FileConfig, } -fn load_file_config() -> Option { - let path = config_path()?; +impl<'a> ConfigResolver<'a> { + pub fn new(cli: &'a Cli) -> Self { + // config file string (cli > env > default string) + let config_file_to_use: String = cli + .config + .clone() + .or_else(|| env::var("COMMITBOT_CONFIG").ok()) + .unwrap_or_else(|| "~/.config/commitbot.toml".to_string()); + + let config_path = expand_tilde_to_path(&config_file_to_use); + log::debug!("Config File: {}", config_path.display()); + + let root = load_file_config_from_path(&config_path); + + let repo_id = detect_repo_id(); + log::debug!("Repo ID: {:?}", repo_id); + + let file_default = root.default.clone().unwrap_or_default(); + let file_repo = repo_id + .as_deref() + .and_then(|id| root.repos.get(id)) + .cloned() + .unwrap_or_default(); + + if let Some(id) = repo_id.as_deref() { + log::debug!("Repo table present: {}", root.repos.contains_key(id)); + } + + Self { + cli, + repo_id, + file_default, + file_repo, + } + } + + fn env_key_for(&self, key: &str) -> Option<&'static str> { + match key { + "provider" => Some("COMMITBOT_PROVIDER"), + "model" => Some("COMMITBOT_MODEL"), + "openai_api_key" => Some("OPENAI_API_KEY"), + "base_url" => Some("COMMITBOT_BASE_URL"), + "max_concurrent_requests" => Some("COMMITBOT_MAX_CONCURRENT_REQUESTS"), + "stream" => Some("COMMITBOT_STREAM"), + "request_timeout_secs" => Some("COMMITBOT_REQUEST_TIMEOUT_SECS"), + "max_diff_bytes" => Some("COMMITBOT_MAX_DIFF_BYTES"), + _ => None, + } + } + + // ---- FILE SOURCES ---- + + fn file_string(&self, key: &str, repo: bool) -> Option { + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; + match key { + "provider" => cfg.provider.clone(), + "model" => cfg.model.clone(), + "openai_api_key" => cfg.openai_api_key.clone(), + "base_url" => cfg.base_url.clone(), + _ => None, + } + } + + fn file_usize(&self, key: &str, repo: bool) -> Option { + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; + match key { + "max_concurrent_requests" => cfg.max_concurrent_requests, + "max_diff_bytes" => cfg.max_diff_bytes, + _ => None, + } + } + + fn file_u64(&self, key: &str, repo: bool) -> Option { + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; + match key { + "request_timeout_secs" => cfg.request_timeout_secs, + _ => None, + } + } + + fn file_bool(&self, key: &str, repo: bool) -> Option { + let cfg = if repo { + &self.file_repo + } else { + &self.file_default + }; + match key { + "stream" => cfg.stream, + _ => None, + } + } + + // ---- ENV SOURCES ---- + + fn env_string(&self, key: &str) -> Option { + let env_key = self.env_key_for(key)?; + env::var(env_key).ok() + } + + fn env_usize(&self, key: &str) -> Option { + let env_key = self.env_key_for(key)?; + env::var(env_key).ok().and_then(|s| s.parse::().ok()) + } + + fn env_u64(&self, key: &str) -> Option { + let env_key = self.env_key_for(key)?; + env::var(env_key).ok().and_then(|s| s.parse::().ok()) + } + + fn env_bool(&self, key: &str) -> Option { + let env_key = self.env_key_for(key)?; + env::var(env_key).ok().and_then(|s| s.parse::().ok()) + } + + // Expectation for a stream flag: + // - `--no-stream` present => stream = Some(false) + // - absent => stream = None (file/env/default wins) + fn cli_string(&self, key: &str) -> Option { + match key { + "provider" => self.cli.provider.clone(), + "model" => self.cli.model.clone(), + "openai_api_key" => self.cli.api_key.clone(), + "base_url" => self.cli.url.clone(), + _ => None, + } + } + + fn cli_usize(&self, key: &str) -> Option { + match key { + "max_concurrent_requests" => self.cli.max, + _ => None, + } + } + + fn cli_bool(&self, key: &str) -> Option { + match key { + "stream" => self.cli.no_stream.then_some(false), + _ => None, + } + } + + fn log_decision(&self, key: &str, value: &T, src: ValueSource) { + // Redact sensitive keys (API keys, tokens, secrets) when printing + // so verbose/debug logs don't leak credentials. For option-like + // values we print /, otherwise we print . + let printable = if self.is_sensitive_key(key) { + // Try to detect Option formatted output ("Some(...)" / "None"). + let debug_str = format!("{:?}", value); + if debug_str == "None" { + "".to_string() + } else if debug_str.starts_with("Some(") { + "".to_string() + } else { + "".to_string() + } + } else { + format!("{:?}", value) + }; + + if let Some(env_key) = self.env_key_for(key) { + log::debug!( + "Config: {} = {} (source={}, env={})", + key, + printable, + source_label(src), + env_key + ); + } else { + log::debug!( + "Config: {} = {} (source={})", + key, + printable, + source_label(src) + ); + } + } + + // Treat a small set of keys as sensitive so logs redact them. + // Add other names here if you later introduce more secrets. + // Currently only the OpenAI API key is treated as sensitive. We keep the + // check centralized here so it can later be expanded. The field in the + // structs is annotated with a doc comment to indicate sensitivity. + fn is_sensitive_key(&self, key: &str) -> bool { + // Use the generated list from the Config struct (proc-macro) + // to determine which fields are sensitive. + Config::sensitive_field_names().contains(&key) + } + + fn log_decision_secret_opt_string(&self, key: &str, present: bool, src: ValueSource) { + let printable = if present { "" } else { "" }; + if let Some(env_key) = self.env_key_for(key) { + log::debug!( + "Config: {} = {} (source={}, env={})", + key, + printable, + source_label(src), + env_key + ); + } else { + log::debug!( + "Config: {} = {} (source={})", + key, + printable, + source_label(src) + ); + } + } + + /// Resolve a required string. + pub fn get_string(&self, key: &str, default: &str) -> String { + let mut value = default.to_string(); + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_string(key, false) { + value = v; + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_string(key, true) { + value = v; + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_string(key) { + value = v; + src = ValueSource::Env; + } + if let Some(v) = self.cli_string(key) { + value = v; + src = ValueSource::Cli; + } + + self.log_decision(key, &value, src); + value + } + + /// Resolve an optional string (None if not set anywhere). + pub fn get_opt_string(&self, key: &str) -> Option { + let mut value: Option = None; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_string(key, false) { + value = Some(v); + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_string(key, true) { + value = Some(v); + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_string(key) { + value = Some(v); + src = ValueSource::Env; + } + if let Some(v) = self.cli_string(key) { + value = Some(v); + src = ValueSource::Cli; + } + + self.log_decision(key, &value, src); + value + } + + /// Resolve an optional secret string; logs / only. + pub fn get_secret_opt_string(&self, key: &str) -> Option { + let mut value: Option = None; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_string(key, false) { + value = Some(v); + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_string(key, true) { + value = Some(v); + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_string(key) { + value = Some(v); + src = ValueSource::Env; + } + if let Some(v) = self.cli_string(key) { + value = Some(v); + src = ValueSource::Cli; + } + + self.log_decision_secret_opt_string(key, value.is_some(), src); + value + } + + /// Resolve a usize. + pub fn get_usize(&self, key: &str, default: usize) -> usize { + let mut value = default; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_usize(key, false) { + value = v; + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_usize(key, true) { + value = v; + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_usize(key) { + value = v; + src = ValueSource::Env; + } + if let Some(v) = self.cli_usize(key) { + value = v; + src = ValueSource::Cli; + } + + self.log_decision(key, &value, src); + value + } + + /// Resolve a u64. + pub fn get_u64(&self, key: &str, default: u64) -> u64 { + let mut value = default; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_u64(key, false) { + value = v; + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_u64(key, true) { + value = v; + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_u64(key) { + value = v; + src = ValueSource::Env; + } + + self.log_decision(key, &value, src); + value + } + + /// Resolve a bool. + pub fn get_bool(&self, key: &str, default: bool) -> bool { + let mut value = default; + let mut src = ValueSource::Hardcoded; + + if let Some(v) = self.file_bool(key, false) { + value = v; + src = ValueSource::FileDefault; + } + if let Some(v) = self.file_bool(key, true) { + value = v; + src = ValueSource::FileRepo; + } + if let Some(v) = self.env_bool(key) { + value = v; + src = ValueSource::Env; + } + if let Some(v) = self.cli_bool(key) { + value = v; + src = ValueSource::Cli; + } + + self.log_decision(key, &value, src); + value + } + + #[allow(dead_code)] + pub fn repo_id(&self) -> Option<&str> { + self.repo_id.as_deref() + } +} + +fn expand_tilde_to_path(s: &str) -> PathBuf { + if let (Some(rest), Some(home)) = (s.strip_prefix("~/"), env::var_os("HOME")) { + return PathBuf::from(home).join(rest); + } + PathBuf::from(s) +} + +fn load_file_config_from_path(path: &Path) -> FileConfigRoot { if !path.exists() { - return None; + log::warn!("Config file not found: {}", path.display()); + return FileConfigRoot::default(); } - let data = fs::read_to_string(&path).ok()?; - toml::from_str::(&data).ok() + let data = match fs::read_to_string(path) { + Ok(s) => s, + Err(err) => { + log::warn!("Failed to read config file {}: {}", path.display(), err); + return FileConfigRoot::default(); + } + }; + + match toml::from_str::(&data) { + Ok(cfg) => cfg, + Err(err) => { + log::warn!("Invalid TOML in {}: {}", path.display(), err); + FileConfigRoot::default() + } + } } diff --git a/src/git.rs b/src/git.rs index 4c9e288..079d86e 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,16 +1,17 @@ use anyhow::{anyhow, Context, Result}; -use std::path::PathBuf; use std::process::Command as GitCommand; -use std::fs; /// How we want to summarize a PR. #[derive(Debug, Clone, Copy)] pub enum PrSummaryMode { + /// Summarize by commits ByCommits, + /// Summarize by PR numbers ByPrs, } impl PrSummaryMode { + /// Convert the mode to a string representation. pub fn as_str(&self) -> &'static str { match self { PrSummaryMode::ByCommits => "commits", @@ -22,13 +23,85 @@ impl PrSummaryMode { /// A commit involved in the PR range, plus any detected PR number. #[derive(Debug, Clone)] pub struct PrItem { + /// Git commit hash pub commit_hash: String, + /// Commit title/message pub title: String, + /// Commit body/description pub body: String, + /// Detected PR number from commit message pub pr_number: Option, } -/// Run a git command and capture stdout as String. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RemoteRepo { + path: String, + web_base_url: String, + pub provider: GitProvider, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GitProvider { + GitHub, + GitLab, + Bitbucket, + AzureDevOps, + Unknown, +} + +impl RemoteRepo { + pub fn repo_id(&self) -> Option { + if self.provider == GitProvider::AzureDevOps { + let segments: Vec<&str> = self.path.split('/').filter(|s| !s.is_empty()).collect(); + if segments.len() >= 4 && segments[2] == "_git" { + return Some(format!("{}/{}", segments[1], segments[3])); + } + } + + let segments: Vec<&str> = self.path.split('/').filter(|s| !s.is_empty()).collect(); + if segments.len() >= 2 { + let owner = segments[segments.len() - 2]; + let repo = segments[segments.len() - 1]; + Some(format!("{owner}/{repo}")) + } else { + None + } + } + + pub fn commit_url(&self, commit_hash: &str) -> Option { + match self.provider { + GitProvider::GitHub => Some(format!("{}/commit/{}", self.web_base_url, commit_hash)), + GitProvider::GitLab => Some(format!("{}/-/commit/{}", self.web_base_url, commit_hash)), + GitProvider::Bitbucket => { + Some(format!("{}/commits/{}", self.web_base_url, commit_hash)) + } + GitProvider::AzureDevOps => { + Some(format!("{}/commit/{}", self.web_base_url, commit_hash)) + } + GitProvider::Unknown => None, + } + } +} + +pub fn format_git_error(args: &[&str], code: Option, stderr: &str) -> anyhow::Error { + let stderr = stderr.trim(); + + if stderr.contains("xcodebuild -license") || stderr.contains("Xcode license") { + return anyhow!( + "Xcode license agreement required.\n\ + Apple's git cannot run until the Xcode / Command Line Tools license is accepted.\n\n\ + Please run:\n sudo xcodebuild -license\n\n\ + Once accepted, run commitbot again." + ); + } + + if stderr.is_empty() { + anyhow!("git {:?} exited with status {:?}", args, code) + } else { + anyhow!("git {:?} exited with status {:?}: {}", args, code, stderr) + } +} + pub fn git_output(args: &[&str]) -> Result { let output = GitCommand::new("git") .args(args) @@ -36,45 +109,29 @@ pub fn git_output(args: &[&str]) -> Result { .with_context(|| format!("failed to run git {:?}", args))?; if !output.status.success() { - return Err(anyhow!( - "git {:?} exited with status {:?}", - args, - output.status.code() - )); + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format_git_error(args, output.status.code(), &stderr)); } Ok(String::from_utf8_lossy(&output.stdout).to_string()) } -/// Get the path to the Git directory (e.g. .git) -pub fn git_dir() -> Result { +fn remote_origin_url() -> Option { let output = GitCommand::new("git") - .args(["rev-parse", "--git-dir"]) + .args(["config", "--get", "remote.origin.url"]) .output() - .context("failed to run git rev-parse --git-dir")?; + .ok()?; if !output.status.success() { - return Err(anyhow!( - "git rev-parse --git-dir exited with status {:?}", - output.status.code() - )); + return None; } - let dir = String::from_utf8_lossy(&output.stdout).trim().to_string(); - Ok(PathBuf::from(dir)) -} - -/// Write the commit message into .git/COMMIT_EDITMSG so the next `git commit` -/// will use it as the default message in the editor. -pub fn write_commit_editmsg(message: &str) -> Result<()> { - let dir = git_dir()?; - let path = dir.join("COMMIT_EDITMSG"); - fs::write(&path, message) - .with_context(|| format!("failed to write commit message to {:?}", path))?; - Ok(()) + String::from_utf8(output.stdout) + .ok() + .map(|url| url.trim().to_string()) + .filter(|url| !url.is_empty()) } -/// Get the current branch name. pub fn current_branch() -> Result { let name = git_output(&["rev-parse", "--abbrev-ref", "HEAD"])? .trim() @@ -82,13 +139,25 @@ pub fn current_branch() -> Result { Ok(name) } -/// Get the full staged diff. -pub fn staged_diff() -> Result { - let diff = git_output(&["diff", "--cached"])?; - Ok(diff) +pub fn looks_like_commit_hash(s: &str) -> bool { + let len = s.len(); + (4..=40).contains(&len) && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +pub fn resolve_commit_diff(hash: &str) -> Result> { + let verified = GitCommand::new("git") + .args(["rev-parse", "--verify", "--quiet", &format!("{hash}^{{commit}}")]) + .output() + .with_context(|| format!("failed to run git rev-parse for '{hash}'"))?; + + if !verified.status.success() { + return Ok(None); + } + + let diff = git_output(&["show", "--format=", hash])?; + Ok(Some(diff)) } -/// Get a list of staged files. pub fn staged_files() -> Result> { let output = git_output(&["diff", "--cached", "--name-only"])?; let files = output @@ -100,13 +169,19 @@ pub fn staged_files() -> Result> { } /// Get per-file staged diff. +/// +/// `staged_files` returns paths relative to the repo root, but a bare pathspec +/// is resolved by git relative to the current working directory. Anchor it +/// with the `:/` top-level magic pathspec so this still works when commitbot +/// is invoked from a subdirectory of the repo. pub fn staged_diff_for_file(path: &str) -> Result { - let diff = git_output(&["diff", "--cached", "--", path])?; + let pathspec = format!(":/{path}"); + let diff = git_output(&["diff", "--cached", "--", &pathspec])?; Ok(diff) } /// Find the first PR number in a string, based on '#123' pattern. -fn find_first_pr_number(text: &str) -> Option { +pub fn find_first_pr_number(text: &str) -> Option { let bytes = text.as_bytes(); let len = bytes.len(); let mut i = 0; @@ -121,9 +196,7 @@ fn find_first_pr_number(text: &str) -> Option { let b = bytes[j]; if b.is_ascii_digit() { found_digit = true; - value = value - .saturating_mul(10) - .saturating_add((b - b'0') as u32); + value = value.saturating_mul(10).saturating_add((b - b'0') as u32); j += 1; } else { break; @@ -186,6 +259,42 @@ pub fn collect_pr_items(base: &str, from: &str) -> Result> { Ok(items) } +/// Split a combined diff string into (path, diff) pairs, one per file. +/// Handles both `diff --git` headers and legacy `--- a/` headers. +pub fn split_diff_by_file(diff: &str) -> Vec<(String, String)> { + let mut results = Vec::new(); + let mut current_path: Option = None; + let mut current_lines: Vec<&str> = Vec::new(); + + for line in diff.lines() { + if line.starts_with("diff --git ") { + // Save previous file + if let Some(path) = current_path.take() { + results.push((path, current_lines.join("\n"))); + } + current_lines = vec![line]; + + // Extract path from "diff --git a/foo b/foo" + let path = line + .split_whitespace() + .last() + .and_then(|s| s.strip_prefix("b/")) + .unwrap_or("") + .to_string(); + current_path = Some(path); + } else { + current_lines.push(line); + } + } + + // Flush the last file + if let Some(path) = current_path.take() { + results.push((path, current_lines.join("\n"))); + } + + results +} + /// Stage all new, modified, and deleted files pub fn stage_all() -> Result<()> { log::info!("Staging all changes"); @@ -195,42 +304,140 @@ pub fn stage_all() -> Result<()> { /// Try to derive a repo identifier like "owner/repo" from `git remote.origin.url`. pub fn detect_repo_id() -> Option { - use std::process::Command; + let remote = remote_origin_url()?; + parse_remote_repo(&remote)?.repo_id() +} - let output = Command::new("git") - .args(["config", "--get", "remote.origin.url"]) - .output() - .ok()?; +pub fn format_pr_commit_appendix(items: &[PrItem]) -> String { + if items.is_empty() { + return String::new(); + } - if !output.status.success() { - return None; + let remote = remote_origin_url().and_then(|url| parse_remote_repo(&url)); + format_pr_commit_appendix_with_remote(items, remote.as_ref()) +} + +pub fn format_pr_commit_appendix_with_remote( + items: &[PrItem], + remote: Option<&RemoteRepo>, +) -> String { + let mut out = String::from("Commits in this PR:\n"); + for item in items { + let short = short_commit_hash(&item.commit_hash); + let title = item.title.trim(); + + match remote.and_then(|repo| repo.commit_url(&item.commit_hash)) { + Some(url) => { + out.push_str(&format!("- [`{short}`]({url}) {title}\n")); + } + None => { + out.push_str(&format!("- `{short}` {title}\n")); + } + } } - let url = String::from_utf8(output.stdout).ok()?; + out.trim_end().to_string() +} + +pub fn short_commit_hash(hash: &str) -> String { + hash.chars().take(7).collect() +} + +pub fn parse_remote_repo(url: &str) -> Option { let trimmed = url.trim().trim_end_matches(".git"); + if trimmed.is_empty() { + return None; + } - // For SSH: git@github.com:owner/repo - // For HTTPS: https://github.com/owner/repo - let path = if let Some(idx) = trimmed.find("://") { - // Strip scheme and host, keep "owner/repo" - let rest = &trimmed[idx + 3..]; - match rest.find('/') { - Some(slash) => &rest[slash + 1..], - None => rest, + if let Some(rest) = trimmed.strip_prefix("git@ssh.dev.azure.com:v3/") { + let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect(); + if parts.len() >= 3 { + let org = parts[0]; + let project = parts[1]; + let repo = parts[2]; + return Some(RemoteRepo { + path: format!("{org}/{project}/_git/{repo}"), + web_base_url: format!("https://dev.azure.com/{org}/{project}/_git/{repo}"), + provider: GitProvider::AzureDevOps, + }); } - } else if let Some(idx) = trimmed.find(':') { - // SSH-style: after ':' is "owner/repo" - &trimmed[idx + 1..] + } + + if let Some(rest) = trimmed.strip_prefix("ssh://") { + return parse_remote_repo_from_authority_path(rest); + } + + if let Some((host_part, path_part)) = trimmed.split_once("://") { + let _scheme = host_part; + return parse_remote_repo_from_authority_path(path_part); + } + + if let Some((user_host, path)) = trimmed.split_once(':') { + let host = user_host.rsplit('@').next()?.to_string(); + return build_remote_repo(host, path.trim_start_matches('/')); + } + + None +} + +fn parse_remote_repo_from_authority_path(input: &str) -> Option { + let without_user = input.rsplit('@').next().unwrap_or(input); + let (host, path) = without_user.split_once('/')?; + build_remote_repo(host.to_string(), path) +} + +fn build_remote_repo(host: String, path: &str) -> Option { + let clean_path = path.trim_matches('/').to_string(); + if clean_path.is_empty() { + return None; + } + + let provider = if host.contains("github") { + GitProvider::GitHub + } else if host.contains("gitlab") { + GitProvider::GitLab + } else if host.contains("bitbucket") { + GitProvider::Bitbucket + } else if host.contains("azure") + || host == "dev.azure.com" + || host.ends_with(".visualstudio.com") + { + GitProvider::AzureDevOps } else { - trimmed + GitProvider::Unknown + }; + + let web_base_url = match provider { + GitProvider::AzureDevOps => normalize_azure_web_base(&host, &clean_path)?, + _ => format!("https://{host}/{clean_path}"), }; + Some(RemoteRepo { + path: clean_path, + web_base_url, + provider, + }) +} + +fn normalize_azure_web_base(host: &str, path: &str) -> Option { let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); - if segments.len() >= 2 { - let owner = segments[segments.len() - 2]; - let repo = segments[segments.len() - 1]; - Some(format!("{}/{}", owner, repo)) - } else { - None + + if host == "dev.azure.com" && segments.len() >= 4 && segments[2] == "_git" { + return Some(format!( + "https://dev.azure.com/{}/{}/_git/{}", + segments[0], segments[1], segments[3] + )); } -} \ No newline at end of file + + if host.ends_with(".visualstudio.com") { + let org = host.trim_end_matches(".visualstudio.com"); + if segments.len() >= 3 && segments[1] == "_git" { + return Some(format!( + "https://{}.visualstudio.com/{}/_git/{}", + org, segments[0], segments[2] + )); + } + } + + None +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..e701e1d --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,138 @@ +//! Core types and shared functionality for commitbot. +//! +//! This module contains shared types and functions used across the application. + +pub mod cli_args; +pub mod config; +pub mod git; +pub mod llm; +pub mod logging; +pub mod setup; + +pub use cli_args::{Cli, Command}; +pub use git::{ + collect_pr_items, current_branch, format_pr_commit_appendix, split_diff_by_file, stage_all, + staged_diff_for_file, staged_files, PrSummaryMode, +}; +pub use llm::LlmClient; + +/// Lock files whose names don't end in `.lock`, so the extension check misses them. +const LOCK_FILE_NAMES: &[&str] = &[ + "package-lock.json", // npm + "npm-shrinkwrap.json", // npm + "pnpm-lock.yaml", // pnpm + "bun.lockb", // bun (pre-1.2 binary format) + "packages.lock.json", // NuGet + "gradle.lockfile", // Gradle +]; + +/// True when the path names a dependency lock file: any `*.lock` file, plus the +/// well-known lock files that use a different extension ([`LOCK_FILE_NAMES`]). +/// +/// Lock files are regenerated wholesale by a package manager, so their diffs +/// carry no intent worth asking the LLM about. We skip summarizing them and +/// only tell the final summary that they were touched. +pub fn is_lock_file(path: &str) -> bool { + let path = std::path::Path::new(path); + + if path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("lock")) + { + return true; + } + + path.file_name().is_some_and(|name| { + LOCK_FILE_NAMES + .iter() + .any(|known| name.eq_ignore_ascii_case(known)) + }) +} + +/// How each file is categorized. The first four come from the user in +/// interactive mode; `Lock` is assigned automatically by [`is_lock_file`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +pub enum FileCategory { + Main, // 1 + Supporting, // 2 + Consequence, // 3 + Ignored, // 4 + Lock, // auto-assigned to *.lock files +} + +impl FileCategory { + /// Convert the category to a string representation. + pub fn as_str(&self) -> &'static str { + match self { + FileCategory::Main => "main", + FileCategory::Supporting => "supporting", + FileCategory::Consequence => "consequence", + FileCategory::Ignored => "ignored", + FileCategory::Lock => "lock", + } + } +} + +/// Truncates an oversized diff before it's ever sent to an LLM. +/// +/// Some diffs (Jupyter notebooks with embedded base64 image outputs, minified +/// bundles, generated files) can run into the megabytes, which blows past any +/// local model's context window and can wedge the upstream server for every +/// other in-flight request. Cutting on a line boundary keeps the remaining +/// diff readable instead of ending mid-line. +pub fn truncate_diff(diff: &str, max_bytes: usize) -> String { + if diff.len() <= max_bytes { + return diff.to_string(); + } + + let mut cut = max_bytes; + while cut > 0 && !diff.is_char_boundary(cut) { + cut -= 1; + } + + let head = match diff[..cut].rfind('\n') { + Some(idx) => &diff[..idx], + None => &diff[..cut], + }; + + let omitted = diff.len() - head.len(); + format!( + "{head}\n... [diff truncated, {omitted} bytes omitted — file is unusually large, \ + likely generated or contains embedded binary/base64 content]" + ) +} + +/// Represents a single staged file's change and metadata. +#[derive(Debug, Clone)] +pub struct FileChange { + /// Path to the file + pub path: String, + /// User-defined category for this file + pub category: FileCategory, + /// Git diff for this file + pub diff: String, + /// LLM-generated summary for this file. Always `None` for + /// [`FileCategory::Lock`] and [`FileCategory::Ignored`] files. + pub summary: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncate_diff_leaves_small_diffs_untouched() { + let diff = "diff --git a/f b/f\n+hello\n"; + assert_eq!(truncate_diff(diff, 1_000), diff); + } + + #[test] + fn truncate_diff_cuts_oversized_diffs_on_a_line_boundary() { + let diff = "line one\nline two\nline three\n"; + let result = truncate_diff(diff, 15); + + assert!(result.starts_with("line one\n")); + assert!(!result.contains("line three")); + assert!(result.contains("truncated")); + } +} diff --git a/src/llm/mod.rs b/src/llm/mod.rs index aee3fc8..68d6b2a 100644 --- a/src/llm/mod.rs +++ b/src/llm/mod.rs @@ -1,20 +1,25 @@ -pub mod openai; pub mod ollama; +pub mod openai; +pub mod prompt_builder; mod prompts; -mod prompt_builder; mod stream; -use crate::git::{PrItem, PrSummaryMode}; use crate::FileChange; +use crate::git::{PrItem, PrSummaryMode}; use anyhow::Result; /// Trait for talking to an LLM (real backend). pub trait LlmClient: Send + Sync { + /// Confirm the configured model is reachable/known by the upstream provider. + fn validate_model(&self) -> Result<()>; + /// Generate a per-file summary based on diff + metadata. fn summarize_file( &self, branch: &str, file: &FileChange, + file_index: usize, + total_files: usize, ticket_summary: Option<&str>, ) -> Result; @@ -26,14 +31,6 @@ pub trait LlmClient: Send + Sync { ticket_summary: Option<&str>, ) -> Result; - /// Simple mode: commit message from entire diff. - fn generate_commit_message_simple( - &self, - branch: &str, - diff: &str, - ticket_summary: Option<&str>, - ) -> Result; - /// PR mode: generate a PR description from commit/PR messages. fn generate_pr_message( &self, @@ -43,4 +40,9 @@ pub trait LlmClient: Send + Sync { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result; + + /// Take aggregated token usage from the client, resetting counters. + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + None + } } diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 2f0725d..898d132 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -1,15 +1,17 @@ -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use log; -use musli::{Encode, Decode}; use musli::json; +use musli::{Decode, Encode}; use reqwest::blocking::Client; use std::io::BufReader; +use std::sync::Mutex; +use std::time::Instant; use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; -use super::{prompt_builder, LlmClient}; use super::stream::read_stream_to_string; +use super::{LlmClient, prompt_builder}; #[derive(Debug, Encode, Decode)] struct OllamaMessage { @@ -26,6 +28,31 @@ struct OllamaChatResponse { struct OllamaStreamResponse { message: Option, done: Option, + /// Token counts, reported only on the final (`done`) chunk. + #[musli(default)] + prompt_eval_count: Option, + #[musli(default)] + eval_count: Option, +} + +#[derive(Debug, Decode)] +struct OllamaUsage { + prompt_tokens: Option, + completion_tokens: Option, + total_tokens: Option, +} + +// Scaffolding for a future "list models" command; only exercised by tests today. +#[allow(dead_code)] +#[derive(Debug, Decode)] +struct OllamaTagModel { + name: String, +} + +#[allow(dead_code)] +#[derive(Debug, Decode)] +struct OllamaTagsResponse { + models: Vec, } /// Synchronous Ollama client using /api/chat. @@ -34,11 +61,33 @@ pub struct OllamaClient { base_url: String, model: String, stream: bool, + /// When true, suppress live-printed streaming chunks (still captured + /// into the returned string) — used for `--oneline quiet`. + quiet: bool, + usage: Mutex, +} + +#[derive(Default)] +struct TokenUsage { + prompt_tokens: u64, + completion_tokens: u64, + total_tokens: u64, } impl OllamaClient { - pub fn new(base_url: impl Into, model: impl Into, stream: bool) -> Self { + pub fn new(base_url: impl Into, model: impl Into, stream: bool, timeout_secs: u64) -> Self { + Self::with_quiet(base_url, model, stream, false, timeout_secs) + } + + pub fn with_quiet( + base_url: impl Into, + model: impl Into, + stream: bool, + quiet: bool, + timeout_secs: u64, + ) -> Self { let http = Client::builder() + .timeout(std::time::Duration::from_secs(timeout_secs)) .build() .expect("failed to build HTTP client"); Self { @@ -46,6 +95,8 @@ impl OllamaClient { base_url: base_url.into().trim_end_matches('/').to_string(), model: model.into(), stream, + quiet, + usage: Mutex::new(TokenUsage::default()), } } @@ -87,6 +138,7 @@ impl OllamaClient { let url = format!("{}/api/chat", self.base_url); + let t0 = Instant::now(); let resp = self .http .post(&url) @@ -99,21 +151,74 @@ impl OllamaClient { if stream { let reader = BufReader::new(resp); - return read_stream_to_string(reader, parse_stream_line); + let result = read_stream_to_string(reader, self.quiet, |line| { + if let Some((prompt, completion)) = parse_stream_usage(line) { + let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); + u.prompt_tokens += prompt; + u.completion_tokens += completion; + u.total_tokens += prompt + completion; + } + parse_stream_line(line) + }); + log::debug!("Ollama response time: {:.2?}", t0.elapsed()); + return result; } let resp_text = resp .text() .map_err(|e| anyhow!("Failed to read Ollama response body: {e}"))?; + log::debug!("Ollama response time: {:.2?}", t0.elapsed()); log::trace!("Ollama raw JSON response: {resp_text}"); - let parsed: OllamaChatResponse = - json::from_str(&resp_text).map_err(|e| anyhow!("Failed to decode Ollama JSON: {e}"))?; + #[derive(Debug, Decode)] + struct OllamaChatWrapper { + message: OllamaMessage, + usage: Option, + } - Ok(parsed.message.content.trim().to_string()) + // First try decoding into the wrapper. If that fails fall back to the + // older shape without usage. + match json::from_str::(&resp_text) { + Ok(parsed) => { + if let Some(usage) = parsed.usage { + // Recover from a poisoned mutex instead of panicking so the CLI + // can continue in the face of concurrent thread panics. + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); + u.prompt_tokens += usage.prompt_tokens.unwrap_or(0) as u64; + u.completion_tokens += usage.completion_tokens.unwrap_or(0) as u64; + u.total_tokens += usage.total_tokens.unwrap_or(0) as u64; + } + Ok(parsed.message.content.trim().to_string()) + } + Err(_) => { + // Fallback to the simple response shape. + let parsed: OllamaChatResponse = json::from_str(&resp_text) + .map_err(|e| anyhow!("Failed to decode Ollama JSON: {e}"))?; + Ok(parsed.message.content.trim().to_string()) + } + } } + /// Scaffolding for a future "list models" command; only exercised by tests today. + #[allow(dead_code)] + fn tags_url(&self) -> String { + format!("{}/api/tags", self.base_url) + } +} + +/// (prompt, completion) token counts from a final streamed chunk, if present. +fn parse_stream_usage(line: &str) -> Option<(u64, u64)> { + let parsed: OllamaStreamResponse = json::from_str(line).ok()?; + if !parsed.done.unwrap_or(false) { + return None; + } + let prompt = parsed.prompt_eval_count? as u64; + let completion = parsed.eval_count.unwrap_or(0) as u64; + Some((prompt, completion)) } fn parse_stream_line(line: &str) -> Result> { @@ -124,21 +229,39 @@ fn parse_stream_line(line: &str) -> Result> { return Ok(None); } - let content = parsed - .message - .and_then(|m| if m.content.is_empty() { None } else { Some(m.content) }); + let content = parsed.message.and_then(|m| { + if m.content.is_empty() { + None + } else { + Some(m.content) + } + }); Ok(content) } impl LlmClient for OllamaClient { + fn validate_model(&self) -> Result<()> { + // Skipping model validation for Ollama; use a future "list models" command + // to query /api/tags if the user requests it. + Ok(()) + } + fn summarize_file( &self, branch: &str, file: &FileChange, + file_index: usize, + total_files: usize, ticket_summary: Option<&str>, ) -> Result { - let prompts = prompt_builder::file_summary_prompt(branch, file, ticket_summary); + let prompts = prompt_builder::file_summary_prompt( + branch, + file, + file_index, + total_files, + ticket_summary, + ); self.chat(prompts.system, prompts.user, false) } @@ -149,17 +272,8 @@ impl LlmClient for OllamaClient { ticket_summary: Option<&str>, ) -> Result { let prompts = prompt_builder::commit_message_prompt(branch, files, ticket_summary); - self.chat(prompts.system, prompts.user, self.stream) - } - - fn generate_commit_message_simple( - &self, - branch: &str, - diff: &str, - ticket_summary: Option<&str>, - ) -> Result { - let prompts = prompt_builder::commit_message_simple_prompt(branch, diff, ticket_summary); - self.chat(prompts.system, prompts.user, self.stream) + let content = self.chat(prompts.system, prompts.user, self.stream)?; + Ok(content) } fn generate_pr_message( @@ -170,8 +284,71 @@ impl LlmClient for OllamaClient { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result { - let prompts = - prompt_builder::pr_message_prompt(base_branch, from_branch, mode, items, ticket_summary); - self.chat(prompts.system, prompts.user, self.stream) + let prompts = prompt_builder::pr_message_prompt( + base_branch, + from_branch, + mode, + items, + ticket_summary, + ); + let content = self.chat(prompts.system, prompts.user, self.stream)?; + Ok(content) + } + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); + + if u.total_tokens > 0 { + let res = (u.prompt_tokens, u.completion_tokens, u.total_tokens); + *u = TokenUsage::default(); + Some(res) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trims_trailing_slash_in_tags_url() { + let client = OllamaClient::new("http://localhost:11434/", "gemma4:31b", false, 90); + assert_eq!(client.tags_url(), "http://localhost:11434/api/tags"); + } + + #[test] + fn decodes_ollama_tags_payload() { + let body = r#"{"models":[{"name":"gemma4:31b"},{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#; + let parsed: OllamaTagsResponse = json::from_str(body).expect("valid tags payload"); + + assert!(parsed + .models + .iter() + .any(|model| model.name == "gemma4:31b")); + assert!(!parsed + .models + .iter() + .any(|model| model.name == "missing:model")); + } + + #[test] + fn reads_token_counts_from_the_final_stream_chunk() { + let line = r#"{"message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":12,"eval_count":5}"#; + assert_eq!(parse_stream_usage(line), Some((12, 5))); + } + + #[test] + fn stream_usage_is_none_until_the_final_chunk() { + let mid = r#"{"message":{"role":"assistant","content":"hi"},"done":false}"#; + assert_eq!(parse_stream_usage(mid), None); + + let done_without_counts = r#"{"message":{"role":"assistant","content":""},"done":true}"#; + assert_eq!(parse_stream_usage(done_without_counts), None); + + assert_eq!(parse_stream_usage("not json"), None); } } diff --git a/src/llm/openai.rs b/src/llm/openai.rs index 125acf7..6104980 100644 --- a/src/llm/openai.rs +++ b/src/llm/openai.rs @@ -1,13 +1,15 @@ use super::LlmClient; +use super::prompt_builder; use super::stream::read_stream_to_string; -use crate::{FileChange}; +use crate::FileChange; use crate::git::{PrItem, PrSummaryMode}; -use anyhow::{anyhow, Context, Result}; -use reqwest::blocking::Client; +use anyhow::{Context, Result, anyhow}; +use reqwest::StatusCode; +use reqwest::blocking::{Client, RequestBuilder}; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::time::Duration; -use super::prompt_builder; +use std::sync::Mutex; /// Minimal request/response structs for OpenAI Chat Completions API. #[derive(Serialize)] @@ -25,6 +27,7 @@ struct ChatMessage { #[derive(Deserialize)] struct ChatResponse { + #[serde(default)] choices: Vec, usage: Option, } @@ -36,18 +39,36 @@ struct ChatChoice { #[derive(Deserialize)] struct ChatMessageResponse { - content: String, + #[serde(default)] + content: Option, + #[serde(default)] + reasoning_content: Option, } -#[derive(Deserialize)] +#[derive(Deserialize, Default)] struct ChatUsage { + #[serde(default)] prompt_tokens: u32, + #[serde(default)] completion_tokens: u32, + #[serde(default)] total_tokens: u32, } +#[derive(Deserialize)] +struct ModelListResponse { + #[serde(default)] + data: Vec, +} + +#[derive(Deserialize)] +struct ModelListEntry { + id: String, +} + #[derive(Deserialize)] struct StreamResponse { + #[serde(default)] choices: Vec, } @@ -58,22 +79,77 @@ struct StreamChoice { #[derive(Deserialize)] struct StreamDelta { + #[serde(default)] content: Option, + #[serde(default)] + #[allow(dead_code)] + reasoning_content: Option, +} + +/// How to confirm the configured model exists on the upstream server. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModelValidation { + /// `GET {base}/v1/models/{model}` — OpenAI's retrieve-model endpoint. + Retrieve, + /// `GET {base}/v1/models`, then look for the id in the listing. LM Studio + /// only implements the list endpoint, not retrieve. + List, } -/// OpenAI-based implementation of LlmClient. +/// Client for OpenAI and any server speaking the same chat-completions API. pub struct OpenAiClient { client: Client, - api_key: String, + api_key: Option, model: String, api_base_url: String, stream: bool, + /// When true, suppress live-printed streaming chunks (still captured + /// into the returned string) — used for `--oneline quiet`. + quiet: bool, + /// Name used in logs and error messages (e.g. "OpenAI", "LM Studio"). + provider_label: String, + model_validation: ModelValidation, + usage: Mutex, +} + +#[derive(Default)] +struct TokenUsage { + prompt_tokens: u64, + completion_tokens: u64, + total_tokens: u64, } impl OpenAiClient { - pub fn new(api_key: String, model: String, api_base_url: String, stream: bool) -> Self { + pub fn new(api_key: String, model: String, api_base_url: String, stream: bool, timeout_secs: u64) -> Self { + Self::openai_compatible( + Some(api_key), + model, + api_base_url, + stream, + false, + timeout_secs, + "OpenAI", + ModelValidation::Retrieve, + ) + } + + /// Client for an OpenAI-compatible server (LM Studio, self-hosted gateways). + /// + /// `api_key` is optional: LM Studio serves unauthenticated requests by + /// default, and omitting the key sends no `Authorization` header at all. + #[allow(clippy::too_many_arguments)] + pub fn openai_compatible( + api_key: Option, + model: String, + api_base_url: String, + stream: bool, + quiet: bool, + timeout_secs: u64, + provider_label: impl Into, + model_validation: ModelValidation, + ) -> Self { let client = Client::builder() - .timeout(Duration::from_secs(90)) + .timeout(Duration::from_secs(timeout_secs)) .build() .expect("failed to build HTTP client"); @@ -81,19 +157,41 @@ impl OpenAiClient { client, api_key, model, - api_base_url: api_base_url.trim_end_matches('/').to_string(), + api_base_url: normalize_base_url(&api_base_url), stream, + quiet, + provider_label: provider_label.into(), + model_validation, + usage: Mutex::new(TokenUsage::default()), } } - fn chat_url(&self) -> String { - if self.api_base_url.ends_with("/v1") { - format!("{}/chat/completions", self.api_base_url) - } else { - format!("{}/v1/chat/completions", self.api_base_url) + /// Attach bearer auth when a key is configured, otherwise send the request + /// unauthenticated. + fn authed(&self, req: RequestBuilder) -> RequestBuilder { + match &self.api_key { + Some(key) => req.bearer_auth(key), + None => req, } } + /// Join `path` under `/v1`, with base URL guaranteed normalized. + fn v1_url(&self, path: &str) -> String { + format!("{}/v1/{}", self.api_base_url, path.trim_start_matches('/')) + } + + fn chat_url(&self) -> String { + self.v1_url("chat/completions") + } + + fn model_url(&self) -> String { + self.v1_url(&format!("models/{}", self.model)) + } + + fn models_url(&self) -> String { + self.v1_url("models") + } + fn call_chat(&self, req: &ChatRequest) -> Result { if req.stream { return self.call_chat_streaming(req); @@ -101,68 +199,281 @@ impl OpenAiClient { let url = self.chat_url(); - log::info!("Calling OpenAI model {:?}", &req.model); + log::info!("Calling {} model {:?}", self.provider_label, req.model); + let t0 = std::time::Instant::now(); let resp = self - .client - .post(url) - .bearer_auth(&self.api_key) + .authed(self.client.post(&url)) .json(req) .send() - .context("failed to send request to OpenAI")?; + .with_context(|| format!("failed to send request to {} at {}", self.provider_label, url))?; if !resp.status().is_success() { let status = resp.status(); let text = resp.text().unwrap_or_default(); return Err(anyhow!( - "OpenAI API error: HTTP {} - {}", + "{} API error: HTTP {} - {}", + self.provider_label, status.as_u16(), text )); } - let chat_resp: ChatResponse = resp.json().context("failed to parse OpenAI response")?; + let chat_resp: ChatResponse = resp + .json() + .with_context(|| format!("failed to parse {} response", self.provider_label))?; + log::debug!("{} response time: {:.2?}", self.provider_label, t0.elapsed()); let content = chat_resp .choices .first() - .map(|c| c.message.content.clone()) - .ok_or_else(|| anyhow!("no choices returned from OpenAI"))?; + .and_then(|c| { + c.message + .content + .clone() + .filter(|s| !s.trim().is_empty()) + .or_else(|| { + c.message + .reasoning_content + .clone() + .filter(|s| !s.trim().is_empty()) + }) + }) + .ok_or_else(|| anyhow!("no content returned from {}", self.provider_label))?; if let Some(usage) = &chat_resp.usage { - log::warn!("Token usage: prompt={}, completion={}, total={}", - usage.prompt_tokens, usage.completion_tokens, usage.total_tokens - ); + self.record_usage(usage); } Ok(content) } + /// Add a response's token counts to the running totals. + fn record_usage(&self, usage: &ChatUsage) { + // Recover from a poisoned mutex instead of panicking so the CLI + // can continue in the face of concurrent thread panics. + let mut u = self.usage.lock().unwrap_or_else(|e| e.into_inner()); + u.prompt_tokens += usage.prompt_tokens as u64; + u.completion_tokens += usage.completion_tokens as u64; + u.total_tokens += usage.total_tokens as u64; + } + fn call_chat_streaming(&self, req: &ChatRequest) -> Result { let url = self.chat_url(); - log::info!("Streaming OpenAI model {:?}", &req.model); + log::info!("Streaming {} model {:?}", self.provider_label, req.model); + // Streamed responses only carry token usage (in a final chunk) when + // asked to. + let mut body = serde_json::to_value(req).context("failed to encode streaming request")?; + body["stream_options"] = serde_json::json!({ "include_usage": true }); + + let t0 = std::time::Instant::now(); let resp = self - .client - .post(url) - .bearer_auth(&self.api_key) - .json(req) + .authed(self.client.post(&url)) + .json(&body) .send() - .context("failed to send streaming request to OpenAI")?; + .with_context(|| { + format!( + "failed to send streaming request to {} at {}", + self.provider_label, url + ) + })?; if !resp.status().is_success() { let status = resp.status(); let text = resp.text().unwrap_or_default(); return Err(anyhow!( - "OpenAI API error: HTTP {} - {}", + "{} API error: HTTP {} - {}", + self.provider_label, status.as_u16(), text )); } let reader = BufReader::new(resp); - read_stream_to_string(reader, parse_stream_line) + let result = read_stream_to_string(reader, self.quiet, |line| { + if let Some(usage) = parse_stream_usage(line) { + self.record_usage(&usage); + } + parse_stream_line(line) + }); + log::debug!( + "{} streaming response time: {:.2?}", + self.provider_label, + t0.elapsed() + ); + result } + + /// `GET /v1/models/{model}` — OpenAI's retrieve-model endpoint. + fn validate_model_by_retrieve(&self) -> Result<()> { + let url = self.model_url(); + let resp = self + .authed(self.client.get(&url)) + .send() + .with_context(|| { + format!( + "failed to send model validation request to {} at {}", + self.provider_label, url + ) + })?; + + if resp.status() == StatusCode::OK { + return Ok(()); + } + + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + Err(anyhow!( + "{} model validation failed for {:?} at {}: HTTP {} - {}", + self.provider_label, + self.model, + url, + status.as_u16(), + text + )) + } + + /// `GET /v1/models` plus a membership check, for servers that list models + /// but do not implement retrieve-by-id. + fn validate_model_by_list(&self) -> Result<()> { + let url = self.models_url(); + let resp = self + .authed(self.client.get(&url)) + .send() + .with_context(|| { + format!( + "failed to reach {} at {} — is the server running and reachable?", + self.provider_label, url + ) + })?; + + if !resp.status().is_success() { + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + return Err(anyhow!( + "{} model listing failed at {}: HTTP {} - {}", + self.provider_label, + url, + status.as_u16(), + text + )); + } + + let listed: ModelListResponse = match resp.json() { + Ok(l) => l, + Err(e) => { + log::warn!( + "{} model listing at {} could not be parsed: {}. Proceeding anyway...", + self.provider_label, + url, + e + ); + return Ok(()); + } + }; + + if listed.data.is_empty() { + log::warn!( + "{} at {} returned an empty model list; proceeding with {:?}", + self.provider_label, + url, + self.model + ); + return Ok(()); + } + + if listed.data.iter().any(|m| matches_model_id(&self.model, &m.id)) { + return Ok(()); + } + + let available = listed + .data + .iter() + .map(|m| m.id.as_str()) + .collect::>() + .join(", "); + + Err(anyhow!( + "{} at {} has no model {:?}. Available: {}", + self.provider_label, + url, + self.model, + if available.is_empty() { + "(none)" + } else { + &available + } + )) + } +} + +/// Normalizes any variation of base URL (e.g. `http://host:1234`, `http://host:1234/v1`, +/// `http://host:1234/V1/`, `http://host:1234/api/v1`, `http://host:1234/v1/chat/completions`) +/// down to the base origin so that `v1_url` can deterministically append `/v1/{path}`. +pub fn normalize_base_url(raw: &str) -> String { + let mut url = raw.trim().trim_end_matches('/').to_string(); + + if url.to_ascii_lowercase().ends_with("/chat/completions") { + url = url[..url.len() - "/chat/completions".len()] + .trim_end_matches('/') + .to_string(); + } else if url.to_ascii_lowercase().ends_with("/models") { + url = url[..url.len() - "/models".len()] + .trim_end_matches('/') + .to_string(); + } + + if url.to_ascii_lowercase().ends_with("/api/v1") { + url = url[..url.len() - "/api/v1".len()] + .trim_end_matches('/') + .to_string(); + } else if url.to_ascii_lowercase().ends_with("/v1") { + url = url[..url.len() - "/v1".len()] + .trim_end_matches('/') + .to_string(); + } + + url +} + +fn clean_model_name(s: &str) -> &str { + let without_gguf = s.strip_suffix(".gguf").unwrap_or(s); + without_gguf.split(':').next().unwrap_or(without_gguf) +} + +/// Check if a model candidate string from the server matches the configured model name. +/// Handles exact match, case-insensitivity, repo prefixes (e.g. "google/gemma-4-12b-qat" vs "gemma-4-12b-qat"), +/// and stripping file extensions like ".gguf" or tags like ":latest". +pub fn matches_model_id(configured: &str, candidate: &str) -> bool { + if configured == candidate { + return true; + } + if configured.eq_ignore_ascii_case(candidate) { + return true; + } + let conf_base = configured.rsplit('/').next().unwrap_or(configured); + let cand_base = candidate.rsplit('/').next().unwrap_or(candidate); + if conf_base.eq_ignore_ascii_case(cand_base) { + return true; + } + let conf_clean = clean_model_name(conf_base); + let cand_clean = clean_model_name(cand_base); + conf_clean.eq_ignore_ascii_case(cand_clean) +} + +#[derive(Deserialize)] +struct StreamUsageChunk { + usage: Option, +} + +/// Token usage from the final streamed chunk, when the server sends one. +fn parse_stream_usage(line: &str) -> Option { + let data = line.trim_start().strip_prefix("data:")?.trim(); + if data == "[DONE]" { + return None; + } + serde_json::from_str::(data).ok()?.usage } fn parse_stream_line(line: &str) -> Result> { @@ -178,28 +489,79 @@ fn parse_stream_line(line: &str) -> Result> { let chunk: StreamResponse = serde_json::from_str(data).context("failed to parse OpenAI streaming chunk")?; - let content = chunk - .choices - .first() - .and_then(|c| c.delta.content.clone()); + let content = chunk.choices.first().and_then(|c| c.delta.content.clone()); Ok(content) } impl LlmClient for OpenAiClient { + fn validate_model(&self) -> Result<()> { + match self.model_validation { + ModelValidation::Retrieve => match self.validate_model_by_retrieve() { + Ok(()) => Ok(()), + Err(e) => { + log::debug!( + "Retrieve model validation failed: {e}. Falling back to list validation." + ); + if let Ok(()) = self.validate_model_by_list() { + return Ok(()); + } + if self.provider_label != "OpenAI" { + log::warn!( + "Could not validate model {:?} on {}: {}. Proceeding anyway...", + self.model, + self.provider_label, + e + ); + Ok(()) + } else { + Err(e) + } + } + }, + ModelValidation::List => match self.validate_model_by_list() { + Ok(()) => Ok(()), + Err(e) => { + log::debug!( + "List model validation failed: {e}. Falling back to retrieve validation." + ); + if let Ok(()) = self.validate_model_by_retrieve() { + return Ok(()); + } + Err(e) + } + }, + } + } + fn summarize_file( &self, branch: &str, file: &FileChange, + file_index: usize, + total_files: usize, ticket_summary: Option<&str>, ) -> Result { - let prompts = prompt_builder::file_summary_prompt(branch, file, ticket_summary); + let prompts = prompt_builder::file_summary_prompt( + branch, + file, + file_index, + total_files, + ticket_summary, + ); log::debug!( - "Per-file summarize prompt for {} ({:?}):\n{}", + "Per-file summarize prompt for {} ({:?}) [truncated]:\n{}", + file.path, + file.category, + truncate(&prompts.user, 1000) + ); + log::trace!( + "Per-file summarize prompt for {} ({:?}) [full]:\n--- SYSTEM ---\n{}\n--- USER ---\n{}", file.path, file.category, - truncate(&prompts.user, 2000) + prompts.system, + prompts.user ); let req = ChatRequest { @@ -229,41 +591,14 @@ impl LlmClient for OpenAiClient { ) -> Result { let prompts = prompt_builder::commit_message_prompt(branch, files, ticket_summary); - log::debug!( - "Final commit-message prompt:\n{}", - truncate(&prompts.user, 3000) + log::info!( + "Final commit-message prompt [truncated]:\n{}", + truncate(&prompts.user, 1000) ); - - let req = ChatRequest { - model: self.model.clone(), - messages: vec![ - ChatMessage { - role: "system".into(), - content: prompts.system, - }, - ChatMessage { - role: "user".into(), - content: prompts.user, - }, - ], - stream: self.stream, - }; - - let content = self.call_chat(&req)?; - Ok(content) - } - - fn generate_commit_message_simple( - &self, - branch: &str, - diff: &str, - ticket_summary: Option<&str>, - ) -> Result { - let prompts = prompt_builder::commit_message_simple_prompt(branch, diff, ticket_summary); - - log::trace!( - "Simple commit-message prompt:\n{}", - truncate(&prompts.user, 3000) + log::debug!( + "Final commit-message prompt [full]:\n--- SYSTEM ---\n{}\n--- USER ---\n{}", + prompts.system, + prompts.user ); let req = ChatRequest { @@ -293,12 +628,22 @@ impl LlmClient for OpenAiClient { items: &[PrItem], ticket_summary: Option<&str>, ) -> Result { - let prompts = - prompt_builder::pr_message_prompt(base_branch, from_branch, mode, items, ticket_summary); + let prompts = prompt_builder::pr_message_prompt( + base_branch, + from_branch, + mode, + items, + ticket_summary, + ); - log::trace!( - "PR description prompt:\n{}", - truncate(&prompts.user, 3500) + log::info!( + "PR description prompt [truncated]:\n{}", + truncate(&prompts.user, 1000) + ); + log::debug!( + "PR description prompt [full]:\n--- SYSTEM ---\n{}\n--- USER ---\n{}", + prompts.system, + prompts.user ); let req = ChatRequest { @@ -319,6 +664,21 @@ impl LlmClient for OpenAiClient { let content = self.call_chat(&req)?; Ok(content) } + + fn take_and_reset_usage(&self) -> Option<(u64, u64, u64)> { + let mut u = self.usage.lock().unwrap_or_else(|e| { + log::warn!("usage mutex was poisoned, recovering token counters"); + e.into_inner() + }); + + if u.total_tokens > 0 { + let res = (u.prompt_tokens, u.completion_tokens, u.total_tokens); + *u = TokenUsage::default(); + Some(res) + } else { + None + } + } } /// Truncate long strings for debug logging. @@ -326,6 +686,247 @@ fn truncate(s: &str, max_len: usize) -> String { if s.len() <= max_len { s.to_string() } else { - format!("{}...\n[truncated {} chars]", &s[..max_len], s.len() - max_len) + format!( + "{}...\n[truncated {} chars]", + &s[..max_len], + s.len() - max_len + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_usage_from_the_final_stream_chunk() { + let usage = parse_stream_usage( + r#"data: {"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":4,"total_tokens":7}}"#, + ) + .expect("usage chunk"); + assert_eq!((usage.prompt_tokens, usage.completion_tokens, usage.total_tokens), (3, 4, 7)); + } + + #[test] + fn stream_usage_ignores_content_chunks_done_and_garbage() { + assert!(parse_stream_usage(r#"data: {"choices":[{"delta":{"content":"hi"}}]}"#).is_none()); + assert!(parse_stream_usage(r#"data: {"choices":[{"delta":{"content":"hi"}}],"usage":null}"#).is_none()); + assert!(parse_stream_usage("data: [DONE]").is_none()); + assert!(parse_stream_usage("data: not json").is_none()); + assert!(parse_stream_usage(": keep-alive").is_none()); + } + + #[test] + fn builds_model_url_from_root_base() { + let client = OpenAiClient::new( + "test-key".into(), + "gpt-5-nano".into(), + "https://api.openai.com".into(), + false, + 90, + ); + + assert_eq!( + client.model_url(), + "https://api.openai.com/v1/models/gpt-5-nano" + ); + } + + #[test] + fn builds_model_url_from_v1_base() { + let client = OpenAiClient::new( + "test-key".into(), + "gpt-5-nano".into(), + "https://api.openai.com/v1".into(), + false, + 90, + ); + + assert_eq!( + client.model_url(), + "https://api.openai.com/v1/models/gpt-5-nano" + ); + } + + fn lm_studio(base_url: &str) -> OpenAiClient { + OpenAiClient::openai_compatible( + None, + "qwen/qwen3-coder-30b".into(), + base_url.into(), + false, + false, + 90, + "LM Studio", + ModelValidation::List, + ) + } + + #[test] + fn builds_lm_studio_urls_from_v1_base() { + let client = lm_studio("http://localhost:1234/v1"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_root_base() { + // Given without the /v1 suffix, and with a trailing slash, still lands + // on the same paths. + let client = lm_studio("http://localhost:1234/"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn lm_studio_validates_against_the_model_list() { + // LM Studio implements GET /v1/models but not GET /v1/models/{id}, + // so validation has to go through the listing. + assert_eq!( + lm_studio("http://localhost:1234/v1").model_validation, + ModelValidation::List + ); + assert_eq!( + OpenAiClient::new("k".into(), "m".into(), "https://api.openai.com".into(), false, 90) + .model_validation, + ModelValidation::Retrieve + ); + } + + #[test] + fn builds_lm_studio_urls_from_uppercase_v1_base() { + let client = lm_studio("http://gpu.garde.one:1234/V1/"); + + assert_eq!(client.models_url(), "http://gpu.garde.one:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://gpu.garde.one:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_api_v1_base() { + let client = lm_studio("http://localhost:1234/api/v1"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn builds_lm_studio_urls_from_full_endpoint() { + let client = lm_studio("http://localhost:1234/v1/chat/completions"); + + assert_eq!(client.models_url(), "http://localhost:1234/v1/models"); + assert_eq!( + client.chat_url(), + "http://localhost:1234/v1/chat/completions" + ); + } + + #[test] + fn matches_model_id_variations() { + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "google/gemma-4-12b-qat" + )); + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "GOOGLE/GEMMA-4-12B-QAT" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat" + )); + assert!(matches_model_id( + "google/gemma-4-12b-qat", + "gemma-4-12b-qat" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat.gguf" + )); + assert!(matches_model_id( + "gemma-4-12b-qat", + "google/gemma-4-12b-qat:latest" + )); + assert!(!matches_model_id( + "gemma-4-12b-qat", + "ibm/granite-4-h-tiny" + )); + } + + #[test] + fn decodes_chat_response_with_null_content_and_reasoning() { + let body = r#"{ + "id": "chatcmpl-test", + "object": "chat.completion", + "created": 123456, + "model": "google/gemma-4-12b-qat", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": null, + "reasoning_content": "Just thinking..." + }, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 10, + "completion_tokens": 5, + "total_tokens": 15 + } + }"#; + + let parsed: ChatResponse = serde_json::from_str(body).expect("valid chat response"); + let choice = parsed.choices.first().expect("choice present"); + assert_eq!(choice.message.content, None); + assert_eq!( + choice.message.reasoning_content.as_deref(), + Some("Just thinking...") + ); + } + + #[test] + fn decodes_streaming_chunk_with_reasoning_and_no_content() { + let line = r#"data: {"id":"c","choices":[{"index":0,"delta":{"reasoning_content":"thought"}}]}"#; + let res = parse_stream_line(line).expect("valid stream line"); + assert_eq!(res, None); + + let line_content = r#"data: {"id":"c","choices":[{"index":0,"delta":{"content":"word"}}]}"#; + let res_content = parse_stream_line(line_content).expect("valid stream line"); + assert_eq!(res_content, Some("word".to_string())); + + let line_done = "data: [DONE]"; + let res_done = parse_stream_line(line_done).expect("valid stream line"); + assert_eq!(res_done, None); + } + + #[test] + fn decodes_model_list_payload() { + let body = r#"{"object":"list","data":[ + {"id":"qwen/qwen3-coder-30b","object":"model","owned_by":"organization_owner"}, + {"id":"text-embedding-nomic-embed-text-v1.5","object":"model","owned_by":"organization_owner"} + ]}"#; + + let parsed: ModelListResponse = serde_json::from_str(body).expect("valid model list"); + let ids: Vec<&str> = parsed.data.iter().map(|m| m.id.as_str()).collect(); + + assert_eq!( + ids, + ["qwen/qwen3-coder-30b", "text-embedding-nomic-embed-text-v1.5"] + ); } } diff --git a/src/llm/prompt_builder.rs b/src/llm/prompt_builder.rs index 92fee3e..dcfc57c 100644 --- a/src/llm/prompt_builder.rs +++ b/src/llm/prompt_builder.rs @@ -1,8 +1,8 @@ use std::collections::BTreeMap; +use crate::git::{PrItem, PrSummaryMode}; use crate::llm::prompts; use crate::{FileCategory, FileChange}; -use crate::git::{PrItem, PrSummaryMode}; pub struct PromptPair { pub system: String, @@ -12,6 +12,8 @@ pub struct PromptPair { pub fn file_summary_prompt( branch: &str, file: &FileChange, + file_index: usize, + total_files: usize, ticket_summary: Option<&str>, ) -> PromptPair { let mut system = prompts::FILE_SUMMARY.to_owned(); @@ -22,11 +24,13 @@ pub fn file_summary_prompt( let user = format!( "Branch: {branch}\n\ - File: {path}\n\ + File {file_num} of {total_files}: {path}\n\ Category: {category}\n\n\ Diff:\n\ ```diff\n{diff}\n```", branch = branch, + file_num = file_index + 1, + total_files = total_files, path = file.path, category = file.category.as_str(), diff = file.diff @@ -47,30 +51,13 @@ pub fn commit_message_prompt( } let per_file = render_per_file_summaries(files); + let lock_files = render_lock_files_touched(files); let user = format!( - "Branch: {branch}\n\nPer-file summaries:\n\n{per_file}", - branch = branch, - per_file = per_file - ); - - PromptPair { system, user } -} - -pub fn commit_message_simple_prompt( - branch: &str, - diff: &str, - ticket_summary: Option<&str>, -) -> PromptPair { - let mut system = prompts::SYSTEM_INSTRUCTIONS.to_owned(); - if let Some(ts) = ticket_summary { - system.push_str("\nOverall ticket goal: "); - system.push_str(ts); - } - - let user = format!( - "Branch: {branch}\n\nDiff:\n```diff\n{diff}\n```", + "Branch: {branch}\n\nFiles Changed: {file_count}\n\nPer-file summaries:\n\n{per_file}{lock_files}", branch = branch, - diff = diff + file_count = files.len(), + per_file = per_file, + lock_files = lock_files ); PromptPair { system, user } @@ -130,31 +117,18 @@ pub fn pr_message_prompt( } } - user.push_str( - "Pull requests contributing to this branch (oldest commits first):\n", - ); + user.push_str("Pull requests contributing to this branch (oldest commits first):\n"); for (num, group) in grouped { - let short = group[0] - .commit_hash - .chars() - .take(7) - .collect::(); + let short = group[0].commit_hash.chars().take(7).collect::(); let title = group[0].title.trim(); user.push_str(&format!("\nPR #{num}: {title} [{short}]\n")); if group.len() > 1 { user.push_str("Additional commits in this PR:\n"); for item in group.iter().skip(1) { - let sh = item - .commit_hash - .chars() - .take(7) - .collect::(); - user.push_str(&format!( - "- {sh}: {title}\n", - title = item.title.trim() - )); + let sh = item.commit_hash.chars().take(7).collect::(); + user.push_str(&format!("- {sh}: {title}\n", title = item.title.trim())); } } } @@ -164,15 +138,8 @@ pub fn pr_message_prompt( "\nCommits without associated PR numbers (may be small fixes or direct pushes):\n", ); for item in no_pr { - let short = item - .commit_hash - .chars() - .take(7) - .collect::(); - user.push_str(&format!( - "- {short}: {title}\n", - title = item.title.trim() - )); + let short = item.commit_hash.chars().take(7).collect::(); + user.push_str(&format!("- {short}: {title}\n", title = item.title.trim())); } } } @@ -181,11 +148,22 @@ pub fn pr_message_prompt( PromptPair { system, user } } +/// Renders only the files we actually asked the LLM about, numbered against +/// that subset so the list has no gaps. Ignored and lock files are reported +/// elsewhere (or not at all), not counted here. fn render_per_file_summaries(files: &[FileChange]) -> String { + let summarized: Vec<&FileChange> = files + .iter() + .filter(|f| !matches!(f.category, FileCategory::Ignored | FileCategory::Lock)) + .collect(); + + let total_files = summarized.len(); let mut out = String::new(); - for file in files.iter().filter(|f| !matches!(f.category, FileCategory::Ignored)) { + for (idx, file) in summarized.iter().enumerate() { out.push_str(&format!( - "File: {path}\nCategory: {category}\nSummary:\n{summary}\n\n", + "File {file_num} of {total_files}: {path}\nCategory: {category}\nSummary:\n{summary}\n\n", + file_num = idx + 1, + total_files = total_files, path = file.path, category = file.category.as_str(), summary = file @@ -196,3 +174,27 @@ fn render_per_file_summaries(files: &[FileChange]) -> String { } out } + +/// Lock file diffs are never sent to the LLM, so the final summary is told only +/// that they were touched. +fn render_lock_files_touched(files: &[FileChange]) -> String { + let paths: Vec<&str> = files + .iter() + .filter(|f| matches!(f.category, FileCategory::Lock)) + .map(|f| f.path.as_str()) + .collect(); + + if paths.is_empty() { + return String::new(); + } + + let mut out = String::from("Lock files touched/updated (diffs not reviewed):\n"); + for path in paths { + out.push_str(&format!("- {path}\n")); + } + out.push_str( + "\nThese were regenerated by a package manager. Mention them only as a dependency \ + lock update, and do not speculate about their contents.\n", + ); + out +} diff --git a/src/llm/prompts.rs b/src/llm/prompts.rs index eaa52a0..1f416b5 100644 --- a/src/llm/prompts.rs +++ b/src/llm/prompts.rs @@ -1,44 +1,57 @@ -pub const FILE_SUMMARY: &str = r#"You are a helpful assistant that explains code changes -file-by-file to later help generate a Git commit message. -Rules: -- Focus on intent, not line-by-line diffs. -- Reading this summary should suplement reading the actual diff, not regurgitate it. -- Do not repeat the code in human-readable form a reviewer will still read the code. You're intent - is to help the reviewer understand the intent of the change. -- Keep the summary to an appropriate number of bullet points that is consistent with the size of the commit. -- At this time you are unaware of any other files being changed; it is unhelpful to mention unseen - changes, only consider this one."#; - -pub const SYSTEM_INSTRUCTIONS: &str = r#"You are a Git commit message assistant. -Write a descriptive Git commit message based on the file summaries. +pub const SYSTEM_INSTRUCTIONS: &str = r#"You are a Git commit message assistant given per-file summaries of a changeset. +Produce the shortest accurate commit message that fully conveys intent. + +Mode A — single line: +- Line 1: 3–12 words summary. +- Line 2: 5-15 words of context if needed. +- ONLY for fixes, corrections, typos, or single-line mechanical changes. + +Mode B — summary + bullet points (preferred for most changes): +- First line under 50 characters. +- Follow with a few bullet points of plain prose describing what was added, changed, or why. +- Use when the change has a single clear purpose but involves multiple files or non-trivial scope. + +Mode C — summary + grouped bullets: +- First line under 50 characters. +- Body uses grouped bullets. +- Use ONLY when there are multiple independent intents that prose would obscure. + +How to choose: +- Default to mode B. +- Downgrade to mode A only for trivial single-purpose changes. +- Upgrade to mode C only when two or more unrelated intents exist in the same commit. + Rules: -1. Start with a summary line under 50 characters, no formatting. -2. Follow with a detailed breakdown grouped by type of change. -3. Use headlines (## Migrations, ## Factories, ## Models, etc.). -4. Use bullet points under each group. -5. If something is new, call it 'Introduced', not 'Refactored' unless it was refactored. -6. If it fixes broken or incomplete behavior, prefer 'Fixed' or 'Refined'. -7. Enclose functions, classes, filenames, and other code with `ticks`. -8. Avoid generic terms like 'update' or 'improve' unless strictly accurate. -9. Group repetitive changes (like renames) instead of repeating them per file, - or even reference the group a single time without listing every place they were changed. -10. Focus on the main purpose and supporting work; only briefly mention consequences or ommit them - interally if they can be inferred from other changes. For example, don't mention importing a - module if also mentioning its usage."#; +- No filler ("various", "multiple", "across modules"). +- Precise verbs over vague ones ("Extract", "Wire up", "Expose" vs "Update", "Improve"). +- Backticks only in modes B and C. +- Use dashes '-' for bullet points, never use '*' or '•'. +- Output only the commit message. +- Do not add commentary or decision reasoning."#; + +pub const FILE_SUMMARY: &str = r#"Summarize the intent of changes to this file into as few bullets as possible. + +- Focus on WHY, not WHAT (the reader has the diff). +- Skip mechanical, formatting, or metadata-only changes — just label them as such. +- No code, no speculation, no narration. +- Output only the bullet list. +- Use dashes '-' for bullet points, never use '*' or '•'."#; pub const PR_INSTRUCTIONS: &str = r#"You are a GitHub Pull Request description assistant. -Your job is to summarize the *overall goal* of the branch and the important changes. +Summarize the *story* and *intent* of the branch, not the diff. + Rules: -1. Start with a concise PR title (<= 72 characters, no formatting). -2. Then include sections, for example: - - ## Overview - - ## Changes - - ## Testing / Validation - - ## Notes / Risks -3. Focus on user-visible behavior and domain-level intent, not line-by-line diffs. -4. De-emphasize purely mechanical changes (formatting-only, CI-only, or style-only). -5. If PR numbers are provided, reference them in the summary (e.g. 'PR #123'). -6. When multiple PRs contributed, explain how they fit together into a single story. -7. Avoid generic phrases like 'misc changes' or 'small fixes'; be specific. -8. In contradiction to point 7, if there are many small changes that don't merit - individual mention it's okay to summarize them briefly and together."#; +- Start with a concise PR title (<= 72 characters and no formatting). +- Then include sections such as: + ## Overview + ## Changes + ## Testing / Validation + ## Notes / Risks +- Focus on user-visible behavior, system impact, and domain intent. +- Treat the PR as a unit of work, not a list of commits. +- De-emphasize mechanical, formatting-only, or metadata-only changes. +- If many small changes exist, summarize them collectively. +- Reference commit hashes when appropriate. +- Avoid generic phrases like "misc changes" or "small fixes". +- Use dashes '-' for bullet points, never use '*' or '•'. +- Do not add commentary or decision reasoning."#; diff --git a/src/llm/stream.rs b/src/llm/stream.rs index ef50704..f34f674 100644 --- a/src/llm/stream.rs +++ b/src/llm/stream.rs @@ -2,13 +2,32 @@ use anyhow::Result; use std::io::{self, BufRead, Write}; /// Read a streaming response line-by-line, printing chunks as they arrive. -pub fn read_stream_to_string(reader: R, mut parse_line: F) -> Result +/// +/// When `quiet` is true, chunks are still captured into the returned string +/// but nothing is written to stdout — used for `--oneline quiet`, where only +/// the final one-line summary should be printed. +pub fn read_stream_to_string(reader: R, quiet: bool, parse_line: F) -> Result where R: BufRead, F: FnMut(&str) -> Result>, { - let mut out = String::new(); - let mut stdout = io::stdout(); + read_stream_to_writer(reader, quiet, &mut io::stdout(), parse_line) +} + +/// Same as [`read_stream_to_string`], but echoes chunks to `out` instead of +/// stdout so the quiet/non-quiet behavior can be tested. +fn read_stream_to_writer( + reader: R, + quiet: bool, + out: &mut W, + mut parse_line: F, +) -> Result +where + R: BufRead, + W: Write, + F: FnMut(&str) -> Result>, +{ + let mut captured = String::new(); for line in reader.lines() { let line = line?; @@ -18,11 +37,77 @@ where } if let Some(chunk) = parse_line(line)? { - out.push_str(&chunk); - print!("{}", chunk); - stdout.flush()?; + captured.push_str(&chunk); + if !quiet { + write!(out, "{}", chunk)?; + out.flush()?; + } } } - Ok(out) + Ok(captured) +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::anyhow; + + /// Treat every non-empty line as a chunk, except `skip` which yields none. + fn echo_lines(line: &str) -> Result> { + Ok(if line == "skip" { None } else { Some(line.to_string()) }) + } + + #[test] + fn echoes_chunks_and_returns_them_when_not_quiet() { + let mut out = Vec::new(); + let result = + read_stream_to_writer("one\ntwo\n".as_bytes(), false, &mut out, echo_lines).unwrap(); + + assert_eq!(result, "onetwo"); + assert_eq!(String::from_utf8(out).unwrap(), "onetwo"); + } + + #[test] + fn quiet_captures_chunks_without_writing_anything() { + let mut out = Vec::new(); + let result = + read_stream_to_writer("one\ntwo\n".as_bytes(), true, &mut out, echo_lines).unwrap(); + + assert_eq!(result, "onetwo"); + assert!(out.is_empty(), "quiet mode must not write: {out:?}"); + } + + #[test] + fn skips_blank_lines_and_lines_without_a_chunk() { + let mut out = Vec::new(); + let result = read_stream_to_writer( + "\n \none\nskip\n\ntwo\n".as_bytes(), + false, + &mut out, + echo_lines, + ) + .unwrap(); + + assert_eq!(result, "onetwo"); + assert_eq!(String::from_utf8(out).unwrap(), "onetwo"); + } + + #[test] + fn propagates_parse_errors() { + let mut out = Vec::new(); + let err = read_stream_to_writer("boom\n".as_bytes(), false, &mut out, |_| { + Err(anyhow!("bad chunk")) + }) + .unwrap_err(); + + assert!(err.to_string().contains("bad chunk")); + } + + #[test] + fn public_wrapper_returns_captured_text() { + // Quiet so the test doesn't spray into the harness's stdout. + let result = read_stream_to_string("a\nb\n".as_bytes(), true, echo_lines).unwrap(); + assert_eq!(result, "ab"); + } } diff --git a/src/logging.rs b/src/logging.rs index ee2614c..8b1f6d7 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -6,7 +6,7 @@ use log::{Level, LevelFilter}; pub fn init_logger(verbosity: u8) { let level = match verbosity { - 0 => LevelFilter::Error, // default: only errors + 0 => LevelFilter::Warn, // default: warn & errors 1 => LevelFilter::Info, // -v: info and up 2 => LevelFilter::Debug, // -vv: debug and up _ => LevelFilter::Trace, // -vvv: trace and up @@ -20,18 +20,13 @@ pub fn init_logger(verbosity: u8) { let level_label = match level { Level::Error => "ERROR".red().bold(), - Level::Warn => "WARN ".yellow().bold(), - Level::Info => "INFO ".white().bold(), + Level::Warn => "WARN ".yellow().bold(), + Level::Info => "INFO ".white().bold(), Level::Debug => "DEBUG".bright_black(), Level::Trace => "TRACE".bright_black(), }; - writeln!( - buf, - "{} {}", - level_label, - record.args() - ) + writeln!(buf, "{} {}", level_label, record.args()) }); builder.init(); diff --git a/src/main.rs b/src/main.rs index e3a2425..7a4ae92 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,27 +1,12 @@ -mod cli_args; -mod config; -mod git; -mod llm; -mod logging; -mod setup; - use anyhow::{anyhow, Result}; use clap::Parser; -use config::Config; -use indicatif::ProgressBar; - -use std::collections::HashSet; -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; -use std::thread; - -use crate::cli_args::{Cli, Command}; -use crate::git::{ - collect_pr_items, current_branch, staged_diff, staged_diff_for_file, staged_files, stage_all, - write_commit_editmsg, PrSummaryMode, +use commitbot::config::Config; +use commitbot::git::{ + collect_pr_items, current_branch, format_pr_commit_appendix, looks_like_commit_hash, + resolve_commit_diff, split_diff_by_file, staged_diff_for_file, staged_files, PrSummaryMode, }; -use crate::llm::LlmClient; - +use commitbot::llm::LlmClient; +use commitbot::{Cli, Command, FileCategory, FileChange}; use crossterm::{ cursor, event::{self, Event, KeyCode}, @@ -29,40 +14,14 @@ use crossterm::{ style::{self, Color}, terminal::{self, Clear, ClearType}, }; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; -/// Re-export for modules like `config` that might refer to `crate::Cli` / `crate::Command`. -pub use cli_args::{Cli as RootCli, Command as RootCommand}; - -/// How the user categorizes each file in interactive mode. -#[derive(Debug, Clone, Copy, serde::Serialize)] -pub enum FileCategory { - Main, // 1 - Supporting, // 2 - Consequence, // 3 - Ignored, // 4 -} - -impl FileCategory { - pub fn as_str(&self) -> &'static str { - match self { - FileCategory::Main => "main", - FileCategory::Supporting => "supporting", - FileCategory::Consequence => "consequence", - FileCategory::Ignored => "ignored", - } - } -} - -/// Represents a single staged file's change and metadata. -#[derive(Debug, Clone)] -pub struct FileChange { - pub path: String, - pub category: FileCategory, - pub diff: String, - pub summary: Option, // Filled by per-file model call (or dummy) -} +use std::collections::HashSet; +use std::io::{self, Read, Write}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; -/// Ask the user a question and return a trimmed input line. fn prompt_input(prompt: &str) -> Result { print!("{prompt}"); io::stdout().flush()?; @@ -79,16 +38,123 @@ fn resolved_ticket_summary(cli: &Cli) -> Option { } } -/// Helper: write a line in raw mode so we also reset the cursor to column 0. fn tprintln(out: &mut W, s: &str) -> io::Result<()> { write!(out, "{}\r\n", s) } -/// Arrow-key UI for choosing a FileCategory (no diff preview). +fn preview_snippet(text: &str) -> String { + let trimmed = text.trim(); + let first_line = trimmed.lines().next().unwrap_or(""); + const MAX: usize = 80; + if first_line.len() > MAX { + format!("{}…", &first_line[..MAX]) + } else { + first_line.to_string() + } +} + +fn dimmed(text: &str) -> String { + format!("\x1b[2m{text}\x1b[0m") +} + +/// Print `s` only when `--oneline quiet` hasn't asked for silence. +macro_rules! readable_println { + ($cfg:expr) => { + if !$cfg.oneline_quiet { + println!(); + } + }; + ($cfg:expr, $($arg:tt)*) => { + if !$cfg.oneline_quiet { + println!($($arg)*); + } + }; +} + +/// Flatten a generated message onto one line by escaping real newlines as the +/// two-character sequence `\n`, and append the LLM stats when available. +fn oneline_summary(cfg: &Config, msg: &str, usage: Option<(u64, u64, u64)>) -> String { + let mut flat = String::with_capacity(msg.len()); + for ch in msg.trim().chars() { + match ch { + '\n' => flat.push_str("\\n"), + '\r' => {} + _ => flat.push(ch), + } + } + + if let Some((p, c, t)) = usage { + flat.push_str(&format!( + " [{} {} | tokens prompt={} completion={} total={}]", + cfg.provider, cfg.model, p, c, t + )); + } + + flat +} + +/// Run `generate`, print it the normal (readable) way unless `--oneline quiet` +/// was passed, then optionally emit a trailing one-line summary when +/// `--oneline` (in either mode) was passed. +/// +/// `appendix` is extra readable text (e.g. the PR commit list) printed between +/// the message and the Provider/Tokens/Time footer, so the footer is always last. +/// +/// Streaming's live chunk-printing already happens (or is suppressed) inside +/// the LLM client itself, based on the same quiet setting, so this function +/// only needs to print the message when *not* streaming. +fn generate_and_report( + cfg: &Config, + llm: &dyn LlmClient, + appendix: &str, + generate: impl FnOnce() -> Result, +) -> Result { + readable_println!(cfg); + + let t0 = std::time::Instant::now(); + let msg = generate()?; + let elapsed = t0.elapsed(); + + let usage = llm.take_and_reset_usage(); + + if !cfg.oneline_quiet { + // Streaming already printed the message live; just make sure the + // cursor ends up on a fresh line before the footer. + if !cfg.stream { + print!("{msg}"); + } + if !msg.ends_with('\n') { + println!(); + } + + if !appendix.is_empty() { + println!(); + println!("{appendix}"); + } + + println!(); + if let Some((p, c, t)) = usage { + println!("Provider: {} {}", cfg.provider, cfg.model); + println!("Tokens: prompt={}, completion={}, total={}", p, c, t); + } + println!("Time: {elapsed:.2?}"); + } + + if cfg.oneline { + readable_println!(cfg); + println!("{}", oneline_summary(cfg, &msg, usage)); + } + + Ok(msg) +} + fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { use FileCategory::*; let mut stdout = io::stdout(); + std::io::stderr() + .flush() + .map_err(|e| anyhow!("failed to flush stderr: {e}"))?; terminal::enable_raw_mode().map_err(|e| anyhow!("failed to enable raw mode: {e}"))?; let res = (|| -> Result { @@ -132,7 +198,6 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { if selected_index == 0 { selected_index = labels.len() - 1; @@ -143,14 +208,10 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { selected_index = (selected_index + 1) % labels.len(); } - - // Numeric shortcuts KeyCode::Char('1') => return Ok(Main), KeyCode::Char('2') => return Ok(Supporting), KeyCode::Char('3') => return Ok(Consequence), KeyCode::Char('4') => return Ok(Ignored), - - // Enter = accept current selection KeyCode::Enter => { let cat = match selected_index { 0 => Main, @@ -161,12 +222,9 @@ fn categorize_file_interactive(idx: usize, total: usize, path: &str) -> Result { return Err(anyhow!("aborted by user")); } - _ => {} } } @@ -187,31 +245,33 @@ struct SummarizeContext<'a> { max_concurrent_requests: usize, } -/// Run per-file summaries concurrently, honoring `max_concurrent_requests`. fn summarize_files_concurrently( file_changes: &mut [FileChange], indices: &[usize], ctx: &SummarizeContext<'_>, pb: &ProgressBar, + file_lines: Option<&[ProgressBar]>, ) -> Result<()> { if indices.is_empty() { return Ok(()); } let max_concurrent = ctx.max_concurrent_requests.max(1); + let total_files = file_changes.len(); - // Store (file_index, result) for all summarizations. let results: SummarizeResults = Arc::new(Mutex::new(Vec::new())); - // Process in chunks of `max_concurrent` so we never have more than that many - // in-flight LLM calls at once. for chunk in indices.chunks(max_concurrent) { thread::scope(|scope| { for &file_idx in chunk { let results = Arc::clone(&results); let pb = pb.clone(); + let file_line = file_lines.and_then(|lines| lines.get(file_idx)).cloned(); + + if let Some(line) = &file_line { + line.set_message("summarizing..."); + } - // Clone just the data we need from this file so we don't share &mut across threads. let path = file_changes[file_idx].path.clone(); let diff = file_changes[file_idx].diff.clone(); let category = file_changes[file_idx].category; @@ -219,6 +279,7 @@ fn summarize_files_concurrently( scope.spawn(move || { log::debug!("Summarizing file: {}", path); + let t0 = std::time::Instant::now(); let res = (|| -> Result { let fc = FileChange { path, @@ -230,14 +291,28 @@ fn summarize_files_concurrently( let summary = ctx.llm.summarize_file( ctx.branch, &fc, + file_idx, + total_files, ctx.ticket_summary, )?; Ok(summary) })(); + let elapsed = t0.elapsed(); - // Always advance the progress bar for this file, even if it errors. pb.inc(1); + if let Some(line) = &file_line { + match &res { + Ok(summary) => { + let snippet = preview_snippet(summary); + line.finish_with_message(dimmed(&format!("{snippet} ({elapsed:.2?})"))); + } + Err(err) => { + line.finish_with_message(dimmed(&format!("error: {err} ({elapsed:.2?})"))); + } + } + } + let mut lock = results.lock().expect("results mutex poisoned"); lock.push((file_idx, res)); }); @@ -245,7 +320,6 @@ fn summarize_files_concurrently( }); } - // Unwrap Arc and Mutex and apply results back onto file_changes. let results = Arc::try_unwrap(results) .expect("results Arc still has multiple owners") .into_inner() @@ -273,15 +347,79 @@ fn summarize_files_concurrently( Ok(()) } -/// Interactive mode: classify files, then do all LLM calls afterward (batched with concurrency). -fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { - let branch = current_branch()?; - let files = staged_files()?; - if files.is_empty() { - println!("No staged changes found."); - return Ok(()); +/// Read the content behind `--diff `. +/// +/// `-` reads stdin. Otherwise, if the argument looks like a commit hash, we +/// first try to resolve it against git history; if that doesn't find a +/// commit, or the argument didn't look like a hash to begin with, we fall +/// back to treating it as a file path. +fn read_diff_arg(diff_arg: &str) -> Result { + if diff_arg == "-" { + let mut buf = String::new(); + io::stdin().read_to_string(&mut buf)?; + return Ok(buf); } + if looks_like_commit_hash(diff_arg) && let Some(diff) = resolve_commit_diff(diff_arg)? { + return Ok(diff); + } + + let path = std::path::Path::new(diff_arg); + if path.is_file() { + std::fs::read_to_string(path) + .map_err(|e| anyhow!("Failed to read diff file '{}': {}", diff_arg, e)) + } else { + Err(anyhow!( + "'{}' is not a known commit hash or an existing file.", + diff_arg + )) + } +} + +/// Branch name paired with a list of (file path, diff) pairs. +type BranchDiffs = (String, Vec<(String, String)>); + +/// Load per-file diffs from `--diff `, splitting a combined diff +/// into (path, diff) pairs. Returns `None` when the resolved content is +/// empty (already reported to the user). +fn load_external_diff(cli: &Cli, diff_arg: &str) -> Result> { + let combined = read_diff_arg(diff_arg)?; + if combined.trim().is_empty() { + println!("No diff content found."); + return Ok(None); + } + let mut per_file = split_diff_by_file(&combined); + if per_file.is_empty() { + per_file = vec![("(diff)".to_string(), combined)]; + } + let branch = cli + .branch + .clone() + .unwrap_or_else(|| current_branch().unwrap_or_else(|_| "unknown-branch".to_string())); + Ok(Some((branch, per_file))) +} + +fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { + let (branch, file_pairs) = if let Some(ref diff_arg) = cli.diff { + match load_external_diff(cli, diff_arg)? { + Some(pair) => pair, + None => return Ok(()), + } + } else { + let branch = current_branch()?; + let files = staged_files()?; + if files.is_empty() { + println!("No staged changes found."); + return Ok(()); + } + let mut pairs = Vec::new(); + for path in files { + let diff = staged_diff_for_file(&path)?; + pairs.push((path, diff)); + } + (branch, pairs) + }; + let mut ticket_summary = resolved_ticket_summary(cli); if ticket_summary.is_none() { let ans = prompt_input("Optional: brief ticket summary (enter to skip): ")?; @@ -292,44 +430,75 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { let mut file_changes: Vec = Vec::new(); - // Phase 1: Cointeractive classification - for (idx, path) in files.iter().enumerate() { - let diff = staged_diff_for_file(path)?; - - let category = categorize_file_interactive(idx, files.len(), path)?; - + let total_files = file_pairs.len(); + for (idx, (path, diff)) in file_pairs.into_iter().enumerate() { + let category = if commitbot::is_lock_file(&path) { + FileCategory::Lock + } else { + categorize_file_interactive(idx, total_files, &path)? + }; file_changes.push(FileChange { - path: path.clone(), + path, category, - diff, + diff: commitbot::truncate_diff(&diff, cfg.max_diff_bytes), summary: None, }); } - // Phase 2: LLM calls - println!(); - println!("Asking {}...", cfg.model); + readable_println!(cfg); + readable_println!(cfg, "Asking {}...", cfg.model); let total = file_changes.len(); - let pb = ProgressBar::new((total + 1) as u64); + let mp = MultiProgress::new(); + let mut file_lines = Vec::new(); + + for fc in &file_changes { + let line = mp.add(ProgressBar::new_spinner()); + line.set_style( + ProgressStyle::with_template("{spinner:.cyan} {prefix:.bold}: {msg}") + .expect("progress style template"), + ); + line.set_prefix(fc.path.clone()); + if matches!(fc.category, FileCategory::Lock) { + line.finish_with_message(dimmed("lock file updated, not summarized")); + } else if matches!(fc.category, FileCategory::Ignored) { + line.finish_with_message(dimmed("ignored")); + } else { + line.enable_steady_tick(Duration::from_millis(120)); + line.set_message("waiting"); + } + file_lines.push(line); + } + + let pb = mp.add(ProgressBar::new((total + 1) as u64)); + pb.set_style( + ProgressStyle::with_template("{wide_bar:.green} {pos}/{len} files") + .unwrap_or_else(|_| ProgressStyle::default_bar()), + ); - // Pre-increment for ignored files and collect indices that actually need summarization. let mut indices_to_summarize = Vec::new(); let mut ignored_count = 0usize; + let mut lock_count = 0usize; for (idx, fc) in file_changes.iter().enumerate() { - if matches!(fc.category, FileCategory::Ignored) { - pb.inc(1); - ignored_count += 1; - } else { - indices_to_summarize.push(idx); + match fc.category { + FileCategory::Ignored => { + pb.inc(1); + ignored_count += 1; + } + FileCategory::Lock => { + pb.inc(1); + lock_count += 1; + } + _ => indices_to_summarize.push(idx), } } log::info!( - "Summarizing {} files ({} ignored). max_concurrent_requests = {}", + "Summarizing {} files ({} ignored, {} lock). max_concurrent_requests = {}", indices_to_summarize.len(), ignored_count, + lock_count, cfg.max_concurrent_requests, ); @@ -340,93 +509,147 @@ fn run_interactive(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { max_concurrent_requests: cfg.max_concurrent_requests, }; - summarize_files_concurrently(&mut file_changes, &indices_to_summarize, &ctx, &pb)?; + summarize_files_concurrently( + &mut file_changes, + &indices_to_summarize, + &ctx, + &pb, + Some(&file_lines), + )?; - // Final commit message - let commit_message = if cfg.stream { - pb.inc(1); - pb.finish_with_message("Done."); + pb.inc(1); + pb.finish_with_message("Done"); - println!(); - println!("----- Commit Message Preview -----"); - let msg = llm.generate_commit_message( - &branch, - &file_changes, - ticket_summary.as_deref(), - )?; - println!(); - println!("----------------------------------"); - msg - } else { - let msg = llm.generate_commit_message( - &branch, - &file_changes, - ticket_summary.as_deref(), - )?; + generate_and_report(cfg, llm, "", || { + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) + })?; - pb.inc(1); - pb.finish_with_message("Done."); + Ok(()) +} - println!(); - println!("----- Commit Message Preview -----"); - println!("{msg}"); - println!("----------------------------------"); - msg - }; +fn run_auto(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { + let using_external_diff = cli.diff.is_some(); + let (branch, file_pairs): (String, Vec<(String, String)>) = + if let Some(ref diff_arg) = cli.diff { + match load_external_diff(cli, diff_arg)? { + Some(pair) => pair, + None => return Ok(()), + } + } else { + let branch = current_branch()?; + let files = staged_files()?; + if files.is_empty() { + println!("No staged changes found."); + return Ok(()); + } + let mut pairs = Vec::new(); + for path in files { + let diff = staged_diff_for_file(&path)?; + pairs.push((path, diff)); + } + (branch, pairs) + }; - if cli.apply { - write_commit_editmsg(&commit_message)?; - println!("(Message written to .git/COMMIT_EDITMSG; run `git commit` to edit/confirm.)"); + let ticket_summary = resolved_ticket_summary(cli); + + let mut file_changes: Vec = file_pairs + .into_iter() + .map(|(path, diff)| { + let category = if commitbot::is_lock_file(&path) { + FileCategory::Lock + } else { + FileCategory::Main + }; + FileChange { + path, + category, + diff: commitbot::truncate_diff(&diff, cfg.max_diff_bytes), + summary: None, + } + }) + .collect(); + + readable_println!(cfg); + readable_println!(cfg, "Asking {}...", cfg.model); + if let Some(ref diff_arg) = cli.diff { + let diff_source = if diff_arg == "-" { "stdin" } else { diff_arg }; + readable_println!(cfg, "Using external diff: {diff_source}"); } - Ok(()) -} + let total = file_changes.len(); + let mp = MultiProgress::new(); + let mut file_lines = Vec::new(); + + for fc in &file_changes { + let line = mp.add(ProgressBar::new_spinner()); + line.set_style( + ProgressStyle::with_template("{spinner:.cyan} {prefix:.bold}: {msg}") + .expect("progress style template"), + ); + let prefix = if using_external_diff { + format!("[diff] {}", fc.path) + } else { + fc.path.clone() + }; + line.set_prefix(prefix); + if matches!(fc.category, FileCategory::Lock) { + line.finish_with_message(dimmed("lock file updated, not summarized")); + } else { + line.enable_steady_tick(Duration::from_millis(120)); + line.set_message("waiting"); + } + file_lines.push(line); + } -/// Simple mode: one-shot commit message from entire staged diff. -fn run_simple(cli: &Cli, cfg: &Config, llm: &dyn LlmClient) -> Result<()> { - let branch = current_branch()?; - let diff = staged_diff()?; + let pb = mp.add(ProgressBar::new((total + 1) as u64)); + pb.set_style( + ProgressStyle::with_template("{wide_bar:.green} {pos}/{len} files") + .unwrap_or_else(|_| ProgressStyle::default_bar()), + ); - if diff.trim().is_empty() { - println!("No staged changes found."); - return Ok(()); + let mut indices_to_summarize: Vec = Vec::new(); + let mut lock_count = 0usize; + + for (idx, fc) in file_changes.iter().enumerate() { + if matches!(fc.category, FileCategory::Lock) { + pb.inc(1); + lock_count += 1; + } else { + indices_to_summarize.push(idx); + } } - let ticket_summary = resolved_ticket_summary(cli); - let commit_message = if cfg.stream { - println!(); - println!("----- Commit Message Preview -----"); - let msg = llm.generate_commit_message_simple( - &branch, - &diff, - ticket_summary.as_deref(), - )?; - println!(); - println!("----------------------------------"); - msg - } else { - let msg = llm.generate_commit_message_simple( - &branch, - &diff, - ticket_summary.as_deref(), - )?; + log::info!( + "Auto-summarizing {} files ({} lock). max_concurrent_requests = {}", + indices_to_summarize.len(), + lock_count, + cfg.max_concurrent_requests, + ); - println!(); - println!("----- Commit Message Preview -----"); - println!("{msg}"); - println!("----------------------------------"); - msg + let ctx = SummarizeContext { + branch: &branch, + ticket_summary: ticket_summary.as_deref(), + llm, + max_concurrent_requests: cfg.max_concurrent_requests, }; - if cli.apply { - write_commit_editmsg(&commit_message)?; - println!("(Message written to .git/COMMIT_EDITMSG; run `git commit` to edit/confirm.)"); - } + summarize_files_concurrently( + &mut file_changes, + &indices_to_summarize, + &ctx, + &pb, + Some(&file_lines), + )?; + + pb.inc(1); + pb.finish_with_message("Done"); + + generate_and_report(cfg, llm, "", || { + llm.generate_commit_message(&branch, &file_changes, ticket_summary.as_deref()) + })?; Ok(()) } - -/// PR mode: summarize commits/PRs between base..from into a PR description. fn run_pr( cli: &Cli, cfg: &Config, @@ -447,13 +670,11 @@ fn run_pr( return Ok(()); } - // Determine mode let mode = if pr_flag { PrSummaryMode::ByPrs } else if commit_flag { PrSummaryMode::ByCommits } else { - // Auto-detect: if multiple distinct PR numbers are present, use PR mode. let mut distinct_prs: HashSet = HashSet::new(); for item in &items { if let Some(n) = item.pr_number { @@ -476,62 +697,48 @@ fn run_pr( log::info!("Found {} commits in range.", items.len()); let ticket_summary = resolved_ticket_summary(cli); - let _pr_message = if cfg.stream { - println!(); - println!("----- PR Message Preview -----"); - let msg = llm.generate_pr_message( - base, - &from_branch, - mode, - &items, - ticket_summary.as_deref(), - )?; - println!(); - println!("------------------------------"); - msg - } else { - let msg = llm.generate_pr_message( - base, - &from_branch, - mode, - &items, - ticket_summary.as_deref(), - )?; - - println!(); - println!("----- PR Message Preview -----"); - println!("{msg}"); - println!("------------------------------"); - msg - }; + let appendix = format_pr_commit_appendix(&items); + generate_and_report(cfg, llm, &appendix, || { + llm.generate_pr_message(base, &from_branch, mode, &items, ticket_summary.as_deref()) + })?; Ok(()) } fn main() -> Result<()> { - // CLI + config let cli = Cli::parse(); - // Initialize logging - logging::init_logger(cli.verbose); + // Handle custom --version early so we print just the version number. + if cli.version { + println!("{}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + + commitbot::logging::init_logger(cli.verbose); + + if cli.diff.is_some() && matches!(&cli.command, Some(Command::Pr { .. })) { + return Err(anyhow!( + "The --diff flag cannot be used with the 'pr' command.\n\ + PR mode analyzes commit history, not staged diffs." + )); + } - let cfg = Config::from_sources(&cli); + let cfg = Config::from_sources(&cli)?; - // Pre-Work Items if cli.stage { - stage_all()?; + commitbot::git::stage_all()?; } - // LLM client setup - let boxed_client = setup::build_llm_client(&cfg); + let boxed_client = commitbot::setup::build_llm_client(&cfg)?; + boxed_client.validate_model()?; match &cli.command { Some(Command::Pr { - base, - from, - pr_mode, - commit_mode, - }) => run_pr( + base, + from, + pr_mode, + commit_mode, + }) => run_pr( &cli, &cfg, boxed_client.as_ref(), @@ -544,8 +751,55 @@ fn main() -> Result<()> { if cli.ask { run_interactive(&cli, &cfg, boxed_client.as_ref()) } else { - run_simple(&cli, &cfg, boxed_client.as_ref()) + run_auto(&cli, &cfg, boxed_client.as_ref()) } } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn test_config() -> Config { + Config { + provider: "lmstudio".into(), + openai_api_key: None, + base_url: None, + model: "test-model".into(), + max_concurrent_requests: 1, + stream: false, + request_timeout_secs: 5, + max_diff_bytes: 1_000, + oneline: true, + oneline_quiet: false, + } + } + + #[test] + fn oneline_summary_escapes_newlines_and_appends_stats() { + let cfg = test_config(); + let flat = oneline_summary(&cfg, "Subject\n\n- one\n- two", Some((10, 20, 30))); + + assert_eq!( + flat, + "Subject\\n\\n- one\\n- two [lmstudio test-model | tokens prompt=10 completion=20 total=30]" + ); + assert!(!flat.contains('\n')); + } + + #[test] + fn oneline_summary_without_usage_has_no_stats_suffix() { + let cfg = test_config(); + assert_eq!(oneline_summary(&cfg, "Subject\n- body", None), "Subject\\n- body"); + } + + #[test] + fn oneline_summary_trims_and_drops_carriage_returns() { + let cfg = test_config(); + assert_eq!( + oneline_summary(&cfg, "\n Subject\r\n- body\r\n\n", None), + "Subject\\n- body" + ); + } +} diff --git a/src/setup.rs b/src/setup.rs index e6cec2d..4d2d652 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1,32 +1,42 @@ +use anyhow::{anyhow, Result}; use crate::config::Config; use crate::llm::LlmClient; -use crate::llm::openai::OpenAiClient; use crate::llm::ollama::OllamaClient; +use crate::llm::openai::{ModelValidation, OpenAiClient}; /// Build the LLM client based on CLI + config. -pub fn build_llm_client(cfg: &Config) -> Box { +pub fn build_llm_client(cfg: &Config) -> Result> { match cfg.provider.as_str() { "openai" => { - let key = cfg - .openai_api_key - .clone() - .expect("OPENAI_API_KEY must be set for provider=openai"); let base_url = cfg .base_url .clone() .unwrap_or_else(|| "https://api.openai.com".to_string()); + let is_custom_endpoint = !base_url.starts_with("https://api.openai.com"); + let validation = if is_custom_endpoint { + ModelValidation::List + } else { + ModelValidation::Retrieve + }; + log::debug!( - "Using OpenAiClient with model: {} (stream={})", - cfg.model, cfg.stream + "Using OpenAiClient with model: {} (stream={}, timeout={}s)", + cfg.model, + cfg.stream, + cfg.request_timeout_secs ); - Box::new(OpenAiClient::new( - key, + Ok(Box::new(OpenAiClient::openai_compatible( + cfg.openai_api_key.clone(), cfg.model.clone(), base_url, cfg.stream, - )) + cfg.oneline_quiet, + cfg.request_timeout_secs, + "OpenAI", + validation, + ))) } "ollama" => { let base_url = cfg @@ -35,16 +45,48 @@ pub fn build_llm_client(cfg: &Config) -> Box { .unwrap_or_else(|| "http://localhost:11434".to_string()); log::debug!( - "Using OllamaClient with model: {} (stream={})", - cfg.model, cfg.stream + "Using OllamaClient with model: {} (stream={}, timeout={}s)", + cfg.model, + cfg.stream, + cfg.request_timeout_secs ); - Box::new(OllamaClient::new( + Ok(Box::new(OllamaClient::with_quiet( base_url, cfg.model.clone(), cfg.stream, - )) + cfg.oneline_quiet, + cfg.request_timeout_secs, + ))) + } + "lmstudio" => { + let base_url = cfg + .base_url + .clone() + .unwrap_or_else(|| "http://localhost:1234".to_string()); + + log::debug!( + "Using LM Studio at {} with model: {} (stream={}, timeout={}s)", + base_url, + cfg.model, + cfg.stream, + cfg.request_timeout_secs + ); + + Ok(Box::new(OpenAiClient::openai_compatible( + cfg.openai_api_key.clone(), + cfg.model.clone(), + base_url, + cfg.stream, + cfg.oneline_quiet, + cfg.request_timeout_secs, + "LM Studio", + ModelValidation::List, + ))) } - other => panic!("Unknown provider: {}", other), + other => Err(anyhow!( + "Unknown provider: {:?} (expected one of: openai, ollama, lmstudio)", + other + )), } } diff --git a/tests/cli_basics.rs b/tests/cli_basics.rs index 6c17a13..f10a597 100644 --- a/tests/cli_basics.rs +++ b/tests/cli_basics.rs @@ -1,4 +1,6 @@ -use assert_cmd::{cargo}; // handy crate for testing CLIs +use assert_cmd::cargo; +use clap::Parser; +use commitbot::{Cli, Command}; #[test] fn prints_help() { @@ -18,4 +20,14 @@ fn prints_version() { .assert() .success() .stdout(predicates::str::contains(env!("CARGO_PKG_VERSION"))); -} \ No newline at end of file +} + +#[test] +fn cli_parsing() { + let cli = Cli::parse_from(["commitbot", "summary"]); + + match cli.command { + Some(Command::Summary(words)) => assert_eq!(words, vec!["summary"]), + other => panic!("expected summary command, got {:?}", other), + } +} diff --git a/tests/config.rs b/tests/config.rs new file mode 100644 index 0000000..88a3297 --- /dev/null +++ b/tests/config.rs @@ -0,0 +1,260 @@ +use clap::Parser; +use commitbot::config::Config; +use commitbot::Cli; +use std::fs; +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn unique_config_path(name: &str) -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system time before unix epoch") + .as_nanos(); + std::env::temp_dir().join(format!("commitbot_{name}_{nanos}.toml")) +} + +fn write_temp_config(name: &str, contents: &str) -> PathBuf { + let path = unique_config_path(name); + fs::write(&path, contents).expect("write temp config"); + path +} + +#[test] +fn missing_config_uses_cli_values() { + let missing_path = unique_config_path("missing"); + let cli = Cli::parse_from([ + "commitbot", + "--config", + missing_path.to_str().expect("utf-8 path"), + "--provider", + "ollama", + "--model", + "qwen3-coder:30b", + "--url", + "http://localhost:11434", + ]); + + let cfg = Config::from_sources(&cli).expect("config should resolve from cli"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "qwen3-coder:30b"); + assert_eq!(cfg.base_url.as_deref(), Some("http://localhost:11434")); + assert!(cfg.stream); +} + +#[test] +fn reads_values_from_default_config_table() { + let config_path = write_temp_config( + "default_table", + r#" +[default] +provider = "ollama" +model = "llama3.1:8b-instruct-q5_K_M" +url = "http://gpu.trigapi.com:11434" +max_concurrent_requests = 2 +stream = false +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("config should load default table"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "llama3.1:8b-instruct-q5_K_M"); + assert_eq!(cfg.base_url.as_deref(), Some("http://gpu.trigapi.com:11434")); + assert_eq!(cfg.max_concurrent_requests, 2); + assert!(!cfg.stream); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn cli_overrides_file_values() { + let config_path = write_temp_config( + "cli_override", + r#" +[default] +provider = "ollama" +model = "qwen3-coder:30b" +url = "http://gpu.trigapi.com:11434" +max_concurrent_requests = 1 +stream = true +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + "--model", + "gpt-oss:20b", + "--url", + "http://localhost:11434", + "--max", + "4", + "--no-stream", + ]); + + let cfg = Config::from_sources(&cli).expect("cli values should override file"); + assert_eq!(cfg.provider, "ollama"); + assert_eq!(cfg.model, "gpt-oss:20b"); + assert_eq!(cfg.base_url.as_deref(), Some("http://localhost:11434")); + assert_eq!(cfg.max_concurrent_requests, 4); + assert!(!cfg.stream); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn lmstudio_needs_no_url_or_api_key() { + // Like ollama: the url is optional and falls back to a local default, + // and no API key is required. + let config_path = write_temp_config( + "lmstudio_defaults", + r#" +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("lmstudio config should resolve"); + assert_eq!(cfg.provider, "lmstudio"); + assert_eq!(cfg.model, "qwen/qwen3-coder-30b"); + assert_eq!(cfg.base_url, None, "the default is applied when building the client"); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn lmstudio_url_can_point_at_a_remote_host() { + let config_path = write_temp_config( + "lmstudio_remote", + r#" +[default] +provider = "lmstudio" +model = "qwen/qwen3-coder-30b" +url = "http://localhost:1234/v1" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + "--url", + "http://gpu.example.com:1234/v1", + ]); + + let cfg = Config::from_sources(&cli).expect("cli url should override file"); + assert_eq!(cfg.provider, "lmstudio"); + assert_eq!( + cfg.base_url.as_deref(), + Some("http://gpu.example.com:1234/v1") + ); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn invalid_openai_config_returns_error() { + let config_path = write_temp_config( + "invalid_openai", + r#" +[default] +provider = "openai" +model = "gpt-5-nano" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let err = Config::from_sources(&cli).expect_err("openai config should require an api key"); + assert!( + err.to_string() + .contains("OPENAI_API_KEY must be set via CLI, env var, or config file") + ); + + fs::remove_file(config_path).ok(); +} + +#[test] +fn custom_openai_endpoint_needs_no_api_key() { + let config_path = write_temp_config( + "custom_openai", + r#" +[default] +provider = "openai" +model = "local-model" +url = "http://192.168.1.16:1234/v1" +"#, + ); + + let cli = Cli::parse_from([ + "commitbot", + "--config", + config_path.to_str().expect("utf-8 path"), + ]); + + let cfg = Config::from_sources(&cli).expect("custom openai endpoint should allow no api key"); + assert_eq!(cfg.provider, "openai"); + assert_eq!(cfg.openai_api_key, None); + assert_eq!(cfg.base_url.as_deref(), Some("http://192.168.1.16:1234/v1")); + + fs::remove_file(config_path).ok(); +} + +fn cfg_for(args: &[&str]) -> Config { + let missing = unique_config_path("oneline"); + // ollama needs no API key, so this works regardless of the environment. + let mut argv = vec![ + "commitbot", + "--config", + missing.to_str().expect("utf-8 path"), + "--provider", + "ollama", + ]; + argv.extend_from_slice(args); + Config::from_sources(&Cli::parse_from(argv)).expect("config should resolve") +} + +#[test] +fn oneline_is_off_by_default() { + let cfg = cfg_for(&[]); + assert!(!cfg.oneline); + assert!(!cfg.oneline_quiet); +} + +#[test] +fn bare_oneline_keeps_readable_output() { + let cfg = cfg_for(&["--oneline"]); + assert!(cfg.oneline); + assert!(!cfg.oneline_quiet); +} + +#[test] +fn oneline_quiet_suppresses_readable_output() { + let cfg = cfg_for(&["--oneline", "quiet"]); + assert!(cfg.oneline); + assert!(cfg.oneline_quiet); +} + +#[test] +fn oneline_with_any_other_mode_stays_readable() { + let cfg = cfg_for(&["--oneline", "readable"]); + assert!(cfg.oneline); + assert!(!cfg.oneline_quiet); +} diff --git a/tests/git.rs b/tests/git.rs new file mode 100644 index 0000000..4b2ef63 --- /dev/null +++ b/tests/git.rs @@ -0,0 +1,296 @@ +use commitbot::git::{ + find_first_pr_number, format_git_error, format_pr_commit_appendix_with_remote, + looks_like_commit_hash, parse_remote_repo, resolve_commit_diff, short_commit_hash, + split_diff_by_file, staged_diff_for_file, staged_files, PrItem, PrSummaryMode, +}; +use std::process::Command; +use std::sync::Mutex; + +/// `std::env::set_current_dir` changes process-wide state, so tests that use +/// it must not run concurrently with each other. +static CWD_LOCK: Mutex<()> = Mutex::new(()); + +/// Set up a throwaway git repo with a staged change in a nested file, and +/// return its tempdir handle plus the nested directory's path. +fn repo_with_staged_nested_file() -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let root = dir.path(); + + let run = |args: &[&str]| { + let output = Command::new("git") + .args(args) + .current_dir(root) + .output() + .expect("run git"); + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let err = format_git_error(args, output.status.code(), &stderr); + panic!("{err}"); + } + }; + + run(&["init", "-q"]); + run(&["config", "user.email", "test@example.com"]); + run(&["config", "user.name", "Test"]); + + let nested_dir = root.join("app").join("Models"); + std::fs::create_dir_all(&nested_dir).expect("mkdir"); + let file = nested_dir.join("OrderItem.php"); + std::fs::write(&file, "original\n").expect("write"); + run(&["add", "."]); + run(&["commit", "-q", "-m", "initial"]); + + std::fs::write(&file, "original\nchanged\n").expect("rewrite"); + run(&["add", "."]); + + (dir, nested_dir) +} + +#[test] +fn parses_github_ssh_remote() { + let remote = parse_remote_repo("git@github.com:owner/repo.git").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::GitHub); + assert_eq!(remote.repo_id().as_deref(), Some("owner/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://github.com/owner/repo/commit/abcdef123456") + ); +} + +#[test] +fn parses_gitlab_https_remote() { + let remote = parse_remote_repo("https://gitlab.example.com/group/subgroup/repo.git").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::GitLab); + assert_eq!(remote.repo_id().as_deref(), Some("subgroup/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://gitlab.example.com/group/subgroup/repo/-/commit/abcdef123456") + ); +} + +#[test] +fn parses_azure_ssh_remote() { + let remote = parse_remote_repo("git@ssh.dev.azure.com:v3/org/project/repo").unwrap(); + assert_eq!(remote.provider, commitbot::git::GitProvider::AzureDevOps); + assert_eq!(remote.repo_id().as_deref(), Some("project/repo")); + assert_eq!( + remote.commit_url("abcdef123456").as_deref(), + Some("https://dev.azure.com/org/project/_git/repo/commit/abcdef123456") + ); +} + +#[test] +fn appendix_falls_back_to_hash_only_when_no_remote() { + let items = vec![PrItem { + commit_hash: "abcdef123456".to_string(), + title: "Refine PR footer rendering".to_string(), + body: String::new(), + pr_number: None, + }]; + + let appendix = format_pr_commit_appendix_with_remote(&items, None); + assert!(appendix.contains("Commits in this PR:")); + assert!(appendix.contains("- `abcdef1` Refine PR footer rendering")); +} + +#[test] +fn find_first_pr_number_in_title() { + let result = find_first_pr_number("Fix bug in #123"); + assert_eq!(result, Some(123)); +} + +#[test] +fn find_first_pr_number_in_body() { + let result = find_first_pr_number("Closes #456"); + assert_eq!(result, Some(456)); +} + +#[test] +fn find_first_pr_number_multiple_hashes() { + let result = find_first_pr_number("Related to #100, fixes #200"); + assert_eq!(result, Some(100)); +} + +#[test] +fn find_first_pr_number_no_hash() { + let result = find_first_pr_number("No PR here"); + assert_eq!(result, None); +} + +#[test] +fn find_first_pr_number_empty() { + let result = find_first_pr_number(""); + assert_eq!(result, None); +} + +#[test] +fn split_diff_by_file_single_file() { + let diff = r#"diff --git a/src/main.rs b/src/main.rs +index 1234567..89abcdef 100644 +--- a/src/main.rs ++++ b/src/main.rs +@@ -1,3 +1,4 @@ ++use std::io; + fn main() { + println!("Hello"); + }"#; + let result = split_diff_by_file(diff); + assert_eq!(result.len(), 1); + assert_eq!(result[0].0, "src/main.rs"); + assert!(result[0].1.contains("diff --git")); +} + +#[test] +fn split_diff_by_file_multiple_files() { + let diff = r#"diff --git a/src/main.rs b/src/main.rs +index 1234567..89abcdef 100644 +--- a/src/main.rs ++++ b/src/main.rs +@@ -1,3 +1,4 @@ ++use std::io; +diff --git a/src/lib.rs b/src/lib.rs +index abcdefg..1234567 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -1,2 +1,3 @@ ++pub fn helper() {} + pub fn other() {}"#; + let result = split_diff_by_file(diff); + assert_eq!(result.len(), 2); + assert_eq!(result[0].0, "src/main.rs"); + assert_eq!(result[1].0, "src/lib.rs"); +} + +#[test] +fn split_diff_by_file_empty() { + let result = split_diff_by_file(""); + assert!(result.is_empty()); +} + +#[test] +fn short_commit_hash_works() { + let result = short_commit_hash("abcdef123456"); + assert_eq!(result, "abcdef1"); +} + +#[test] +fn short_commit_hash_short_input() { + let result = short_commit_hash("abc"); + assert_eq!(result, "abc"); +} + +#[test] +fn staged_diff_for_file_works_from_subdirectory() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = (|| { + let files = staged_files()?; + assert_eq!(files, vec!["app/Models/OrderItem.php".to_string()]); + + let diff = staged_diff_for_file(&files[0])?; + assert!( + diff.contains("+changed"), + "expected diff to contain the staged change, got: {diff:?}" + ); + anyhow::Ok(()) + })(); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + result.expect("staged diff lookup from subdirectory"); +} + +#[test] +fn pr_summary_mode_as_str() { + assert_eq!(PrSummaryMode::ByCommits.as_str(), "commits"); + assert_eq!(PrSummaryMode::ByPrs.as_str(), "prs"); +} + +#[test] +fn format_git_error_detects_xcode_license_error() { + let stderr = "You have not agreed to the Xcode license agreements. Please run 'sudo xcodebuild -license' from within a Terminal window to review and agree to the Xcode and Apple SDKs license."; + let err = format_git_error(&["rev-parse", "--abbrev-ref", "HEAD"], Some(69), stderr); + let msg = err.to_string(); + assert!(msg.contains("Xcode license agreement required")); + assert!(msg.contains("sudo xcodebuild -license")); +} + +#[test] +fn format_git_error_legacy_xcode_license_error() { + let stderr = "Agreeing to the Xcode/iOS license requires admin privileges, please run 'sudo xcodebuild -license' and then retry this command."; + let err = format_git_error(&["diff", "--cached"], Some(69), stderr); + let msg = err.to_string(); + assert!(msg.contains("Xcode license agreement required")); + assert!(msg.contains("sudo xcodebuild -license")); +} + +#[test] +fn format_git_error_standard_git_error() { + let stderr = "fatal: not a git repository (or any of the parent directories): .git"; + let err = format_git_error(&["status"], Some(128), stderr); + let msg = err.to_string(); + assert!(msg.contains("git [\"status\"] exited with status Some(128)")); + assert!(msg.contains("fatal: not a git repository")); +} + +#[test] +fn looks_like_commit_hash_accepts_hex_strings_in_range() { + assert!(looks_like_commit_hash("a5484b6")); + assert!(looks_like_commit_hash("a5484b6ce03e4f1503c7a0fdda7c120bf73c8bc")); + assert!(looks_like_commit_hash("dead")); +} + +#[test] +fn looks_like_commit_hash_rejects_non_hex_or_bad_length() { + assert!(!looks_like_commit_hash("abc")); // too short + assert!(!looks_like_commit_hash("my-changes.diff")); // not hex + assert!(!looks_like_commit_hash("-")); // stdin marker + assert!(!looks_like_commit_hash( + "a5484b6ce03e4f1503c7a0fdda7c120bf73c8bcaa" // too long + )); +} + +#[test] +fn resolve_commit_diff_finds_existing_commit() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = (|| { + let hash = commitbot::git::git_output(&["rev-parse", "HEAD"])? + .trim() + .to_string(); + let diff = resolve_commit_diff(&hash)?.expect("commit should resolve"); + assert!(diff.contains("OrderItem.php")); + anyhow::Ok(()) + })(); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + result.expect("resolve_commit_diff for existing commit"); +} + +#[test] +fn resolve_commit_diff_returns_none_for_unknown_hash() { + let _guard = CWD_LOCK.lock().expect("cwd lock"); + let (_dir, nested_dir) = repo_with_staged_nested_file(); + + let original_cwd = std::env::current_dir().expect("current dir"); + std::env::set_current_dir(&nested_dir).expect("chdir into nested dir"); + + let result = resolve_commit_diff("deadbeef"); + + std::env::set_current_dir(original_cwd).expect("restore cwd"); + assert_eq!(result.expect("should not error"), None); +} + +#[test] +fn format_git_error_empty_stderr() { + let err = format_git_error(&["status"], Some(1), ""); + let msg = err.to_string(); + assert_eq!(msg, "git [\"status\"] exited with status Some(1)"); +} diff --git a/tests/lib_types.rs b/tests/lib_types.rs new file mode 100644 index 0000000..d13de98 --- /dev/null +++ b/tests/lib_types.rs @@ -0,0 +1,49 @@ +//! Tests for core types and functionality in lib.rs + +use commitbot::{is_lock_file, FileCategory, FileChange}; + +#[test] +fn file_category_str_representation() { + assert_eq!(FileCategory::Main.as_str(), "main"); + assert_eq!(FileCategory::Supporting.as_str(), "supporting"); + assert_eq!(FileCategory::Consequence.as_str(), "consequence"); + assert_eq!(FileCategory::Ignored.as_str(), "ignored"); + assert_eq!(FileCategory::Lock.as_str(), "lock"); +} + +#[test] +fn lock_files_are_detected_by_extension() { + assert!(is_lock_file("Cargo.lock")); + assert!(is_lock_file("yarn.lock")); + assert!(is_lock_file("sub/dir/Gemfile.lock")); + assert!(is_lock_file("composer.LOCK")); + + // Lock files that do not use the .lock extension. + assert!(is_lock_file("package-lock.json")); + assert!(is_lock_file("npm-shrinkwrap.json")); + assert!(is_lock_file("pnpm-lock.yaml")); + assert!(is_lock_file("bun.lockb")); + assert!(is_lock_file("packages.lock.json")); + assert!(is_lock_file("gradle.lockfile")); + assert!(is_lock_file("web/frontend/package-lock.json")); + + assert!(!is_lock_file("Cargo.toml")); + assert!(!is_lock_file("package.json")); + assert!(!is_lock_file("src/lock.rs")); + assert!(!is_lock_file("lock")); + assert!(!is_lock_file("locked.json")); +} + +#[test] +fn file_change_creation() { + let file_change = FileChange { + path: "src/main.rs".to_string(), + category: FileCategory::Main, + diff: "diff --git a/src/main.rs b/src/main.rs\n--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,3 @@\n-println!(\"Hello world\");\n+println!(\"Hello commitbot\");\n".to_string(), + summary: Some("Update hello message".to_string()), + }; + + assert_eq!(file_change.path, "src/main.rs"); + assert_eq!(file_change.category, FileCategory::Main); + assert_eq!(file_change.summary.as_deref(), Some("Update hello message")); +} diff --git a/tests/oneline_output.rs b/tests/oneline_output.rs new file mode 100644 index 0000000..1184a1c --- /dev/null +++ b/tests/oneline_output.rs @@ -0,0 +1,326 @@ +//! End-to-end tests for the output modes (`--oneline`, `--oneline quiet`) and +//! the trailing Provider/Tokens/Time footer. +//! +//! They run the real binary against a tiny in-process fake of an +//! OpenAI-compatible server (what LM Studio speaks), so no network or real +//! model is needed. + +use assert_cmd::cargo; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::thread; + +const MESSAGE_PARTS: [&str; 2] = ["Add widget\n\n", "- first bullet\n- second bullet"]; +const MESSAGE: &str = "Add widget\n\n- first bullet\n- second bullet"; +const ESCAPED_MESSAGE: &str = "Add widget\\n\\n- first bullet\\n- second bullet"; + +const DIFF: &str = "diff --git a/src/widget.rs b/src/widget.rs\n\ +index 111..222 100644\n\ +--- a/src/widget.rs\n\ ++++ b/src/widget.rs\n\ +@@ -1,2 +1,3 @@\n\ + fn widget() {}\n\ ++fn gadget() {}\n"; + +/// Read one HTTP request, returning (request line, body). +fn read_request(stream: &mut TcpStream) -> Option<(String, String)> { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + let header_end = loop { + let n = stream.read(&mut chunk).ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break pos + 4; + } + }; + + let head = String::from_utf8_lossy(&buf[..header_end]).to_string(); + let content_length = head + .lines() + .find_map(|l| { + let (k, v) = l.split_once(':')?; + k.eq_ignore_ascii_case("content-length").then(|| v.trim().parse::().ok())? + }) + .unwrap_or(0); + + while buf.len() < header_end + content_length { + let n = stream.read(&mut chunk).ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + + let body = String::from_utf8_lossy(&buf[header_end..]).to_string(); + let request_line = head.lines().next().unwrap_or("").to_string(); + Some((request_line, body)) +} + +fn respond(stream: &mut TcpStream, content_type: &str, body: &str) { + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); +} + +fn handle(mut stream: TcpStream) { + let Some((request_line, body)) = read_request(&mut stream) else { + return; + }; + + if request_line.contains("/api/chat") { + // Ollama: NDJSON when streaming, a single JSON document otherwise. + if body.contains("\"stream\":true") { + let mut nd = String::new(); + for part in MESSAGE_PARTS { + nd.push_str(&format!( + "{}\n", + serde_json::json!({ "message": { "role": "assistant", "content": part }, "done": false }) + )); + } + nd.push_str(&format!("{}\n", serde_json::json!({ "message": { "role": "assistant", "content": "" }, "done": true, "prompt_eval_count": 11, "eval_count": 7 }))); + respond(&mut stream, "application/x-ndjson", &nd); + } else { + let body = serde_json::json!({ + "message": { "role": "assistant", "content": MESSAGE }, + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }) + .to_string(); + respond(&mut stream, "application/json", &body); + } + } else if request_line.contains("/models") { + let body = serde_json::json!({ "data": [{ "id": "test-model" }] }).to_string(); + respond(&mut stream, "application/json", &body); + } else if body.contains("\"stream\":true") { + let mut sse = String::new(); + for part in MESSAGE_PARTS { + let chunk = serde_json::json!({ "choices": [{ "delta": { "content": part } }] }); + sse.push_str(&format!("data: {chunk}\n\n")); + } + // Like a real server, report usage in a trailing chunk, but only when + // the client asked for it. + if body.contains("include_usage") { + let usage = serde_json::json!({ + "choices": [], + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }); + sse.push_str(&format!("data: {usage}\n\n")); + } + sse.push_str("data: [DONE]\n\n"); + respond(&mut stream, "text/event-stream", &sse); + } else { + let body = serde_json::json!({ + "choices": [{ "message": { "content": MESSAGE } }], + "usage": { "prompt_tokens": 11, "completion_tokens": 7, "total_tokens": 18 } + }) + .to_string(); + respond(&mut stream, "application/json", &body); + } +} + +/// Start the fake server on a free port; it lives until the test process exits. +fn spawn_fake_server() -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fake server"); + let url = format!("http://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + thread::spawn(move || handle(stream)); + } + }); + url +} + +struct Run { + stdout: String, + stderr: String, +} + +fn run_commitbot(extra_args: &[&str]) -> Run { + run_commitbot_with("lmstudio", extra_args) +} + +fn run_commitbot_with(provider: &str, extra_args: &[&str]) -> Run { + let url = spawn_fake_server(); + let dir = tempfile::tempdir().expect("tempdir"); + let diff_path: PathBuf = dir.path().join("change.diff"); + std::fs::write(&diff_path, DIFF).unwrap(); + + let output = cargo::cargo_bin_cmd!() + .current_dir(dir.path()) + // Never pick up the developer's real config or credentials. + .env("HOME", dir.path()) + .env_remove("OPENAI_API_KEY") + .args(["--config", dir.path().join("none.toml").to_str().unwrap()]) + .args(["--provider", provider, "--model", "test-model", "--url", &url]) + .args(["--branch", "main", "--diff", diff_path.to_str().unwrap()]) + .args(extra_args) + .output() + .expect("run commitbot"); + + let run = Run { + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + }; + assert!(output.status.success(), "commitbot failed: {}", run.stderr); + run +} + +fn assert_footer_order(stdout: &str) { + let provider = stdout.find("Provider: ").expect("Provider line"); + let tokens = stdout.find("Tokens:").expect("Tokens line"); + let time = stdout.find("Time:").expect("Time line"); + assert!(provider < tokens && tokens < time, "footer order wrong:\n{stdout}"); + assert!(!stdout.contains("generated in"), "old timing line is back:\n{stdout}"); +} + +#[test] +fn default_output_streams_message_then_footer() { + let run = run_commitbot(&[]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); + // The streamed message has no trailing newline; the footer must not be + // glued onto its last line. + assert!( + run.stdout.contains("- second bullet\n"), + "footer ran into message:\n{}", + run.stdout + ); + assert!(!run.stdout.contains(ESCAPED_MESSAGE)); +} + +#[test] +fn no_stream_output_prints_message_then_footer() { + let run = run_commitbot(&["--no-stream"]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); +} + +#[test] +fn oneline_adds_a_summary_after_the_readable_output() { + for extra in [&["--oneline"][..], &["--oneline", "--no-stream"][..]] { + let run = run_commitbot(extra); + + assert!(run.stdout.contains("Asking test-model"), "readable output missing"); + assert_footer_order(&run.stdout); + + let last = run.stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap(); + assert!(last.starts_with(ESCAPED_MESSAGE), "one-liner wrong: {last}"); + assert!(last.contains("[lmstudio test-model | tokens prompt="), "stats missing: {last}"); + } +} + +#[test] +fn oneline_quiet_prints_only_the_summary_line() { + for extra in [&["--oneline", "quiet"][..], &["--oneline=quiet", "--no-stream"][..]] { + let run = run_commitbot(extra); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); + assert!(lines[0].contains("[lmstudio test-model | tokens prompt=")); + + for noise in ["Asking", "Provider:", "Tokens:", "Time:", "Using external diff"] { + assert!(!run.stdout.contains(noise), "{noise:?} leaked:\n{}", run.stdout); + } + } +} + +#[test] +fn ollama_quiet_streaming_prints_only_the_summary_line() { + for extra in [&["--oneline", "quiet"][..], &["--oneline", "quiet", "--no-stream"][..]] { + let run = run_commitbot_with("ollama", extra); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); + assert!(lines[0].contains("[ollama test-model | tokens prompt="), "stats: {}", lines[0]); + } +} + +#[test] +fn ollama_default_output_streams_message_then_footer() { + let run = run_commitbot_with("ollama", &[]); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); +} + +fn git(dir: &std::path::Path, args: &[&str]) { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(["-c", "user.name=Test", "-c", "user.email=test@example.com"]) + .args(["-c", "commit.gpgsign=false", "-c", "init.defaultBranch=main"]) + .args(args) + .output() + .expect("run git"); + assert!(out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// Run `commitbot pr main feature` in a throwaway repo with one commit ahead. +fn run_pr(extra_args: &[&str]) -> Run { + let url = spawn_fake_server(); + let dir = tempfile::tempdir().expect("tempdir"); + let repo = dir.path(); + + git(repo, &["init", "-q"]); + std::fs::write(repo.join("a.txt"), "one\n").unwrap(); + git(repo, &["add", "."]); + git(repo, &["commit", "-q", "-m", "Initial commit"]); + git(repo, &["checkout", "-q", "-b", "feature"]); + std::fs::write(repo.join("a.txt"), "two\n").unwrap(); + git(repo, &["commit", "-q", "-am", "Add the second line"]); + + let output = cargo::cargo_bin_cmd!() + .current_dir(repo) + .env("HOME", repo) + .env_remove("OPENAI_API_KEY") + .args(["--config", repo.join("none.toml").to_str().unwrap()]) + .args(["--provider", "lmstudio", "--model", "test-model", "--url", &url]) + .args(extra_args) + .args(["pr", "main", "feature"]) + .output() + .expect("run commitbot pr"); + + let run = Run { + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + }; + assert!(output.status.success(), "commitbot pr failed: {}", run.stderr); + run +} + +#[test] +fn pr_output_puts_the_footer_below_the_commit_appendix() { + for extra in [&["--no-stream"][..], &[][..]] { + let run = run_pr(extra); + + assert!(run.stdout.contains(MESSAGE), "message missing:\n{}", run.stdout); + assert_footer_order(&run.stdout); + assert!( + run.stdout.contains("Tokens: prompt=11, completion=7, total=18"), + "token counts missing:\n{}", + run.stdout + ); + + let commits = run.stdout.find("Add the second line").expect("commit appendix missing"); + let provider = run.stdout.find("Provider: ").unwrap(); + assert!(commits < provider, "footer must come after the commit list:\n{}", run.stdout); + assert!(run.stdout.trim_end().lines().last().unwrap().starts_with("Time:")); + } +} + +#[test] +fn pr_oneline_quiet_prints_only_the_summary_line() { + let run = run_pr(&["--oneline", "quiet", "--no-stream"]); + + let lines: Vec<&str> = run.stdout.lines().filter(|l| !l.trim().is_empty()).collect(); + assert_eq!(lines.len(), 1, "expected exactly one line, got:\n{}", run.stdout); + assert!(lines[0].starts_with(ESCAPED_MESSAGE), "one-liner wrong: {}", lines[0]); +} diff --git a/tests/prompt_builder.rs b/tests/prompt_builder.rs new file mode 100644 index 0000000..18eafe8 --- /dev/null +++ b/tests/prompt_builder.rs @@ -0,0 +1,85 @@ +//! Tests for the prompts we hand to the LLM. + +use commitbot::llm::prompt_builder::commit_message_prompt; +use commitbot::{FileCategory, FileChange}; + +fn file(path: &str, category: FileCategory, summary: Option<&str>) -> FileChange { + FileChange { + path: path.to_string(), + category, + diff: "diff --git a/x b/x".to_string(), + summary: summary.map(str::to_string), + } +} + +#[test] +fn lock_files_are_listed_instead_of_summarized() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("Cargo.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(prompt.user.contains("src/main.rs")); + assert!(prompt.user.contains("- Wire up X")); + assert!(prompt.user.contains("Lock files touched/updated")); + assert!(prompt.user.contains("- Cargo.lock")); + // The lock file never gets a per-file block, so it can't be reported missing. + assert!(!prompt.user.contains("Cargo.lock\nCategory:")); + assert!(!prompt.user.contains("[missing per-file summary]")); +} + +#[test] +fn no_lock_section_without_lock_files() { + let files = vec![file("src/main.rs", FileCategory::Main, Some("- Wire up X"))]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(!prompt.user.contains("Lock files touched/updated")); +} + +#[test] +fn ignored_files_stay_out_of_the_lock_section() { + let files = vec![ + file("notes.txt", FileCategory::Ignored, None), + file("yarn.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + assert!(!prompt.user.contains("notes.txt")); + assert!(prompt.user.contains("- yarn.lock")); +} + +#[test] +fn file_count_matches_the_changeset() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("src/lib.rs", FileCategory::Supporting, Some("- Export X")), + file("Cargo.lock", FileCategory::Lock, None), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + // Every changed file is counted, including the ones we did not summarize. + assert!(prompt.user.contains("Files Changed: 3")); +} + +#[test] +fn per_file_blocks_are_numbered_without_gaps() { + let files = vec![ + file("src/main.rs", FileCategory::Main, Some("- Wire up X")), + file("Cargo.lock", FileCategory::Lock, None), + file("notes.txt", FileCategory::Ignored, None), + file("src/lib.rs", FileCategory::Supporting, Some("- Export X")), + ]; + + let prompt = commit_message_prompt("feature/x", &files, None); + + // Two files were summarized, so they are "1 of 2" and "2 of 2" — the + // skipped files in between must not leave a hole in the numbering. + assert!(prompt.user.contains("File 1 of 2: src/main.rs")); + assert!(prompt.user.contains("File 2 of 2: src/lib.rs")); + assert!(!prompt.user.contains("of 4")); +} diff --git a/tests/prompt_live.rs b/tests/prompt_live.rs new file mode 100644 index 0000000..fd00755 --- /dev/null +++ b/tests/prompt_live.rs @@ -0,0 +1,492 @@ +//! Live integration tests for prompt validation +//! +//! These tests actually invoke the commitbot binary with test diffs and +//! validate the LLM output against various constraints. + +use assert_cmd::cargo; +use std::fs; +use std::path::PathBuf; + +/// Test case definition +struct TestCase { + name: &'static str, + language: &'static str, + diff_file: &'static str, + expected_keywords: Vec<&'static str>, + min_words: usize, + max_words: usize, + max_lines: usize, + max_summary_length: usize, +} + +/// Output metrics +#[derive(Debug)] +struct OutputMetrics { + lines: usize, + words: usize, + characters: usize, + summary_length: usize, + //has_body: bool, +} + +impl OutputMetrics { + fn from_output(text: &str) -> Self { + let trimmed = text.trim(); + let lines: Vec<&str> = trimmed.lines().collect(); + + Self { + lines: lines.len(), + words: trimmed.split_whitespace().count(), + characters: trimmed.chars().count(), + summary_length: lines.first().map(|l| l.len()).unwrap_or(0), + //has_body: lines.len() > 2 && lines.get(1).map(|l| l.is_empty()).unwrap_or(false), + } + } +} + +/// Test result +#[derive(Debug)] +struct TestResult { + name: String, + language: String, + output: String, + metrics: OutputMetrics, + keywords_found: Vec, + keywords_missing: Vec, + constraint_failures: Vec, +} + +impl TestResult { + fn passed(&self) -> bool { + self.constraint_failures.is_empty() + } + + fn print_summary(&self) { + let status = if self.passed() { + "✅ PASS" + } else { + "❌ FAIL" + }; + println!("\n{} {} ({})", status, self.name, self.language); + println!(" Output: \"{}\"", self.output.lines().next().unwrap_or("")); + println!( + " Metrics: {} lines, {} words, {} chars, summary={} chars", + self.metrics.lines, + self.metrics.words, + self.metrics.characters, + self.metrics.summary_length + ); + println!( + " Keywords: {}/{} found", + self.keywords_found.len(), + self.keywords_found.len() + self.keywords_missing.len() + ); + + if !self.keywords_missing.is_empty() { + println!(" Missing keywords: {:?}", self.keywords_missing); + } + + if !self.constraint_failures.is_empty() { + println!(" Constraint failures:"); + for failure in &self.constraint_failures { + println!(" - {}", failure); + } + } + } +} + +fn print_llm_output(label: &str, output: &str) { + println!("\n--- LLM Output: {label} ---"); + println!("{}", output.trim()); + println!("--- End LLM Output ---"); +} + +fn get_test_diffs_dir() -> PathBuf { + let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + path.push("tests"); + path.push("test_diffs"); + path +} + +fn run_commitbot_with_diff(diff_file: &str, branch: &str) -> Result { + let diff_path = get_test_diffs_dir().join(diff_file); + + if !diff_path.exists() { + return Err(format!("Diff file not found: {:?}", diff_path)); + } + + let mut cmd = cargo::cargo_bin_cmd!("commitbot"); + + cmd.arg("--diff") + .arg(&diff_path) + .arg("--branch") + .arg(branch) + .arg("--no-stream"); // Disable streaming for easier output capture + + let output = cmd.output().expect("Failed to execute commitbot"); + + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + Err(String::from_utf8_lossy(&output.stderr).to_string()) + } +} + +fn validate_output(test: &TestCase, output: &str) -> TestResult { + let metrics = OutputMetrics::from_output(output); + let mut failures = Vec::new(); + let mut found = Vec::new(); + let mut missing = Vec::new(); + + let output_lower = output.to_lowercase(); + + // Check keywords + for kw in &test.expected_keywords { + if output_lower.contains(&kw.to_lowercase()) { + found.push(kw.to_string()); + } else { + missing.push(kw.to_string()); + } + } + + // Check constraints + if metrics.words < test.min_words { + failures.push(format!("words {} < min {}", metrics.words, test.min_words)); + } + if metrics.words > test.max_words { + failures.push(format!("words {} > max {}", metrics.words, test.max_words)); + } + if metrics.lines > test.max_lines { + failures.push(format!("lines {} > max {}", metrics.lines, test.max_lines)); + } + if metrics.summary_length > test.max_summary_length { + failures.push(format!( + "summary {} > max {}", + metrics.summary_length, test.max_summary_length + )); + } + + TestResult { + name: test.name.to_string(), + language: test.language.to_string(), + output: output.trim().to_string(), + metrics, + keywords_found: found, + keywords_missing: missing, + constraint_failures: failures, + } +} + +fn all_test_cases() -> Vec { + vec![ + TestCase { + name: "Rust Auth Feature", + language: "Rust", + diff_file: "rust_auth_feature.diff", + expected_keywords: vec!["auth", "token", "validate"], + min_words: 15, + max_words: 60, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "Rust Fix Panic", + language: "Rust", + diff_file: "rust_fix_panic.diff", + expected_keywords: vec!["fix", "error", "panic"], + min_words: 3, + max_words: 55, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "Python Rate Limiter", + language: "Python", + diff_file: "python_rate_limit.diff", + expected_keywords: vec!["rate", "limit", "decorator"], + min_words: 3, + max_words: 75, + max_lines: 11, + max_summary_length: 72, + }, + TestCase { + name: "JavaScript Debounce Hook", + language: "JavaScript", + diff_file: "js_debounce_hook.diff", + expected_keywords: vec!["debounce", "hook"], + min_words: 3, + max_words: 80, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "TypeScript API Types", + language: "TypeScript", + diff_file: "ts_api_types.diff", + expected_keywords: vec!["type", "interface", "api"], + min_words: 3, + max_words: 65, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "Go Logging Middleware", + language: "Go", + diff_file: "go_logging_middleware.diff", + expected_keywords: vec!["logging", "middleware", "http"], + min_words: 3, + max_words: 65, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "Java Email Service", + language: "Java", + diff_file: "java_email_service.diff", + expected_keywords: vec!["email", "service"], + min_words: 3, + max_words: 65, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "PHP Phone Validation", + language: "PHP", + diff_file: "php_phone_validation.diff", + expected_keywords: vec!["validation", "phone"], + min_words: 3, + max_words: 65, + max_lines: 10, + max_summary_length: 72, + }, + TestCase { + name: "C# Repository Pattern", + language: "C#", + diff_file: "csharp_repository.diff", + expected_keywords: vec!["repository"], + min_words: 3, + max_words: 100, + max_lines: 15, + max_summary_length: 72, + }, + TestCase { + name: "Ruby Soft Delete", + language: "Ruby", + diff_file: "ruby_soft_delete.diff", + expected_keywords: vec!["soft", "delete"], + min_words: 3, + max_words: 60, + max_lines: 10, + max_summary_length: 72, + }, + ] +} + +// ============================================================================= +// TESTS +// ============================================================================= + +#[test] +fn test_all_diff_files_exist() { + let diffs_dir = get_test_diffs_dir(); + + for test in all_test_cases() { + let path = diffs_dir.join(test.diff_file); + assert!( + path.exists(), + "Missing diff file: {} ({:?})", + test.name, + path + ); + + let content = fs::read_to_string(&path).expect("Failed to read diff file"); + assert!(!content.is_empty(), "Empty diff file: {}", test.name); + assert!( + content.contains("diff --git") || content.contains("---"), + "Invalid diff format in {}", + test.name + ); + } + + println!( + "✅ All {} diff files exist and are valid", + all_test_cases().len() + ); +} + +#[test] +fn test_list_available_fixtures() { + println!("\n=== Available Test Fixtures ===\n"); + + for test in all_test_cases() { + println!("📁 {} ({})", test.name, test.language); + println!(" File: {}", test.diff_file); + println!(" Expected keywords: {:?}", test.expected_keywords); + println!( + " Constraints: {}-{} words, max {} lines, summary <= {} chars", + test.min_words, test.max_words, test.max_lines, test.max_summary_length + ); + println!(); + } +} + +#[test] +#[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] +fn live_test_all_languages() { + let mut total_passed = 0; + let mut total_failed = 0; + let mut results = Vec::new(); + + for test in all_test_cases() { + print!("Testing {} ({})... ", test.name, test.language); + + match run_commitbot_with_diff( + test.diff_file, + &format!("feature/{}", test.language.to_lowercase()), + ) { + Ok(output) => { + print_llm_output(test.name, &output); + let result = validate_output(&test, &output); + if result.passed() { + println!("✅"); + total_passed += 1; + } else { + println!("❌"); + total_failed += 1; + } + results.push(result); + } + Err(e) => { + println!("❌ Error: {}", e); + total_failed += 1; + } + } + } + + println!("\n=== Detailed Results ==="); + for result in &results { + result.print_summary(); + } + + println!("\n=== Summary ==="); + println!("Passed: {}/{}", total_passed, total_passed + total_failed); + println!("Failed: {}/{}", total_failed, total_passed + total_failed); + + // Generate CSV report + println!("\n=== CSV Report ==="); + println!("name,language,lines,words,chars,summary_len,keywords_found,keywords_missing,passed"); + for result in &results { + println!( + "{},{},{},{},{},{},{},{},{}", + result.name, + result.language, + result.metrics.lines, + result.metrics.words, + result.metrics.characters, + result.metrics.summary_length, + result.keywords_found.len(), + result.keywords_missing.len(), + result.passed() + ); + } +} + +#[test] +#[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] +fn live_test_single_rust() { + let test = &all_test_cases()[0]; // Rust Auth Feature + + println!("\nRunning single test: {}", test.name); + + match run_commitbot_with_diff(test.diff_file, "feature/auth") { + Ok(output) => { + let result = validate_output(test, &output); + result.print_summary(); + + // For manual inspection during prompt tuning + print_llm_output(test.name, &output); + } + Err(e) => { + println!("Error: {}", e); + } + } +} + +// ============================================================================= +// METRIC-FOCUSED TESTS FOR PROMPT TUNING +// ============================================================================= + +#[test] +#[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] +fn live_test_word_count_distribution() { + let mut word_counts = Vec::new(); + + for test in all_test_cases() { + if let Ok(output) = run_commitbot_with_diff(test.diff_file, "feature/test") { + print_llm_output(test.name, &output); + let metrics = OutputMetrics::from_output(&output); + word_counts.push((test.name, test.language, metrics.words)); + } + } + + word_counts.sort_by_key(|x| x.2); + + println!("Word count distribution (sorted):"); + for (name, lang, words) in &word_counts { + let bar = "█".repeat(*words); + println!("{:>3} words | {:20} | {} | {}", words, name, lang, bar); + } + + if !word_counts.is_empty() { + let avg: f64 = + word_counts.iter().map(|x| x.2 as f64).sum::() / word_counts.len() as f64; + let min = word_counts.first().map(|x| x.2).unwrap_or(0); + let max = word_counts.last().map(|x| x.2).unwrap_or(0); + + println!("\nStatistics:"); + println!(" Min: {} words", min); + println!(" Max: {} words", max); + println!(" Avg: {:.1} words", avg); + } +} + +#[test] +#[cfg_attr(test, doc = "example")] +#[ignore = "requires live LLM access"] +fn live_test_keyword_hit_rate() { + let mut total_expected = 0; + let mut total_found = 0; + + for test in all_test_cases() { + if let Ok(output) = run_commitbot_with_diff(test.diff_file, "feature/test") { + print_llm_output(test.name, &output); + let result = validate_output(&test, &output); + let expected = result.keywords_found.len() + result.keywords_missing.len(); + let found = result.keywords_found.len(); + + total_expected += expected; + total_found += found; + + let rate = if expected > 0 { + (found as f64 / expected as f64) * 100.0 + } else { + 0.0 + }; + println!( + "{:20} | {}/{} ({:.0}%) | Found: {:?}", + test.name, found, expected, rate, result.keywords_found + ); + } + } + + if total_expected > 0 { + let overall_rate = (total_found as f64 / total_expected as f64) * 100.0; + println!( + "\nOverall keyword hit rate: {}/{} ({:.1}%)", + total_found, total_expected, overall_rate + ); + } +} diff --git a/tests/setup.rs b/tests/setup.rs new file mode 100644 index 0000000..17401de --- /dev/null +++ b/tests/setup.rs @@ -0,0 +1,31 @@ +use clap::Parser; +use commitbot::config::Config; +use commitbot::setup::build_llm_client; +use commitbot::Cli; + +fn build(args: &[&str]) -> anyhow::Result<()> { + let missing = std::env::temp_dir().join("commitbot_setup_test_missing.toml"); + let mut argv = vec!["commitbot", "--config", missing.to_str().unwrap()]; + argv.extend_from_slice(args); + let cfg = Config::from_sources(&Cli::parse_from(argv))?; + build_llm_client(&cfg).map(|_| ()) +} + +#[test] +fn builds_every_provider_with_and_without_quiet_oneline() { + for quiet in [&[][..], &["--oneline", "quiet"][..]] { + for provider_args in [ + &["--provider", "openai", "--api-key", "test-key", "--model", "m"][..], + &["--provider", "ollama", "--url", "http://localhost:11434", "--model", "m"][..], + &["--provider", "lmstudio", "--url", "http://localhost:1234", "--model", "m"][..], + ] { + let args: Vec<&str> = provider_args.iter().chain(quiet).copied().collect(); + build(&args).unwrap_or_else(|e| panic!("{args:?} failed: {e}")); + } + } +} + +#[test] +fn rejects_unknown_provider() { + assert!(build(&["--provider", "nope", "--model", "m"]).is_err()); +} diff --git a/tests/test_diffs/csharp_repository.diff b/tests/test_diffs/csharp_repository.diff new file mode 100644 index 0000000..cfaae85 --- /dev/null +++ b/tests/test_diffs/csharp_repository.diff @@ -0,0 +1,81 @@ +diff --git a/src/Data/Repository.cs b/src/Data/Repository.cs +new file mode 100644 +index 0000000..fedcba9 +--- /dev/null ++++ b/src/Data/Repository.cs +@@ -0,0 +1,42 @@ ++using System.Linq.Expressions; ++using Microsoft.EntityFrameworkCore; ++ ++namespace App.Data; ++ ++public class Repository : IRepository where T : class ++{ ++ private readonly DbContext _context; ++ private readonly DbSet _dbSet; ++ ++ public Repository(DbContext context) ++ { ++ _context = context; ++ _dbSet = context.Set(); ++ } ++ ++ public async Task GetByIdAsync(int id) ++ => await _dbSet.FindAsync(id); ++ ++ public async Task> GetAllAsync() ++ => await _dbSet.ToListAsync(); ++ ++ public async Task> FindAsync(Expression> predicate) ++ => await _dbSet.Where(predicate).ToListAsync(); ++ ++ public async Task AddAsync(T entity) ++ { ++ awadiff --git a/src/Data/Repository.cs b/src/Data/Repository.cs +new file mode 100644 +index 0000000..fedcsknew file mode 100644 +index 0000000..fedcba9 +--- /dev/null ++);index 0000000..fedcnt--- /dev/null ++++ b/s);+++ b/src/Da @@ -0,0 +1,42 @@ ++using Sysyn+using System.L +using Microsoft.EntityFramewoy)+ ++namespace App.Data; ++ ++public clasAsy+ ++public class Rep +cat > /Users/mikegarde/dev/github-mikegarde/commitbot/tests/test_diffs/ruby_soft_delete.diff << 'EOF' +diff --git a/app/models/concerns/soft_deletable.rb b/app/models/concerns/soft_deletable.rb +new file mode 100644 +index 0000000..1234abc +--- /dev/null ++++ b/app/models/concerns/soft_deletable.rb +@@ -0,0 +1,28 @@ ++module SoftDeletable ++ extend ActiveSupport::Concern ++ ++ included do ++ default_scope { where(deleted_at: nil) } ++ scope :with_deleted, -> { unscope(where: :deleted_at) } ++ scope :only_deleted, -> { with_deleted.where.not(deleted_at: nil) } ++ end ++ ++ def soft_delete ++ update(deleted_at: Time.current) ++ end ++ ++ def restore ++ update(deleted_at: nil) ++ end ++ ++ def deleted? ++ deleted_at.present? ++ end ++ ++ def destroy ++ soft_delete ++ end ++ ++ def really_destroy! ++ with_deleted { super } ++ end ++end diff --git a/tests/test_diffs/go_logging_middleware.diff b/tests/test_diffs/go_logging_middleware.diff new file mode 100644 index 0000000..ed40aa4 --- /dev/null +++ b/tests/test_diffs/go_logging_middleware.diff @@ -0,0 +1,41 @@ +diff --git a/middleware/logging.go b/middleware/logging.go +new file mode 100644 +index 0000000..aaabbbc +--- /dev/null ++++ b/middleware/logging.go +@@ -0,0 +1,35 @@ ++package middleware ++ ++import ( ++"log" ++"net/http" ++"time" ++) ++ ++type responseWriter struct { ++vi-http.ResponseWriter ++vi-statusCode int ++} ++ ++func (rw *responseWriter) WriteHeader(code int) { ++vi-rw.statusCode = code ++vi-rw.ResponseWriter.WriteHeader(code) ++} ++ ++func LoggingMiddleware(next http.Handler) http.Handler { ++vi-return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++start := time.Now() ++vi- ++vi-rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK} ++vi-next.ServeHTTP(rw, r) ++vi- ++vi-duration := time.Since(start) ++vi-log.Printf( ++"%s %s %d %v", ++r.Method, ++r.RequestURI, ++rw.statusCode, ++duration, ++) ++vi-}) ++} diff --git a/tests/test_diffs/java_email_service.diff b/tests/test_diffs/java_email_service.diff new file mode 100644 index 0000000..6fc45a2 --- /dev/null +++ b/tests/test_diffs/java_email_service.diff @@ -0,0 +1,83 @@ +diff --git a/src/main/java/com/app/service/EmailService.java b/src/main/java/com/app/service/EmailService.java +new file mode 100644 +index 0000000..1234567 +--- /dev/null ++++ b/src/main/java/com/app/service/EmailService.java +@@ -0,0 +1,45 @@ ++package com.app.service; ++ ++import org.springframework.mail.SimpleMailMessage; ++import org.springframework.mail.javamail.JavaMailSender; ++import org.springframework.scheduling.annotation.Async; ++import org.springframework.stereotype.Service; ++ ++import java.util.concurrent.CompletableFuture; ++ ++@Service ++public class EmailService { ++ ++ private final JavaMailSender mailSender; ++ private final String fromAddress; ++ ++ public EmailService(JavaMailSender mailSender, String fromAddress) { ++ this.mailSender = mailSender; ++ this.fromAddress = fromAddress; ++ } ++ ++ @Async ++ public CompletableFuture sendWelcomeEmail(String to, String usernamediff --git a/src/main/java/com/app/service/EmailService.java b/src/main/java/com/app/service/EmailServatnew file mode 100644 +index 0000000..1234567 +--- /dev/null ++++ b/src/main/java/com/app/service/EmailService.jaubindex 0000000..1234{ +--- /dev/null ++++ b/s +++ b/src/maai@@ -0,0 +1,45 @@ ++package com.app.service; ++ ++import +package com.apro+ ++import org.springfram +import org.springframework.mail.javamail.JavaMailt(+import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; ++ ++impoet+ ++import java.util.concurrent.CompletableFutu + ++@Service ++public class EmailService { ++ ++ n Co+public eF+ ++ private final JavaMa); +++ private final Strincat > /Users/mikegarde/dev/github-mikegarde/commitbot/tests/test_diffs/php_phone_validation.diff << 'EOF' +diff --git a/app/Rules/PhoneNumber.php b/app/Rules/PhoneNumber.php +new file mode 100644 +index 0000000..abcdef1 +--- /dev/null ++++ b/app/Rules/PhoneNumber.php +@@ -0,0 +1,32 @@ ++country = $country; ++ } ++ ++ public function passes($attribute, $value): bool ++ { ++ $patterns = [ ++ 'US' => '/^(\+1)?[2-9]\d{2}[2-9]\d{6}$/', ++ 'UK' => '/^(\+44)?[1-9]\d{9,10}$/', ++ 'DE' => '/^(\+49)?[1-9]\d{10,11}$/', ++ ]; ++ ++ return preg_match($patterns[$this->country] ?? $patterns['US'], $value); ++ } ++ ++ public function message(): string ++ { ++ return 'The :attribute must be a valid phone number.'; ++ } ++} diff --git a/tests/test_diffs/js_debounce_hook.diff b/tests/test_diffs/js_debounce_hook.diff new file mode 100644 index 0000000..1e77164 --- /dev/null +++ b/tests/test_diffs/js_debounce_hook.diff @@ -0,0 +1,27 @@ +diff --git a/src/hooks/useDebounce.js b/src/hooks/useDebounce.js +new file mode 100644 +index 0000000..1234567 +--- /dev/null ++++ b/src/hooks/useDebounce.js +@@ -0,0 +1,22 @@ ++import { useState, useEffect } from 'react'; ++ ++/** ++ * Custom hook that debounces a value. ++ * @param {any} value - The value to debounce ++ * @param {number} delay - Delay in milliseconds ++ * @returns {any} The debounced value ++ */ ++export function useDebounce(value, delay = 300) { ++ const [debouncedValue, setDebouncedValue] = useState(value); ++ ++ useEffect(() => { ++ const timer = setTimeout(() => { ++ setDebouncedValue(value); ++ }, delay); ++ ++ return () => clearTimeout(timer); ++ }, [value, delay]); ++ ++ return debouncedValue; ++} diff --git a/tests/test_diffs/php_phone_validation.diff b/tests/test_diffs/php_phone_validation.diff new file mode 100644 index 0000000..5a2981f --- /dev/null +++ b/tests/test_diffs/php_phone_validation.diff @@ -0,0 +1,37 @@ +diff --git a/app/Rules/PhoneNumber.php b/app/Rules/PhoneNumber.php +new file mode 100644 +index 0000000..abcdef1 +--- /dev/null ++++ b/app/Rules/PhoneNumber.php +@@ -0,0 +1,32 @@ ++country = $country; ++ } ++ ++ public function passes($attribute, $value): bool ++ { ++ $patterns = [ ++ 'US' => '/^(\+1)?[2-9]\d{2}[2-9]\d{6}$/', ++ 'UK' => '/^(\+44)?[1-9]\d{9,10}$/', ++ 'DE' => '/^(\+49)?[1-9]\d{10,11}$/', ++ ]; ++ ++ return preg_match($patterns[$this->country] ?? $patterns['US'], $value); ++ } ++ ++ public function message(): string ++ { ++ return 'The :attribute must be a valid phone number.'; ++ } ++} diff --git a/tests/test_diffs/python_rate_limit.diff b/tests/test_diffs/python_rate_limit.diff new file mode 100644 index 0000000..9b5064e --- /dev/null +++ b/tests/test_diffs/python_rate_limit.diff @@ -0,0 +1,60 @@ +diff --git a/app/decorators.py b/app/decorators.py +index aaa1111..bbb2222 100644 +--- a/app/decorators.py ++++ b/app/decorators.py +@@ -1,5 +1,7 @@ + from functools import wraps + from flask import request, jsonify ++from redis import Redis ++from datetime import timedelta + def require_auth(f): + @wraps(f) +@@ -10,3 +12,25 @@ def require_auth(f): + return jsonify({'error': 'Unauthorized'}), 401 + return f(*args, **kwargs) + return decorated ++ ++redis_client = Redis(host='localhost', port=6379, db=0) ++ ++def rate_limit(max_requests: int = 100, window: int = 3600): ++ """Rate limiting decorator using Redis sliding window.""" ++ def decorator(f): ++ @wraps(f) ++ def decorated(*args, **kwargs): ++ client_ip = request.remote_addr ++ key = f"rate_limit:{f.__name__}:{client_ip}" ++ ++ current = redis_client.incr(key) ++ if current == 1diff --git a/app/decorators.py b/app/decorators.py +index aaa1111..bbb2222 100644 +--- a/app/decoratorsstindex aaa1111..bbb2222 100644 +--- a/app/decoratore --- a/app/decorators.py ++++ +++ b/app/decorators.ptu@@ -1,5 +1,7 @@ + from + from functoolde from flask import request,or+fromcat > /Users/mikegarde/dev/github-mikegarde/commitbot/tests/test_diffs/js_debounce_hook.diff << 'EOF' +diff --git a/src/hooks/useDebounce.js b/src/hooks/useDebounce.js +new file mode 100644 +index 0000000..1234567 +--- /dev/null ++++ b/src/hooks/useDebounce.js +@@ -0,0 +1,22 @@ ++import { useState, useEffect } from 'react'; ++ ++/** ++ * Custom hook that debounces a value. ++ * @param {any} value - The value to debounce ++ * @param {number} delay - Delay in milliseconds ++ * @returns {any} The debounced value ++ */ ++export function useDebounce(value, delay = 300) { ++ const [debouncedValue, setDebouncedValue] = useState(value); ++ ++ useEffect(() => { ++ const timer = setTimeout(() => { ++ setDebouncedValue(value); ++ }, delay); ++ ++ return () => clearTimeout(timer); ++ }, [value, delay]); ++ ++ return debouncedValue; ++} diff --git a/tests/test_diffs/ruby_soft_delete.diff b/tests/test_diffs/ruby_soft_delete.diff new file mode 100644 index 0000000..c60d3e8 --- /dev/null +++ b/tests/test_diffs/ruby_soft_delete.diff @@ -0,0 +1,35 @@ +diff --git a/app/models/concerns/soft_deletable.rb b/app/models/concerns/soft_deletable.rb +new file mode 100644 +index 0000000..1234abc +--- /dev/null ++++ b/app/models/concerns/soft_deletable.rb +@@ -0,0 +1,28 @@ ++module SoftDeletable ++ extend ActiveSupport::Concern ++ ++ included do ++ default_scope { where(deleted_at: nil) } ++ scope :with_deleted, -> { unscope(where: :deleted_at) } ++ scope :only_deleted, -> { with_deleted.where.not(deleted_at: nil) } ++ end ++ ++ def soft_delete ++ update(deleted_at: Time.current) ++ end ++ ++ def restore ++ update(deleted_at: nil) ++ end ++ ++ def deleted? ++ deleted_at.present? ++ end ++ ++ def destroy ++ soft_delete ++ end ++ ++ def really_destroy! ++ with_deleted { super } ++ end ++end diff --git a/tests/test_diffs/rust_auth_feature.diff b/tests/test_diffs/rust_auth_feature.diff new file mode 100644 index 0000000..f4daae9 --- /dev/null +++ b/tests/test_diffs/rust_auth_feature.diff @@ -0,0 +1,26 @@ +diff --git a/src/auth.rs b/src/auth.rs +index 1234567..abcdefg 100644 +--- a/src/auth.rs ++++ b/src/auth.rs +@@ -10,6 +10,25 @@ use crate::models::User; + pub struct AuthService { + secret_key: String, ++ token_expiry: u64, ++} ++ ++impl AuthService { ++ pub fn validate_token(&self, token: &str) -> Result { ++ let decoded = decode::( ++ token, ++ &DecodingKey::from_secret(self.secret_key.as_bytes()), ++ &Validation::default(), ++ )?; ++ ++ if decoded.claims.exp < current_timestamp() { ++ return Err(AuthError::TokenExpired); ++ } ++ ++ User::find_by_id(decoded.claims.sub) ++ .ok_or(AuthError::UserNotFound) ++ } + } diff --git a/tests/test_diffs/rust_fix_panic.diff b/tests/test_diffs/rust_fix_panic.diff new file mode 100644 index 0000000..9edb703 --- /dev/null +++ b/tests/test_diffs/rust_fix_panic.diff @@ -0,0 +1,17 @@ +diff --git a/src/parser.rs b/src/parser.rs +index abc1234..def5678 100644 +--- a/src/parser.rs ++++ b/src/parser.rs +@@ -45,8 +45,12 @@ impl Parser { + } + pub fn parse(&mut self, input: &str) -> Result { +- let first_token = self.tokens.first().unwrap(); +- self.parse_expression(first_token) ++ let first_token = self.tokens.first() ++ .ok_or_else(|| ParseError::EmptyInput)?; ++ ++ self.parse_expression(first_token).map_err(|e| { ++ ParseError::InvalidSyntax { line: e.line, message: e.to_string() } ++ }) + } + } diff --git a/tests/test_diffs/ts_api_types.diff b/tests/test_diffs/ts_api_types.diff new file mode 100644 index 0000000..a73bcbe --- /dev/null +++ b/tests/test_diffs/ts_api_types.diff @@ -0,0 +1,36 @@ +diff --git a/src/types/api.ts b/src/types/api.ts +index eee5555..fff6666 100644 +--- a/src/types/api.ts ++++ b/src/types/api.ts +@@ -1,8 +1,32 @@ +-export interface User { ++export interface BaseEntity { ++ id: string; ++ createdAt: Date; ++ updatedAt: Date; ++} ++ ++export interface User extends BaseEntity { + id: string; + email: string; + name: string; +- createdAt: Date; ++ role: UserRole; ++} ++ ++export type UserRole = 'admin' | 'user' | 'guest'; ++ ++export interface ApiResponse { ++ data: T; ++ success: boolean; ++ message?: string; ++} ++ ++export interface PaginatedResponse extends ApiResponse { ++ pagination: { ++ page: number; ++ pageSize: number; ++ totalPages: number; ++ totalItems: number; ++ }; + }