pax_global_header00006660000000000000000000000064150224001560014505gustar00rootroot0000000000000052 comment=eda1ddca6e2a1d25d2ba651ff9d1ac65af84720b pay-respects-0.7.8/000077500000000000000000000000001502240015600141405ustar00rootroot00000000000000pay-respects-0.7.8/.editorconfig000066400000000000000000000002261502240015600166150ustar00rootroot00000000000000root = true [*] indent_style = tab charset = utf-8 end_of_line = lf insert_final_newline = true [*.{yml,yaml}] indent_style = space indent_size = 2 pay-respects-0.7.8/.github/000077500000000000000000000000001502240015600155005ustar00rootroot00000000000000pay-respects-0.7.8/.github/FUNDING.yml000066400000000000000000000000561502240015600173160ustar00rootroot00000000000000github: [ iffse ] ko_fi: iffse liberapay: iff pay-respects-0.7.8/.github/ISSUE_TEMPLATE/000077500000000000000000000000001502240015600176635ustar00rootroot00000000000000pay-respects-0.7.8/.github/ISSUE_TEMPLATE/bug-report.yaml000066400000000000000000000017351502240015600226430ustar00rootroot00000000000000name: Bug Report description: File a bug report title: '[Bug]: ' labels: - bug body: - type: textarea id: description attributes: label: What happened? description: Please leave a brief description about the bug you file. validations: required: true - type: textarea id: log attributes: label: The command and output description: Please provide us the command and output you are running validations: required: true - type: textarea id: build attributes: label: Build information description: The output of `pay-respects --version` validations: required: true - type: checkboxes id: no-similar-issue attributes: label: No similar issue description: There is no similar issue found in the [issues](https://github.com/iffse/pay-respects/issues) options: - label: I have searched the issue list and there is no similar issue found required: true pay-respects-0.7.8/.github/ISSUE_TEMPLATE/feature-request.yaml000066400000000000000000000005071502240015600236720ustar00rootroot00000000000000name: Feature Request description: File a feature request title: '[Feature Request]: ' labels: - feature-request body: - type: textarea id: feature-request-content attributes: label: What do you want us to work on? description: Please let us know what do you think validations: required: true pay-respects-0.7.8/.github/dependabot.yaml000066400000000000000000000005221502240015600204700ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: weekly target-branch: main - package-ecosystem: cargo directory: / schedule: interval: weekly target-branch: main ignore: - dependency-name: "*" update-types: ["version-update:semver-patch"] pay-respects-0.7.8/.github/workflows/000077500000000000000000000000001502240015600175355ustar00rootroot00000000000000pay-respects-0.7.8/.github/workflows/build.yaml000066400000000000000000000074731502240015600215330ustar00rootroot00000000000000name: Build on: push: tags: - v* permissions: contents: write env: CARGO_INCREMENTAL: 0 jobs: build: name: ${{ matrix.target }} runs-on: ${{ matrix.os }} defaults: run: shell: bash strategy: fail-fast: true matrix: include: - os: ubuntu-latest target: x86_64-unknown-linux-musl deb: true rpm: true musl: true - os: ubuntu-latest target: i686-unknown-linux-musl deb: true rpm: true cross: true musl: true - os: ubuntu-latest target: aarch64-unknown-linux-musl deb: true rpm: true cross: true musl: true - os: ubuntu-latest target: armv7-unknown-linux-musleabihf deb: true rpm: true cross: true musl: true - os: ubuntu-latest target: aarch64-linux-android cross: true - os: macos-latest target: x86_64-apple-darwin - os: macos-latest target: aarch64-apple-darwin - os: windows-latest target: x86_64-pc-windows-msvc - os: windows-latest target: aarch64-pc-windows-msvc steps: - uses: actions/checkout@v4 - name: Get version id: version run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT - name: Setup Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable override: true target: ${{ matrix.target }} profile: minimal - name: Install musl if: matrix.musl == true run: sudo apt-get install -y musl-tools - name: Caching uses: Swatinem/rust-cache@v2 with: key: ${{ matrix.target }} - name: Build if: ${{ matrix.cross == false }} run: cargo build --release --workspace --locked --target ${{ matrix.target }} - name: Build (cross) if: ${{ matrix.cross == true}} # cross 0.2.5 broken for android run: | cargo install cross --locked --git https://github.com/cross-rs/cross --rev 99b8069c0d977a14cd421ad8a3ef3255dc5802be cross build --release --workspace --locked --target ${{ matrix.target }} - name: Package deb if: ${{ matrix.deb == true }} run: | cargo install cargo-deb --locked cargo deb -p pay-respects --no-build --no-strip --output . --target ${{ matrix.target }} - name: Package rpm if: ${{ matrix.rpm == true }} run: | cargo install cargo-generate-rpm --locked cargo-generate-rpm -p core -o . --target ${{ matrix.target }} - name: Zipping files (unix) if: runner.os != 'Windows' run: > tar --zstd -cf pay-respects-${{ steps.version.outputs.VERSION }}-${{ matrix.target }}.tar.zst LICENSE -C target/${{ matrix.target }}/release pay-respects _pay-respects-module-100-runtime-rules _pay-respects-fallback-100-request-ai - name: Zipping files (exe) if: runner.os == 'Windows' run: > 7z a pay-respects-${{ steps.version.outputs.VERSION }}-${{ matrix.target }}.zip ./LICENSE ./target/${{ matrix.target }}/release/pay-respects.exe ./target/${{ matrix.target }}/release/_pay-respects-module-100-runtime-rules.exe ./target/${{ matrix.target }}/release/_pay-respects-fallback-100-request-ai.exe - name: Uploading to release uses: ncipollo/release-action@v1 with: artifacts: | *.tar.zst *.zip *.deb *.rpm allowUpdates: true makeLatest: true pay-respects-0.7.8/.github/workflows/test.yml000066400000000000000000000007001502240015600212340ustar00rootroot00000000000000name: Test on: push: branches: [ "main" ] pull_request: branches: [ "main" ] env: CARGO_TERM_COLOR: always CARGO_INCREMENTAL: 0 jobs: build-and-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Caching uses: Swatinem/rust-cache@v2 with: key: build-and-test - name: Build run: cargo build --verbose - name: Tests run: make test pay-respects-0.7.8/.gitignore000066400000000000000000000000171502240015600161260ustar00rootroot00000000000000/target result pay-respects-0.7.8/.rustfmt.toml000066400000000000000000000000211502240015600166100ustar00rootroot00000000000000hard_tabs = true pay-respects-0.7.8/CHANGELOG.md000066400000000000000000000220351502240015600157530ustar00rootroot00000000000000# Changelog All notable changes to components of this project since 0.5.14 will be documented in this file. The format is based on [Keep a Changelog], and this project adheres to [Semantic Versioning]. [Keep a Changelog]: https://keepachangelog.com/en/1.1.0/ [Semantic Versioning]: https://semver.org/spec/v2.0.0.html ## [Unreleased] ## [0.7.8] - 2025-06-12 ### Fixed - Nix: Shell install via `nix-shell` ## [0.7.7] - 2025-06-11 ### Added - Configuration file, allowing to customize some parameters - (Nix/Guix): Installation method as shell, without installing to system profile - Option for let the working shell be responsible for the suggestions ### Changed - Terminal environment variable for locales now has higher priority than system locales (MacOS or Windows that have different locales between system and `LANG`) ### Fixed - MacOS: Fixed arguments not available in MacOS ## [0.7.6] - 2025-04-22 ### Added - Compile-time variable to specify package manager (to be set by each distribution) - Rules for `size` and `brew` - General rule parsing for `runtime-rules` ### Changed - Re-enabled filtering when selecting candidate (`jk` does not work as Vim mode is also enabled) - Workaround to move terminal cursor away from last line (cannot hide as `inquire` controls the cursor) ### Fixed - Fixed panics for commands starting with a character more than 1 byte - Fish: Don't run CNF mode recursively (in case that user's config does not have an early return in non-interactive session) ## [0.7.5] - 2025-04-10 ### Fixed - Multi-line suggestions are run multiple times in the last release instead of adding to history ## [0.7.4] - 2025-04-10 [YANKED] ### Added - Adding executed commands to history for Bash, Zsh, and Fish ### Fixed - PowerShell's init wasn't executing returned commands to be evaluated ## [0.7.3] - 2025-04-09 ### Added - Regex support for conditions matching - `,` cannot be used though ### Changed - Using Damerau variation for string comparison ### Fixed - Panics in core and runtime-rules module - Removed duplicated characters in stream output ### Removed - `exe_contains` rule as it can be done with regex ## [0.7.2] - 2025-04-08 ### Added - Streaming output support for AI module - Wasn't easy as my brain is pretty much dead at the time of writing - `guix` support in package installation by [gs-101](https://github.com/iffse/pay-respects/pull/44) ### Fixed - Redundant packages from `nix-index` by [SigmaSquadron](https://github.com/iffse/pay-respects/pull/45) ### Removed - No longer depends on `libcurl`. Now using `rustls` ## [0.7.1] - 2025-04-06 ### Added - Support reasoning AI models (can take more than 20 seconds) - Allow adding additional prompts for role-playing with perversion or whatever - `exe_contains` condition to check if the command contains the argument ### Fixed - Parsing command environment variables (e.g. `LANG=ja_JP.UTF-8 pacman` will work as intended) - Not getting `command-not-found`'s output as it goes into `stderr` ## [0.7.0] - 2025-04-05 ### Breaking - Manual aliasing no longer supported ### Added - `noconfirm` mode: Run suggestions without confirmation - Suggestion tests ### Fixed - PowerShell's initialization for versions that does not support `Get-Error` ### Changed - Reimplemented initialization with templates ## [0.6.14] - 2025-03-13 ### Added - Nushell: Added alias support - Also allows arbitrary shell to provide support - `echo` mode: Only print suggestion ### Fixed - No longer having newlines when expanding alias ### Changed - (Windows) Separator for `_PR_LIB` has changed to `;` by [codyduong](https://github.com/iffse/pay-respects/pull/37) ## [0.6.13] - 2025-02-12 ### Changed - CI binaries now use statically linked musl library - Multi-suggest format changed to unordered bullet list - Single suggests merged into multi-suggest ## [0.6.12] - 2025-01-26 ### Fixed - `nix-index` panic by [jakobhellermann](https://github.com/iffse/pay-respects/pull/31) ### Changed - Executables environment variable passed to modules is now limited to 100k characters - Changed the format for multi-suggest ## [0.6.11] - 2025-01-18 ### Fixed - No longer panics when interrupting multi-suggest - Bash & Zsh: Reverted function based initialization to alias ## [0.6.10] - 2025-01-07 ### Fixed - Wrong starting distance when including all candidates - Spacings for `opt` placeholder ### Changed - Merged `exes` placeholder of last version into new `select` placeholder ## [0.6.9] - 2025-01-06 ### Added - Include all candidates with the same distances for executable typos ### Changed - Running standard modules in a separated thread - Bash init: use `fc` instead of history ## [0.6.8] - 2025-01-02 ### Fixed - Broken rule for `git` in the last version ### Removed - Removed binary files from history. Hash of all relevant commits will change ## [0.6.7] - 2024-12-31 ### Fixed - No longer running `get_error` in CNF mode (makes PowerShell hang with recursive calls) - Not showing `sudo` in successive suggestions (although they were applied) ### Changed - Licenses for libraries changed to MPL-2.0 from AGPL-3.0 ## [0.6.6] - 2024-12-18 ### Added - RPM packaging ### Fixed - Panic on `sudo` input command ## [0.6.5] - 2024-12-13 ### Added - AI module: Show raw body on parse failure (sometime the AI forgets a bracket) ### Fixed - Not getting `stderr` from command-not-found ## [0.6.4] - 2024-12-12 ### Added - Flakes install in `nix` - Override package manager using `_PR_PACKAGE_MANAGER` - AI module: - Allow multiple suggestions - More default values ### Changed - Compile-time `_PR_LIB` changed to `_DEF_PR_LIB` to be explicit ## [0.6.3] - 2024-12-11 ### Added - FHS 3.0 compliance: Compile-time and runtime environment variable `_PR_LIB` specifying `lib` directories for storing modules, separated by `:` - Search in `PATH` if not provided ## [0.6.2] - 2024-12-10 ### Added - Aliases matching to command-not-found - Relative path command fixes - Does not work in `bash` and `zsh`: Not considered a command ### Changed - **BREAKING:** Executable list passed to modules is now a space ` ` instead of a comma `,` - Skip privilege elevation for `nix` ## [0.6.1] - 2024-12-09 ### Added - Custom priority for modules ### Changed - `--nocnf` option in docs wasn't the same as in the code `--noncf`. They are normalized to `--nocnf` ## [0.6.0] - 2024-12-08 ### Added - Modular system - Package manager integration for `apt` (also `snap` and `pkg` via `command-not-found`), `dnf`, `portage`, `nix`, `yum` - Adding aliases to executable match ### Changed - Heavy project refactoring - `runtime-rules` and `request-ai` are now modules instead of features ## [0.5.15] - 2024-12-07 ### Added - PowerShell support by [artiga033](https://github.com/iffse/pay-respects/pull/15) - MSYS2 fix by [mokurin000](https://github.com/iffse/pay-respects/pull/12) - Command not found mode: Run `pay-respects` automatically by shell - Suggest command if a good match is found - If no good match is found, search if package manager (`pacman` only) has a binary with the same name and prompt to install - Multiple suggestions ### Changed - Major project refactoring - Default request-AI API - i18n updates ## [0.5.14] - 2024-11-23 History start. [unreleased]: https://github.com/iffse/pay-respects/compare/v0.7.8..HEAD [0.7.8]: https://github.com/iffse/pay-respects/compare/v0.7.7..v0.7.8 [0.7.7]: https://github.com/iffse/pay-respects/compare/v0.7.6..v0.7.7 [0.7.6]: https://github.com/iffse/pay-respects/compare/v0.7.5..v0.7.6 [0.7.5]: https://github.com/iffse/pay-respects/compare/v0.7.4..v0.7.5 [0.7.4]: https://github.com/iffse/pay-respects/compare/v0.7.3..v0.7.4 [0.7.3]: https://github.com/iffse/pay-respects/compare/v0.7.2..v0.7.3 [0.7.2]: https://github.com/iffse/pay-respects/compare/v0.7.1..v0.7.2 [0.7.1]: https://github.com/iffse/pay-respects/compare/v0.7.0..v0.7.1 [0.7.0]: https://github.com/iffse/pay-respects/compare/v0.6.14..v0.7.0 [0.6.14]: https://github.com/iffse/pay-respects/compare/v0.6.13..v0.6.14 [0.6.13]: https://github.com/iffse/pay-respects/compare/v0.6.12..v0.6.13 [0.6.12]: https://github.com/iffse/pay-respects/compare/v0.6.11..v0.6.12 [0.6.11]: https://github.com/iffse/pay-respects/compare/v0.6.10..v0.6.11 [0.6.10]: https://github.com/iffse/pay-respects/compare/v0.6.9..v0.6.10 [0.6.9]: https://github.com/iffse/pay-respects/compare/v0.6.8..v0.6.9 [0.6.8]: https://github.com/iffse/pay-respects/compare/v0.6.7..v0.6.8 [0.6.7]: https://github.com/iffse/pay-respects/compare/v0.6.6..v0.6.7 [0.6.6]: https://github.com/iffse/pay-respects/compare/v0.6.5..v0.6.6 [0.6.5]: https://github.com/iffse/pay-respects/compare/v0.6.4..v0.6.5 [0.6.4]: https://github.com/iffse/pay-respects/compare/v0.6.3..v0.6.4 [0.6.3]: https://github.com/iffse/pay-respects/compare/v0.6.2..v0.6.3 [0.6.2]: https://github.com/iffse/pay-respects/compare/v0.6.1..v0.6.2 [0.6.1]: https://github.com/iffse/pay-respects/compare/v0.6.0..v0.6.1 [0.6.0]: https://github.com/iffse/pay-respects/compare/v0.5.15..v0.6.0 [0.5.15]: https://github.com/iffse/pay-respects/compare/v0.5.14..v0.5.15 [0.5.14]: https://github.com/iffse/pay-respects/commits/v0.5.14 pay-respects-0.7.8/Cargo.lock000066400000000000000000001573721502240015600160640ustar00rootroot00000000000000# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "addr2line" version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" dependencies = [ "gimli", ] [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "arc-swap" version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" [[package]] name = "askama" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4744ed2eef2645831b441d8f5459689ade2ab27c854488fbab1fbe94fce1a7" dependencies = [ "askama_derive", "itoa", "percent-encoding", "serde", "serde_json", ] [[package]] name = "askama_derive" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d661e0f57be36a5c14c48f78d09011e67e0cb618f269cca9f2fd8d15b68c46ac" dependencies = [ "askama_parser", "basic-toml", "memchr", "proc-macro2", "quote", "rustc-hash", "serde", "serde_derive", "syn", ] [[package]] name = "askama_parser" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf315ce6524c857bb129ff794935cf6d42c82a6cff60526fe2a63593de4d0d4f" dependencies = [ "memchr", "serde", "serde_derive", "winnow", ] [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "backtrace" version = "0.3.75" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" dependencies = [ "addr2line", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", "windows-targets 0.52.6", ] [[package]] name = "base62" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10e52a7bcb1d6beebee21fb5053af9e3cbb7a7ed1a4909e534040e676437ab1f" dependencies = [ "rustversion", ] [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "basic-toml" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" dependencies = [ "serde", ] [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "bstr" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4" dependencies = [ "memchr", "serde", ] [[package]] name = "bumpalo" version = "3.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db76d6187cd04dff33004d8e6c9cc4e05cd330500379d2394209271b4aeee" [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "cc" version = "1.2.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "956a5e21988b87f372569b66183b78babf23ebc2e744b733e4350a752c4dafac" dependencies = [ "shlex", ] [[package]] name = "cfg-if" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "colored" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crossterm" version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67" dependencies = [ "bitflags 1.3.2", "crossterm_winapi", "libc", "mio 0.8.11", "parking_lot", "signal-hook", "signal-hook-mio", "winapi", ] [[package]] name = "crossterm_winapi" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" dependencies = [ "winapi", ] [[package]] name = "displaydoc" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "dyn-clone" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c7a8fb8a9fbf66c1f703fe16184d10ca0ee9d23be5b4436400408ba54a95005" [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18" dependencies = [ "libc", "windows-sys 0.59.0", ] [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] [[package]] name = "futures-channel" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", ] [[package]] name = "futures-core" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "futures-io" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-macro" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "futures-sink" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" [[package]] name = "futures-task" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" [[package]] name = "futures-util" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-core", "futures-io", "futures-macro", "futures-sink", "futures-task", "memchr", "pin-project-lite", "pin-utils", "slab", ] [[package]] name = "fuzzy-matcher" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" dependencies = [ "thread_local", ] [[package]] name = "fxhash" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" dependencies = [ "byteorder", ] [[package]] name = "getrandom" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "js-sys", "libc", "wasi 0.11.1+wasi-snapshot-preview1", "wasm-bindgen", ] [[package]] name = "getrandom" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "js-sys", "libc", "r-efi", "wasi 0.14.2+wasi-0.2.4", "wasm-bindgen", ] [[package]] name = "gimli" version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "glob" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "globset" version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54a1028dfc5f5df5da8a56a73e6c153c9a9708ec57232470703592a3f18e49f5" dependencies = [ "aho-corasick", "bstr", "log", "regex-automata", "regex-syntax", ] [[package]] name = "globwalk" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93e3af942408868f6934a7b85134a3230832b9977cf66125df2f9edcfce4ddcc" dependencies = [ "bitflags 1.3.2", "ignore", "walkdir", ] [[package]] name = "hashbrown" version = "0.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" [[package]] name = "http" version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" dependencies = [ "bytes", "fnv", "itoa", ] [[package]] name = "http-body" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ "bytes", "http", ] [[package]] name = "http-body-util" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", "futures-core", "http", "http-body", "pin-project-lite", ] [[package]] name = "httparse" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80" dependencies = [ "bytes", "futures-channel", "futures-util", "http", "http-body", "httparse", "itoa", "pin-project-lite", "smallvec", "tokio", "want", ] [[package]] name = "hyper-rustls" version = "0.27.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" dependencies = [ "http", "hyper", "hyper-util", "rustls", "rustls-pki-types", "tokio", "tokio-rustls", "tower-service", "webpki-roots", ] [[package]] name = "hyper-util" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc2fdfdbff08affe55bb779f33b053aa1fe5dd5b54c257343c17edfa55711bdb" dependencies = [ "base64", "bytes", "futures-channel", "futures-core", "futures-util", "http", "http-body", "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", "socket2", "tokio", "tower-service", "tracing", ] [[package]] name = "icu_collections" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" dependencies = [ "displaydoc", "potential_utf", "yoke", "zerofrom", "zerovec", ] [[package]] name = "icu_locale_core" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" dependencies = [ "displaydoc", "litemap", "tinystr", "writeable", "zerovec", ] [[package]] name = "icu_normalizer" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" dependencies = [ "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", "icu_provider", "smallvec", "zerovec", ] [[package]] name = "icu_normalizer_data" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" [[package]] name = "icu_properties" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" dependencies = [ "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", "icu_provider", "potential_utf", "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" [[package]] name = "icu_provider" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" dependencies = [ "displaydoc", "icu_locale_core", "stable_deref_trait", "tinystr", "writeable", "yoke", "zerofrom", "zerotrie", "zerovec", ] [[package]] name = "idna" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" dependencies = [ "idna_adapter", "smallvec", "utf8_iter", ] [[package]] name = "idna_adapter" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", ] [[package]] name = "ignore" version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d89fd380afde86567dfba715db065673989d6253f42b88179abd3eae47bda4b" dependencies = [ "crossbeam-deque", "globset", "log", "memchr", "regex-automata", "same-file", "walkdir", "winapi-util", ] [[package]] name = "indexmap" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "inquire" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fddf93031af70e75410a2511ec04d49e758ed2f26dad3404a934e0fb45cc12a" dependencies = [ "bitflags 2.9.1", "crossterm", "dyn-clone", "fuzzy-matcher", "fxhash", "newline-converter", "once_cell", "unicode-segmentation", "unicode-width 0.1.14", ] [[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" dependencies = [ "memchr", "serde", ] [[package]] name = "itertools" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" dependencies = [ "either", ] [[package]] name = "itertools" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "js-sys" version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ "once_cell", "wasm-bindgen", ] [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "linux-raw-sys" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "litemap" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" [[package]] name = "lock_api" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "lru-slab" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "memchr" version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "miniz_oxide" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", ] [[package]] name = "mio" version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" dependencies = [ "libc", "log", "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.48.0", ] [[package]] name = "mio" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.59.0", ] [[package]] name = "newline-converter" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b6b097ecb1cbfed438542d16e84fd7ad9b0c76c8a65b7f9039212a3d14dc7f" dependencies = [ "unicode-segmentation", ] [[package]] name = "normpath" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8911957c4b1549ac0dc74e30db9c8b0e66ddcd6d7acc33098f4c63a64a6d7ed" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "object" version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "parking_lot" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-targets 0.52.6", ] [[package]] name = "pay-respects" version = "0.7.8" dependencies = [ "askama", "colored", "inquire", "itertools 0.14.0", "pay-respects-parser", "pay-respects-utils", "regex-lite", "rust-i18n", "serde", "sys-locale", "toml", ] [[package]] name = "pay-respects-module-request-ai" version = "0.2.4" dependencies = [ "askama", "colored", "futures-util", "reqwest", "rust-i18n", "serde", "serde_json", "sys-locale", "terminal_size", "textwrap", "tokio", ] [[package]] name = "pay-respects-module-runtime-rules" version = "0.1.10" dependencies = [ "pay-respects-utils", "regex-lite", "serde", "toml", ] [[package]] name = "pay-respects-parser" version = "0.3.9" dependencies = [ "proc-macro2", "quote", "serde", "syn", "toml", ] [[package]] name = "pay-respects-utils" version = "0.1.8" dependencies = [ "itertools 0.14.0", "regex-lite", ] [[package]] name = "percent-encoding" version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "potential_utf" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" 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 = "proc-macro2" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] [[package]] name = "quinn" version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626214629cda6781b6dc1d316ba307189c85ba657213ce642d9c77670f8202c8" dependencies = [ "bytes", "cfg_aliases", "pin-project-lite", "quinn-proto", "quinn-udp", "rustc-hash", "rustls", "socket2", "thiserror", "tokio", "tracing", "web-time", ] [[package]] name = "quinn-proto" version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49df843a9161c85bb8aae55f101bc0bac8bcafd637a620d9122fd7e0b2f7422e" dependencies = [ "bytes", "getrandom 0.3.3", "lru-slab", "rand", "ring", "rustc-hash", "rustls", "rustls-pki-types", "slab", "thiserror", "tinyvec", "tracing", "web-time", ] [[package]] name = "quinn-udp" version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee4e529991f949c5e25755532370b8af5d114acae52326361d68d47af64aa842" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", "windows-sys 0.59.0", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" [[package]] name = "rand" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom 0.3.3", ] [[package]] name = "redox_syscall" version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af" dependencies = [ "bitflags 2.9.1", ] [[package]] name = "regex" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-lite" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53a49587ad06b26609c52e423de037e7f57f20d53535d66e08c695f347df952a" [[package]] name = "regex-syntax" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "reqwest" version = "0.12.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813" dependencies = [ "base64", "bytes", "futures-core", "futures-util", "http", "http-body", "http-body-util", "hyper", "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", "rustls", "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "tokio", "tokio-rustls", "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "wasm-streams", "web-sys", "webpki-roots", ] [[package]] name = "ring" version = "0.17.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", "getrandom 0.2.16", "libc", "untrusted", "windows-sys 0.52.0", ] [[package]] name = "rust-i18n" version = "3.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fda2551fdfaf6cc5ee283adc15e157047b92ae6535cf80f6d4962d05717dc332" dependencies = [ "globwalk", "once_cell", "regex", "rust-i18n-macro", "rust-i18n-support", "smallvec", ] [[package]] name = "rust-i18n-macro" version = "3.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22baf7d7f56656d23ebe24f6bb57a5d40d2bce2a5f1c503e692b5b2fa450f965" dependencies = [ "glob", "once_cell", "proc-macro2", "quote", "rust-i18n-support", "serde", "serde_json", "serde_yaml", "syn", ] [[package]] name = "rust-i18n-support" version = "3.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940ed4f52bba4c0152056d771e563b7133ad9607d4384af016a134b58d758f19" dependencies = [ "arc-swap", "base62", "globwalk", "itertools 0.11.0", "lazy_static", "normpath", "once_cell", "proc-macro2", "regex", "serde", "serde_json", "serde_yaml", "siphasher", "toml", "triomphe", ] [[package]] name = "rustc-demangle" version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" [[package]] name = "rustc-hash" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "rustix" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" dependencies = [ "bitflags 2.9.1", "errno", "libc", "linux-raw-sys", "windows-sys 0.59.0", ] [[package]] name = "rustls" version = "0.23.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "730944ca083c1c233a75c09f199e973ca499344a2b7ba9e755c457e86fb4a321" dependencies = [ "once_cell", "ring", "rustls-pki-types", "rustls-webpki", "subtle", "zeroize", ] [[package]] name = "rustls-pki-types" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" dependencies = [ "web-time", "zeroize", ] [[package]] name = "rustls-webpki" version = "0.103.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435" dependencies = [ "ring", "rustls-pki-types", "untrusted", ] [[package]] name = "rustversion" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d" [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "serde_spanned" version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" dependencies = [ "serde", ] [[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 = "serde_yaml" version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ "indexmap", "itoa", "ryu", "serde", "unsafe-libyaml", ] [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook" version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-mio" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd" dependencies = [ "libc", "mio 0.8.11", "signal-hook", ] [[package]] name = "signal-hook-registry" version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" dependencies = [ "libc", ] [[package]] name = "siphasher" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" [[package]] name = "slab" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ "autocfg", ] [[package]] name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "smawk" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" [[package]] name = "socket2" version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ "libc", "windows-sys 0.52.0", ] [[package]] name = "stable_deref_trait" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" version = "2.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6397daf94fa90f058bd0fd88429dd9e5738999cca8d701813c80723add80462" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" dependencies = [ "futures-core", ] [[package]] name = "synstructure" version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "sys-locale" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" dependencies = [ "libc", ] [[package]] name = "terminal_size" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ "rustix", "windows-sys 0.59.0", ] [[package]] name = "textwrap" version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" dependencies = [ "smawk", "unicode-linebreak", "unicode-width 0.2.1", ] [[package]] name = "thiserror" version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "thread_local" version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ "cfg-if", "once_cell", ] [[package]] name = "tinystr" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" dependencies = [ "displaydoc", "zerovec", ] [[package]] name = "tinyvec" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71" 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.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779" dependencies = [ "backtrace", "bytes", "libc", "mio 1.0.4", "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.52.0", ] [[package]] name = "tokio-macros" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tokio-rustls" version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" dependencies = [ "rustls", "tokio", ] [[package]] name = "tokio-util" version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66a539a9ad6d5d281510d5bd368c973d636c02dbf8a67300bfb6b950696ad7df" dependencies = [ "bytes", "futures-core", "futures-sink", "pin-project-lite", "tokio", ] [[package]] name = "toml" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", "serde_spanned", "toml_datetime", "toml_edit", ] [[package]] name = "toml_datetime" version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "toml_write", "winnow", ] [[package]] name = "toml_write" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "tower" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" dependencies = [ "futures-core", "futures-util", "pin-project-lite", "sync_wrapper", "tokio", "tower-layer", "tower-service", ] [[package]] name = "tower-http" version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" dependencies = [ "bitflags 2.9.1", "bytes", "futures-util", "http", "http-body", "iri-string", "pin-project-lite", "tower", "tower-layer", "tower-service", ] [[package]] name = "tower-layer" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] name = "tower-service" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" dependencies = [ "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" dependencies = [ "once_cell", ] [[package]] name = "triomphe" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef8f7726da4807b58ea5c96fdc122f80702030edc33b35aff9190a51148ccc85" dependencies = [ "arc-swap", "serde", "stable_deref_trait", ] [[package]] name = "try-lock" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "unicode-linebreak" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] name = "unicode-segmentation" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "unicode-width" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" [[package]] name = "unsafe-libyaml" version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" [[package]] name = "untrusted" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" version = "2.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" dependencies = [ "form_urlencoded", "idna", "percent-encoding", ] [[package]] name = "utf8_iter" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ "try-lock", ] [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wasm-bindgen" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" version = "0.4.50" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" dependencies = [ "cfg-if", "js-sys", "once_cell", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-streams" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" dependencies = [ "futures-util", "js-sys", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", ] [[package]] name = "web-sys" version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "web-time" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "webpki-roots" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2853738d1cc4f2da3a225c18ec6c3721abb31961096e9dbf5ab35fa88b19cfdb" dependencies = [ "rustls-pki-types", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys 0.59.0", ] [[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-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets 0.52.6", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets 0.52.6", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" dependencies = [ "memchr", ] [[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags 2.9.1", ] [[package]] name = "writeable" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" [[package]] name = "yoke" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" dependencies = [ "serde", "stable_deref_trait", "yoke-derive", "zerofrom", ] [[package]] name = "yoke-derive" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" dependencies = [ "proc-macro2", "quote", "syn", "synstructure", ] [[package]] name = "zerocopy" version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "zerofrom" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", "syn", "synstructure", ] [[package]] name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" [[package]] name = "zerotrie" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" dependencies = [ "displaydoc", "yoke", "zerofrom", ] [[package]] name = "zerovec" version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" dependencies = [ "yoke", "zerofrom", "zerovec-derive", ] [[package]] name = "zerovec-derive" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" dependencies = [ "proc-macro2", "quote", "syn", ] pay-respects-0.7.8/Cargo.toml000066400000000000000000000003151502240015600160670ustar00rootroot00000000000000[workspace] resolver = "2" members = [ "core", # optional modules "module-runtime-rules", "module-request-ai", ] default-members = ["core"] [profile.release] strip = true codegen-units = 1 lto = true pay-respects-0.7.8/Cross.toml000066400000000000000000000000601502240015600161220ustar00rootroot00000000000000[build.env] passthrough = ["CARGO_INCREMENTAL"] pay-respects-0.7.8/LICENSE000066400000000000000000001045261502240015600151550ustar00rootroot00000000000000 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . pay-respects-0.7.8/Makefile000066400000000000000000000012301502240015600155740ustar00rootroot00000000000000build: cargo build release: cargo build --release build-all: cargo build --workspace release-all: cargo build --release --workspace clean: cargo clean test-rust: cargo test --workspace --verbose fmt: cargo fmt fix: cargo clippy --all --fix --allow-dirty --allow-staged install: echo "Installing pay-respects core. Use `install-all` to install all modules." cargo install --path core install-all: echo "Installing pay-respects core and all modules." cargo install --path core cargo install --path module-runtime-rules cargo install --path module-request-ai test-suggestions: build cd tests && bash main.sh test: test-rust test-suggestions pay-respects-0.7.8/README.md000066400000000000000000000177741502240015600154370ustar00rootroot00000000000000# Pay Respects Typed a wrong command or don't know what to do? Pay Respects will suggest a fix to your console command by simply pressing `F`! - 🚀 **Blazing fast suggestion**: You won't notice any delay for asking suggestions! - 🎯 **Accurate results**: Suggestions are verified before being prompted to the user, no `sudo` suggestions when you are using `doas`! - ✏️ **Easy to write rules**: You don't need to know Rust. The rules are written in a TOML file! - 🔩 **Modular**: TOML not your taste? Add sources using your favorite language with a custom module! - 🤖 **AI Support**: AI module comes in aid when there is no rule for your error! - 🪶 **Tiny binary size**: Not even 1MB for core features! ![showcase](https://raw.githubusercontent.com/iffse/static-assets/refs/heads/main/pay-respects/showcase.gif) ## How to Pay Respects Please follow the instruction for your shell:
Bash / Zsh / Fish > Append the following line to your configuration file (`--alias` no longer > required for v0.7+): > ```sh > eval "$(pay-respects bash --alias)" > eval "$(pay-respects zsh --alias)" > pay-respects fish --alias | source > ``` > Arguments: > - `--alias [alias]`: Alias to a custom key, defaults to `f` > - `--nocnf`: Disables `command_not_found` handler > Manual aliasing (**REMOVED** after v0.7): > ```sh > alias f="$(pay-respects bash)" > alias f="$(pay-respects zsh)" > alias f="$(pay-respects fish)" > ```
Nushell > Add the following output to your configuration file: > ```sh > pay-respects nushell --alias [] > ``` > Or save it as a file: > ```sh > pay-respects nushell --alias [] | save -f ~/.pay-respects.nu > ``` > and source from your config file: > ```sh > source ~/.pay-respects.nu > ```
PowerShell > Append the following output to your profile: > ```pwsh > pay-respects pwsh --alias [] > ``` > Or directly pipe the output to your profile: > ```pwsh > pay-respects pwsh --alias [] >> $PROFILE > ```
Custom initialization for arbitrary shell > pay-respects only requires 2 environment variables to function: > > - `_PR_SHELL`: The binary name of the current working shell > - `_PR_LAST_COMMAND`: The last command > > pay-respects echos back, if applicable, a `cd` command that can be evaluated > by the current working shell. > General example: > ```sh > eval $(_PR_SHELL=sh _PR_LAST_COMMAND="git comit" pay-respects) > ``` > Following variables are not required, but can be used to reduce unnecessary > operations: > > - `_PR_ALIAS`: A list of aliases to commands. Separated by newlines with > zsh-like formatting, e.g. `gc=git commit` > - `_PR_ERROR_MSG`: Error message from the previous command. `pay-respects` > will rerun previous command to get the error message if absent > - `_PR_EXECUTABLES`: A space separated list of commands/executables. > `pay-respects` will search for `$PATH` if absent
Environment variable configurations > - `_PR_LIB`: Directory of modules, analogous to `PATH`. If not provided, > search in `PATH` or compile-time provided value > - `_PR_PACKAGE_MANAGER`: Use defined package manager instead of > auto-detecting alphabetically. Empty value disables package search > functionality > - `_DEF_PR_PACKAGE_MANAGER`: compile-time value > You can specify different modes to run with `_PR_MODE`: > > - `noconfirm`: Execute suggestions without confirm > - `echo`: Print suggestions to `stdout` without executing > - `cnf`: Used for command not found hook > > Example usage with `noconfirm`: > > ```sh > function ff() { > ( > export _PR_MODE="noconfirm" > f > ) > } > ```
You can now **[Press `F` to Pay Respects]**! [Press `F` to Pay Respects]: https://en.wikipedia.org/wiki/Press_F_to_pay_respects ## Installing Install from your package manager if available: [![Packaging status](https://repology.org/badge/vertical-allrepos/pay-respects.svg)](https://repology.org/project/pay-respects/versions)
Instructions for package managers > | OS / Distribution | Repository | Instructions | > |-------------------|-----------------|---------------------------------------------------| > | Arch Linux | [AUR] | `paru -S pay-respects` (`-bin`) | > | Arch Linux (ARM) | [Arch Linux CN] | `sudo pacman -S pay-respects` | > | MacOS / *Any* | [timescam] | `brew install timescam/homebrew-tap/pay-respects` | > | NixOS / *Any* | [nixpkgs] | `nix-env -iA nixos.pay-respects` | [AUR]: https://aur.archlinux.org/ [Arch Linux CN]: https://github.com/archlinuxcn/repo [nixpkgs]: https://github.com/NixOS/nixpkgs [timescam]: https://github.com/timescam/homebrew-tap
Alternatively, install pre-built binaries from [GitHub releases]. An [install script] is available: ```sh curl -sSfL https://raw.githubusercontent.com/iffse/pay-respects/main/install.sh | sh ``` [GitHub releases]: https://github.com/iffse/pay-respects/releases [install script]: ./install.sh
Cargo / Compile from source (any OS/architecture supported by Rust) > This installation requires you to have Cargo (the Rust package manager) installed. > Install from [crates.io](https://crates.io/), modules are optional > ```sh > cargo install pay-respects > cargo install pay-respects-module-runtime-rules > cargo install pay-respects-module-request-ai > ``` > Clone from git and install, suitable for adding custom compile-time rules: > ```sh > git clone --depth 1 https://github.com/iffse/pay-respects > cd pay-respects > cargo install --path core > cargo install --path module-runtime-rules > cargo install --path module-request-ai > ```
## Configuration See [configuration](./config.md). ## Rules & Modules See the following pages: - [Writing rules (TOML)](./rules.md) - [Custom modules](./modules.md) ## AI Integration > **Disclaimer**: You are using AI generated content on your own risk. Please > double-check its suggestions before accepting. AI suggestions should work out of the box with `request-ai` module installed. An API key is included with the source (your distribution might have stripped them out). It should always work unless I can no longer afford this public service or rate limits are reached. If it's useful to you, consider making a donation:
Donate using Liberapay Donate using Ko-fi
Donate using Stripe Donate using PayPal
[AI usages and API configurations](./module-request-ai/README.md) ## Contributing Current option to write rules should cover most of the cases. We need more rules, contributions are welcomed! There's also a [roadmap] for contribution opportunities. [roadmap]: ./roadmap.md This project is hosted at various sites, you can choose the one that you feel most comfortable with: - [Codeberg](https://codeberg.org/iff/pay-respects) - [GitHub](https://github.com/iffse/pay-respects) - [GitLab](https://gitlab.com/iffse/pay-respects) ## Licenses - **Binaries**: AGPL-3.0 - Core and modules - **Libraries**: MPL-2.0 - Parser and utils pay-respects-0.7.8/config.md000066400000000000000000000014331502240015600157300ustar00rootroot00000000000000# Configuration File Configuration file for `pay-respects` is located at: - `$HOME/.config/pay-respects/config.toml` (*nix) - `%APPDATA%/pay-respects/config.toml` (Windows) ## Options All available options are listed in the following example file: ```toml # maximum time in milliseconds for getting previous output timeout = 3000 # how suggestions are evaluated after being confirmed # options can be: # - Internal: commands are evaluated inside `pay-respects` # - Shell: current working shell is responsible for execution eval_method = "Internal" [package_manager] # preferred package manager package_manager = "pacman" # preferred installation method, can be limited by the package manager # available options are: # - System # - Shell (nix and guix only) install_method = "System" ``` pay-respects-0.7.8/core/000077500000000000000000000000001502240015600150705ustar00rootroot00000000000000pay-respects-0.7.8/core/Cargo.toml000066400000000000000000000026611502240015600170250ustar00rootroot00000000000000[package] name = "pay-respects" authors = ["iff "] version = "0.7.8" edition = "2021" # for crates.io description = "Command suggestions, command-not-found and thefuck replacement written in Rust" homepage = "https://codeberg.org/iff/pay-respects" repository = "https://github.com/iffse/pay-respects" keywords = ["cli", "terminal", "utility", "shell"] categories = ["command-line-utilities"] license = "AGPL-3.0-or-later" include = ["**/*.rs", "**/*.toml", "templates/**/*"] [dependencies] colored = "3" sys-locale = "0.3" rust-i18n = "3" regex-lite = "0.1" askama = "0.13" inquire = "0.7" # config file toml = { version = "0.8" } serde = { version = "1.0", features = ["derive"] } pay-respects-parser = { version = "0.3", path = "../parser" } pay-respects-utils = { version ="0.1", path = "../utils"} itertools = "0.14.0" [package.metadata.deb] assets = [ ["target/release/pay-respects", "usr/bin/", "755"], ["target/release/_pay-respects-module-100-runtime-rules", "usr/bin/", "755"], ["target/release/_pay-respects-fallback-100-request-ai", "usr/bin/", "755"], ] priority = "optional" section = "utils" [package.metadata.generate-rpm] assets = [ { source = "target/release/pay-respects", dest = "/usr/bin/", mode = "755"}, { source = "target/release/_pay-respects-module-100-runtime-rules", dest = "/usr/bin/", mode = "755"}, { source = "target/release/_pay-respects-fallback-100-request-ai", dest = "/usr/bin/", mode = "755"}, ] pay-respects-0.7.8/core/README.md000077700000000000000000000000001502240015600200342../README.mdustar00rootroot00000000000000pay-respects-0.7.8/core/i18n/000077500000000000000000000000001502240015600156475ustar00rootroot00000000000000pay-respects-0.7.8/core/i18n/i18n.toml000066400000000000000000000220011502240015600173160ustar00rootroot00000000000000_version = 2 [help] en = ''' Usage: %{usage} %{eval}: Add the following line to your configuration file: %{eval_examples} %{manual}: Add the following output to your configuration file %{manual_examples} ''' es = ''' Uso: %{usage} %{eval}: Agrega la siguiente línea a tu archivo de configuración: %{eval_examples} %{manual}: Agrega la siguiente salida a tu archivo de configuración %{manual_examples} ''' de = ''' Verwendung: %{usage} %{eval}: Fügen Sie die folgende Zeile zu Ihrer Konfigurationsdatei hinzu: %{eval_examples} %{manual}: Fügen Sie die folgende Ausgabe zu Ihrer Konfigurationsdatei hinzu: %{manual_examples} ''' fr = ''' Utilisation: %{usage} %{eval}: Ajoutez la ligne suivante à votre fichier de configuration : %{eval_examples} %{manual}: Ajoutez la sortie suivante à votre fichier de configuration : %{manual_examples} ''' it = ''' Utilizzo: %{usage} %{eval}: Aggiungi la seguente riga al tuo file di configurazione: %{eval_examples} %{manual}: Aggiungi l'output seguente al tuo file di configurazione: %{manual_examples} ''' pt = ''' Uso: %{usage} %{eval}: Adicione a seguinte linha ao seu arquivo de configuração: %{eval_examples} %{manual}: Adicione a seguinte saída ao seu arquivo de configuração: %{manual_examples} ''' ru = ''' Использование: %{usage} %{eval}: Добавьте следующую строку в ваш файл конфигурации: %{eval_examples} %{manual}: Добавьте следующий вывод в ваш файл конфигурации: %{manual_examples} ''' ja = ''' 使い方: %{usage} %{eval}: 次の行を設定ファイルに追加してください: %{eval_examples} %{manual}: 次の出力を設定ファイルに追加してください: %{manual_examples} ''' ko = ''' 사용법: %{usage} %{eval}: 다음 줄을 설정 파일에 추가하십시오: %{eval_examples} %{manual}: 다음 출력을 설정 파일에 추가하십시오: %{manual_examples} ''' zh = ''' 使用方法: %{usage} %{eval}: 将以下行添加到您的配置文件中: %{eval_examples} %{manual}: 将以下输出添加到您的配置文件中: %{manual_examples} ''' [no-env-setup] en = "No %{var} in environment. Have you aliased the command with the correct argument?\n\nUse `%{help}` for help." es = "No se encontró %{var} en el entorno. ¿Has aliado el comando con el argumento correcto?\n\nUsa `%{help}` para obtener ayuda." de = "Kein %{var} in der Umgebung gefunden. Hast du den Befehl mit dem richtigen Argument verknüpft?\n\nBenutze `%{help}` für Hilfe." fr = "Aucun %{var} trouvé dans l'environnement. Avez-vous associé la commande avec le bon argument ?\n\nUtilisez `%{help}` pour obtenir de l'aide." it = "Nessun %{var} trovato nell'ambiente. Hai associato il comando con l'argomento corretto?\n\nUsa `%{help}` per ottenere aiuto." pt = "Nenhum %{var} encontrado no ambiente. Você associou o comando com o argumento correto?\n\nUse `%{help}` para obter ajuda." ru = "Переменная %{var} не найдена в окружении. Вы создали псевдоним для команды с правильным аргументом?\n\nИспользуйте `%{help}` для помощи." ja = "環境変数 %{var} が見つかりません。コマンドを正しい引数でエイリアスしましたか?\n\nヘルプを表示するには `%{help}` を使用してください。" ko = "환경 변수 %{var}을(를) 찾을 수 없습니다. 명령을 올바른 인수로 별칭 지정했습니까?\n\n도움말을 보려면 `%{help}`를 사용하십시오." zh = "在环境中找不到 %{var}。您是否使用正确的参数别名了命令?\n\n使用 `%{help}` 获取帮助。" [no-shell] en = "No shell specified. Please specify a shell." es = "No se especificó ninguna shell. Por favor, especifica una shell." de = "Keine Shell angegeben. Bitte gib eine Shell an." fr = "Aucune shell spécifiée. Veuillez spécifier une shell." it = "Nessuna shell specificata. Specificare una shell." pt = "Nenhuma shell especificada. Por favor, especifique uma shell." ru = "Оболочка не указана. Укажите оболочку." ja = "シェルが指定されていません。シェルを指定してください。" ko = "쉘이 지정되지 않았습니다. 쉘을 지정하십시오." zh = "未指定 shell。请指定一个 shell。" [empty-command] en = "Last command was empty" es = "El último comando estaba vacío" de = "Der letzte Befehl war leer" fr = "La dernière commande était vide" it = "L'ultimo comando era vuoto" pt = "O último comando estava vazio" ru = "Последняя команда была пустой" ja = "最後のコマンドは空でした" ko = "마지막 명령이 비어 있었습니다" zh = "最后一个命令是空的" [multi-suggest] en = "%{num} suggestion(s) found" es = "%{num} sugerencia(s) encontrada(s)" de = "%{num} Vorschlag(e) gefunden" fr = "%{num} suggestion(s) trouvée(s)" it = "%{num} proposta/e trovata/e" pt = "%{num} sugestão(ões) encontrada(s)" ru = "Найдено %{num} предложение(й)" ja = "%{num} 件の提案が見つかりました" ko = "%{num} 개의 제안이 발견되었습니다" zh = "找到 %{num} 个建议" [install-package] en = "Package(s) for the missing command found" es = "Paquete(s) para el comando faltante encontrado(s)" de = "Paket(e) für den fehlenden Befehl gefunden" fr = "Paquet(s) pour la commande manquante trouvé(s)" it = "Pacchetto(i) per il comando mancante trovato(i)" pt = "Pacote(s) para o comando ausente encontrado(s)" ru = "Найден пакет(ы) для отсутствующей команды" ja = "不足しているコマンドのパッケージが見つかりました" ko = "누락된 명령에 대한 패키지가 발견되었습니다" zh = "找到缺失命令的包" [confirm] en = "Execute suggestion?" es = "¿Ejecutar sugerencia?" de = "Vorschlag ausführen?" fr = "Exécuter la suggestion?" it = "Eseguire la proposta?" pt = "Executar sugestão?" ru = "Выполнить предложение?" ja = "提案を実行しますか?" ko = "제안 실행?" zh = "执行建议?" [confirm-yes] en = "Enter" es = "Entrar" de = "Eingabetaste" fr = "Entrée" it = "Invio" pt = "Entrar" ru = "Ввод" ja = "エンター" ko = "엔터" zh = "回车" [retry] en = "Looking for new suggestion" es = "Buscando nueva sugerencia" de = "Suche nach neuem Vorschlag" fr = "Recherche d'une nouvelle suggestion" it = "Ricerca di una nuova proposta" pt = "Procurando nova sugestão" ru = "Поиск нового предложения" ja = "新しい提案を探しています" ko = "새 제안 찾는 중" zh = "寻找新建议" [no-suggestion] en = "No suggestion found for command" es = "No se encontró ninguna sugerencia para el comando" de = "Kein Vorschlag für den Befehl gefunden" fr = "Aucune suggestion trouvée pour la commande" it = "Nessuna proposta trovata per il comando" pt = "Nenhuma sugestão encontrada para o comando" ru = "Предложение для команды не найдено" ja = "コマンドの提案が見つかりません" ko = "명령에 대한 제안을 찾을 수 없습니다" zh = "找不到命令的建议" [command-not-found] en = "Command not found" es = "Comando no encontrado" de = "Befehl nicht gefunden" fr = "Commande introuvable" it = "Comando non trovato" pt = "Comando não encontrado" ru = "Команда не найдена" ja = "コマンドが見つかりません" ko = "명령을 찾을 수 없습니다" zh = "找不到命令" [package-not-found] en = "No matching package found" es = "No se encontró ningún paquete coincidente" de = "Kein passendes Paket gefunden" fr = "Aucun paquet correspondant trouvé" it = "Nessun pacchetto corrispondente trovato" pt = "Nenhum pacote correspondente encontrado" ru = "Совпадающий пакет не найден" ja = "一致するパッケージが見つかりません" ko = "일치하는 패키지를 찾을 수 없습니다" zh = "找不到匹配的包" [contribute] en = "If you think there should be a suggestion, please open an issue or send a pull request!" es = "Si crees que debería haber una sugerencia, ¡por favor abre un issue o envía un pull request!" de = "Wenn du denkst, dass es einen Vorschlag geben sollte, öffne bitte ein Issue oder sende einen Pull-Request!" fr = "Si vous pensez qu'il devrait y avoir une suggestion, veuillez ouvrir un ticket ou envoyer une demande de tirage !" it = "Se pensi che dovrebbe esserci una proposta, apri una issue o invia una pull request!" pt = "Se você acha que deveria haver uma sugestão, por favor abra uma issue ou envie um pull request!" ru = "Если вы считаете, что должно быть предложение, пожалуйста, откройте issue или отправьте pull request!" ja = "提案があるべきだと思う場合は、issueまたはpull requestを送信してください!" ko = "제안이 있어야 한다고 생각하는 경우 이슈를 열거나 풀 리퀘스트를 보내주세요!" zh = "如果您认为应该有建议,请打开一个 issue 或发送一个 pull request!" pay-respects-0.7.8/core/rules000077700000000000000000000000001502240015600174302../rulesustar00rootroot00000000000000pay-respects-0.7.8/core/src/000077500000000000000000000000001502240015600156575ustar00rootroot00000000000000pay-respects-0.7.8/core/src/args.rs000066400000000000000000000062771502240015600171750ustar00rootroot00000000000000use crate::{init::Init, shell::initialization}; use colored::Colorize; pub enum Status { Continue, Exit, // version, help, etc. Error, } pub fn handle_args(args: impl IntoIterator) -> Status { let mut iter = args.into_iter().peekable(); let mut init = Init::new(); if let Some(binary_path) = iter.next() { init.binary_path = binary_path; } if iter.peek().is_none() { return Status::Continue; } while let Some(arg) = iter.next() { match arg.as_str() { "-h" | "--help" => { print_help(); return Status::Exit; } "-v" | "--version" => { print_version(); return Status::Exit; } "-a" | "--alias" => match iter.peek() { Some(next_arg) if !next_arg.starts_with('-') => { init.alias = next_arg.to_string(); iter.next(); } _ => init.alias = String::from("f"), }, "--nocnf" => init.cnf = false, _ => init.shell = arg, } } if init.shell.is_empty() { eprintln!("{}", t!("no-shell")); return Status::Error; } initialization(&mut init); Status::Exit } fn print_help() { println!( "{}", t!( "help", usage = "pay-respects [--alias []] [--nocnf]", eval = "Bash / Zsh / Fish".bold(), eval_examples = r#" eval "$(pay-respects bash)" eval "$(pay-respects zsh)" pay-respects fish | source "#, manual = "Nushell / PowerShell".bold(), manual_examples = r#" pay-respects nushell pay-respects pwsh "# ) ); } fn print_version() { println!( "version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown") ); let lib = option_env!("_DEF_PR_LIB").map(|dir| dir.to_string()); if lib.is_some() { println!("Default lib directory: {}", lib.unwrap()); } let package_manager = option_env!("_DEF_PR_PACKAGE_MANAGER").map(|dir| dir.to_string()); if package_manager.is_some() { println!("Default package manager: {}", package_manager.unwrap()); } } #[cfg(test)] mod tests { use super::{handle_args, Status}; #[test] fn test_handle_args() { assert!(matches!( handle_args([String::from("pay-respects")]), Status::Continue )); for args in [ [String::new(), String::from("-h")], [String::new(), String::from("--help")], [String::new(), String::from("-v")], [String::new(), String::from("--version")], [String::new(), String::from("zsh")], ] { println!("Arguments {:?} should return Exit", args); assert!(matches!(handle_args(args), Status::Exit)); } for args in [ [String::new(), String::from("fish"), String::from("--alias")], [String::new(), String::from("bash"), String::from("--nocnf")], ] { println!("Arguments {:?} should return Exit", args); assert!(matches!(handle_args(args), Status::Exit)); } for args in [ [String::new(), String::from("-a")], [String::new(), String::from("--alias")], [String::new(), String::from("--nocnf")], ] { println!("Arguments {:?} should return Error", args); assert!(matches!(handle_args(args), Status::Error)); } for args in [ [String::new(), String::from("-a"), String::from("--nocnf")], [ String::new(), String::from("--alias"), String::from("--nocnf"), ], ] { println!("Argument {:?} should return Error", args); assert!(matches!(handle_args(args), Status::Error)); } } } pay-respects-0.7.8/core/src/config.rs000066400000000000000000000031101502240015600174650ustar00rootroot00000000000000use serde::Deserialize; #[allow(dead_code)] #[derive(Deserialize, Default)] pub struct Config { pub sudo: Option, #[serde(default)] pub timeout: Timeout, #[serde(default)] pub eval_method: EvalMethod, #[serde(default)] pub package_manager: PackageManagerConfig, } #[allow(dead_code)] #[derive(Deserialize, Default)] pub struct PackageManagerConfig { pub package_manager: Option, #[serde(default)] pub install_method: InstallMethod, } #[derive(Deserialize)] pub struct Timeout(pub u64); impl Default for Timeout { fn default() -> Self { Timeout(3000) } } #[derive(Deserialize, Default, PartialEq)] pub enum InstallMethod { #[default] System, // !TODO: Implement other install methods // User, // Temp, Shell, } #[derive(Deserialize, Default, PartialEq)] pub enum EvalMethod { #[default] Internal, Shell, } pub fn load_config() -> Config { let path = config_path(); let exists = std::path::Path::new(&path).exists(); if exists { let content = std::fs::read_to_string(&path).expect("Failed to read config file"); let config: Config = toml::from_str(&content).unwrap_or_else(|_| { eprintln!( "Failed to parse config file at {}. Using default configuration.", path ); Config::default() }); return config; } Config::default() } fn config_path() -> String { #[cfg(windows)] let xdg_config_home = std::env::var("APPDATA").unwrap(); #[cfg(not(windows))] let xdg_config_home = std::env::var("XDG_CONFIG_HOME") .unwrap_or_else(|_| std::env::var("HOME").unwrap() + "/.config"); format!("{}/pay-respects/config.toml", xdg_config_home) } pay-respects-0.7.8/core/src/data.rs000066400000000000000000000155721502240015600171500ustar00rootroot00000000000000use pay_respects_utils::evals::split_command; use pay_respects_utils::files::get_path_files; use pay_respects_utils::files::path_env_sep; use itertools::Itertools; use std::process::exit; use std::collections::HashMap; #[cfg(windows)] use pay_respects_utils::files::path_convert; use crate::config::load_config; use crate::config::Config; use crate::shell::alias_map; use crate::shell::builtin_commands; use crate::shell::expand_alias_multiline; use crate::shell::get_error; use crate::shell::get_shell; use crate::shell::last_command; use crate::shell::run_mode; pub const PRIVILEGE_LIST: [&str; 2] = ["sudo", "doas"]; #[derive(PartialEq)] pub enum Mode { Suggestion, Echo, NoConfirm, Cnf, } pub struct Data { pub shell: String, pub env: Option, pub command: String, pub suggest: Option, pub candidates: Vec, pub split: Vec, pub alias: Option>, pub privilege: Option, pub error: String, pub executables: Vec, pub modules: Vec, pub fallbacks: Vec, pub config: Config, pub mode: Mode, } impl Data { pub fn init() -> Data { let shell = get_shell(); let command = last_command(&shell).trim().to_string(); let alias = alias_map(&shell); let mode = run_mode(); let (mut executables, modules, fallbacks); let lib_dir = { if let Ok(lib_dir) = std::env::var("_PR_LIB") { Some(lib_dir) } else { option_env!("_DEF_PR_LIB").map(|dir| dir.to_string()) } }; #[cfg(debug_assertions)] eprintln!("lib_dir: {:?}", lib_dir); if lib_dir.is_none() { (executables, modules, fallbacks) = { let path_executables = get_path_files(); let mut executables = vec![]; let mut modules = vec![]; let mut fallbacks = vec![]; for exe in path_executables { if exe.starts_with("_pay-respects-module-") { modules.push(exe.to_string()); } else if exe.starts_with("_pay-respects-fallback-") { fallbacks.push(exe.to_string()); } else { executables.push(exe.to_string()); } } modules.sort_unstable(); fallbacks.sort_unstable(); if alias.is_some() { let alias = alias.as_ref().unwrap(); for command in alias.keys() { if executables.contains(command) { continue; } executables.push(command.to_string()); } } (executables, modules, fallbacks) }; } else { (executables, modules, fallbacks) = { let mut modules = vec![]; let mut fallbacks = vec![]; let lib_dir = lib_dir.unwrap(); let mut executables = get_path_files(); if alias.is_some() { let alias = alias.as_ref().unwrap(); for command in alias.keys() { if executables.contains(command) { continue; } executables.push(command.to_string()); } } let path = lib_dir.split(path_env_sep()).collect::>(); for p in path { #[cfg(windows)] let p = path_convert(p); let files = match std::fs::read_dir(p) { Ok(files) => files, Err(_) => continue, }; for file in files { let file = file.unwrap(); let file_name = file.file_name().into_string().unwrap(); let file_path = file.path(); if file_name.starts_with("_pay-respects-module-") { modules.push(file_path.to_string_lossy().to_string()); } else if file_name.starts_with("_pay-respects-fallback-") { fallbacks.push(file_path.to_string_lossy().to_string()); } } } modules.sort_unstable(); fallbacks.sort_unstable(); (executables, modules, fallbacks) }; } let builtins = builtin_commands(&shell); executables.extend(builtins.clone()); executables = executables.iter().unique().cloned().collect(); let config = load_config(); let mut init = Data { shell, env: None, command, suggest: None, candidates: vec![], alias, split: vec![], privilege: None, error: "".to_string(), executables, modules, fallbacks, config, mode, }; init.split(); init.extract_env(); init.expand_command(); if init.mode != Mode::Cnf { init.update_error(None); } #[cfg(debug_assertions)] { eprintln!("/// data initialization"); eprintln!("shell: {}", init.shell); eprintln!("env: {:?}", init.env); eprintln!("command: {}", init.command); eprintln!("error: {}", init.error); eprintln!("modules: {:?}", init.modules); eprintln!("fallbacks: {:?}", init.fallbacks); } init } pub fn expand_command(&mut self) { if self.alias.is_none() { return; } let alias = self.alias.as_ref().unwrap(); if let Some(command) = expand_alias_multiline(alias, &self.command) { #[cfg(debug_assertions)] eprintln!("expand_command: {}", command); self.update_command(&command); } } pub fn expand_suggest(&mut self) { if self.alias.is_none() { return; } let alias = self.alias.as_ref().unwrap(); if let Some(suggest) = expand_alias_multiline(alias, self.suggest.as_ref().unwrap()) { #[cfg(debug_assertions)] eprintln!("expand_suggest: {}", suggest); self.update_suggest(&suggest); } } pub fn split(&mut self) { self.extract_privilege(); let split = split_command(&self.command); #[cfg(debug_assertions)] eprintln!("split: {:?}", split); if split.is_empty() { eprintln!("{}", t!("empty-command")); exit(1); } self.split = split; } pub fn extract_privilege(&mut self) { let command = { let first = self.command.split_whitespace().next(); if let Some(first) = first { first.to_string() } else { return; } }; if let Some(sudo) = self.config.sudo.as_ref() { if command == *sudo { self.privilege = Some(command.to_string()); self.command = self.command.replacen(sudo, "", 1); } return; } if PRIVILEGE_LIST.contains(&command.as_str()) { self.privilege = Some(command.to_string()); self.command = self.command.replacen(&self.split[0], "", 1); } } pub fn extract_env(&mut self) { let mut envs = vec![]; loop { let mut char = self.split[0].char_indices(); char.next(); let offset = char.offset(); if self.split[0][offset..].contains("=") { envs.push(self.split.remove(0)); } else { break; } } if !envs.is_empty() { self.env = Some(envs.join(" ")); self.command = self.split.join(" "); } } pub fn update_error(&mut self, error: Option) { if let Some(error) = error { self.error = error .to_lowercase() .split_whitespace() .collect::>() .join(" "); } else { self.error = get_error(&self.shell, &self.command, self); } } pub fn update_command(&mut self, command: &str) { self.command = command.to_string(); self.split(); } pub fn update_suggest(&mut self, suggest: &str) { let split = split_command(suggest); if PRIVILEGE_LIST.contains(&split[0].as_str()) { self.suggest = Some(suggest.replacen(&split[0], "", 1)); self.privilege = Some(split[0].clone()) } else { self.suggest = Some(suggest.to_string()); }; } } pay-respects-0.7.8/core/src/init.rs000066400000000000000000000004061502240015600171700ustar00rootroot00000000000000pub struct Init { pub shell: String, pub binary_path: String, pub alias: String, pub cnf: bool, } impl Init { pub fn new() -> Init { Init { shell: String::from(""), binary_path: String::from(""), alias: String::from("f"), cnf: true, } } } pay-respects-0.7.8/core/src/main.rs000066400000000000000000000044351502240015600171570ustar00rootroot00000000000000// pay-respects: Press F to correct your command // Copyright (C) 2023 iff // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . use std::env; use sys_locale::get_locale; mod args; mod config; mod data; mod init; mod modes; mod rules; mod shell; mod style; mod suggestions; mod system; #[macro_use] extern crate rust_i18n; i18n!("i18n", fallback = "en", minify_key = true); fn main() -> Result<(), std::io::Error> { colored::control::set_override(true); let init = init(); let mut data = if let Err(status) = init { match status { args::Status::Exit => { return Ok(()); } args::Status::Error => { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid input", )); } _ => { unreachable!() } } } else { init.ok().unwrap() }; use data::Mode::*; match data.mode { Suggestion => modes::suggestion(&mut data), Echo => modes::echo(&mut data), NoConfirm => modes::noconfirm(&mut data), Cnf => modes::cnf(&mut data), } Ok(()) } fn init() -> Result { let locale = { let sys_locale = { // use terminal locale if available if let Ok(locale) = env::var("LANG") { locale } else if let Ok(locale) = env::var("LC_ALL") { locale } else if let Ok(locale) = env::var("LC_MESSAGES") { locale } else { get_locale().unwrap_or("en-US".to_string()) } }; if sys_locale.len() < 2 { "en-US".to_string() } else { sys_locale } }; rust_i18n::set_locale(&locale[0..2]); let status = args::handle_args(env::args()); match status { args::Status::Exit => { return Err(status); } args::Status::Error => { return Err(status); } _ => {} } Ok(data::Data::init()) } pay-respects-0.7.8/core/src/modes.rs000066400000000000000000000134401502240015600173360ustar00rootroot00000000000000use colored::Colorize; use inquire::*; use std::path::Path; use ui::Color; use pay_respects_utils::evals::best_matches_path; use pay_respects_utils::files::best_match_file; use crate::data::Data; use crate::shell::shell_evaluated_commands; use crate::style::highlight_difference; use crate::suggestions::suggest_candidates; use crate::system; use crate::{config, suggestions}; pub fn suggestion(data: &mut Data) { let mut last_command; loop { last_command = data.command.clone(); suggest_candidates(data); if data.candidates.is_empty() { break; }; suggestions::select_candidate(data); let execution = suggestions::confirm_suggestion(data); if execution.is_ok() { return; } else { data.update_command(&data.suggest.clone().unwrap()); let msg = Some(execution.err().unwrap()); data.update_error(msg); let retry_message = format!("{}...", t!("retry")); eprintln!("\n{}\n", retry_message.cyan().bold()); } } eprintln!("{}: {}\n", t!("no-suggestion"), last_command.red()); eprintln!( "{}\n{}", t!("contribute"), option_env!("CARGO_PKG_REPOSITORY").unwrap_or("https://github.com/iffse/pay-respects/") ); } pub fn echo(data: &mut Data) { suggest_candidates(data); if data.candidates.is_empty() { return; }; println!("{}", data.candidates.join("\n")); } pub fn noconfirm(data: &mut Data) { let mut last_command; loop { last_command = data.command.clone(); suggest_candidates(data); if data.candidates.is_empty() { break; }; let candidate = data.candidates[0].clone(); eprintln!("{}", highlight_difference(data, &candidate).unwrap()); data.update_suggest(&candidate); data.candidates.clear(); let execution = suggestions::confirm_suggestion(data); if execution.is_ok() { return; } else { data.update_command(&data.suggest.clone().unwrap()); let msg = Some(execution.err().unwrap()); data.update_error(msg); let retry_message = format!("{}...", t!("retry")); eprintln!("\n{}\n", retry_message.cyan().bold()); } } eprintln!("{}: {}\n", t!("no-suggestion"), last_command.red()); eprintln!( "{}\n{}", t!("contribute"), option_env!("CARGO_PKG_REPOSITORY").unwrap_or("https://github.com/iffse/pay-respects/") ); } pub fn cnf(data: &mut Data) { let shell = data.shell.clone(); let mut split_command = data.split.clone(); let executable = split_command[0].as_str(); let shell_msg = format!("{}:", shell); eprintln!( "{} {}: {}\n", shell_msg.bold().red(), t!("command-not-found"), executable ); let best_matches = { if executable.contains(std::path::MAIN_SEPARATOR) { let file = best_match_file(executable); if file.is_some() { Some(vec![file.unwrap()]) } else { None } } else { best_matches_path(executable, &data.executables) } }; if let Some(best_matches) = best_matches { for best_match in best_matches { split_command[0] = best_match; let suggest = split_command.join(" "); data.candidates.push(suggest); } suggestions::select_candidate(data); let status = suggestions::confirm_suggestion(data); if status.is_err() { let suggest = data.suggest.clone().unwrap(); data.update_command(&suggest); let msg = Some(status.err().unwrap()); data.update_error(msg); let retry_message = format!("{}...", t!("retry")); eprintln!("\n{}\n", retry_message.cyan().bold()); suggestion(data); } } else { let package_manager = match system::get_package_manager(data) { Some(package_manager) => match package_manager.as_str() { "apt" => { let cnf_dirs = [ "/usr/lib/", "/data/data/com.termux/files/usr/libexec/termux/", ]; let mut package_manager = package_manager; for bin_dir in &cnf_dirs { let bin = format!("{}{}", bin_dir, "command-not-found"); if Path::new(&bin).exists() { package_manager = bin; break; } } package_manager } _ => package_manager, }, None => { return; } }; #[cfg(debug_assertions)] eprintln!("package_manager: {}", package_manager); let packages = match system::get_packages(data, &package_manager, executable) { Some(packages) => packages, None => { eprintln!("{} {}", "pay-respects:".red(), t!("package-not-found")); return; } }; #[cfg(debug_assertions)] eprintln!("packages: {:?}", packages); let style = ui::Styled::default(); let render_config = ui::RenderConfig::default() .with_prompt_prefix(style) .with_highlighted_option_prefix(ui::Styled::new(">").with_fg(Color::LightBlue)) .with_scroll_up_prefix(ui::Styled::new("^")) .with_scroll_down_prefix(ui::Styled::new("v")) .with_option_index_prefix(ui::IndexPrefix::SpacePadded); let msg = format!("{}:", t!("install-package")).bold().blue(); let confirm = format!("[{}]", t!("confirm-yes")).green(); let hint = format!("{} {} {}", "[↑/↓/j/k]".blue(), confirm, "[ESC]".red()); eprintln!("{}", msg); eprintln!("{}", hint); let package = Select::new("\n", packages) .with_vim_mode(true) .without_help_message() .with_render_config(render_config) .without_filtering() .prompt() .unwrap_or_else(|_| std::process::exit(1)); let install_method = &data.config.package_manager.install_method; if install_method == &config::InstallMethod::Shell { // let the shell handle the installation and place the user in a shell // environment with the package installed println!( "{}", system::shell_package(data, &package_manager, &package) ); return; } // retry after installing package if system::install_package(data, &package_manager, &package) { let status = suggestions::run_suggestion(data, &data.command); if status.success() { shell_evaluated_commands(&shell, &data.command, true); } else { shell_evaluated_commands(&shell, &data.command, false); data.update_error(None); suggestion(data); } } } } pay-respects-0.7.8/core/src/rules.rs000066400000000000000000000007231502240015600173610ustar00rootroot00000000000000use crate::data::Data; use pay_respects_parser::parse_rules; use pay_respects_utils::evals::*; pub fn match_pattern(executable: &str, data: &Data) -> Option> { let error_msg = &data.error; let shell = &data.shell; let last_command = &data.command; let executables = &data.executables; let mut candidates = vec![]; let split = split_command(last_command); parse_rules!("rules"); if candidates.is_empty() { None } else { Some(candidates) } } pay-respects-0.7.8/core/src/shell.rs000066400000000000000000000302031502240015600173320ustar00rootroot00000000000000use askama::Template; use std::process::{exit, Stdio}; use std::collections::HashMap; use std::sync::mpsc::channel; use std::thread; use std::time::Duration; #[cfg(windows)] use pay_respects_utils::files::path_convert; use crate::data::{Data, Mode}; use crate::init::Init; const PRIVILEGE_LIST: [&str; 2] = ["sudo", "doas"]; pub fn elevate(data: &mut Data, command: &mut String) { if is_privileged(command, data) { return; } if data.config.sudo.is_some() { *command = format!("{} {}", data.config.sudo.as_ref().unwrap(), command); return; } for privilege in PRIVILEGE_LIST.iter() { if data.executables.contains(&privilege.to_string()) { *command = format!("{} {}", privilege, command); break; } } } pub fn is_privileged(command: &str, data: &Data) -> bool { if data.config.sudo.is_some() { return command == data.config.sudo.as_ref().unwrap(); } PRIVILEGE_LIST.contains(&command) } pub fn add_candidates_no_dup( command: &str, candidates: &mut Vec, new_candidates: &[String], ) { for candidate in new_candidates { let candidate = candidate.trim(); if candidate.is_empty() { continue; } if candidate != command && !candidates.contains(&candidate.to_string()) { candidates.push(candidate.to_string()); } } } pub fn get_error(shell: &str, command: &str, data: &Data) -> String { let error_msg = std::env::var("_PR_ERROR_MSG"); let error = if let Ok(error_msg) = error_msg { std::env::remove_var("_PR_ERROR_MSG"); error_msg } else { let timeout = data.config.timeout.0; #[cfg(debug_assertions)] eprintln!("timeout: {}", timeout); error_output_threaded(shell, command, timeout) }; error .to_lowercase() .split_whitespace() .collect::>() .join(" ") } pub fn error_output_threaded(shell: &str, command: &str, timeout: u64) -> String { let (sender, receiver) = channel(); thread::scope(|s| { s.spawn(|| { sender .send( std::process::Command::new(shell) .arg("-c") .arg(command) .env("LC_ALL", "C") .output() .expect("failed to execute process"), ) .expect("failed to send output"); }); match receiver.recv_timeout(Duration::from_millis(timeout)) { Ok(output) => match output.stderr.is_empty() { true => String::from_utf8_lossy(&output.stdout).to_string(), false => String::from_utf8_lossy(&output.stderr).to_string(), }, Err(_) => { use colored::*; eprintln!("Timeout while executing command: {}", command.red()); exit(1); } } }) } pub fn command_output(shell: &str, command: &str) -> String { let output = std::process::Command::new(shell) .arg("-c") .arg(command) .env("LC_ALL", "C") .output() .expect("failed to execute process"); let err = String::from_utf8_lossy(&output.stderr); if !err.is_empty() { eprintln!("Error while executing command: {}", command); eprintln!(" {}", err.replace("\n", "\n ")); } String::from_utf8_lossy(&output.stdout).to_string() } pub fn command_output_or_error(shell: &str, command: &str) -> String { let output = std::process::Command::new(shell) .arg("-c") .arg(command) .env("LC_ALL", "C") .output() .expect("failed to execute process"); if !output.stdout.is_empty() { String::from_utf8_lossy(&output.stdout).to_string() } else { String::from_utf8_lossy(&output.stderr).to_string() } } pub fn module_output(data: &Data, module: &str) -> Option> { let shell = &data.shell; let executable = &data.split[0]; let last_command = &data.command; let error_msg = &data.error; let executables = { let exes = data.executables.clone().join(" "); if exes.len() < 100_000 { exes } else { "".to_string() } }; let output = std::process::Command::new(shell) .arg("-c") .arg(module) .env("_PR_COMMAND", executable) .env("_PR_SHELL", shell) .env("_PR_LAST_COMMAND", last_command) .env("_PR_ERROR_MSG", error_msg) .env("_PR_EXECUTABLES", executables) .stderr(Stdio::inherit()) .output() .expect("failed to execute process"); if output.stdout.is_empty() { return None; } let break_holder = "<_PR_BR>"; Some( String::from_utf8_lossy(&output.stdout) .trim_end_matches(break_holder) .split("<_PR_BR>") .map(|s| s.trim().to_string()) .collect::>(), ) } pub fn last_command(shell: &str) -> String { let last_command = match std::env::var("_PR_LAST_COMMAND") { Ok(command) => command, Err(_) => { eprintln!( "{}", t!( "no-env-setup", var = "_PR_LAST_COMMAND", help = "pay-respects -h" ) ); exit(1); } }; match shell { "bash" => last_command, "zsh" => last_command, "fish" => last_command, "nu" => last_command, _ => last_command, } } pub fn run_mode() -> Mode { match std::env::var("_PR_MODE") { Ok(mode) => match mode.as_str() { "suggestion" => Mode::Suggestion, "cnf" => Mode::Cnf, "noconfirm" => Mode::NoConfirm, "echo" => Mode::Echo, _ => { eprintln!("Invalid mode: {}", mode); exit(1); } }, Err(_) => Mode::Suggestion, } } #[allow(clippy::wildcard_in_or_patterns)] pub fn alias_map(shell: &str) -> Option> { let env = std::env::var("_PR_ALIAS"); if env.is_err() { return None; } let env = env.unwrap(); if env.is_empty() { return None; } let mut alias_map = HashMap::new(); match shell { "bash" => { for line in env.lines() { let alias = line.replace("alias ", ""); let (alias, command) = alias.split_once('=').unwrap(); let command = command.trim().trim_matches('\''); alias_map.insert(alias.to_string(), command.to_string()); } } "zsh" => { for line in env.lines() { let (alias, command) = line.split_once('=').unwrap(); let command = command.trim().trim_matches('\''); alias_map.insert(alias.to_string(), command.to_string()); } } "fish" => { for line in env.lines() { let alias = line.replace("alias ", ""); let (alias, command) = alias.split_once(' ').unwrap(); let command = command.trim().trim_matches('\''); alias_map.insert(alias.to_string(), command.to_string()); } } "nu" | _ => { for line in env.lines() { let (alias, command) = line.split_once('=').unwrap(); alias_map.insert(alias.to_string(), command.to_string()); } } } std::env::remove_var("_PR_ALIAS"); Some(alias_map) } pub fn expand_alias(map: &HashMap, command: &str) -> Option { let (command, args) = if let Some(split) = command.split_once(' ') { (split.0, split.1) } else { (command, "") }; map.get(command) .map(|expand| format!("{} {}", expand, args)) } pub fn expand_alias_multiline(map: &HashMap, command: &str) -> Option { let lines = command.lines().collect::>(); let mut expanded = String::new(); let mut expansion = false; for line in lines { if let Some(expand) = expand_alias(map, line) { expanded = format!("{}\n{}", expanded, expand); expansion = true; } else { expanded = format!("{}\n{}", expanded, line); } } if expansion { Some(expanded.trim().to_string()) } else { None } } pub fn initialization(init: &mut Init) { let alias = &init.alias; let cnf = init.cnf; let binary_path = &init.binary_path; let shell = &init.shell; #[derive(Template)] #[template(path = "init.bash", escape = "none")] struct BashTemplate<'a> { alias: &'a str, binary_path: &'a str, cnf: bool, } #[derive(Template)] #[template(path = "init.zsh", escape = "none")] struct ZshTemplate<'a> { alias: &'a str, binary_path: &'a str, cnf: bool, } #[derive(Template)] #[template(path = "init.fish", escape = "none")] struct FishTemplate<'a> { alias: &'a str, binary_path: &'a str, cnf: bool, } #[derive(Template)] #[template(path = "init.ps1", escape = "none")] struct PowershellTemplate<'a> { alias: &'a str, binary_path: &'a str, cnf: bool, } #[derive(Template)] #[template(path = "init.nu", escape = "none")] struct NuTemplate<'a> { alias: &'a str, binary_path: &'a str, } let initialize = match shell.as_str() { "bash" => BashTemplate { alias, binary_path, cnf, } .render() .unwrap(), "zsh" => ZshTemplate { alias, binary_path, cnf, } .render() .unwrap(), "fish" => FishTemplate { alias, binary_path, cnf, } .render() .unwrap(), "pwsh" | "powershell" | "ps" => PowershellTemplate { alias, binary_path, cnf, } .render() .unwrap(), "nu" | "nush" | "nushell" => NuTemplate { alias, binary_path }.render().unwrap(), _ => { eprintln!("{}: {}", t!("unknown-shell"), shell); exit(1); } }; println!("{}", initialize); } pub fn get_shell() -> String { match std::env::var("_PR_SHELL") { Ok(shell) => shell, Err(_) => { eprintln!( "{}", t!("no-env-setup", var = "_PR_SHELL", help = "pay-respects -h") ); std::process::exit(1); } } } #[allow(unused_variables)] pub fn builtin_commands(shell: &str) -> Vec { // TODO: add the commands for each shell // these should cover most of the builtin commands // (maybe with false positives) let builtin = vec![ "alias", "bg", "bind", "break", "builtin", "case", "cd", "command", "compgen", "complete", "continue", "declare", "dirs", "disown", "echo", "enable", "eval", "exec", "exit", "export", "fc", "fg", "getopts", "hash", "help", "history", "if", "jobs", "kill", "let", "local", "logout", "popd", "printf", "pushd", "pwd", "read", "readonly", "return", "set", "shift", "shopt", "source", "suspend", "test", "times", "trap", "type", "typeset", "ulimit", "umask", "unalias", "unset", "until", "wait", "while", "which", ]; builtin.iter().map(|&cmd| cmd.to_string()).collect() } pub fn shell_syntax(shell: &str, command: &str) -> String { #[allow(clippy::single_match)] match shell { "nu" => command.replace("&&\n", ";\n").to_string(), _ => command.to_string(), } } pub fn add_privilege(shell: &str, privilege: &str, command: &str) -> String { if command.contains("&&") || command.contains("||") || command.contains('>') { format!( "{} {} -c \"{}\"", privilege, shell, command.replace("\"", "\\\"") ) } else { format!("{} {}", privilege, command) } } pub fn shell_evaluated_commands(shell: &str, command: &str, success: bool) { let lines = command .lines() .map(|line| line.trim().trim_end_matches(['\\', ';', '|', '&'])) .collect::>(); let cd = if success { let dirs = { let mut dirs = Vec::new(); for line in lines { if let Some(dir) = line.strip_prefix("cd ") { dirs.push(dir.to_string()); } } dirs.join("") }; if dirs.is_empty() { None } else { Some(dirs.to_string()) } } else { None }; #[derive(Template)] #[template(path = "eval.bash", escape = "none")] struct BashTemplate<'a> { command: &'a str, cd: Option<&'a str>, } #[derive(Template)] #[template(path = "eval.zsh", escape = "none")] struct ZshTemplate<'a> { command: &'a str, cd: Option<&'a str>, } #[derive(Template)] #[template(path = "eval.fish", escape = "none")] struct FishTemplate<'a> { command: &'a str, cd: Option<&'a str>, } #[derive(Template)] #[template(path = "eval.nu", escape = "none")] struct NuTemplate<'a> { cd: Option<&'a str>, } #[derive(Template)] #[template(path = "eval.sh", escape = "none")] struct GenericTemplate<'a> { cd: Option<&'a str>, } let print = match shell { "bash" => { let command = command .replace("$", "\\$") .replace("`", "\\`") .replace("\"", "\\\""); let template = BashTemplate { command: &command, cd: cd.as_deref(), }; template.render().unwrap() } "zsh" => { let command = command .replace("$", "\\$") .replace("`", "\\`") .replace("\"", "\\\""); let template = ZshTemplate { command: &command, cd: cd.as_deref(), }; template.render().unwrap() } "fish" => { let command = command .replace("$", "\\$") .replace("`", "\\`") .replace("\"", "\\\""); let template = FishTemplate { command: &command, cd: cd.as_deref(), }; template.render().unwrap() } "nu" => { let template = NuTemplate { cd: cd.as_deref() }; template.render().unwrap() } _ => { let template = GenericTemplate { cd: cd.as_deref() }; template.render().unwrap() } }; let print = print.trim(); if !print.is_empty() { println!("{}", print); } } pay-respects-0.7.8/core/src/style.rs000066400000000000000000000045071502240015600173730ustar00rootroot00000000000000use crate::data::Data; use crate::shell::is_privileged; use colored::*; use pay_respects_utils::evals::split_command; // to_string() is necessary here, otherwise there won't be color in the output #[warn(clippy::unnecessary_to_owned)] pub fn highlight_difference(data: &Data, suggested_command: &str) -> Option { // let replaced_newline = suggested_command.replace('\n', r" {{newline}} "); let shell = &data.shell; let last_command = &data.command; let mut split_suggested_command = split_command(suggested_command); let split_last_command = split_command(last_command); if split_suggested_command == split_last_command { return None; } if split_suggested_command.is_empty() { return None; } let privileged = is_privileged(&split_suggested_command[0], data); let mut old_entries = Vec::new(); for command in &split_suggested_command { if command.is_empty() { continue; } for old in split_last_command.clone() { if command == &old { old_entries.push(command.clone()); break; } } } // let mut highlighted = suggested_command.to_string(); 'next: for entry in split_suggested_command.iter_mut() { if entry == "\n" { continue; } for old in &old_entries { if old == entry { *entry = entry.blue().to_string(); continue 'next; } } *entry = entry.red().bold().to_string(); } if privileged && (suggested_command.contains("&&") || suggested_command.contains("||") || suggested_command.contains('>')) { split_suggested_command[1] = format!("{} -c \"", shell).red().bold().to_string() + &split_suggested_command[1]; let len = split_suggested_command.len() - 1; split_suggested_command[len] = split_suggested_command[len].clone() + "\"".red().bold().to_string().as_str(); } if let Some(sudo) = data.privilege.clone() { if suggested_command.contains("&&") || suggested_command.contains("||") || suggested_command.contains('>') { split_suggested_command[0] = format!("{} -c \"", shell).blue().to_string() + &split_suggested_command[0]; let len = split_suggested_command.len() - 1; split_suggested_command[len] = split_suggested_command[len].clone() + "\"".blue().to_string().as_str(); } split_suggested_command.insert(0, sudo.blue().to_string()); } let highlighted = split_suggested_command.join(" "); Some(highlighted.replace(" \n ", "\n")) } pay-respects-0.7.8/core/src/suggestions.rs000066400000000000000000000146651502240015600206130ustar00rootroot00000000000000use std::io::stderr; use std::process::{exit, Stdio}; use std::thread; use std::time::{Duration, Instant}; use colored::Colorize; use inquire::*; use ui::Color; use crate::config; use crate::data::Data; use crate::rules::match_pattern; use crate::shell::{ add_candidates_no_dup, add_privilege, module_output, shell_evaluated_commands, shell_syntax, }; use crate::style::highlight_difference; pub fn suggest_candidates(data: &mut Data) { if data.split.is_empty() { return; } let shell = &data.shell; let executable = &data.split[0] .rsplit(std::path::MAIN_SEPARATOR) .next() .unwrap(); let command = &data.command; let privilege = &data.privilege; let mut suggest_candidates = vec![]; let mut module_candidates = vec![]; let mut final_candidates = vec![]; let modules = &data.modules; let fallbacks = &data.fallbacks; #[cfg(debug_assertions)] { eprintln!("/// suggest_candidates"); eprintln!("split: {:?}", data.split); eprintln!("command: {command}"); eprintln!("privilege: {privilege:?}"); eprintln!("modules: {modules:?}"); eprintln!("fallbacks: {fallbacks:?}"); } thread::scope(|s| { s.spawn(|| { for module in modules { let new_candidates = module_output(data, module); if let Some(candidates) = new_candidates { add_candidates_no_dup(command, &mut module_candidates, &candidates); } } }); if let Some(candidates) = match_pattern(executable, data) { add_candidates_no_dup(command, &mut suggest_candidates, &candidates); } if let Some(candidates) = match_pattern("_PR_general", data) { add_candidates_no_dup(command, &mut suggest_candidates, &candidates); } if privilege.is_none() { if let Some(candidates) = match_pattern("_PR_privilege", data) { add_candidates_no_dup(command, &mut suggest_candidates, &candidates); } } }); if !module_candidates.is_empty() { add_candidates_no_dup(command, &mut final_candidates, &module_candidates); } if !suggest_candidates.is_empty() { add_candidates_no_dup(command, &mut final_candidates, &suggest_candidates); } if !final_candidates.is_empty() { data.candidates = final_candidates .iter() .map(|s| shell_syntax(shell, s)) .collect(); return; } for fallback in fallbacks { let candidates = module_output(data, fallback); if candidates.is_some() { add_candidates_no_dup(command, &mut final_candidates, &candidates.unwrap()); data.candidates = final_candidates .iter() .map(|s| shell_syntax(shell, s)) .collect(); return; } } } pub fn select_candidate(data: &mut Data) { let candidates = &data.candidates; #[cfg(debug_assertions)] eprintln!("candidates: {candidates:?}"); let mut highlight_candidates = candidates .iter() .map(|candidate| highlight_difference(data, candidate).unwrap()) .collect::>(); if highlight_candidates.iter().any(|x| x.contains('\n')) { for candidate in highlight_candidates.iter_mut() { *candidate = format!("* {}", candidate.replace("\n", "\n ")); } } let style = ui::Styled::default(); let render_config = ui::RenderConfig::default() .with_prompt_prefix(style) .with_highlighted_option_prefix(ui::Styled::new(">").with_fg(Color::LightBlue)) .with_scroll_up_prefix(ui::Styled::new("^").with_fg(Color::LightBlue)) .with_scroll_down_prefix(ui::Styled::new("v").with_fg(Color::LightBlue)); let msg = format!("{}", t!("multi-suggest", num = candidates.len())) .bold() .blue(); let confirm = format!("[{}]", t!("confirm-yes")).green(); let hint = format!("{} {} {}", "[↑/↓/j/k]".blue(), confirm, "[ESC]".red()); eprintln!("{}", msg); eprint!("{}", hint); let ans = Select::new("\n", highlight_candidates.clone()) .with_vim_mode(true) // .without_filtering() .without_help_message() .with_render_config(render_config) .prompt() .unwrap_or_else(|_| exit(1)); let pos = highlight_candidates.iter().position(|x| x == &ans).unwrap(); let suggestion = candidates[pos].to_string(); data.update_suggest(&suggestion); data.expand_suggest(); data.candidates.clear(); } pub fn confirm_suggestion(data: &Data) -> Result<(), String> { let shell = &data.shell; let command = &data.suggest.clone().unwrap(); #[cfg(debug_assertions)] eprintln!("running command: {command}"); let eval_method = &data.config.eval_method; if eval_method == &config::EvalMethod::Shell { shell_suggestion(data, command); return Ok(()); }; let now = Instant::now(); let process = run_suggestion(data, command); if process.success() { shell_evaluated_commands(shell, command, true); Ok(()) } else { shell_evaluated_commands(shell, command, false); if now.elapsed() > Duration::from_secs(3) { exit(1); } suggestion_err(data, command) } } pub fn run_suggestion(data: &Data, command: &str) -> std::process::ExitStatus { let shell = &data.shell; let privilege = &data.privilege; let command = if let Some(env) = &data.env { format!("{env} {command}") } else { command.to_string() }; match privilege { Some(sudo) => std::process::Command::new(sudo) .arg(shell) .arg("-c") .arg(command) .stdout(stderr()) .stderr(Stdio::inherit()) .status() .expect("failed to execute process"), None => std::process::Command::new(shell) .arg("-c") .arg(command) .stdout(stderr()) .stderr(Stdio::inherit()) .status() .expect("failed to execute process"), } } pub fn shell_suggestion(data: &Data, command: &str) { let shell = &data.shell; let privilege = &data.privilege; let command = if let Some(env) = &data.env { format!("{env} {command}") } else { command.to_string() }; let command = if let Some(privilege) = privilege { add_privilege(shell, privilege, &command) } else { command }; println!("{}", command); } fn suggestion_err(data: &Data, command: &str) -> Result<(), String> { let shell = &data.shell; let privilege = &data.privilege; let command = if let Some(env) = &data.env { format!("{env} {command}") } else { command.to_string() }; let process = match privilege { Some(sudo) => std::process::Command::new(sudo) .arg(shell) .arg("-c") .arg(command) .env("LC_ALL", "C") .output() .expect("failed to execute process"), None => std::process::Command::new(shell) .arg("-c") .arg(command) .env("LC_ALL", "C") .output() .expect("failed to execute process"), }; let error_msg = match process.stderr.is_empty() { true => String::from_utf8_lossy(&process.stdout).to_lowercase(), false => String::from_utf8_lossy(&process.stderr).to_lowercase(), }; Err(error_msg.to_string()) } pay-respects-0.7.8/core/src/system.rs000066400000000000000000000147621502240015600175630ustar00rootroot00000000000000use crate::data::Data; use crate::shell::command_output_or_error; use crate::shell::{command_output, elevate}; use colored::Colorize; use std::io::stderr; use std::process::Command; use std::process::Stdio; pub fn get_package_manager(data: &mut Data) -> Option { if let Ok(package_manager) = std::env::var("_PR_PACKAGE_MANAGER") { if package_manager.is_empty() { return None; } return Some(package_manager); } if let Some(package_manager) = data.config.package_manager.package_manager.as_ref() { if package_manager.is_empty() { return None; } return Some(package_manager.to_string()); } if let Some(package_manager) = option_env!("_DEF_PR_PACKAGE_MANAGER") { if package_manager.is_empty() { return None; } return Some(package_manager.to_string()); } for package_manager in &[ "apt", "dnf", "emerge", "guix", "nix", "pacman", "yum", // "zypper", ] { if data.executables.iter().any(|exe| exe == package_manager) { return Some(package_manager.to_string()); } } None } pub fn get_packages( data: &mut Data, package_manager: &str, executable: &str, ) -> Option> { let shell = &data.shell.clone(); match package_manager { "apt" => { if !data.executables.contains(&"apt-file".to_string()) { eprintln!( "{} apt-file is required to find packages", "pay-respects:".yellow() ); return None; } let result = command_output( shell, &format!("apt-file find --regexp '.*/bin/{}$'", executable), ); if result.is_empty() { return None; } let packages: Vec = result .lines() .map(|line| line.split_once(':').unwrap().0.to_string()) .collect(); if packages.is_empty() { None } else { Some(packages) } } "dnf" | "yum" => { let result = command_output( shell, &format!("{} provides '/usr/bin/{}'", package_manager, executable), ); if result.is_empty() { return None; } let packages: Vec = result .lines() .map(|line| line.split_whitespace().next().unwrap().to_string()) .collect(); if packages.is_empty() { None } else { Some(packages) } } "emerge" => { if !data.executables.contains(&"e-file".to_string()) { eprintln!( "{} pfl is required to find packages", "pay-respects:".yellow() ); return None; } let result = command_output(shell, &format!("e-file /usr/bin/{}", executable)); if result.is_empty() { return None; } let mut packages = vec![]; for line in result.lines() { if !line.starts_with(" ") { packages.push(line.to_string()); } } if packages.is_empty() { None } else { Some(packages) } } "guix" => { let result = command_output(shell, &format!("{} locate {}", package_manager, executable)); if result.is_empty() { return None; } let packages: Vec = result .lines() .map(|line| line.split_whitespace().next().unwrap().to_string()) .collect(); if packages.is_empty() { None } else { Some(packages) } } "nix" => { if !data.executables.contains(&"nix-locate".to_string()) { eprintln!( "{} nix-index is required to find packages", "pay-respects:".yellow() ); return None; } let result = command_output(shell, &format!("nix-locate --regex 'bin/{}$'", executable)); if result.is_empty() { return None; } let packages: Vec = result .lines() .map(|line| { line.split_whitespace() .next() .unwrap() .rsplit_once('.') .unwrap() .0 .to_string() }) .collect(); if packages.is_empty() { None } else { Some(packages) } } "pacman" => { let result = if data.executables.contains(&"pkgfile".to_string()) { command_output(shell, &format!("pkgfile -b {}", executable)) } else { command_output(shell, &format!("pacman -Fq /usr/bin/{}", executable)) }; if result.is_empty() { return None; } let packages: Vec = result .lines() .map(|line| line.split_whitespace().next().unwrap().to_string()) .collect(); if packages.is_empty() { None } else { Some(packages) } } _ => match package_manager.ends_with("command-not-found") { true => { let result = command_output_or_error(shell, &format!("{} {}", package_manager, executable)); if result.is_empty() { return None; } if result.contains("did you mean") || result.contains("is not installed") { let packages = result .lines() .skip(1) .map(|line| line.trim().to_string()) .collect(); return Some(packages); } None } false => { eprintln!("{} Unsupported package manager", "pay-respects:".yellow()); None } }, } } pub fn install_package(data: &mut Data, package_manager: &str, package: &str) -> bool { let shell = &data.shell.clone(); let mut install = match package_manager { "apt" | "dnf" | "pkg" | "yum" | "zypper" => { format!("{} install {}", package_manager, package) } "emerge" => format!("emerge {}", package), "guix" => format!("guix package -i {}", package), "nix" => format!("nix profile install nixpkgs#{}", package), "pacman" => format!("pacman -S {}", package), _ => match package_manager.ends_with("command-not-found") { true => match package.starts_with("Command ") { false => package.to_string(), true => { let split = package.split_whitespace().collect::>(); let command = split[1]; let package = split[split.len() - 1]; let new_command = data.command.clone().replacen(&data.split[0], command, 1); data.update_command(&new_command); format!("apt install {}", package) } }, false => unreachable!("Unsupported package manager"), }, }; // guix and nix do not require privilege escalation #[allow(clippy::single_match)] match package_manager { "guix" | "nix" => {} _ => elevate(data, &mut install), } #[cfg(debug_assertions)] eprintln!("install: {}", install); let result = Command::new(shell) .arg("-c") .arg(install) .stdout(stderr()) .stderr(Stdio::inherit()) .status() .expect("failed to execute process"); result.success() } pub fn shell_package(data: &Data, package_manager: &str, package: &str) -> String { let command = data.command.clone(); match package_manager { "guix" => format!("guix shell {} -- {}", package, command), "nix" => format!( r#"nix-shell -p {} --command "{};return""#, package, command ), _ => unreachable!("Only `nix` and `guix` are supported for shell installation"), } } pay-respects-0.7.8/core/templates/000077500000000000000000000000001502240015600170665ustar00rootroot00000000000000pay-respects-0.7.8/core/templates/eval.bash000066400000000000000000000001261502240015600206530ustar00rootroot00000000000000history -s "{{ command }}"; {%- if let Some(cd) = self.cd %} cd {{ cd }} {% endif %} pay-respects-0.7.8/core/templates/eval.fish000066400000000000000000000001711502240015600206670ustar00rootroot00000000000000builtin history append "{{ command }}"; builtin history merge; {%- if let Some(cd) = self.cd %} cd {{ cd }} {% endif %} pay-respects-0.7.8/core/templates/eval.nu000066400000000000000000000000661502240015600203630ustar00rootroot00000000000000{%- if let Some(cd) = self.cd %} {{ cd }} {% endif %} pay-respects-0.7.8/core/templates/eval.sh000066400000000000000000000000711502240015600203470ustar00rootroot00000000000000{%- if let Some(cd) = self.cd %} cd {{ cd }} {% endif %} pay-respects-0.7.8/core/templates/eval.zsh000066400000000000000000000001241502240015600205400ustar00rootroot00000000000000print -s "{{ command }}"; {%- if let Some(cd) = self.cd %} cd {{ cd }} {% endif %} pay-respects-0.7.8/core/templates/init.bash000066400000000000000000000004261502240015600206720ustar00rootroot00000000000000alias {{ alias }}='eval $(_PR_LAST_COMMAND="$(fc -ln -1)" _PR_ALIAS="`alias`" _PR_SHELL="bash" "{{ binary_path }}")' {%- if cnf %} command_not_found_handle() { eval $(_PR_LAST_COMMAND="$@" _PR_ALIAS="`alias`" _PR_SHELL="bash" _PR_MODE="cnf" "{{ binary_path }}") } {% endif %} pay-respects-0.7.8/core/templates/init.fish000066400000000000000000000006331502240015600207060ustar00rootroot00000000000000function {{ alias }} -d "Suggest fixes to the previous command" eval $(_PR_LAST_COMMAND="$(history | head -n 1)" _PR_ALIAS="$(alias)" _PR_SHELL="fish" "{{ binary_path }}") end {%if cnf %} if status is-interactive function fish_command_not_found --on-event fish_command_not_found eval $(_PR_LAST_COMMAND="$argv" _PR_ALIAS="$(alias)" _PR_SHELL="fish" _PR_MODE="cnf" "{{ binary_path }}") end end {% endif %} pay-respects-0.7.8/core/templates/init.nu000066400000000000000000000004141502240015600203740ustar00rootroot00000000000000def --env {{ alias }} [] { let dir = (with-env { _PR_LAST_COMMAND: (history | last).command, _PR_ALIAS: (help aliases | select name expansion | each ({ |row| $row.name + "=" + $row.expansion }) | str join (char nl)), _PR_SHELL: nu } { {{ binary_path }} }) cd $dir } pay-respects-0.7.8/core/templates/init.ps1000066400000000000000000000030111502240015600204510ustar00rootroot00000000000000function {{ alias }} { try { # fetch command and error from session history only when not in cnf mode if ($env:_PR_MODE -ne 'cnf') { $env:_PR_LAST_COMMAND = (Get-History | Select-Object -Last 1 | ForEach-Object {$_.CommandLine}); if ($PSVersionTable.PSVersion.Major -ge 7) { $err = Get-Error; if ($env:_PR_LAST_COMMAND -eq $err.InvocationInfo.Line) { $env:_PR_ERROR_MSG = $err.Exception.Message } } } $env:_PR_SHELL = 'pwsh'; &'{{ binary_path }}' | Invoke-Expression; } finally { # restore mode from cnf if ($env:_PR_MODE -eq 'cnf') { $env:_PR_MODE = $env:_PR_PWSH_ORIGIN_MODE; $env:_PR_PWSH_ORIGIN_MODE = $null; } } } {%- if cnf %} # Uncomment this block to enable command not found hook # It's not useful as we can't retrieve arguments, # and it seems to be a recursion bug # $ExecutionContext.InvokeCommand.CommandNotFoundAction = # { # param( # [string] # $commandName, # [System.Management.Automation.CommandLookupEventArgs] # $eventArgs # ) # # powershell does not support run command with specific environment variables # # but you must set global variables. so we are memorizing the current mode and the alias function will reset it later. # $env:_PR_PWSH_ORIGIN_MODE=$env:_PR_MODE; # $env:_PR_MODE='cnf'; # # powershell may search command with prefix 'get-' or '.\' first when this hook is hit, strip them # $env:_PR_LAST_COMMAND=$commandName -replace '^get-|\.\\',''; # $eventArgs.Command = (Get-Command {{ alias }}); # $eventArgs.StopSearch = $True; # } {% endif %} pay-respects-0.7.8/core/templates/init.zsh000066400000000000000000000004251502240015600205600ustar00rootroot00000000000000alias {{ alias }}='eval $(_PR_LAST_COMMAND="$(fc -ln -1)" _PR_ALIAS="`alias`" _PR_SHELL="zsh" "{{ binary_path }}")' {%- if cnf %} command_not_found_handler() { eval $(_PR_LAST_COMMAND="$@" _PR_SHELL="zsh" _PR_ALIAS="`alias`" _PR_MODE="cnf" "{{ binary_path }}") } {% endif %} pay-respects-0.7.8/flake.lock000066400000000000000000000010671502240015600161000ustar00rootroot00000000000000{ "nodes": { "nixpkgs": { "locked": { "lastModified": 1733759999, "narHash": "sha256-463SNPWmz46iLzJKRzO3Q2b0Aurff3U1n0nYItxq7jU=", "owner": "nixos", "repo": "nixpkgs", "rev": "a73246e2eef4c6ed172979932bc80e1404ba2d56", "type": "github" }, "original": { "owner": "nixos", "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "nixpkgs": "nixpkgs" } } }, "root": "root", "version": 7 } pay-respects-0.7.8/flake.nix000066400000000000000000000024231502240015600157430ustar00rootroot00000000000000{ inputs = { nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; }; outputs = { self, nixpkgs }: let inherit (nixpkgs.lib) genAttrs importTOML licenses cleanSource ; eachSystem = f: genAttrs [ "aarch64-darwin" "aarch64-linux" "x86_64-darwin" "x86_64-linux" ] (system: f nixpkgs.legacyPackages.${system}); in { formatter = eachSystem (pkgs: pkgs.nixfmt-rfc-style); packages = eachSystem ( pkgs: let cargoPackage = (importTOML (src + "/core/Cargo.toml")).package; src = cleanSource self; inherit (pkgs) rustPlatform versionCheckHook ; in { default = rustPlatform.buildRustPackage { pname = cargoPackage.name; inherit (cargoPackage) version; inherit src; cargoLock.lockFile = src + "/Cargo.lock"; nativeInstallCheckInputs = [ versionCheckHook ]; meta = { inherit (cargoPackage) description homepage; license = licenses.agpl3Plus; mainProgram = "pay-respects"; }; }; } ); }; } pay-respects-0.7.8/init.fish000066400000000000000000000001501502240015600157520ustar00rootroot00000000000000if command -sq zoxide pay-respects fish --alias | source else echo "pay-respects is not in $PATH" end pay-respects-0.7.8/install.sh000066400000000000000000000272021502240015600161450ustar00rootroot00000000000000#!/bin/sh # adapted from zoxide installer # credits: Ajeet D'Souza <98ajeet@gmail.com> main() { # The version of ksh93 that ships with many illumos systems does not support the "local" # extension. Print a message rather than fail in subtle ways later on: if [ "${KSH_VERSION-}" = 'Version JM 93t+ 2010-03-05' ]; then err 'the installer does not work with this ksh93 version; please try bash' fi set -u parse_args "$@" local _arch _arch="${ARCH:-$(ensure get_architecture)}" assert_nz "${_arch}" "arch" echo "Detected architecture: ${_arch}" local _bin_name="pay-respects" local _modules="_pay-respects-module-100-runtime-rules _pay-respects-fallback-100-request-ai" case "${_arch}" in *windows*) _bin_name="${_bin_name}.exe" local _modules_win="" for _module in ${_modules}; do _modules_win="${_modules_win} ${_module}.exe" done _modules="${_modules_win}" ;; *) ;; esac # Create and enter a temporary directory. local _tmp_dir _tmp_dir="$(mktemp -d)" || err "mktemp: could not create temporary directory" cd "${_tmp_dir}" || err "cd: failed to enter directory: ${_tmp_dir}" # Download and extract pay-respects. local _package _package="$(ensure download_pay_respects "${_arch}")" assert_nz "${_package}" "package" echo "Downloaded package: ${_package}" case "${_package}" in *.tar.zst) need_cmd tar ensure tar -xf "${_package}" ;; *.zip) need_cmd unzip ensure unzip -oq "${_package}" ;; *) err "unsupported package format: ${_package}" ;; esac # Install binary. ensure try_sudo mkdir -p -- "${BIN_DIR}" ensure try_sudo cp -- "${_bin_name}" "${BIN_DIR}/${_bin_name}" ensure try_sudo chmod +x "${BIN_DIR}/${_bin_name}" for _module in ${_modules}; do ensure try_sudo cp -- "${_module}" "${BIN_DIR}/${_module}" ensure try_sudo chmod +x "${BIN_DIR}/${_module}" done echo "Installed pay-respects to ${BIN_DIR}" # Print success message and check $PATH. echo "" echo "pay-respects is installed!" if ! echo ":${PATH}:" | grep -Fq ":${BIN_DIR}:"; then echo "Note: ${BIN_DIR} is not on your \$PATH. pay-respects will not work unless it is added to \$PATH." fi } # Parse the arguments passed and set variables accordingly. parse_args() { BIN_DIR_DEFAULT="${HOME}/.local/bin" MAN_DIR_DEFAULT="${HOME}/.local/share/man" SUDO_DEFAULT="sudo" BIN_DIR="${BIN_DIR_DEFAULT}" MAN_DIR="${MAN_DIR_DEFAULT}" SUDO="${SUDO_DEFAULT}" while [ "$#" -gt 0 ]; do case "$1" in --arch) ARCH="$2" && shift 2 ;; --arch=*) ARCH="${1#*=}" && shift 1 ;; --bin-dir) BIN_DIR="$2" && shift 2 ;; --bin-dir=*) BIN_DIR="${1#*=}" && shift 1 ;; --man-dir) MAN_DIR="$2" && shift 2 ;; --man-dir=*) MAN_DIR="${1#*=}" && shift 1 ;; --sudo) SUDO="$2" && shift 2 ;; --sudo=*) SUDO="${1#*=}" && shift 1 ;; -h | --help) usage && exit 0 ;; *) err "Unknown option: $1" ;; esac done } usage() { # heredocs are not defined in POSIX. local _text_heading _text_reset _text_heading="$(tput bold || true 2>/dev/null)$(tput smul || true 2>/dev/null)" _text_reset="$(tput sgr0 || true 2>/dev/null)" local _arch _arch="$(get_architecture || true)" echo "\ ${_text_heading}pay-respects installer${_text_reset} Fetches and installs pay-respects. If pay-respects is already installed, it will be updated to the latest version. ${_text_heading}Usage:${_text_reset} install.sh [OPTIONS] ${_text_heading}Options:${_text_reset} --arch Override the architecture identified by the installer [current: ${_arch}] --bin-dir Override the installation directory [default: ${BIN_DIR_DEFAULT}] --man-dir Override the manpage installation directory [default: ${MAN_DIR_DEFAULT}] --sudo Override the command used to elevate to root privileges [default: ${SUDO_DEFAULT}] -h, --help Print help" } download_pay_respects() { local _arch="$1" if check_cmd curl; then _dld=curl elif check_cmd wget; then _dld=wget else need_cmd 'curl or wget' fi need_cmd grep local _releases_url="https://api.github.com/repos/iffse/pay-respects/releases/latest" local _releases case "${_dld}" in curl) _releases="$(curl -sL "${_releases_url}")" || err "curl: failed to download ${_releases_url}" ;; wget) _releases="$(wget -qO- "${_releases_url}")" || err "wget: failed to download ${_releases_url}" ;; *) err "unsupported downloader: ${_dld}" ;; esac (echo "${_releases}" | grep -q 'API rate limit exceeded') && err "you have exceeded GitHub's API rate limit. Please try again later, or use a different installation method." local _package_url _package_url="$(echo "${_releases}" | grep "browser_download_url" | cut -d '"' -f 4 | grep -- "${_arch}")" || err "unpackaged architecture" local _ext case "${_package_url}" in *.tar.zst) _ext="tar.zst" ;; *.zip) _ext="zip" ;; *) err "unsupported package format: ${_package_url}" ;; esac local _package="pay-respects.${_ext}" case "${_dld}" in curl) _releases="$(curl -sLo "${_package}" "${_package_url}")" || err "curl: failed to download ${_package_url}" ;; wget) _releases="$(wget -qO "${_package}" "${_package_url}")" || err "wget: failed to download ${_package_url}" ;; *) err "unsupported downloader: ${_dld}" ;; esac echo "${_package}" } try_sudo() { if "$@" >/dev/null 2>&1; then return 0 fi need_sudo "${SUDO}" "$@" } need_sudo() { if ! check_cmd "${SUDO}"; then err "\ could not find the command \`${SUDO}\` needed to get permissions for install. If you are on Windows, please run your shell as an administrator, then rerun this script. Otherwise, please run this script as root, or install \`sudo\`." fi if ! "${SUDO}" -v; then err "sudo permissions not granted, aborting installation" fi } # The below functions have been extracted with minor modifications from the # Rustup install script: # # https://github.com/rust-lang/rustup/blob/4c1289b2c3f3702783900934a38d7c5f912af787/rustup-init.sh get_architecture() { local _ostype _cputype _bitness _arch _clibtype _ostype="$(uname -s)" _cputype="$(uname -m)" _clibtype="musl" if [ "${_ostype}" = Linux ]; then if [ "$(uname -o || true)" = Android ]; then _ostype=Android fi fi if [ "${_ostype}" = Darwin ] && [ "${_cputype}" = i386 ]; then # Darwin `uname -m` lies if sysctl hw.optional.x86_64 | grep -q ': 1'; then _cputype=x86_64 fi fi if [ "${_ostype}" = SunOS ]; then # Both Solaris and illumos presently announce as "SunOS" in "uname -s" # so use "uname -o" to disambiguate. We use the full path to the # system uname in case the user has coreutils uname first in PATH, # which has historically sometimes printed the wrong value here. if [ "$(/usr/bin/uname -o || true)" = illumos ]; then _ostype=illumos fi # illumos systems have multi-arch userlands, and "uname -m" reports the # machine hardware name; e.g., "i86pc" on both 32- and 64-bit x86 # systems. Check for the native (widest) instruction set on the # running kernel: if [ "${_cputype}" = i86pc ]; then _cputype="$(isainfo -n)" fi fi case "${_ostype}" in Android) _ostype=linux-android ;; Linux) check_proc _ostype=unknown-linux-${_clibtype} _bitness=$(get_bitness) ;; FreeBSD) _ostype=unknown-freebsd ;; NetBSD) _ostype=unknown-netbsd ;; DragonFly) _ostype=unknown-dragonfly ;; Darwin) _ostype=apple-darwin ;; illumos) _ostype=unknown-illumos ;; MINGW* | MSYS* | CYGWIN* | Windows_NT) _ostype=pc-windows-msvc ;; *) err "unrecognized OS type: ${_ostype}" ;; esac case "${_cputype}" in i386 | i486 | i686 | i786 | x86) _cputype=i686 ;; xscale | arm) _cputype=arm if [ "${_ostype}" = "linux-android" ]; then _ostype=linux-androideabi fi ;; armv6l) _cputype=arm if [ "${_ostype}" = "linux-android" ]; then _ostype=linux-androideabi else _ostype="${_ostype}eabihf" fi ;; armv7l | armv8l) _cputype=armv7 if [ "${_ostype}" = "linux-android" ]; then _ostype=linux-androideabi else _ostype="${_ostype}eabihf" fi ;; aarch64 | arm64) _cputype=aarch64 ;; x86_64 | x86-64 | x64 | amd64) _cputype=x86_64 ;; mips) _cputype=$(get_endianness mips '' el) ;; mips64) if [ "${_bitness}" -eq 64 ]; then # only n64 ABI is supported for now _ostype="${_ostype}abi64" _cputype=$(get_endianness mips64 '' el) fi ;; ppc) _cputype=powerpc ;; ppc64) _cputype=powerpc64 ;; ppc64le) _cputype=powerpc64le ;; s390x) _cputype=s390x ;; riscv64) _cputype=riscv64gc ;; *) err "unknown CPU type: ${_cputype}" ;; esac # Detect 64-bit linux with 32-bit userland if [ "${_ostype}" = unknown-linux-musl ] && [ "${_bitness}" -eq 32 ]; then case ${_cputype} in x86_64) # 32-bit executable for amd64 = x32 if is_host_amd64_elf; then { err "x32 userland is unsupported" }; else _cputype=i686 fi ;; mips64) _cputype=$(get_endianness mips '' el) ;; powerpc64) _cputype=powerpc ;; aarch64) _cputype=armv7 if [ "${_ostype}" = "linux-android" ]; then _ostype=linux-androideabi else _ostype="${_ostype}eabihf" fi ;; riscv64gc) err "riscv64 with 32-bit userland unsupported" ;; *) ;; esac fi # Detect armv7 but without the CPU features Rust needs in that build, # and fall back to arm. # See https://github.com/rust-lang/rustup.rs/issues/587. if [ "${_ostype}" = "unknown-linux-musleabihf" ] && [ "${_cputype}" = armv7 ]; then if ensure grep '^Features' /proc/cpuinfo | grep -q -v neon; then # At least one processor does not have NEON. _cputype=arm fi fi _arch="${_cputype}-${_ostype}" echo "${_arch}" } get_bitness() { need_cmd head # Architecture detection without dependencies beyond coreutils. # ELF files start out "\x7fELF", and the following byte is # 0x01 for 32-bit and # 0x02 for 64-bit. # The printf builtin on some shells like dash only supports octal # escape sequences, so we use those. local _current_exe_head _current_exe_head=$(head -c 5 /proc/self/exe) if [ "${_current_exe_head}" = "$(printf '\177ELF\001')" ]; then echo 32 elif [ "${_current_exe_head}" = "$(printf '\177ELF\002')" ]; then echo 64 else err "unknown platform bitness" fi } get_endianness() { local cputype="$1" local suffix_eb="$2" local suffix_el="$3" # detect endianness without od/hexdump, like get_bitness() does. need_cmd head need_cmd tail local _current_exe_endianness _current_exe_endianness="$(head -c 6 /proc/self/exe | tail -c 1)" if [ "${_current_exe_endianness}" = "$(printf '\001')" ]; then echo "${cputype}${suffix_el}" elif [ "${_current_exe_endianness}" = "$(printf '\002')" ]; then echo "${cputype}${suffix_eb}" else err "unknown platform endianness" fi } is_host_amd64_elf() { need_cmd head need_cmd tail # ELF e_machine detection without dependencies beyond coreutils. # Two-byte field at offset 0x12 indicates the CPU, # but we're interested in it being 0x3E to indicate amd64, or not that. local _current_exe_machine _current_exe_machine=$(head -c 19 /proc/self/exe | tail -c 1) [ "${_current_exe_machine}" = "$(printf '\076')" ] } check_proc() { # Check for /proc by looking for the /proc/self/exe link. # This is only run on Linux. if ! test -L /proc/self/exe; then err "unable to find /proc/self/exe. Is /proc mounted? Installation cannot proceed without /proc." fi } need_cmd() { if ! check_cmd "$1"; then err "need '$1' (command not found)" fi } check_cmd() { command -v -- "$1" >/dev/null 2>&1 } # Run a command that should never fail. If the command fails execution # will immediately terminate with an error showing the failing # command. ensure() { if ! "$@"; then err "command failed: $*"; fi } assert_nz() { if [ -z "$1" ]; then err "found empty string: $2"; fi } err() { echo "Error: $1" >&2 exit 1 } # This is put in braces to ensure that the script does not run until it is # downloaded completely. { main "$@" || exit 1 } pay-respects-0.7.8/module-request-ai/000077500000000000000000000000001502240015600175025ustar00rootroot00000000000000pay-respects-0.7.8/module-request-ai/Cargo.toml000066400000000000000000000014051502240015600214320ustar00rootroot00000000000000[package] name = "pay-respects-module-request-ai" version = "0.2.4" edition = "2021" description = "AI request module for the pay-respects CLI tool" homepage = "https://codeberg.org/iff/pay-respects" repository = "https://github.com/iffse/pay-respects" license = "AGPL-3.0-or-later" include = ["**/*.rs", "templates/*"] [dependencies] colored = "3" sys-locale = "0.3" rust-i18n = "3" serde_json = { version = "1.0" } serde = { version = "1.0", features = ["derive"]} textwrap = "0.16" terminal_size = "0.4" askama = "0.13" reqwest = { version = "0.12", features = ["stream", "json", "rustls-tls"], default-features = false } tokio = { version = "1", features = ["full"] } futures-util = "0.3" [[bin]] name = "_pay-respects-fallback-100-request-ai" path = "src/main.rs" pay-respects-0.7.8/module-request-ai/README.md000066400000000000000000000053261502240015600207670ustar00rootroot00000000000000# Request AI Module Module for [pay-respects](https://codeberg.org/iff/pay-respects) to request AI for suggestions. ## Configurations Configuration is done via environment variables: - `_PR_AI_API_KEY`: Your own API key - `_PR_AI_URL`: Any OpenAI compatible URL can be used, e.g.: - `https://api.openai.com/v1/chat/completions`: OpenAI ChatGPT - `https://api.groq.com/openai/v1/chat/completions`: GroqCloud - `http://localhost:11434/api/chat`: Local Ollama - `_PR_AI_MODEL`: Model used. Reasoning models are also supported - `_PR_AI_DISABLE`: Setting to any value disables AI integration - `_PR_AI_LOCALE`: Locale in which the AI explains the suggestion. Defaults to user system locale. Useful when you use small models that speak only English, for example. - `_PR_AI_ADDITIONAL_PROMPT`: Additional prompts to be included. (Yes, you can include role-playing prompts you pervert) - `User's environment is Zsh running in Arch Linux.` - `You are a cute catgirl. Always use cute phrases and expressions to prove your cuteness in the section, including cat imitations like nya~, にゃ~, 喵~.` Compile time variables: Default values for the respective variables above when not set - `_DEF_PR_AI_API_KEY` - `_DEF_PR_AI_URL` - `_DEF_PR_AI_MODEL` If default values were not provided, pay-respects' own values will be used. Your request will be filtered to avoid abuse usages. Request will then be forwarded to a LLM provider that will not use your data for training. This service is provided free and is not guaranteed to always work. Donations would be appreciated:
Donate using Liberapay Donate using Ko-fi
Donate using Stripe Donate using PayPal
## Advanced Usages For non-trivial suggestions, you can add more context as comments (for Bash and Zsh, interactive comments needs to be explicitly enabled): ```sh pacman -S # how do I install Rust? ``` pay-respects-0.7.8/module-request-ai/i18n/000077500000000000000000000000001502240015600202615ustar00rootroot00000000000000pay-respects-0.7.8/module-request-ai/i18n/i18n.toml000066400000000000000000000011061502240015600217330ustar00rootroot00000000000000_version = 2 [ai-suggestion] en = "Suggestion from AI" es = "Sugerencia de la IA" de = "Vorschlag von KI" fr = "Suggestion de l'IA" it = "Proposta dall'IA" pt = "Sugestão da IA" ru = "Предложение от ИИ" ja = "AIからの提案" ko = "AI 제안" zh = "AI 建议" [ai-thinking] en = "AI is thinking..." es = "La IA está pensando..." de = "KI denkt nach..." fr = "L'IA réfléchit..." it = "L'IA sta pensando..." pt = "A IA está pensando..." ru = "ИИ думает..." ja = "AIが考えています..." ko = "AI가 생각 중입니다..." zh = "AI正在思考..." pay-respects-0.7.8/module-request-ai/src/000077500000000000000000000000001502240015600202715ustar00rootroot00000000000000pay-respects-0.7.8/module-request-ai/src/buffer.rs000066400000000000000000000115171502240015600221150ustar00rootroot00000000000000use std::io::Write; use textwrap::fill as textwrap_fill; fn termwidth() -> usize { use terminal_size::{terminal_size, Height, Width}; let size = terminal_size(); if let Some((Width(w), Height(_))) = size { std::cmp::min(w as usize, 80) } else { 80 } } fn fill(str: &str) -> Option { let width = termwidth(); let filled = textwrap_fill(str, width); if filled.contains('\n') { Some(filled) } else { None } } fn clear_format(str: &str) -> String { let width = termwidth(); let whitespace = " ".repeat(width); let filled = textwrap_fill(str, width); format!("\r{}\r{}", whitespace, filled) } use colored::Colorize; #[derive(PartialEq)] enum State { Write, Think, Buf, } pub struct Buffer { pub buf: String, state: State, } impl Buffer { pub fn new() -> Self { Buffer { buf: String::new(), state: State::Write, } } pub fn proc(&mut self, data: &str) { match self.state { State::Write => self.proc_write(data), State::Think => self.proc_think(data), State::Buf => self.buf.push_str(data), } } pub fn print_return_remain(&mut self) -> String { let buffered = self.buf.trim().to_string(); self.buf.clear(); if self.state == State::Buf { return buffered; } let split = buffered.split_once(""); if let Some((first, last)) = split { eprint!("{}", first); std::io::stdout().flush().unwrap(); return last.to_string(); } "".to_string() } fn proc_write(&mut self, data: &str) { if !data.contains("\n") { self.buf.push_str(data); let buffered = self.buf.trim().to_string(); let filled = fill(&buffered); if let Some(filled) = filled { self.buf.clear(); let formatted = clear_format(&filled); eprint!("{}", formatted); self.buf.push_str(formatted.split_once("\n").unwrap().1); std::io::stdout().flush().unwrap(); return; } eprint!("{}", data); std::io::stdout().flush().unwrap(); return; } let mut data = data.to_string(); while data.contains("\n") { let lines = data.split_once("\n").unwrap(); let first = lines.0; let last = lines.1; self.buf.push_str(first); let buffered = self.buf.trim().to_string(); self.buf.clear(); if buffered.ends_with("") { let warn = format!("{}:", t!("ai-suggestion")) .bold() .blue() .to_string(); let first = buffered.replace("", &warn); eprintln!("\r{}", first); std::io::stdout().flush().unwrap(); } else if buffered.ends_with("") { let tag = ""; let whitespace = " ".repeat(tag.len()); let clear = whitespace.to_string(); let first = buffered.replace("
", &clear); eprintln!("\r{}", first); self.state = State::Buf; std::io::stdout().flush().unwrap(); } else if buffered.ends_with("") { let tag = ""; let warn = format!("{}:", t!("ai-thinking")).bold().blue().to_string(); let first = buffered.replace(tag, &warn); self.state = State::Think; eprintln!("\r{}", first); std::io::stdout().flush().unwrap(); } else if buffered.ends_with("") { let tag = ""; let whitespace = " ".repeat(tag.len()); let clear = whitespace.to_string(); let first = buffered.replace(tag, &clear); eprintln!("\r{}", first); std::io::stdout().flush().unwrap(); } else if buffered.ends_with("```") { let tag = "```"; let whitespace = " ".repeat(tag.len()); let formatted = format!("\r{}", whitespace); let first = buffered.replace(tag, &formatted); eprintln!("{}", first); std::io::stdout().flush().unwrap(); } else { eprintln!("{}", first); std::io::stdout().flush().unwrap(); } data = last.to_string(); } eprint!("{}", data); } fn proc_think(&mut self, data: &str) { if !data.contains("\n") { self.buf.push_str(data); let buffered = self.buf.trim().to_string(); let filled = fill(&buffered); if let Some(filled) = filled { self.buf.clear(); let formatted = clear_format(&filled); eprint!("{}", formatted); self.buf.push_str(formatted.split_once("\n").unwrap().1); std::io::stdout().flush().unwrap(); return; } eprint!("{}", data); std::io::stdout().flush().unwrap(); return; } let mut data = data.to_string(); while data.contains("\n") { let lines = data.split_once("\n").unwrap(); let first = lines.0; let last = lines.1; self.buf.push_str(first); let buffered = self.buf.trim().to_string(); self.buf.clear(); if buffered.ends_with("") { let tag = ""; let whitespace = " ".repeat(tag.len()); let clear = whitespace.to_string(); let first = buffered.replace(tag, &clear); self.state = State::Write; eprintln!("\r{}", first); std::io::stdout().flush().unwrap(); } else { eprintln!("{}", first); std::io::stdout().flush().unwrap(); } data = last.to_string(); } eprint!("{}", data); } } pay-respects-0.7.8/module-request-ai/src/main.rs000066400000000000000000000042221502240015600215630ustar00rootroot00000000000000// pay-respects-ai-module: Request AI suggestions for command errors // Copyright (C) 2024 iff // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . use std::env; use crate::requests::ai_suggestion; use sys_locale::get_locale; mod buffer; mod requests; #[macro_use] extern crate rust_i18n; i18n!("i18n", fallback = "en", minify_key = true); #[tokio::main] async fn main() -> Result<(), std::io::Error> { if std::env::var("_PR_AI_DISABLE").is_ok() { return Ok(()); } let mode = std::env::var("_PR_MODE"); if let Ok(mode) = mode { if mode.as_str() == "noconfirm" { return Ok(()); } } let locale = { let sys_locale = { // use terminal locale if available if let Ok(locale) = env::var("LANG") { locale } else if let Ok(locale) = env::var("LC_ALL") { locale } else if let Ok(locale) = env::var("LC_MESSAGES") { locale } else { get_locale().unwrap_or("en-US".to_string()) } }; if sys_locale.len() < 2 { "en-US".to_string() } else { sys_locale } }; rust_i18n::set_locale(&locale[0..2]); let command = std::env::var("_PR_LAST_COMMAND").expect("_PR_LAST_COMMAND not set"); let error = std::env::var("_PR_ERROR_MSG").expect("_PR_ERROR_MSG not set"); colored::control::set_override(true); #[cfg(debug_assertions)] { eprintln!("last_command: {}", command); eprintln!("error_msg: {}", error); } // skip for commands with no arguments, // very likely to be an error showing the usage if command.split_whitespace().count() == 1 { return Ok(()); } ai_suggestion(&command, &error, &locale).await; Ok(()) } pay-respects-0.7.8/module-request-ai/src/requests.rs000066400000000000000000000125161502240015600225170ustar00rootroot00000000000000use askama::Template; use std::collections::HashMap; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; use crate::buffer; struct Conf { key: String, url: String, model: String, } #[derive(Serialize)] struct Input { role: String, content: String, } #[derive(Serialize)] struct Messages { messages: Vec, model: String, stream: bool, } #[derive(Debug, Deserialize)] pub struct ChatCompletion { // id: String, // object: String, // created: usize, choices: Vec, } #[derive(Debug, Deserialize)] pub struct Choice { delta: Delta, // index: usize, // finish_reason: Option, } #[derive(Debug, Deserialize)] pub struct Delta { content: Option, } #[derive(Template)] #[template(path = "prompt.txt")] struct AiPrompt<'a> { last_command: &'a str, error_msg: &'a str, additional_prompt: &'a str, set_locale: &'a str, } pub async fn ai_suggestion(last_command: &str, error_msg: &str, locale: &str) { let conf = match Conf::new() { Some(conf) => conf, None => { return; } }; let error_msg = if error_msg.len() > 300 { &error_msg[..300] } else { error_msg }; let mut map = HashMap::new(); map.insert("last_command", last_command); map.insert("error_msg", error_msg); let user_locale = { let locale = std::env::var("_PR_AI_LOCALE").unwrap_or_else(|_| locale.to_string()); if locale.len() < 2 { "en-US".to_string() } else { locale } }; let set_locale = if !user_locale.starts_with("en") { format!(". Use language for locale {}", user_locale) } else { "".to_string() }; let addtional_prompt = if std::env::var("_PR_AI_ADDITIONAL_PROMPT").is_ok() { std::env::var("_PR_AI_ADDITIONAL_PROMPT").unwrap() } else { "".to_string() }; let ai_prompt = AiPrompt { last_command, error_msg, additional_prompt: &addtional_prompt, set_locale: &set_locale, } .render() .unwrap() .trim() .to_string(); #[cfg(debug_assertions)] eprintln!("AI module: AI prompt: {}", ai_prompt); // let res; let body = Messages { messages: vec![Input { role: "user".to_string(), content: ai_prompt.trim().to_string(), }], model: conf.model, stream: true, }; let client = reqwest::Client::new(); let res = client .post(&conf.url) .body(serde_json::to_string(&body).unwrap()) .header("Content-Type", "application/json") .bearer_auth(&conf.key) .send() .await .unwrap(); if res.status() != 200 { eprintln!("AI module: Status code: {}", res.status()); eprintln!( "AI module: Error message:\n {}", res.text().await.unwrap().replace("\n", "\n ") ); return; } let mut stream = res.bytes_stream(); let mut json_buffer = String::new(); let mut buffer = buffer::Buffer::new(); while let Some(item) = stream.next().await { let item = item.unwrap(); let str = std::str::from_utf8(&item).unwrap(); if json_buffer.is_empty() { json_buffer.push_str(str); continue; } if !str.contains("\n\ndata: {") { json_buffer.push_str(str); continue; } let data_loc = str.find("\n\ndata: {").unwrap(); let split = str.split_at(data_loc); json_buffer.push_str(split.0); let working_str = json_buffer.clone(); json_buffer.clear(); json_buffer.push_str(split.1); for part in working_str.split("\n\n") { if let Some(data) = part.strip_prefix("data: ") { if data == "[DONE]" { break; } let json = serde_json::from_str::(data).unwrap_or_else(|_| { panic!("AI module: Failed to parse JSON content: {}", data) }); let choice = json.choices.first().expect("AI module: No choices found"); if let Some(content) = &choice.delta.content { buffer.proc(content); } } } } if !json_buffer.is_empty() { let working_str = json_buffer.clone(); for part in working_str.split("\n\n") { if let Some(data) = part.strip_prefix("data: ") { if data == "[DONE]" { break; } let json = serde_json::from_str::(data).unwrap_or_else(|_| { panic!("AI module: Failed to parse JSON content: {}", data) }); let choice = json.choices.first().expect("AI module: No choices found"); if let Some(content) = &choice.delta.content { buffer.proc(content); } } } json_buffer.clear(); } let suggestions = buffer .print_return_remain() .trim() .trim_end_matches("```") .trim() .trim_start_matches("") .trim_end_matches("") .replace("
", "<_PR_BR>"); println!("{}", suggestions); } impl Conf { pub fn new() -> Option { let key = match std::env::var("_PR_AI_API_KEY") { Ok(key) => key, Err(_) => { if let Some(key) = option_env!("_DEF_PR_AI_API_KEY") { key.to_string() } else { "Y29uZ3JhdHVsYXRpb25zLCB5b3UgZm91bmQgdGhlIHNlY3JldCE=".to_string() } } }; if key.is_empty() { return None; } let url = match std::env::var("_PR_AI_URL") { Ok(url) => url, Err(_) => { if let Some(url) = option_env!("_DEF_PR_AI_URL") { url.to_string() } else { "https://iff.envs.net/stream-completions.py".to_string() } } }; if url.is_empty() { return None; } let model = match std::env::var("_PR_AI_MODEL") { Ok(model) => model, Err(_) => { if let Some(model) = option_env!("_DEF_PR_AI_MODEL") { model.to_string() } else { "{{ _PR_AI_MODEL }}".to_string() } } }; if model.is_empty() { return None; } Some(Conf { key, url, model }) } } pay-respects-0.7.8/module-request-ai/templates/000077500000000000000000000000001502240015600215005ustar00rootroot00000000000000pay-respects-0.7.8/module-request-ai/templates/prompt.txt000066400000000000000000000007311502240015600235630ustar00rootroot00000000000000{{ additional_prompt }} `{{ last_command }}` returns the following message: `{{ error_msg }}`. Guess its intention and provide possible shell commands to solve the issue. Provide only commands in the section. Do not include any additional text. No text allowed outside the and sections. Your answer should be in the following format: ``` Explain your suggestions here{{ set_locale }}. command
command
``` pay-respects-0.7.8/module-runtime-rules/000077500000000000000000000000001502240015600202365ustar00rootroot00000000000000pay-respects-0.7.8/module-runtime-rules/Cargo.toml000066400000000000000000000011061502240015600221640ustar00rootroot00000000000000[package] name = "pay-respects-module-runtime-rules" version = "0.1.10" edition = "2021" # for crates.io description = "Runtime rules module for the pay-respects CLI tool" homepage = "https://codeberg.org/iff/pay-respects" repository = "https://github.com/iffse/pay-respects" license = "AGPL-3.0-or-later" include = ["**/*.rs"] [dependencies] regex-lite = "0.1" toml = { version = "0.8" } serde = { version = "1.0", features = ["derive"] } pay-respects-utils = { version = "0.1", path = "../utils" } [[bin]] name = "_pay-respects-module-100-runtime-rules" path = "src/main.rs" pay-respects-0.7.8/module-runtime-rules/README.md000066400000000000000000000014271502240015600215210ustar00rootroot00000000000000# Runtime Rules Module Module for [pay-respects] which allows you to add rules at runtime. Syntax is currently 100% compatible with [upstream's compile-time rules]. [pay-respects]: https://codeberg.org/iff/pay-respects [upstream's compile-time rules]: https://codeberg.org/iff/pay-respects/src/branch/main/rules.md Rules are searched in these directories: - `XDG_CONFIG_HOME`, defaults to `$HOME/.config`. - `XDG_CONFIG_DIRS`, defaults to `/etc/xdg`. - `XDG_DATA_DIRS`, defaults to `/usr/local/share:/usr/share`. The actual rule file should be placed under `pay-respects/rules/`, for example: `~/.config/pay-respects/rules/cargo.toml`. To avoid parsing unnecessary rules, the name of the file **MUST** match the command name. An exception is `_PR_GENERAL.toml` that is always parsed. pay-respects-0.7.8/module-runtime-rules/src/000077500000000000000000000000001502240015600210255ustar00rootroot00000000000000pay-respects-0.7.8/module-runtime-rules/src/main.rs000066400000000000000000000032111502240015600223140ustar00rootroot00000000000000// pay-respects-runtime-module: Runtime parsing of rules // Copyright (C) 2024 iff // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . mod replaces; mod rules; use pay_respects_utils::files::get_path_files; fn main() -> Result<(), std::io::Error> { let executable = std::env::var("_PR_COMMAND").expect("_PR_COMMAND not set"); let shell = std::env::var("_PR_SHELL").expect("_PR_SHELL not set"); let last_command = std::env::var("_PR_LAST_COMMAND").expect("_PR_LAST_COMMAND not set"); let error_msg = std::env::var("_PR_ERROR_MSG").expect("_PR_ERROR_MSG not set"); let executables: Vec = get_path_files(); #[cfg(debug_assertions)] { eprintln!("shell: {}", shell); eprintln!("executable: {}", executable); eprintln!("last_command: {}", last_command); eprintln!("error_msg: {}", error_msg); eprintln!("executables: {:?}", executables); } rules::runtime_match(&executable, &shell, &last_command, &error_msg, &executables); rules::runtime_match( "_PR_GENERAL", &shell, &last_command, &error_msg, &executables, ); Ok(()) } pay-respects-0.7.8/module-runtime-rules/src/replaces.rs000066400000000000000000000142711502240015600231760ustar00rootroot00000000000000use pay_respects_utils::evals::*; fn tag(name: &str, x: i32) -> String { format!("{{{}{}}}", name, x) } pub fn eval_placeholder( string: &str, start: &str, end: &str, ) -> (std::ops::Range, std::ops::Range) { let start_index = string.find(start).unwrap(); let end_index = string[start_index..].find(end).unwrap() + start_index + end.len(); let placeholder = start_index..end_index; let args = start_index + start.len()..end_index - end.len(); (placeholder, args) } pub fn opts(suggest: &mut String, last_command: &mut String, opt_list: &mut Vec<(String, String)>) { let mut replace_tag = 0; let tag_name = "opts"; while suggest.contains(" {{opt::") { let (placeholder, args) = eval_placeholder(suggest, " {{opt::", "}}"); let opt = &suggest[args.to_owned()]; let regex = opt.trim(); let current_tag = tag(tag_name, replace_tag); let opts = { let caps = opt_regex(regex, last_command); if caps.is_empty() { "".to_string() } else { format!(" {}", caps) } }; opt_list.push((current_tag.clone(), opts)); suggest.replace_range(placeholder, ¤t_tag); replace_tag += 1; } } pub fn cmd_reg(suggest: &mut String, last_command: &str) { while suggest.contains("{{cmd::") { let (placeholder, args) = eval_placeholder(suggest, "{{cmd::", "}}"); let regex = suggest[args.to_owned()].trim(); let command = cmd_regex(regex, last_command); suggest.replace_range(placeholder, &command) } } pub fn err(suggest: &mut String, error_msg: &str) { while suggest.contains("{{err::") { let (placeholder, args) = eval_placeholder(suggest, "{{err::", "}}"); let regex = suggest[args.to_owned()].trim(); let command = err_regex(regex, error_msg); suggest.replace_range(placeholder, &command) } } pub fn command(suggest: &mut String, split_command: &[String]) { while suggest.contains("{{command") { let (placeholder, args) = eval_placeholder(suggest, "{{command", "}}"); let range = suggest[args.to_owned()].trim_matches(|c| c == '[' || c == ']'); if let Some((start, end)) = range.split_once(':') { let mut start_index = start.parse::().unwrap_or(0); if start_index < 0 { start_index += split_command.len() as i32; }; let mut end_index; let parsed_end = end.parse::(); if parsed_end.is_err() { end_index = split_command.len() as i32; } else { end_index = parsed_end.unwrap(); if end_index < 0 { end_index += split_command.len() as i32 + 1; } else { end_index += 1; } }; let command = split_command[start_index as usize..end_index as usize].join(" "); suggest.replace_range(placeholder, &command); } else { let range = range.parse::().unwrap_or(0); let command = &split_command[range]; suggest.replace_range(placeholder, command); } } } pub fn typo(suggest: &mut String, split_command: &[String], executables: &[String]) { while suggest.contains("{{typo") { let (placeholder, args) = eval_placeholder(suggest, "{{typo", "}}"); let index = if suggest.contains('[') { let split = suggest[args.to_owned()] .split(&['[', ']']) .collect::>(); let command_index = split[1]; if !command_index.contains(':') { let command_index = command_index.parse::().unwrap(); let index = if command_index < 0 { split_command.len() as i32 + command_index } else { command_index }; index as usize..index as usize + 1 } else { let (start, end) = command_index.split_once(':').unwrap(); let start = start.parse::().unwrap_or(0); let start_index = if start < 0 { split_command.len() as i32 + start } else { start }; let end = end.parse::(); let end_index = if end.is_err() { split_command.len() as i32 } else { let end = end.unwrap(); if end < 0 { split_command.len() as i32 + end + 1 } else { end + 1 } }; start_index as usize..end_index as usize } } else { unreachable!("Typo suggestion must have a command index"); }; let match_list = if suggest.contains('(') { let split = suggest[args.to_owned()] .split_once("(") .unwrap() .1 .rsplit_once(")") .unwrap() .0; split.split(&[',', '\n']).collect::>() } else { unreachable!("Typo suggestion must have a match list"); }; let match_list = match_list .iter() .map(|s| s.trim().to_string()) .collect::>(); let command = suggest_typo(&split_command[index], &match_list, executables); suggest.replace_range(placeholder, &command); } } pub fn select(suggest: &mut String, split_command: &[String], select_list: &mut Vec) { if suggest.contains("{{select") { let (placeholder, args) = eval_placeholder(suggest, "{{select", "}}"); let _ = if suggest.contains('[') { let split = suggest[args.to_owned()] .split(&['[', ']']) .collect::>(); let command_index = split[1]; if !command_index.contains(':') { let command_index = command_index.parse::().unwrap(); let index = if command_index < 0 { split_command.len() as i32 + command_index } else { command_index }; index as usize } else { unreachable!("Select suggestion does not support range"); } } else { 0 }; let selection_list = if suggest.contains('(') { let split = suggest[args.to_owned()] .split_once("(") .unwrap() .1 .rsplit_once(")") .unwrap() .0; split.split(&[',', '\n']).collect::>() } else { unreachable!("Select suggestion must have a match list"); }; let selection_list = selection_list .iter() .map(|s| s.trim().to_string()) .collect::>(); let selects = selection_list; for match_ in selects { select_list.push(match_); } let tag = "{{selection}}"; let placeholder = suggest[placeholder.clone()].to_owned(); *suggest = suggest.replace(&placeholder, tag); } } pub fn shell(suggest: &mut String, shell: &str) { while suggest.contains("{{shell") { let (placeholder, args) = eval_placeholder(suggest, "{{shell", "}}"); let range = suggest[args.to_owned()].trim_matches(|c| c == '(' || c == ')'); let command = eval_shell_command(shell, range); suggest.replace_range(placeholder, &command.join("\n")); } } pay-respects-0.7.8/module-runtime-rules/src/rules.rs000066400000000000000000000125041502240015600225270ustar00rootroot00000000000000use crate::replaces; use pay_respects_utils::evals::*; #[derive(serde::Deserialize)] struct Rule { match_err: Vec, } #[derive(serde::Deserialize)] struct MatchError { pattern: Vec, suggest: Vec, } pub fn runtime_match( executable: &str, shell: &str, last_command: &str, error_msg: &str, executables: &[String], ) { let file = get_rule(executable); if file.is_none() { return; } let file = std::fs::read_to_string(file.unwrap()).unwrap(); let rule: Rule = toml::from_str(&file).unwrap(); let split_command = split_command(last_command); let mut pure_suggest; for match_err in rule.match_err { for pattern in match_err.pattern { if error_msg.contains(&pattern) { 'suggest: for suggest in &match_err.suggest { if suggest.starts_with('#') { let mut lines = suggest.lines().collect::>(); let mut conditions = String::new(); for (i, line) in lines[0..].iter().enumerate() { conditions.push_str(line); if line.ends_with(']') { lines = lines[i + 1..].to_vec(); break; } } let conditions = conditions .trim_start_matches(['#', '[']) .trim_end_matches(']') .split(',') .collect::>(); for condition in conditions { let (mut condition, arg) = condition.split_once('(').unwrap(); condition = condition.trim(); let arg = arg .to_string() .chars() .take(arg.len() - 1) .collect::(); let reverse = match condition.starts_with('!') { true => { condition = condition.trim_start_matches('!'); true } false => false, }; if eval_condition( condition, &arg, shell, last_command, error_msg, &split_command, executables, ) == reverse { continue 'suggest; } } pure_suggest = lines.join("\n").to_owned(); } else { pure_suggest = suggest.to_owned(); } // replacing placeholders if pure_suggest.contains("{{command}}") { pure_suggest = pure_suggest.replace("{{command}}", last_command); } let suggests = eval_suggest(&pure_suggest, last_command, error_msg, executables, shell); for suggest in suggests { print!("{}", suggest); print!("<_PR_BR>"); } } break; } } } } fn eval_condition( condition: &str, arg: &str, shell: &str, last_command: &str, error_msg: &str, split_command: &[String], executables: &[String], ) -> bool { match condition { "executable" => executables.contains(&arg.to_string()), "err_contains" => regex_match(arg, error_msg), "cmd_contains" => regex_match(arg, last_command), "min_length" => split_command.len() >= arg.parse::().unwrap(), "length" => split_command.len() == arg.parse::().unwrap(), "max_length" => split_command.len() <= arg.parse::().unwrap() + 1, "shell" => shell == arg, _ => unreachable!("Unknown condition when evaluation condition: {}", condition), } } fn eval_suggest( suggest: &str, last_command: &str, error_msg: &str, executables: &[String], shell: &str, ) -> Vec { let mut suggest = suggest.to_owned(); if suggest.contains("{{command}}") { suggest = suggest.replace("{{command}}", "{last_command}"); } let mut last_command = last_command.to_owned(); let mut opt_list = Vec::new(); replaces::opts(&mut suggest, &mut last_command, &mut opt_list); let split_command = split_command(&last_command); replaces::cmd_reg(&mut suggest, &last_command); replaces::err(&mut suggest, error_msg); replaces::command(&mut suggest, &split_command); replaces::shell(&mut suggest, shell); replaces::typo(&mut suggest, &split_command, executables); let mut select_list = Vec::new(); replaces::select(&mut suggest, &split_command, &mut select_list); for (tag, value) in opt_list { suggest = suggest.replace(&tag, &value); } let mut suggests = vec![]; if select_list.is_empty() { suggests.push(suggest); } else { for selection in select_list { let eval_suggest = suggest.clone().replace("{{selection}}", &selection); suggests.push(eval_suggest); } } suggests } fn get_rule(executable: &str) -> Option { #[cfg(windows)] let xdg_config_home = std::env::var("APPDATA").unwrap(); #[cfg(not(windows))] let xdg_config_home = std::env::var("XDG_CONFIG_HOME") .unwrap_or_else(|_| std::env::var("HOME").unwrap() + "/.config"); let check_dirs = |dirs: &[&str]| -> Option { for dir in dirs { let rule_dir = format!("{}/pay-respects/rules", dir); let rule_file = format!("{}/{}.toml", rule_dir, executable); if std::path::Path::new(&rule_file).exists() { return Some(rule_file); } } None }; if let Some(file) = check_dirs(&[&xdg_config_home]) { return Some(file); } #[cfg(not(windows))] { let xdg_config_dirs = std::env::var("XDG_CONFIG_DIRS").unwrap_or("/etc/xdg".to_owned()); let xdg_config_dirs = xdg_config_dirs.split(':').collect::>(); if let Some(file) = check_dirs(&xdg_config_dirs) { return Some(file); } let xdg_data_dirs = std::env::var("XDG_DATA_DIRS").unwrap_or("/usr/local/share:/usr/share".to_owned()); let xdg_data_dirs = xdg_data_dirs.split(':').collect::>(); if let Some(file) = check_dirs(&xdg_data_dirs) { return Some(file); } } None } pay-respects-0.7.8/modules.md000066400000000000000000000110361502240015600161330ustar00rootroot00000000000000# Modules `pay-respects` followed a very stupid approach —or better said, *Keep It Simple, Stupid*— when it comes to implementing the module / plugin system: - Modules interacts with core program by passing **messages through processes**. In other words, we are sending necessary information to the module, so it can return the required suggestion. - This approach is the most extendable way, as it has the least amount of limitations compared to: - Dynamic libraries (Safe): Requires the module to be compiled in the same compiler version as the core, which also limits the language available - FFI (Unsafe): Requires overloading of dynamic libraries, limits to C types, and not extendable as it's overloading a library instead of appending - Embedding a runtime: Unnecessary binary sizes if never used - `pay-respects` takes the message passing approach as its core is blazing fast without observable delay so having a small overhead is acceptable. This allows: - **Modules in any language**: Regardless of compiled binary or interpreted scripts, just make them executable and that's a module! - **Extendable**: As many modules as you want - **Performance or ease? Both!**: Write in a compiled language if it's something computational heavy, or just use a shell script as module right away ## Creating a Module There are 2 types of modules: - **Standard module**: Will always run to retrieve suggestions - Naming convention: `_pay-respects-module--` - **Fallback module**: Will only be run if no previous suggestion were found - **CAUTION**: Will immediately return if a suggestion is obtained - Naming convention: `_pay-respects-fallback--` Priority is used to retrieve suggestions in a specific order by an [unstable sort](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable). Default modules have a priority of `100`. When running your module, you will get the following environment variables: - `_PR_SHELL`: User shell - `_PR_COMMAND`: The command, without arguments - `_PR_LAST_COMMAND`: Full command with arguments - `_PR_ERROR_MSG`: Error message from the command - `_PR_EXECUTABLES`: A space (` `) separated list of executables in `PATH`. Limited to 100k characters, empty if exceeded. Your module should print: - **To `stdout`**: Only suggestions. - At the end of each suggestion, append `<_PR_BR>` so pay-respects knows you are either done or adding another suggestion - **To `stderr`**: Any relevant information that should display to the user (e.g, warning for AI generated content) An example of a shell based module that always suggest adding a `sudo` or `doas`: ```sh #!/bin/sh echo "sudo $_PR_LAST_COMMAND" echo "<_PR_BR>" echo "doas $_PR_LAST_COMMAND" ``` ## Adding a Module Expose your module as executable (`chmod u+x`) in `PATH`, and done! ## `LIB` directories If exposing modules in `PATH` annoys you, you can set the `_PR_LIB` environment variable to specify directories to find the modules, separated by `:` or `;` (analogous to `PATH`): Example in a [FHS 3.0 compliant system](https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s06.html): ```shell # compile-time export _DEF_PR_LIB="/usr/lib" # runtime export _PR_LIB="/usr/lib:$HOME/.local/share" ``` Example in Windows/DOS compliant systems ```pwsh $env:_PR_LIB = @( (Join-Path $env:APPDATA "pay-respects" "modules"), (Join-Path $env:USERPROFILE ".cargo" "bin") ) -join ';' ``` This is not the default as there is no general way to know its value and depends on distribution (`/usr/lib`, `/usr/libexec`, or NixOS which isn't FHS compliant at all). System programs usually have a hard-coded path looking for `lib`. If you are a package maintainer for a distribution, setting this value when compiling, so it fits into your distribution standard. If you installed the module with `cargo install`, the binary will be placed in `bin` subdirectory under Cargo's home which should be in the `PATH` anyway. Cargo has no option to place in subdirectories with other names. The following snippet is what I have included into Arch Linux's package with workflows binaries, adding a `_PR_LIB` declaration along with initialization. The script is `/usr/bin/pay-respects` and the actual executable is located somewhere else. ```sh #!/bin/sh if [ "$#" -gt 1 ] && [ -z "$_PR_LIB" ]; then SHELL=$(basename $SHELL) LIB="/usr/lib/pay-respects" if [ "$SHELL" = "nu" ]; then echo "env:_PR_LIB=$LIB" elif [[ "$SHELL" = "pwsh" ]]; then echo "\$env:_PR_LIB=\"$LIB\"" else echo "export _PR_LIB=$LIB" fi fi /opt/pay-respects/bin/pay-respects "$@" ``` pay-respects-0.7.8/parser/000077500000000000000000000000001502240015600154345ustar00rootroot00000000000000pay-respects-0.7.8/parser/Cargo.toml000066400000000000000000000006521502240015600173670ustar00rootroot00000000000000[package] name = "pay-respects-parser" version = "0.3.9" edition = "2021" # for crates.io description = "Compile time rule parser for the pay-respects CLI tool" repository = "https://github.com/iffse/pay-respects" license = "MPL-2.0" include = [ "**/*.rs", "**/*.toml", ] [lib] proc-macro = true [dependencies] syn = "2.0" quote = "1.0" proc-macro2 = "1.0" toml = "0.8" serde = { version = "1.0", features = ["derive"] } pay-respects-0.7.8/parser/src/000077500000000000000000000000001502240015600162235ustar00rootroot00000000000000pay-respects-0.7.8/parser/src/lib.rs000066400000000000000000000140111502240015600173340ustar00rootroot00000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use std::path::Path; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; mod replaces; #[proc_macro] pub fn parse_rules(input: TokenStream) -> TokenStream { let rules = get_rules(input.to_string().trim_matches('"')); gen_match_rules(&rules) } #[derive(serde::Deserialize)] struct Rule { command: String, match_err: Vec, } #[derive(serde::Deserialize)] struct MatchError { pattern: Vec, suggest: Vec, } fn get_rules(directory: &str) -> Vec { let files = std::fs::read_dir(directory).expect("Failed to read directory."); let mut rules = Vec::new(); for file in files { let file = file.expect("Failed to read file."); let path = file.path(); let path = path.to_str().expect("Failed to convert path to string."); let rule_file = parse_file(Path::new(path)); rules.push(rule_file); } rules } fn gen_match_rules(rules: &[Rule]) -> TokenStream { let command = rules .iter() .map(|x| x.command.to_owned()) .collect::>(); let command_matches = rules .iter() .map(|x| { x.match_err .iter() .map(|x| { let pattern = x .pattern .iter() .map(|x| x.to_lowercase()) .collect::>(); let suggests = x .suggest .iter() .map(|x| x.to_string()) .collect::>(); (pattern, suggests) }) .collect::, Vec)>>() }) .collect::, Vec)>>>(); let mut matches_tokens = Vec::new(); for match_err in command_matches { let mut suggestion_tokens = Vec::new(); let mut patterns_tokens = Vec::new(); for (pattern, suggests) in match_err { // let mut match_condition = Vec::new(); let mut pattern_suggestions = Vec::new(); for suggest in suggests { let (suggestion_no_condition, conditions) = parse_conditions(&suggest); let suggest = eval_suggest(&suggestion_no_condition); let suggestion = quote! { if #(#conditions)&&* { #suggest; }; }; pattern_suggestions.push(suggestion); } let match_tokens = quote! { #(#pattern_suggestions)* }; suggestion_tokens.push(match_tokens); let string_patterns = pattern.join("\", \""); let string_patterns: TokenStream2 = format!("[\"{}\"]", string_patterns).parse().unwrap(); patterns_tokens.push(string_patterns); } matches_tokens.push(quote! { #( for pattern in #patterns_tokens { if error_msg.contains(pattern) { #suggestion_tokens; break; }; })* }) } quote! { let mut last_command = last_command.to_string(); match executable { #( #command => { #matches_tokens } )* _ => {} }; } .into() } fn parse_file(file: &Path) -> Rule { let file = std::fs::read_to_string(file).expect("Failed to read file."); toml::from_str(&file).expect("Failed to parse toml.") } fn parse_conditions(suggest: &str) -> (String, Vec) { let mut eval_conditions = Vec::new(); if suggest.starts_with('#') { let mut lines = suggest.lines().collect::>(); let mut conditions = String::new(); for (i, line) in lines[0..].iter().enumerate() { conditions.push_str(line); if line.ends_with(']') { lines = lines[i + 1..].to_vec(); break; } } let conditions = conditions .trim_start_matches(['#', '[']) .trim_end_matches(']') .split(',') .collect::>(); for condition in conditions { let (mut condition, arg) = condition.split_once('(').unwrap(); condition = condition.trim(); // remove only the last character which is ')' // other ')' are kept for regex let arg = arg .to_string() .chars() .take(arg.len() - 1) .collect::(); let reverse = match condition.starts_with('!') { true => { condition = condition.trim_start_matches('!'); true } false => false, }; let evaluated_condition = eval_condition(condition, &arg); eval_conditions.push(quote! {#evaluated_condition == !#reverse}); } let suggest = lines.join("\n"); return (suggest, eval_conditions); } (suggest.to_owned(), vec![quote! {true}]) } fn eval_condition(condition: &str, arg: &str) -> TokenStream2 { match condition { "executable" => quote! {executables.contains(&#arg.to_string())}, "err_contains" => quote! {regex_match(#arg, &error_msg)}, "cmd_contains" => quote! {regex_match(#arg, &last_command)}, "min_length" => quote! {(split.len() >= #arg.parse::().unwrap())}, "length" => quote! {(split.len() == #arg.parse::().unwrap())}, "max_length" => quote! {(split.len() <= #arg.parse::().unwrap() + 1)}, "shell" => quote! {(shell == #arg)}, _ => unreachable!("Unknown condition when evaluation condition: {}", condition), } } fn eval_suggest(suggest: &str) -> TokenStream2 { let mut suggest = suggest.to_owned(); if suggest.contains("{{command}}") { suggest = suggest.replace("{{command}}", "{last_command}"); } let mut replace_list = Vec::new(); let mut select_list = Vec::new(); let mut opt_list = Vec::new(); let mut cmd_list = Vec::new(); replaces::opts(&mut suggest, &mut replace_list, &mut opt_list); replaces::cmd_reg(&mut suggest, &mut replace_list); replaces::err(&mut suggest, &mut replace_list); replaces::command(&mut suggest, &mut replace_list); replaces::shell(&mut suggest, &mut cmd_list); replaces::typo(&mut suggest, &mut replace_list); replaces::select(&mut suggest, &mut select_list); replaces::shell_tag(&mut suggest, &mut replace_list, &cmd_list); let suggests = if select_list.is_empty() { quote! { candidates.push(format!{#suggest, #(#replace_list),*}); } } else { quote! { #(#select_list)* let suggest = format!{#suggest, #(#replace_list),*}; for select in selects { let suggest = suggest.replace("{{selection}}", &select); candidates.push(suggest); } } }; quote! { #(#opt_list)* #suggests } } pay-respects-0.7.8/parser/src/replaces.rs000066400000000000000000000235601502240015600203750ustar00rootroot00000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use proc_macro2::TokenStream as TokenStream2; use quote::quote; fn rtag(name: &str, x: i32, y: &str) -> TokenStream2 { format!("{}{} = {}", name, x, y).parse().unwrap() } fn tag(name: &str, x: i32) -> String { format!("{{{}{}}}", name, x) } fn eval_placeholder( string: &str, start: &str, end: &str, ) -> (std::ops::Range, std::ops::Range) { let start_index = string.find(start).unwrap(); let end_index = string[start_index..].find(end).unwrap() + start_index + end.len(); let placeholder = start_index..end_index; let args = start_index + start.len()..end_index - end.len(); (placeholder, args) } pub fn opts( suggest: &mut String, replace_list: &mut Vec, opt_list: &mut Vec, ) { let mut replace_tag = 0; let tag_name = "opts"; while suggest.contains(" {{opt::") { let (placeholder, args) = eval_placeholder(suggest, " {{opt::", "}}"); let opt = &suggest[args.to_owned()]; let regex = opt.trim(); let current_tag = tag(tag_name, replace_tag); let token_tag: TokenStream2 = format!("{}{}", tag_name, replace_tag).parse().unwrap(); let opts = quote! { let caps = opt_regex(#regex, &mut last_command); let #token_tag = { if caps.is_empty() { "".to_string() } else { format!(" {}", caps) } }; }; opt_list.push(opts); replace_list.push(rtag(tag_name, replace_tag, ¤t_tag)); suggest.replace_range(placeholder, ¤t_tag); replace_tag += 1; } if replace_tag > 0 { let split = quote! { let split = split_command(&last_command); }; opt_list.push(split); } } pub fn cmd_reg(suggest: &mut String, replace_list: &mut Vec) { let mut replace_tag = 0; let tag_name = "cmd"; while suggest.contains("{{cmd::") { let (placeholder, args) = eval_placeholder(suggest, "{{cmd::", "}}"); let regex = suggest[args.to_owned()].trim(); let command = format!("cmd_regex(r###\"{}\"###, &last_command)", regex); replace_list.push(rtag(tag_name, replace_tag, &command)); suggest.replace_range(placeholder, &tag(tag_name, replace_tag)); replace_tag += 1; } } pub fn err(suggest: &mut String, replace_list: &mut Vec) { let mut replace_tag = 0; let tag_name = "err"; while suggest.contains("{{err::") { let (placeholder, args) = eval_placeholder(suggest, "{{err::", "}}"); let regex = suggest[args.to_owned()].trim(); let command = format!("err_regex(r###\"{}\"###, error_msg)", regex); replace_list.push(rtag(tag_name, replace_tag, &command)); suggest.replace_range(placeholder, &tag(tag_name, replace_tag)); replace_tag += 1; } } pub fn command(suggest: &mut String, replace_list: &mut Vec) { let mut replace_tag = 0; let tag_name = "command"; while suggest.contains("{{command") { let (placeholder, args) = eval_placeholder(suggest, "{{command", "}}"); let range = suggest[args.to_owned()].trim_matches(|c| c == '[' || c == ']'); if let Some((start, end)) = range.split_once(':') { let mut start_string = start.to_string(); let start = start.parse::().unwrap_or(0); if start < 0 { start_string = format!("split.len() {}", start); }; let end_string; let parsed_end = end.parse::(); if parsed_end.is_err() { end_string = String::from("split.len()"); } else { let end = parsed_end.clone().unwrap(); if end < 0 { end_string = format!("split.len() {}", end + 1); } else { end_string = (end + 1).to_string(); } }; let command = format! {r#"split[{}..{}].join(" ")"#, start_string, end_string}; replace_list.push(rtag(tag_name, replace_tag, &command)); suggest.replace_range(placeholder, &tag(tag_name, replace_tag)); } else { let range = range.parse::().unwrap_or(0); let command = if range < 0 { format!("split[std::cmp::max(split.len() {}, 0)]", range) } else { format!("split[{}]", range) }; replace_list.push(rtag(tag_name, replace_tag, &command)); suggest.replace_range(placeholder, &tag(tag_name, replace_tag)); } replace_tag += 1; } } pub fn typo(suggest: &mut String, replace_list: &mut Vec) { let mut replace_tag = 0; let tag_name = "typo"; while suggest.contains("{{typo") { let (placeholder, args) = eval_placeholder(suggest, "{{typo", "}}"); let string_index = if suggest.contains('[') { let split = suggest[args.to_owned()] .split(&['[', ']']) .collect::>(); let command_index = split[1]; if !command_index.contains(':') { let command_index = command_index.parse::().unwrap(); let index = if command_index < 0 { format!("split.len() {}", command_index) } else { command_index.to_string() }; format!("{}..{} + 1", index, index) } else { let (start, end) = command_index.split_once(':').unwrap(); let start = start.parse::().unwrap_or(0); let start_string = if start < 0 { format!("split.len() {}", start) } else { start.to_string() }; let end = end.parse::(); let end_string = if end.is_err() { String::from("split.len()") } else { let end = end.unwrap(); if end < 0 { format!("split.len() {}", end + 1) } else { (end + 1).to_string() } }; format!("{}..{}", start_string, end_string) } } else { unreachable!("Typo suggestion must have a command index"); }; let match_list = if suggest.contains('(') { let split = suggest[args.to_owned()] .split_once("(") .unwrap() .1 .rsplit_once(")") .unwrap() .0; split.split(',').collect::>() } else { unreachable!("Typo suggestion must have a match list"); }; let match_list = match_list .iter() .map(|s| s.trim().to_string()) .collect::>(); let command = if match_list[0].starts_with("eval_shell_command(") { let function = match_list.join(","); // add a " after first comma, and a " before last ) let function = format!( "{}\"{}{}", &function[..function.find(',').unwrap() + 1], &function[function.find(',').unwrap() + 1..function.len() - 1], "\")" ); format!( "suggest_typo(&split[{}], &{}, executables)", string_index, function ) } else { let string_match_list = match_list.join("\".to_string(), \""); let string_match_list = format!("\"{}\".to_string()", string_match_list); format!( "suggest_typo(&split[{}], &[{}], executables)", string_index, string_match_list ) }; replace_list.push(rtag(tag_name, replace_tag, &command)); suggest.replace_range(placeholder, &tag(tag_name, replace_tag)); replace_tag += 1; } } pub fn select(suggest: &mut String, select_list: &mut Vec) { if suggest.contains("{{select") { let (placeholder, args) = eval_placeholder(suggest, "{{select", "}}"); let index = if suggest.contains('[') { let split = suggest[args.to_owned()] .split(&['[', ']']) .collect::>(); let command_index = split[1]; if !command_index.contains(':') { let command_index = command_index.parse::().unwrap(); if command_index < 0 { quote! {split.len() as usize + #command_index} } else { quote! {#command_index as usize} } } else { unreachable!("Select suggestion does not support range"); } } else { quote! {0} }; let selection_list = if suggest.contains('(') { let split = suggest[args.to_owned()] .split_once("(") .unwrap() .1 .rsplit_once(")") .unwrap() .0; split.split(',').collect::>() } else { unreachable!("Select suggestion must have a selection list"); }; let selection_list = selection_list .iter() .map(|s| s.trim().to_string()) .collect::>(); let command = if selection_list[0].starts_with("eval_shell_command(") { let function = selection_list.join(","); // add a " after first comma, and a " before last ) let function: TokenStream2 = format!( "{}\"{}{}", &function[..function.find(',').unwrap() + 1], &function[function.find(',').unwrap() + 1..function.len() - 1], "\")" ) .parse() .unwrap(); quote! { let selects = #function; } } else if selection_list[0] == "path" { quote! { let selects = { let res = best_matches_path(&split[#index], executables); if res.is_none() { vec![split[#index].clone()] } else { res.unwrap() } }; } } else { let string_match_list = selection_list.join("\".to_string(), \""); let string_match_list = format!("\"{}\".to_string()", string_match_list); quote! { let selects = vec![#string_match_list]; } }; select_list.push(command); let tag = "{{{{selection}}}}"; let placeholder = suggest[placeholder.clone()].to_owned(); *suggest = suggest.replace(&placeholder, tag); } } pub fn shell(suggest: &mut String, cmd_list: &mut Vec) { while suggest.contains("{{shell") { let (placeholder, args) = eval_placeholder(suggest, "{{shell", "}}"); let range = suggest[args.to_owned()].trim_matches(|c| c == '(' || c == ')'); let command = format!("eval_shell_command(shell, {})", range); suggest.replace_range(placeholder, &command); cmd_list.push(command); } } pub fn shell_tag(suggest: &mut String, replace_list: &mut Vec, cmd_list: &[String]) { let mut replace_tag = 0; let tag_name = "shell"; for command in cmd_list { if suggest.contains(command) { *suggest = suggest.replace(command, &tag(tag_name, replace_tag)); let split = command.split_once(',').unwrap(); let argument = split.1.trim_end_matches(')').trim(); let argument = format!("\"{}\"", argument); let function = format!("{}, {}).join(\"\")", split.0, argument); // let function = format!("\"{}, {}\"", split.0, split.1); replace_list.push(rtag(tag_name, replace_tag, &function)); replace_tag += 1; } } } pay-respects-0.7.8/pay-respects.plugin.zsh000066400000000000000000000001711502240015600206010ustar00rootroot00000000000000if (( $+commands[pay-respects] )); then eval "$(pay-respects zsh --alias)" else echo "pay-respects is not in $PATH" fi pay-respects-0.7.8/roadmap.md000066400000000000000000000007471502240015600161150ustar00rootroot00000000000000# Roadmap ## Shell Integrations - ✅: Working - ⚠️: Partial working - ❌: Not implemented / Cannot implement | Feature | Bash | Zsh | Fish | Nush | Pwsh | |-------------------|------|-----|------|------|--------| | Get other alias | ✅ | ✅ | ✅ | ✅ | ❌ | | Command not found | ✅ | ✅ | ✅ | ❌ | ⚠️ [^1] | [^1]: Cannot retrieve arguments. ## Features Pending Implementation - Chained commands (e.g. `echo "1\n2" | grepp "2"`) pay-respects-0.7.8/rules.md000066400000000000000000000110631502240015600156150ustar00rootroot00000000000000# Writing Rules Rule files placed under [rules](./rules) in the project directory are parsed at compilation, everything is parsed to Rust code before compiling. You don't have to know the project structure nor Rust to write blazing fast rules! For compile-time rules, if only rules are changed, cargo won't recompile the project because Rust code were intact. You will have to notify it manually by: ```shell touch core/src/rules.rs && cargo build ``` Runtime-rules support is provided by `runtime-rules` module. Directories are searched with the following priority: - `XDG_CONFIG_HOME`, defaults to `$HOME/.config`. - `XDG_CONFIG_DIRS`, defaults to `/etc/xdg`. - `XDG_DATA_DIRS`, defaults to `/usr/local/share:/usr/share`. The actual rule file should be placed under `pay-respects/rules/`, for example: `~/.config/pay-respects/rules/cargo.toml`. Note that for runtime rules, the name of the file **MUST** match the command name. Except `_PR_GENERAL.toml` that is always parsed ## Syntax Syntax of a rule file: ```toml # the name of the command command = "helloworld" # you can add as many `[[match_err]]` section as you want [[match_err]] # Note: # - patterns must be in lowercase without extra space characters # - patterns should be the output with `LC_ALL=C` environment variable # - this is a first-pass match. It should be quick so regex is not supported pattern = [ "pattern 1", "pattern 2" ] # if pattern is matched, suggest changing the first argument to fix: suggest = [ ''' {{command[0]}} fix {{command[2:]}} ''' ] [[match_err]] pattern = [ "pattern 1" ] # this will add a `sudo` before the command if: # - the `sudo` is found as executable # - the last command does not contain `sudo` suggest = [ ''' #[executable(sudo), !cmd_contains(sudo)] sudo {{command}} ''' ] ``` The placeholder is evaluated as following: - `{{command}}`: All the command without any modification - `{{command[1]}}`: The first argument of the command (the command itself has index of 0) - Negative values will count from reverse. - `{{command[2:5]}}`: The second to fifth arguments - If any of the side is not specified, then it defaults to the start (if it is left) or the end (if it is right) - `{{typo[2](fix1, fix2)}}`: Try to change the second argument to candidates in the parenthesis. - The argument in parentheses must have at least 2 values - Single arguments are reserved for specific matches, for instance, `path` to search all commands found in the `$PATH` environment, or the `{{shell}}` placeholder, among others - `{{select[3](selection1, selection2)}}`: A derivative of `typo` placeholder. Will create a suggestion for each selection in the parenthesis - The argument in parentheses also must have at least 2 values - Single arguments are reserved for specific selections, for instance, `path` to search all commands found in the `$PATH` environment with the minimum shared linguistic distance, or the `{{shell}}` placeholder - To avoid permutations and combinations, only one instance is evaluated. If you need to apply the same selection in multiple places, use `{{selection}}` - Index is optional as it only has effect when using with `path`, and defaults to `0` - `{{opt::}}`: Optional patterns captured in the command with RegEx ([see regex crate for syntax]) - All patterns matching this placeholder will be removed from indexing - `{{cmd::}}`: Get the matching captures from the last command - Unlike `{{opt}}`, this won't remove the string after matching - `{{err::)}}`: Replace with the output of the shell command - Can be used along `{{typo}}` or `{{select}}` as its only argument, where each newline will be evaluated to a candidate/selection [see regex crate for syntax]: https://docs.rs/regex-lite/latest/regex_lite/#syntax Suggestions can have additional conditions to check. To specify conditions, add a `#[...]` at the first line (just like derive macros in Rust). Available conditions: - `executable`: Check if the argument can be found in path - `cmd_contains`: Check if the last user input contains the argument. Regex supported (you can't use `,` currently because it's used as condition separator) - `err_contains`: Same as `cmd_contains` but for error message - `length`: Check if the given command has the length of the argument - `min_length`: Check if the given command has at least the length of the argument - `max_length`: Check if the given command has at most the length of the argument - `shell`: Check if the current running shell is the argument pay-respects-0.7.8/rules/000077500000000000000000000000001502240015600152725ustar00rootroot00000000000000pay-respects-0.7.8/rules/_PR_GENERAL.toml000066400000000000000000000006231502240015600200050ustar00rootroot00000000000000command = "_PR_general" [[match_err]] pattern = [ "command not found", "unknown command", "nu::shell::external_command", "is not recognized as a name of a cmdlet" ] suggest = [ ''' {{select[0](path)}} {{command[1:]}} ''' ] [[match_err]] pattern = [ "permission denied", "is not an executable file" ] suggest = [ ''' #[cmd_contains((?m)^(\S*)\/(\S*))] chmod +x {{command[0]}} && {{command}}''' ] pay-respects-0.7.8/rules/_PR_PRIVILEGE.toml000066400000000000000000000012371502240015600202600ustar00rootroot00000000000000command = "_PR_privilege" [[match_err]] pattern = [ "as root", "authentication is required", "be root", "be superuser", "cannot access", "eacces", "edspermissionerror", "insufficient privileges", "need root", "non-root users cannot", "not super-user", "only root can", "operation not permitted", "permission denied", "requires root", "root privilege", "root user", "sudorequirederror", "superuser privilege", "unless you are root", "can not open a temporary file", "use `sudo`", "you don't have access", "you don't have write permissions" ] suggest = [ ''' #[executable(sudo)] sudo {{command}} ''', ''' #[executable(doas)] doas {{command}} ''' ] pay-respects-0.7.8/rules/brew.toml000066400000000000000000000027211502240015600171300ustar00rootroot00000000000000command = "brew" [[match_err]] pattern = [ "unknown command" ] suggest = [ ''' {{command[0]}} {{typo[1]( --cache, --caskroom, --cellar, --env, --prefix, --repository, --version, alias, analytics, audit, autoremove, bottle, bump, bump-cask-pr, bump-formula-pr, bump-revision, bump-unversioned-casks, bundle, casks, cat, cleanup, command, commands, completions, config, contributions, create, debugger, deps, desc, determine-test-runners, developer, dispatch-build-bottle, docs, doctor, edit, extract, fetch, formula, formula-analytics, formulae, generate-analytics-api, generate-cask-api, generate-cask-ci-matrix, generate-formula-api, generate-man-completions, gist-logs, help, home, info, install, install-bundler-gems, irb, leaves, link, linkage, list, livecheck, log, migrate, missing, nodenv-sync, options, outdated, pin, postinstall, pr-automerge, pr-publish, pr-pull, pr-upload, prof, pyenv-sync, rbenv-sync, readall, reinstall, release, rubocop, ruby, rubydoc, search, services, setup-ruby, sh, shellenv, style, tab, tap, tap-info, tap-new, test, tests, typecheck, unalias, unbottled, uninstall, unlink, unpack, unpin, untap, update, update-if-needed, update-license-data, update-maintainers, update-python-resources, update-report, update-reset, update-sponsors, update-test, upgrade, uses, vendor-gems, vendor-install, verify )}} {{command[2:]}} ''' ] [[match_err]] pattern = [ "this command updates brew itself" ] suggest = [ ''' {{command[0]}} upgrade {{command[2:]}} ''' ] pay-respects-0.7.8/rules/c_typo.toml000066400000000000000000000003301502240015600174600ustar00rootroot00000000000000command = "c" [[match_err]] pattern = [ "command not found", "unknown command", "nu::shell::external_command" ] suggest = [ ''' #[length(2)] cd {{command[1:]}} ''', ''' #[min_length(3)] cp {{command[1:]}} ''' ] pay-respects-0.7.8/rules/cargo.toml000066400000000000000000000020441502240015600172620ustar00rootroot00000000000000command = "cargo" [[match_err]] pattern = [ "no such command" ] suggest = [ ''' #[err_contains(did you mean)] {{command[0]}} {{err::(?:did you mean `)(.*)(?:`\?)}} {{command[2:]}} ''', ''' #[err_contains(a command with a similar name exists)] {{command[0]}} {{err::(?:a command with a similar name exists: `)(\S+)(?:`)}} {{command[2:]}} ''', ''' #[!err_contains(did you mean), !err_contains(a command with a similar name exists)] {{command[0]}} {{typo[1]( add, bench, build, check, clean, clippy, config, deb, doc, expand, fetch, fix, fmt, generate-lockfil, generate-rpm, git-checkout, help, info, init, install, lipo, locate-project, login, logout, make, metadata, miri, new, owner, package, pkgid, publish, read-manifest, remove, report, rm, run, rustc, rustdoc, search, test, tree, uninstall, update, vendor, verify-project, version, yank )}} {{command[2:]}} ''', ] [[match_err]] pattern = [ "using `cargo install` to install the binaries from the package in current working directory is no longer supported", ] suggest = [ ''' {{command}} --path .''' ] pay-respects-0.7.8/rules/cat.toml000066400000000000000000000003151502240015600167350ustar00rootroot00000000000000command = "cat" [[match_err]] pattern = [ "no such file or directory" ] suggest = [ ''' cat {{typo[1](file)}} ''' ] [[match_err]] pattern = [ "is a directory" ] suggest = [ ''' ls {{command[1:]}}''' ] pay-respects-0.7.8/rules/cd.toml000066400000000000000000000005241502240015600165560ustar00rootroot00000000000000command = "cd" [[match_err]] pattern = [ "no such file or directory", "does not exist" ] suggest = [ ''' cd {{typo[1](file)}} ''', ''' #[!shell(nu)] mkdir --parents {{command[1]}} && cd {{command[1]}} ''' ] [[match_err]] pattern = [ "nu::shell::directory_not_found" ] suggest = [ ''' mkdir {{command[1]}} and \ cd {{command[1]}} ''' ] pay-respects-0.7.8/rules/cp.toml000066400000000000000000000005171502240015600165740ustar00rootroot00000000000000command = "cp" [[match_err]] pattern = [ "-r not specified", ] suggest = [ ''' {{command[0]}} -r {{command[1:]}} ''' ] [[match_err]] pattern = [ "cannot create", ] suggest = [ ''' #[err_contains(no such file or directory)] mkdir -p {{cmd::(?m)\s(\S+[\\\/])\S*\s*$}} && {{command[0]}} {{opt::(?:\s)(-[\w]+)}} {{command[1:]}} ''' ] pay-respects-0.7.8/rules/eza.toml000066400000000000000000000002551502240015600167500ustar00rootroot00000000000000command = "eza" [[match_err]] pattern = [ "no such file or directory", "does not exist" ] suggest = [ ''' {{command[0]}} {{typo[1](file)}} {{opt::(?:\s)(-[\S]+)}} ''', ] pay-respects-0.7.8/rules/git.toml000066400000000000000000000040441502240015600167540ustar00rootroot00000000000000command = "git" [[match_err]] pattern = [ "is not a git command" ] suggest = [ ''' #[err_contains(the most similar command is)] {{command[0]}} {{err::(?:the most similar command is )(\S+)}} {{command[2:]}}''', ''' #[!err_contains(the most similar command is)] {{command[0]}} {{typo[1]( add, am, archive, bisect, branch, bundle, checkout, cherry-pick, citool, clean, clone, commit, describe, diff, fetch, format-patch, gc, gitk, grep, gui, init, log, maintenance, merge, mv, notes, pull, push, range-diff, rebase, reset, restore, revert, rm, scalar, shortlog, show, sparse-checkout, stash, status, submodule, switch, tag, worktree, config, fast-export, fast-import, filter-branch, mergetool, pack-refs, prune, reflog, remote, repack, replace, )}} {{command[2:]}}''' ] [[match_err]] pattern = [ "did not match any file" ] suggest = [ ''' #[cmd_contains(checkout)] git checkout {{typo[2]({{shell(git branch | sed 's/^*//')}})}} ''', ''' #[cmd_contains(checkout)] git checkout -b {{command[2]}} ''' ] [[match_err]] pattern = [ "has no upstream branch" ] suggest = [ ''' #[cmd_contains(push)] git push --set-upstream origin {{shell(git rev-parse --abbrev-ref HEAD)}} ''' ] [[match_err]] pattern = [ "no tracking information for the current branch" ] suggest = [ ''' #[cmd_contains(pull)] git pull --set-upstream origin {{shell(git rev-parse --abbrev-ref HEAD)}} ''' ] [[match_err]] pattern = [ "a branch named" ] suggest = [ ''' #[cmd_contains(branch)] git checkout {{command[2]}} ''' ] [[match_err]] pattern = [ "updates were rejected" ] suggest = [ ''' #[cmd_contains(push)] git pull && {{command}} ''', ''' #[cmd_contains(push)] {{command}} --force ''' ] [[match_err]] pattern = [ "you have unstaged changes", "stash them" ] suggest = [ ''' #[cmd_contains(pull)] {{command}} --rebase --autostash ''', ''' git stash && {{command}} && git stash pop ''' ] [[match_err]] pattern = [ "you have divergent branches and need to specify how to reconcile them" ] suggest = [ ''' #[cmd_contains(pull)] {{command}} --rebase ''', ''' #[cmd_contains(pull)] {{command}} --merge ''' ] pay-respects-0.7.8/rules/jj.toml000066400000000000000000000005511502240015600165730ustar00rootroot00000000000000command = "jj" [[match_err]] pattern = [ "pass `--ignore-immutable`" ] suggest = [ ''' {{command}} --ignore-immutable''' ] [[match_err]] pattern = [ "use --allow-new to push new bookmark" ] suggest = [ ''' {{command}} --allow-new''' ] [[match_err]] pattern = [ "no bookmarks found in the default push revset" ] suggest = [ ''' {{command}} --change @''' ] pay-respects-0.7.8/rules/ls.toml000066400000000000000000000002541502240015600166060ustar00rootroot00000000000000command = "ls" [[match_err]] pattern = [ "no such file or directory", "does not exist" ] suggest = [ ''' {{command[0]}} {{typo[1](file)}} {{opt::(?:\s)(-[\S]+)}} ''', ] pay-respects-0.7.8/rules/mkdir.toml000066400000000000000000000002541502240015600172760ustar00rootroot00000000000000command = "mkdir" [[match_err]] pattern = [ "cannot create directory" ] suggest = [ ''' #[err_contains(no such file or directory)] {{command[0]}} -p {{command[1:]}}''' ] pay-respects-0.7.8/rules/mv.toml000066400000000000000000000002431502240015600166100ustar00rootroot00000000000000command = "mv" [[match_err]] pattern = [ "no such file or directory", "not a directory" ] suggest = [ ''' mkdir --parents {{command[-1]}} && {{command}} ''' ] pay-respects-0.7.8/rules/npm.toml000066400000000000000000000012141502240015600167570ustar00rootroot00000000000000command = "npm" [[match_err]] pattern = [ "unknown command" ] suggest = [ ''' {{command[0]}} {{typo[1]( access, adduser, audit, bugs, cache, ci, completion, config, dedupe, deprecate, diff, dist-tag, docs, doctor, edit, exec, explain, explore, find-dupes, fund, get, help, help-search, hook, init, install, install-ci-test, install-test, link, ll, login, logout, ls, org, outdated, owner, pack, ping, pkg, prefix, profile, prune, publish, query, rebuild, repo, restart, root, run-script, sbom, search, set, shrinkwrap, star, stars, start, stop, team, test, token, uninstall, unpublish, unstar, update, version, view, whoami )}} {{command[2:]}} ''' ] pay-respects-0.7.8/rules/pacman.toml000066400000000000000000000004541502240015600174310ustar00rootroot00000000000000command = "pacman" [[match_err]] pattern = [ "no operation specified" ] suggest = [ ''' #[length(1)] {{command}} -Syu''', ''' #[min_length(2)] {{command[0]}} -S {{command[1:]}}''', ] [[match_err]] pattern = [ "no targets specified" ] suggest = [ ''' #[cmd_contains(-S)] {{command[0]}} -Syu''', ] pay-respects-0.7.8/rules/rm.toml000066400000000000000000000004521502240015600166060ustar00rootroot00000000000000command = "rm" [[match_err]] pattern = [ "is a directory", "try --recursive" ] suggest = [ ''' {{command[0]}} -r {{command[1:]}} ''' ] [[match_err]] pattern = [ "no such file or directory", "file(s) not found" ] suggest = [ ''' {{command[0}} {{opt::(?:\s)(-[\w]+)}} {{typo[1:](file)}} ''' ] pay-respects-0.7.8/rules/size.toml000066400000000000000000000003261502240015600171420ustar00rootroot00000000000000command = "size" [[match_err]] pattern = [ "file format not recognized", ] suggest = [ ''' du -h {{command[1:]}} ''' ] [[match_err]] pattern = [ "is a directory", ] suggest = [ ''' du -hs {{command[1:]}} ''' ] pay-respects-0.7.8/rules/touch.toml000066400000000000000000000005631502240015600173150ustar00rootroot00000000000000command = "touch" [[match_err]] pattern = [ "no such file or directory" ] suggest = [ ''' #[!shell(nu)] mkdir -p {{cmd::(?:\s)+(.*[\\\/])(?:\s)*}} && touch {{command[1:]}} ''' ] [[match_err]] pattern = [ "nu::shell::create_not_possible", "no such file or directory", ] suggest = [ ''' #[shell(nu)] mkdir {{cmd::(?:\s)+(.*[\\\/])(?:\s)*}}; touch {{command[1:]}} ''' ] pay-respects-0.7.8/rules/yarn.toml000066400000000000000000000012061502240015600171370ustar00rootroot00000000000000command = "yarn" [[match_err]] pattern = [ "not found" ] suggest = [ ''' #[err_contains(command)] {{command[0]}} {{typo[1]( access, add, audit, autoclean, bin, cache, check, config, create, exec, generate-lock-entry, generateLockEntry, global, help, import, info, init, install, licenses, link, list, login, logout, node, outdated, owner, pack, policies, publish, remove, run, tag, team, unlink, unplug, upgrade, upgrade-interactive, upgradeInteractive, version, versions, why, workspace, workspaces )}} {{command[2:]}} ''' ] [[match_err]] pattern = [ "`install` has been replaced with `add`" ] suggest = [ ''' yarn add {{command[2:]}} ''' ] pay-respects-0.7.8/tests/000077500000000000000000000000001502240015600153025ustar00rootroot00000000000000pay-respects-0.7.8/tests/cases/000077500000000000000000000000001502240015600164005ustar00rootroot00000000000000pay-respects-0.7.8/tests/cases/file_path000066400000000000000000000001661502240015600202610ustar00rootroot00000000000000case="file path typo" command="cd ./correc" error="no such file or directory" expect="cd ./correct" mkdir -p correct pay-respects-0.7.8/tests/cases/privilege000066400000000000000000000002431502240015600203100ustar00rootroot00000000000000case="privilege" command="pacman -Syu" error="you cannot perform this operation unless you are root" expect="sudo pacman -Syu" export _PR_EXECUTABLES="sudo doas" pay-respects-0.7.8/tests/cases/regex_cmd000066400000000000000000000001761502240015600202640ustar00rootroot00000000000000case="regex: command" command="touch dir/file" error="no such file or directory" expect="\ mkdir -p dir/ && touch dir/file\ " pay-respects-0.7.8/tests/cases/regex_err000066400000000000000000000002031502240015600203000ustar00rootroot00000000000000case="regex: error" command="cargo built" error=" error: no such command: \`built\` Did you mean \`build\`? " expect="cargo build" pay-respects-0.7.8/tests/cases/regex_opt000066400000000000000000000001721502240015600203170ustar00rootroot00000000000000case="regex: options" command="rm correc -r" error="no such file or directory" expect="rm -r ./correct" mkdir -p correct pay-respects-0.7.8/tests/cases/typo000066400000000000000000000001131502240015600173110ustar00rootroot00000000000000case="command typo" command="echp" error="command not found" expect="echo" pay-respects-0.7.8/tests/main.sh000077500000000000000000000022211502240015600165620ustar00rootroot00000000000000#!/usr/bin/bash export PR=$(realpath ../target/debug/pay-respects) export _PR_SHELL="bash" export _PR_LIB="" export _PR_MODE="echo" export TMP=$(mktemp -d) PASSED=0 FAILED=0 export green='\033[0;32m' export red='\033[0;31m' export reset='\033[0m' run_test() { export _PR_LAST_COMMAND=$command export _PR_ERROR_MSG=$error result=$($PR 2>/dev/null) if [[ $result == *"$expect"* ]]; then echo -e "${green}[Passed]${reset}: $case" return 0 else echo -e "${red}[Failed]${reset}: $case" echo -e "\texpected: $expect" echo -e "\tgot: $result" return 1 fi } run_case() { ( source $1 run_test "$case" "$command" "$error" "$expect" ) if [[ $? == 0 ]]; then PASSED=$((PASSED + 1)) else FAILED=$((FAILED + 1)) fi } main() { echo "Starting suggestion tests..." echo "-----------------------------------------" WORKDIR=$(pwd) cd $TMP for case in $WORKDIR/cases/*; do run_case $case done echo "-----------------------------------------" echo -en "${green}Passed${reset}: $PASSED\t" echo -en "${red}Failed${reset}: $FAILED\t" echo -e "Total: $((PASSED + FAILED))" rm -rf $TMP if [[ $FAILED -ne 0 ]]; then exit 1 fi } main "$@" pay-respects-0.7.8/utils/000077500000000000000000000000001502240015600153005ustar00rootroot00000000000000pay-respects-0.7.8/utils/Cargo.toml000066400000000000000000000005321502240015600172300ustar00rootroot00000000000000[package] name = "pay-respects-utils" version = "0.1.8" edition = "2021" # for crates.io description = "Utilities for the pay-respects CLI tool" homepage = "https://codeberg.org/iff/pay-respects" repository = "https://github.com/iffse/pay-respects" license = "MPL-2.0" include = ["**/*.rs"] [dependencies] regex-lite = "0.1" itertools = "0.14" pay-respects-0.7.8/utils/src/000077500000000000000000000000001502240015600160675ustar00rootroot00000000000000pay-respects-0.7.8/utils/src/evals.rs000066400000000000000000000141611502240015600175520ustar00rootroot00000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use crate::files::*; use itertools::Itertools; use regex_lite::Regex; fn regex_captures(regex: &str, string: &str) -> Vec { let regex = Regex::new(regex).unwrap(); let mut caps = Vec::new(); for captures in regex.captures_iter(string) { for cap in captures.iter().skip(1).flatten() { caps.push(cap.as_str().to_owned()); } } caps } pub fn regex_match(regex: &str, string: &str) -> bool { let regex = Regex::new(regex).unwrap(); regex.is_match(string) } pub fn opt_regex(regex: &str, command: &mut String) -> String { let opts = regex_captures(regex, command); for opt in opts.clone() { *command = command.replace(&opt, ""); } opts.join(" ") } pub fn err_regex(regex: &str, error_msg: &str) -> String { let err = regex_captures(regex, error_msg); err.join(" ") } pub fn cmd_regex(regex: &str, command: &str) -> String { let cmd = regex_captures(regex, command); cmd.join(" ") } /// Returns the output of a shell command as a vector of strings /// Each string is a line of output pub fn eval_shell_command(shell: &str, command: &str) -> Vec { let output = std::process::Command::new(shell) .arg("-c") .arg(command) .output() .expect("failed to execute process"); let output = String::from_utf8_lossy(&output.stdout); let split_output = output.split('\n').collect::>(); split_output .iter() .map(|s| s.trim().to_string()) .collect::>() } /// Split the full command into command and arguments pub fn split_command(command: &str) -> Vec { #[cfg(debug_assertions)] eprintln!("command: {command}"); // this regex splits the command separated by spaces, except when the space // is escaped by a backslash or surrounded by quotes let regex = r#"([^\s"'\\]+|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\\ )+|\\|\n"#; let regex = Regex::new(regex).unwrap(); let split_command = regex .find_iter(command) .map(|cap| cap.as_str().to_owned()) .collect::>(); split_command } pub fn suggest_typo(typos: &[String], candidates: &[String], executables: &[String]) -> String { let mut suggestions = Vec::new(); for typo in typos { let typo = typo.as_str(); if candidates.len() == 1 { match candidates[0].as_str() { "path" => { if typo.contains(std::path::MAIN_SEPARATOR) { if let Some(suggest) = best_match_file(typo) { suggestions.push(suggest); } else { suggestions.push(typo.to_string()); } continue; } if let Some(suggest) = find_similar(typo, executables, Some(2)) { suggestions.push(suggest); } else { suggestions.push(typo.to_string()); } } "file" => { if let Some(suggest) = best_match_file(typo) { suggestions.push(suggest); } else { suggestions.push(typo.to_string()); } } _ => { unreachable!("suggest_typo: must have at least two candidates") } } } else if let Some(suggest) = find_similar(typo, candidates, Some(2)) { suggestions.push(suggest); } else { suggestions.push(typo.to_string()); } } suggestions.join(" ") } pub fn best_match_path(typo: &str, executables: &[String]) -> Option { find_similar(typo, executables, Some(3)) } pub fn best_matches_path(typo: &str, executables: &[String]) -> Option> { find_similars(typo, executables, Some(3)) } /// Find the best match for a typo given a list of candidates /// higher the threshold, stricter the comparison /// 1: anything /// 2: 50% /// 3: 33% /// ... etc pub fn find_similar(typo: &str, candidates: &[String], threshold: Option) -> Option { let threshold = threshold.unwrap_or(2); let mut min_distance = typo.chars().count() / threshold + 1; let mut min_distance_index = None; for (i, candidate) in candidates.iter().enumerate() { if candidate.is_empty() { continue; } let distance = compare_string(typo, candidate); if distance < min_distance { min_distance = distance; min_distance_index = Some(i); } } if let Some(min_distance_index) = min_distance_index { return Some(candidates[min_distance_index].to_string()); } None } /// Similar to `find_similar`, but returns a vector of all candidates /// with the same minimum distance pub fn find_similars( typo: &str, candidates: &[String], threshold: Option, ) -> Option> { let threshold = threshold.unwrap_or(2); let mut min_distance = typo.chars().count() / threshold + 1; let mut min_distance_index = vec![]; for (i, candidate) in candidates.iter().enumerate() { if candidate.is_empty() { continue; } let distance = compare_string(typo, candidate); use std::cmp::Ordering::*; match distance.cmp(&min_distance) { Equal => { if !min_distance_index.is_empty() { min_distance_index.push(i) } } Less => { min_distance = distance; min_distance_index.clear(); min_distance_index.push(i); } _ => {} } } if !min_distance_index.is_empty() { return Some( min_distance_index .iter() .map(|&i| candidates[i].to_string()) .collect::>() .into_iter() .unique() .collect(), ); } None } /// Damerau-Levenshtein distance algorithm #[allow(clippy::needless_range_loop)] pub fn compare_string(a: &str, b: &str) -> usize { let mut matrix = vec![vec![0; b.chars().count() + 1]; a.chars().count() + 1]; for i in 0..a.chars().count() + 1 { matrix[i][0] = i; } for j in 0..b.chars().count() + 1 { matrix[0][j] = j; } for (i, ca) in a.chars().enumerate() { for (j, cb) in b.chars().enumerate() { let cost = if ca == cb { 0 } else { 1 }; matrix[i + 1][j + 1] = std::cmp::min( std::cmp::min(matrix[i][j + 1] + 1, matrix[i + 1][j] + 1), matrix[i][j] + cost, ); // addition for optimal string alignment distance if i > 0 && j > 0 && ca == b.chars().nth(j - 1).unwrap() && a.chars().nth(i - 1).unwrap() == cb { matrix[i + 1][j + 1] = std::cmp::min(matrix[i + 1][j + 1], matrix[i - 1][j - 1] + 1); } } } matrix[a.chars().count()][b.chars().count()] } pay-respects-0.7.8/utils/src/files.rs000066400000000000000000000074661502240015600175540ustar00rootroot00000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use crate::evals::find_similar; use itertools::Itertools; pub fn get_path_files() -> Vec { let env = std::env::var("_PR_EXECUTABLES"); if let Ok(env) = env { if !env.is_empty() { return env.split(' ').map(|s| s.to_owned()).collect(); } } let path_env = path_env(); #[cfg(debug_assertions)] eprintln!("path_env: {path_env}"); let path_env_sep = path_env_sep(); let path = path_env.split(path_env_sep).collect::>(); let mut all_executable = vec![]; for p in path { #[cfg(windows)] let p = path_convert(p); #[cfg(debug_assertions)] eprintln!("p={p}"); let files = match std::fs::read_dir(p) { Ok(files) => files, Err(_) => continue, }; for file in files { let file = file.unwrap(); #[allow(unused_mut)] let mut file_name = file.file_name().into_string().unwrap(); #[cfg(windows)] strip_extension(&mut file_name); all_executable.push(file_name); } } #[cfg(debug_assertions)] { let mut all_executable = all_executable.clone(); all_executable.sort_unstable(); eprintln!("all_executable={all_executable:?}"); } all_executable.iter().unique().cloned().collect() } pub fn best_match_file(input: &str) -> Option { let mut input = input.trim_matches(|c| c == '\'' || c == '"').to_owned(); #[cfg(debug_assertions)] eprintln!("best_match_file input: {input}"); let mut exit_dirs = Vec::new(); let mut files = loop { match std::fs::read_dir(&input) { Ok(files) => break files, Err(_) => { if let Some((dirs, exit_dir)) = input.rsplit_once(std::path::MAIN_SEPARATOR) { exit_dirs.push(exit_dir.to_owned()); input = dirs.to_owned(); } else { exit_dirs.push(input.to_owned()); input = ".".to_owned(); break std::fs::read_dir("./").unwrap(); } } } }; while let Some(exit_dir) = exit_dirs.pop() { let dir_files = files .map(|file| { let file = file.unwrap(); file.file_name().into_string().unwrap().replace(' ', "\\ ") }) .collect::>(); let best_match = find_similar(&exit_dir, &dir_files, Some(2)); best_match.as_ref()?; input = format!("{}/{}", input, best_match.unwrap()); files = match std::fs::read_dir(&input) { Ok(files) => files, Err(_) => return Some(input), }; } Some(input) } #[cfg(windows)] fn msys2_conv_path(p: &str) -> std::io::Result { std::process::Command::new("cygpath") .arg("-w") .arg(p) .output() .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned()) } #[cfg(windows)] fn is_msystem() -> bool { std::env::var("MSYSTEM").is_ok() } #[cfg(windows)] fn path_env() -> String { if is_msystem() { String::from_utf8_lossy( &std::process::Command::new("bash") .arg("-c") .arg("echo $PATH") .output() .unwrap() .stdout, ) .trim() .to_owned() } else { std::env::var("PATH").unwrap() } } #[cfg(windows)] pub fn path_env_sep() -> &'static str { if is_msystem() { ":" } else { ";" } } #[cfg(windows)] pub fn path_convert(path: &str) -> String { if is_msystem() { msys2_conv_path(path).expect("Failed to convert path for msys") } else { path.to_owned() } } #[cfg(windows)] fn strip_extension(file_name: &str) -> String { let mut file_name = file_name.to_owned(); let suffixies = [".exe", ".sh", ".ps1"]; for suffix in suffixies { if let Some(file_name_strip) = file_name.strip_suffix(suffix) { file_name = file_name_strip.to_owned(); break; } } if !file_name.contains(".") { file_name = file_name.to_owned(); } file_name } #[cfg(not(windows))] fn path_env() -> String { std::env::var("PATH").unwrap() } #[cfg(not(windows))] pub fn path_env_sep() -> &'static str { ":" } pay-respects-0.7.8/utils/src/lib.rs000066400000000000000000000003511502240015600172020ustar00rootroot00000000000000// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. pub mod evals; pub mod files;