pax_global_header 0000666 0000000 0000000 00000000064 15173770737 0014533 g ustar 00root root 0000000 0000000 52 comment=33b5bc391d0c52aaa5f7a4e401a6a54a07141e33
pay-respects-0.8.8/ 0000775 0000000 0000000 00000000000 15173770737 0014167 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/.editorconfig 0000664 0000000 0000000 00000000226 15173770737 0016644 0 ustar 00root root 0000000 0000000 root = 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.8.8/.github/ 0000775 0000000 0000000 00000000000 15173770737 0015527 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/.github/FUNDING.yml 0000664 0000000 0000000 00000000056 15173770737 0017345 0 ustar 00root root 0000000 0000000 github: [ iffse ]
ko_fi: iffse
liberapay: iff
pay-respects-0.8.8/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 15173770737 0017712 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/.github/ISSUE_TEMPLATE/bug-report.yaml 0000664 0000000 0000000 00000001735 15173770737 0022672 0 ustar 00root root 0000000 0000000 name: 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.8.8/.github/ISSUE_TEMPLATE/feature-request.yaml 0000664 0000000 0000000 00000000503 15173770737 0023715 0 ustar 00root root 0000000 0000000 name: Feature Request
description: File a feature request
title: '[Feature Request]: '
labels:
- enhancement
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.8.8/.github/ISSUE_TEMPLATE/rule-request.yaml 0000664 0000000 0000000 00000000467 15173770737 0023242 0 ustar 00root root 0000000 0000000 name: Rule Request
description: File a rule request
title: '[Rule Request]: '
labels:
- rules
body:
- type: textarea
id: rule-request-content
attributes:
label: What rules do you want us to work on?
description: Please let us know what do you think
validations:
required: true
pay-respects-0.8.8/.github/dependabot.yaml 0000664 0000000 0000000 00000000522 15173770737 0020517 0 ustar 00root root 0000000 0000000 version: 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.8.8/.github/pull_request_template.md 0000664 0000000 0000000 00000001277 15173770737 0022477 0 ustar 00root root 0000000 0000000 ## Pull Request Description
## Checklists
Please check the boxes that apply to this pull request:
- [ ] I have tested and validated my changes
- [ ] I have used generative AI tools in the development of this pull request
Please select the type of change that best describes your pull request:
- [ ] bug
- [ ] enhancement
- [ ] documentation
- [ ] refactor
- [ ] tests
- [ ] performance
- [ ] security
- [ ] other
pay-respects-0.8.8/.github/workflows/ 0000775 0000000 0000000 00000000000 15173770737 0017564 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/.github/workflows/build-nightly.yaml 0000664 0000000 0000000 00000007376 15173770737 0023240 0 ustar 00root root 0000000 0000000 name: Build-Nightly
on:
push:
tags:
- nightly
workflow_dispatch:
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
musl: true
- os: ubuntu-latest
target: i686-unknown-linux-musl
cross: true
musl: true
- os: ubuntu-latest
target: aarch64-unknown-linux-musl
cross: true
musl: true
- os: ubuntu-latest
target: armv7-unknown-linux-musleabihf
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@v6
- name: Get version
id: version
run: echo "VERSION=nightly" >> $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
man
-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
-mx=9
./LICENSE
./man
./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:
name: Nightly build
tag: nightly
artifacts: |
*.tar.zst
*.zip
*.deb
*.rpm
allowUpdates: true
makeLatest: false
pay-respects-0.8.8/.github/workflows/build.yaml 0000664 0000000 0000000 00000007551 15173770737 0021557 0 ustar 00root root 0000000 0000000 name: 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@v6
- 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
man
-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
-mx=9
./LICENSE
./man
./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.8.8/.github/workflows/pr-mirror.yaml 0000664 0000000 0000000 00000001227 15173770737 0022403 0 ustar 00root root 0000000 0000000 name: Merge to Codeberg
on:
pull_request:
types: [closed]
jobs:
mirror:
if: github.event.pull_request.merged == true
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Set up SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.CODEBERG_SSH_KEY }}" > ~/.ssh/key
chmod 600 ~/.ssh/key
ssh-keyscan codeberg.org >> ~/.ssh/known_hosts
echo "Host codeberg.org" > ~/.ssh/config
echo " IdentityFile ~/.ssh/key" >> ~/.ssh/config
- name: Push to Codeberg
run: |
git push git@codeberg.org:iff/pay-respects.git
pay-respects-0.8.8/.github/workflows/test.yml 0000664 0000000 0000000 00000000700 15173770737 0021263 0 ustar 00root root 0000000 0000000 name: 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@v6
- 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.8.8/.gitignore 0000664 0000000 0000000 00000000017 15173770737 0016155 0 ustar 00root root 0000000 0000000 /target
result
pay-respects-0.8.8/.rustfmt.toml 0000664 0000000 0000000 00000000021 15173770737 0016637 0 ustar 00root root 0000000 0000000 hard_tabs = true
pay-respects-0.8.8/.woodpecker/ 0000775 0000000 0000000 00000000000 15173770737 0016407 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/.woodpecker/check-nightly.yaml 0000664 0000000 0000000 00000001775 15173770737 0022036 0 ustar 00root root 0000000 0000000 steps:
- name: nightly-tag
image: alpine
when:
event: cron
cron: "nightly build"
environment:
GIT_NAME: iff
GIT_EMAIL: iff@ik.me
KEY:
from_secret: Codeberg-CI
commands:
- apk add --no-cache git
- git fetch --tags origin
- LAST_COMMIT_TS=$(git log -1 --format=%ct)
- NOW_TS=$(date +%s)
- DIFF=$((NOW_TS - LAST_COMMIT_TS))
- |
if [ "$DIFF" -le 86400 ]; then
echo "Updating nightly tag"
git tag -f nightly
apk add --no-cache openssh-client
mkdir -p ~/.ssh
echo "$KEY" > ~/.ssh/key
chmod 600 ~/.ssh/key
ssh-keyscan codeberg.org >> ~/.ssh/known_hosts
echo "Host codeberg.org" > ~/.ssh/config
echo " IdentityFile ~/.ssh/key" >> ~/.ssh/config
git config --global user.name "$GIT_NAME"
git config --global user.email "$GIT_EMAIL"
git push git@codeberg.org:iff/pay-respects.git --tags --force
fi
pay-respects-0.8.8/CHANGELOG.md 0000664 0000000 0000000 00000040150 15173770737 0016000 0 ustar 00root root 0000000 0000000 # 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.8.8]
### Fixed
- Bash and Zsh: Command not found handler was not getting the arguments after
reworked templates
- AI module: Removed `extra_body` from requests if unused.
### Added
- Selection now supports pagination.
- AI module: Added `extra` field.
## [0.8.7]
This release fixes various problems specific to Windows.
### Breaking Changes
- For Nushell and PowerShell, the shell argument will now be treated as the
shell executable name.
- If you were using `pay-respects nushell` and your binary is named `nu`, you
have to change it to `pay-respects nu`
### Fixed
- Windows:
- Not actually stripping extensions
- Not getting non-localized outputs
- Draining terminal inputs
- Recovered commits that were supposed to be included in the last release
### Added
- AI module: `extra_body` field for model customization
## [0.8.6]
### Added
- Added `run0` and`sudo-rs` to internal privilege elevation list
- Alias expansion for PowerShell
- Accepted suggestions are now appended to the shell history on Nushell
and PowerShell, matching the existing behavior for Bash, Zsh, and Fish
(codeberg #36).
### Changed
- All initialization templates have been reworked
### Fixed
- Fallback modules not being called
- More robust tag parsing for AI module
## [0.8.5] - 2026-04-07
### Added
- **Automatic shell prefix detection**, no longer requires manually setting
`_PR_PREFIX` for multiplexer supports
### Fixed
- Wrong indentation and wrong capture when using multiplexer integrations
## [0.8.4] - 2026-04-06
### Added
- Inline mode rule support for runtime rules
### Changed
- **Terminal multiplexer integration now requires configuration**
- Desperate functions are now only executed when no previous suggestion is
found, improving performance
### Fixed
- Compile time parser now supports quotes in patterns
## [0.8.3] - 2026-04-05
### Added
- **GNU Screen**, **Zellij**, **WezTerm**, and **kitty** integrations
- Short command fixes: `gi tpush` can now be fixed into `git push`.
- Fuzzy recovery now provides support for options. Instead of `ls
--group-directories-first --color`, was suggesting `ls group directory first
color`
### Changed
- Logic for CNF is restored to the one used during older versions, as the
aggressive fuzzy search created too many false positives. E.g. instead of
installing `fastfetch`, was suggesting `last fetch`
- Difference highlighting no longer highlights comments.
### Fixed
- `err` placeholder changes during [0.7.13] wasn't adapted to all codebase,
such that error messages obtained through retries are still in lower cases.
- `tmux` integration wasn't complete like the point above, which wasn't being
used when retrying.
- The introduction of Inline mode on [0.8.1] come with a bug that will rerun
the previous command even on Inline and CNF modes. Shouldn't be a big problem
most of the time, excepting performance penalty.
- Comments are no longer part of the command to be fixed. However, modules will
still get the command with the comments.
## [0.8.2] - 2026-04-04
### Added
- **`tmux` integration**: No longer needs to rerun your command if you are inside
a tmux session with English locale.
- **Inline fixes**: Fixing commands on the fly, with no execution:
- All supported shell now have a new key-binding on `Ctrl-X`
- Fixes current typed command as good as possible:
- `gitcommit` + `C-X` `C-X` → `git commit`
- `z payrespe` + `C-X` `C-X` → `cd /home/iff/Code/pay-respects`
- Better search algorithm including: Segmentation, fuzzy search, etc.
## [0.8.1] - 2026-04-03
### Added
- **`zoxide` integration**: Usable for both `cd` and `z` fixes, when `zoxide`
is installed.
- **Rust rules**: Now rules can be written in Rust natively for complex logics
- **Trigram search**: New default search algorithm, with higher precision
- **Suggestions for blocking commands**: Now if a command is in a given list of
blocking commands, it won't try to run (e.g. interactive commands that do not
return anything). This allows fixing commands such as `vim file-with-typo`
- `extends` field for rule files: Allows reusing existing rules of other files
- `merge_commands` field for configuration files: Make multiple commands to use
the same rules
## [0.8.0] - 2026-04-02
### Changed
- Introducing an in-house selection UI! Now we have a UI of a great taste (which was not possible with an external library)!
- Discrete highlighting between selected and non-selected suggestions
- Quick selection with shortcuts (keys from 1 to 9)
## [0.7.13] - 2026-04-02
### Changed
- **Reproducibility**: Every single version before is not actually
*reproducible* because the procedural generation of Rust code places codes in
a random order. This does not affect how the program performs, but does make
the hash and binary sizes differs between different builds.
- [Unreproducible tests from
Debian.](https://tests.reproducible-builds.org/debian/rb-pkg/unstable/amd64/pay-respects.html)
- Source code is now reproducible, and technically should be for binaries as
well.
- `err` placeholder is now case-sensitive to preserve usable upper-cases for
suggestions.
### Added
- Configurable linguistic distances
### Fixed
- Nushell: Paths are now correctly formatted (`\ ` is unsupported by Nushell)
## [0.7.12] - 2026-02-08
### Fixed
- Default timeout was 3 milliseconds instead of 3 seconds, therefore last
version is not usable unless having a configuration file.
- Rolling back `reqwest` to version `0.12`. New version does not work on
android due to `rustls-platform-verifier`, despite the `0.13.1` changelog says
something is fixed.
## [0.7.11] - 2026-02-07 [YANKED]
### Added
- Layered configuration, allowing a system-wide configuration
### Fixed
- HTTPS connection of AI module
### Changed
- Default AI proxy is now serverless (URL changed)
## [0.7.10] - 2026-02-03
Maintenance release, no major changes.
### Fixed
- Many panics in various rare cases
### Added
- New rules for `cargo`, `snap`, `git`, and `jj`
## [0.7.9] - 2025-08-26
### Changed
- Install command is now explicit
- Nix and Guix: Default installation for missing commands changed to shell
- Nix: Adding `nix-search` as package query tool in addition to `nix-index`
## [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.8.8..HEAD
[0.8.8]: https://github.com/iffse/pay-respects/compare/v0.8.7..v0.8.8
[0.8.7]: https://github.com/iffse/pay-respects/compare/v0.8.6..v0.8.7
[0.8.6]: https://github.com/iffse/pay-respects/compare/v0.8.5..v0.8.6
[0.8.5]: https://github.com/iffse/pay-respects/compare/v0.8.4..v0.8.5
[0.8.4]: https://github.com/iffse/pay-respects/compare/v0.8.3..v0.8.4
[0.8.3]: https://github.com/iffse/pay-respects/compare/v0.8.2..v0.8.3
[0.8.2]: https://github.com/iffse/pay-respects/compare/v0.8.1..v0.8.2
[0.8.1]: https://github.com/iffse/pay-respects/compare/v0.8.0..v0.8.1
[0.8.0]: https://github.com/iffse/pay-respects/compare/v0.7.13..v0.8.0
[0.7.13]: https://github.com/iffse/pay-respects/compare/v0.7.12..v0.7.13
[0.7.12]: https://github.com/iffse/pay-respects/compare/v0.7.11..v0.7.12
[0.7.11]: https://github.com/iffse/pay-respects/compare/v0.7.10..v0.7.11
[0.7.10]: https://github.com/iffse/pay-respects/compare/v0.7.9..v0.7.10
[0.7.9]: https://github.com/iffse/pay-respects/compare/v0.7.8..v0.7.9
[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.8.8/Cargo.lock 0000664 0000000 0000000 00000173504 15173770737 0016106 0 ustar 00root root 0000000 0000000 # This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arc-swap"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207"
dependencies = [
"rustversion",
]
[[package]]
name = "askama"
version = "0.15.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b8246bcbf8eb97abef10c2d92166449680d41d55c0fc6978a91dec2e3619608"
dependencies = [
"askama_macros",
"itoa",
"percent-encoding",
"serde",
"serde_json",
]
[[package]]
name = "askama_derive"
version = "0.15.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f9670bc84a28bb3da91821ef74226949ab63f1265aff7c751634f1dd0e6f97c"
dependencies = [
"askama_parser",
"basic-toml",
"memchr",
"proc-macro2",
"quote",
"rustc-hash",
"serde",
"serde_derive",
"syn",
]
[[package]]
name = "askama_macros"
version = "0.15.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0756b45480437dded0565dfc568af62ccce146fb6cfe902e808ba86e445f44f"
dependencies = [
"askama_derive",
]
[[package]]
name = "askama_parser"
version = "0.15.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0af3691ba3af77949c0b5a3925444b85cb58a0184cc7fec16c68ba2e7be868"
dependencies = [
"rustc-hash",
"serde",
"serde_derive",
"unicode-ident",
"winnow 1.0.2",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "base62"
version = "2.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd637ac531c60eb7fbc4684dc061c2d7d90d73d758181aa02eeff0464b9eee4b"
[[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.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "bstr"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"
dependencies = [
"memchr",
"serde",
]
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cc"
version = "1.2.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "colored"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "convert_case"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
dependencies = [
"unicode-segmentation",
]
[[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.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
dependencies = [
"bitflags 2.11.1",
"crossterm_winapi",
"derive_more",
"document-features",
"mio",
"parking_lot",
"rustix",
"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 = "derive_more"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn",
]
[[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 = "document-features"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
dependencies = [
"litrs",
]
[[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.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "fastrand"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-io"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
[[package]]
name = "futures-macro"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"slab",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
[[package]]
name = "getrandom"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
"wasip2",
"wasip3",
]
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "globset"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52dfc19153a48bde0cbd630453615c8151bce3a5adfac7a0aebfbf0a1e1f57e3"
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.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "http"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
dependencies = [
"bytes",
"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.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"
dependencies = [
"atomic-waker",
"bytes",
"futures-channel",
"futures-core",
"http",
"http-body",
"httparse",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
]
[[package]]
name = "icu_collections"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
[[package]]
name = "icu_properties"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
dependencies = [
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
[[package]]
name = "icu_provider"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
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.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3d782a365a015e0f5c04902246139249abf769125006fbe7649e2ee88169b4a"
dependencies = [
"crossbeam-deque",
"globset",
"log",
"memchr",
"regex-automata",
"same-file",
"walkdir",
"winapi-util",
]
[[package]]
name = "indexmap"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown 0.17.0",
"serde",
"serde_core",
]
[[package]]
name = "ipnet"
version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
[[package]]
name = "iri-string"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20"
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.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
dependencies = [
"cfg-if",
"futures-util",
"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 = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
version = "0.2.185"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "litrs"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[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.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
[[package]]
name = "normpath"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf23ab2b905654b4cb177e30b629937b3868311d4e1cba859f899c041046e69b"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "pay-respects"
version = "0.8.8"
dependencies = [
"askama",
"colored",
"itertools 0.14.0",
"pay-respects-parser",
"pay-respects-select",
"pay-respects-utils",
"regex-lite",
"rust-i18n",
"serde",
"sys-locale",
"tempfile",
"toml 1.1.2+spec-1.1.0",
]
[[package]]
name = "pay-respects-module-request-ai"
version = "0.2.10"
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.14"
dependencies = [
"pay-respects-utils",
"regex-lite",
"serde",
"toml 1.1.2+spec-1.1.0",
]
[[package]]
name = "pay-respects-parser"
version = "0.3.16"
dependencies = [
"itertools 0.14.0",
"pay-respects-utils",
"proc-macro2",
"quote",
"serde",
"syn",
"toml 0.9.12+spec-1.1.0",
]
[[package]]
name = "pay-respects-select"
version = "0.1.4"
dependencies = [
"colored",
"crossterm",
]
[[package]]
name = "pay-respects-utils"
version = "0.1.18"
dependencies = [
"colored",
"itertools 0.14.0",
"regex-lite",
"serde",
"toml 1.1.2+spec-1.1.0",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "potential_utf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
dependencies = [
"zerovec",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quinn"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
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.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
dependencies = [
"bytes",
"getrandom 0.3.4",
"lru-slab",
"rand",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
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.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.11.1",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-lite"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "reqwest"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
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.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rust-i18n"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21031bf5e6f2c0ae745d831791c403608e99a8bd3776c7e5e5535acd70c3b7ba"
dependencies = [
"globwalk",
"regex",
"rust-i18n-macro",
"rust-i18n-support",
"smallvec",
]
[[package]]
name = "rust-i18n-macro"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51fe5295763b358606f7ca26a564e20f4469775a57ec1f09431249a33849ff52"
dependencies = [
"glob",
"proc-macro2",
"quote",
"rust-i18n-support",
"serde",
"serde_json",
"serde_yaml",
"syn",
]
[[package]]
name = "rust-i18n-support"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69bcc115c8eea2803aa3d85362e339776f4988a0349f2f475af572e497443f6f"
dependencies = [
"arc-swap",
"base62",
"globwalk",
"itertools 0.11.0",
"lazy_static",
"normpath",
"proc-macro2",
"regex",
"serde",
"serde_json",
"serde_yaml",
"siphasher",
"toml 0.8.23",
"triomphe",
]
[[package]]
name = "rustc-hash"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.11.1",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "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 = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[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_spanned"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "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.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "siphasher"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[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.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[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.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
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 = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.2",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "terminal_size"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
dependencies = [
"rustix",
"windows-sys 0.61.2",
]
[[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",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tinystr"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.52.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6"
dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
dependencies = [
"rustls",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
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 0.6.9",
"toml_datetime 0.6.11",
"toml_edit",
]
[[package]]
name = "toml"
version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned 1.1.1",
"toml_datetime 0.7.5+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow 0.7.15",
]
[[package]]
name = "toml"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned 1.1.1",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow 1.0.2",
]
[[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_datetime"
version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [
"serde_core",
]
[[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 0.6.9",
"toml_datetime 0.6.11",
"toml_write",
"winnow 0.7.15",
]
[[package]]
name = "toml_parser"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
dependencies = [
"winnow 1.0.2",
]
[[package]]
name = "toml_write"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]]
name = "toml_writer"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db"
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-http"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
dependencies = [
"bitflags 2.11.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.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "triomphe"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd69c5aa8f924c7519d6372789a74eac5b94fb0f8fcf0d4a97eb0bfc3e785f39"
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.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[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.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[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.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[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 = "wasip2"
version = "1.0.3+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
dependencies = [
"wit-bindgen 0.57.1",
]
[[package]]
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"wit-bindgen 0.51.0",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[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 = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags 2.11.1",
"hashbrown 0.15.5",
"indexmap",
"semver",
]
[[package]]
name = "web-sys"
version = "0.3.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d"
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.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
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.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
]
[[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-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[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.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[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 0.52.6",
"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-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm 0.53.1",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
]
[[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_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[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_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[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_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[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_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[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_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
dependencies = [
"memchr",
]
[[package]]
name = "winnow"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags 2.11.1",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "writeable"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]]
name = "yoke"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zerofrom"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]]
name = "zerotrie"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
pay-respects-0.8.8/Cargo.toml 0000664 0000000 0000000 00000000315 15173770737 0016116 0 ustar 00root root 0000000 0000000 [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.8.8/Cross.toml 0000664 0000000 0000000 00000000060 15173770737 0016151 0 ustar 00root root 0000000 0000000 [build.env]
passthrough = ["CARGO_INCREMENTAL"]
pay-respects-0.8.8/LICENSE 0000664 0000000 0000000 00000104526 15173770737 0015204 0 ustar 00root root 0000000 0000000 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.8.8/Makefile 0000664 0000000 0000000 00000001673 15173770737 0015636 0 ustar 00root root 0000000 0000000 .PHONY: man
man-src := $(wildcard man-src/*.md)
build:
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 test.sh
test: test-rust test-suggestions
bench: release-all
cd tests && bash benchmark.sh
man:
@for i in $(man-src); do \
output=$$(echo $$i | sed 's/\.md$$//' | sed 's/^man-src\///'); \
pandoc -s -t man $$i -o man/$$output; \
echo "Generated man page: $$output"; \
done
pay-respects-0.8.8/README.md 0000664 0000000 0000000 00000026655 15173770737 0015464 0 ustar 00root root 0000000 0000000 # 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**: Sub-millisecond (<1ms) performance! See
[benchmarks](#benchmarks).
- 🎯 **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 format that gets parsed into Rust code!
- 🦀 **Full Rust capability**: Raw Rust code can be used if TOML rules are not
enough for complex situations!
- 🔩 **Modular**: TOML and Rust 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!

## 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
> # replace `nu` for `nush` or `nushell` if your executable is named differently
> pay-respects nu --alias []
> ```
> Or save it as a file:
> ```sh
> pay-respects nu --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
> # replace `pwsh` for `powershell` if your executable is named differently
> 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 work:
>
> - `_PR_SHELL`: The binary name of the current working shell
> - `_PR_LAST_COMMAND`: The last command
>
> pay-respects echos back, if applicable, commands that should be evaluated by
> the working shell, such as `cd` commands to change the directory
>
> 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 capture output from multiplexers or 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
You can now **[Press `F` to Pay Respects]**!
[Press `F` to Pay Respects]: https://en.wikipedia.org/wiki/Press_F_to_pay_respects
You will also have a key-binding available on `Ctrl+X` for **experimental
inline mode**, on-the-fly correction with no execution:
- `gitcommit` + `C-X` `C-X` → `git commit`
- `z payrespe` + `C-X` `C-X` → `cd /home/iff/Code/pay-respects`
Integrations with other tools
> - **tmux**, **GNU Screen**, **Zellij**, **WezTerm**, **kitty**:
> - Command log capturing inside the session without the need to rerun commands
> to get error messages. **Requires English locale** (actually `LANG=C`, which
> output is used for matching) to guarantee correct logs.
> - Requires a prompt prefix before your command. Initialization templates
> set it for you automatically.
> - **zoxide**: Uses zoxide's database to navigate through directories.
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
> - `inline`: Returns best fix with no execution
> - `echo`: Print suggestions to `stdout` without executing
> - `cnf`: Used for command not found hook
>
> Example usage with `noconfirm`:
>
> ```sh
> # new versions
> alias ff="__pr_main noconfirm"
>
> # old versions
> function ff() {
> (
> export _PR_MODE="noconfirm"
> f
> )
> }
> ```
>
> Relating to features:
>
> - `_PR_NO_CONFIG`: Don't load configurations
> - `_PR_NO_DESPERATE`: Disable desperate functions, which are slow but might
> give better results
> - `_PR_PREFIX`: Shell prefix before the command acting as identifier.
> Required for multiplexer command log capturing
> - Disabling integrations:
> - `_PR_NO_ZOXIDE`
> - `_PR_NO_MULTIPLEXER`: Equivalent of turning all the followings:
> - `_PR_NO_TMUX`
> - `_PR_NO_SCREEN`
> - `_PR_NO_ZELLIJ`
> - `_PR_NO_WEZTERM`
> - `_PR_NO_KITTY`
## Installing
Install from your package manager if available:
[](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]. Install
scripts are available. For Unix:
```sh
curl -sSfL https://raw.githubusercontent.com/iffse/pay-respects/main/install.sh | sh
```
For Windows, with PowerShell:
```pwsh
irm https://raw.githubusercontent.com/iffse/pay-respects/main/install.ps1 | iex
```
[GitHub releases]: https://github.com/iffse/pay-respects/releases
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 or Rust)](./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.
You can disable it by setting `_PR_AI_DISABLE`:
```sh
export _PR_AI_DISABLE=1
```
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.
[I don't track nor store
anything.](https://github.com/iffse/pay-respects-serverless)
If it's useful to you, consider making a donation:
[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, utils, and select
## Benchmarks
Benchmark script can be executed with `make bench` using `hyperfine`. Here are
the results on my potato computer (AMD Ryzen 5 5600X, DDR4 2400 MHz, HDD 7200
RPM with Btrfs transparent compression, glibc build), you can expect better
results on yours.
| Case | Results |
|---------------------------|---------------------|
| Initialization | 493.7 µs ± 38.1 µs |
| Privilege | 655.0 µs ± 100.4 µs |
| Typo: Command | 5.1 ms ± 0.2 ms |
| Typo: File path | 3.6 ms ± 0.4 ms |
| RegEx: Command | 3.3 ms ± 0.1 ms |
| RegEx: Options | 3.3 ms ± 0.2 ms |
| RegEx: Error | 3.3 ms ± 0.1 ms |
| Desperate: Fuzzy recovery | 703.5 µs ± 65.9 µs |
| Desperate: File look up | 3.4 ms ± 0.2 ms |
Caveats:
- **Integrations are turned off**: In real usage you may feel a delay due to the
execution of `zoxide` itself, for instance, which takes 50ms.
- Binaries are **optimized for size, not speed**, using regex-lite instead of
regex because it's smaller, although slower. A smaller binary helps in
loading times, specially for cold runs.
## Flowchart
Here's a flowchart on how this program works:

pay-respects-0.8.8/config.md 0000664 0000000 0000000 00000005061 15173770737 0015760 0 ustar 00root root 0000000 0000000 # Configuration File
User configuration file for `pay-respects` is located at:
- `$HOME/.config/pay-respects/config.toml` (*nix)
- `%APPDATA%/pay-respects/config.toml` (Windows)
Directories for system-wide configuration, which fields can be overwritten
individually by the user configuration file are searched on:
- `$XDG_CONFIG_DIRS` (*nix)
- If not set, `/etc/xdg`
- `$PROGRAMDATA` (Windows)
- If not set, `C:\ProgramData`
With the same directory structure, e.g. `/etc/xdg/pay-respects/config.toml`
## Options
All available options are listed in the following example file:
```toml
# Preferred command for privileged acesses
privilege = "sudo"
# Maximum time in milliseconds for getting previous output
timeout = 3000
# Apply existing rules to a set of commands. Every set will use the rule
# corresponding to the first entry
merge_commands = [
["ls", "exa"], # both using rules corresponding to `ls`
["grep", "rg"], # both using rules corresponding to `grep`
]
# Commands that won't return any message when run,
# which is most of the interactive commands
blocking_commands = ["vim", "nano"]
# 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"
# Algorithm used for fuzzy searching
# Options:
# - TrigramDamerauLevenshtein: More computationally expensive
# - DamerauLevenshtein: Fast
search_type = "TrigramDamerauLevenshtein"
# Minimum characters required to start seaching
# Avoids false positive when input strings are too short
search_threshold = 3
# Minimum score for the result to be valid: [0,1]
[trigram]
minimum_score = 0.5
# Configuring the linguistic distance (Damerau-Levenshtein)
# - Percentage: How many characters can be different in the suggestion, rounded
# to the nearest integer.
# - Threshold: How many characters are required for the reference string to
# start searching to avoid false positives when the reference string is too
# short.
# - Max: Maximum distance allowed between the reference and the suggestion.
# - Min: Minimum strating distance required. Seach only starts if the distance
# obtained after the percentage calculation is above or equal to this value.
[dl_distance]
percentage = 27.1828182845904523536028747135266250
max = 5
min = 1
[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.8.8/core/ 0000775 0000000 0000000 00000000000 15173770737 0015117 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/Cargo.toml 0000664 0000000 0000000 00000004042 15173770737 0017047 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects"
authors = ["iff "]
version = "0.8.8"
edition = "2024"
# 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 = "4"
regex-lite = "0.1"
askama = "0.15"
itertools = "0.14.0"
# config file
toml = { version = "1.0" }
serde = { version = "1.0", features = ["derive"] }
pay-respects-parser = { version = "0.3", path = "../parser" }
pay-respects-utils = { version ="0.1", path = "../utils"}
pay-respects-select = { version ="0.1", path = "../select"}
tempfile = "3.27.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"],
["man/pay-respects.1", "usr/share/man/man1/", "644"],
["man/pay-respects-rules.5", "usr/share/man/man5/", "644"],
["man/pay-respects-modules.5", "usr/share/man/man5/", "644"],
["LICENSE", "usr/share/doc/pay-respects/", "644"],
]
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"},
{ source = "man/pay-respects.1", dest = "/usr/share/man/man1/", mode = "644"},
{ source = "man/pay-respects-rules.5", dest = "/usr/share/man/man5/", mode = "644"},
{ source = "man/pay-respects-modules.5", dest = "/usr/share/man/man5/", mode = "644"},
{ source = "LICENSE", dest = "/usr/share/doc/pay-respects/", mode = "644"},
]
pay-respects-0.8.8/core/LICENSE 0000777 0000000 0000000 00000000000 15173770737 0017337 2../LICENSE ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/README.md 0000777 0000000 0000000 00000000000 15173770737 0020063 2../README.md ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/build.rs 0000664 0000000 0000000 00000000141 15173770737 0016560 0 ustar 00root root 0000000 0000000 fn main() {
// recompile when rules are updated
println!("cargo::rerun-if-changed=./rules/")
}
pay-respects-0.8.8/core/i18n/ 0000775 0000000 0000000 00000000000 15173770737 0015676 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/i18n/i18n.toml 0000664 0000000 0000000 00000022001 15173770737 0017345 0 ustar 00root root 0000000 0000000 _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.8.8/core/man 0000777 0000000 0000000 00000000000 15173770737 0016521 2../man ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/rules 0000777 0000000 0000000 00000000000 15173770737 0017457 2../rules ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/src/ 0000775 0000000 0000000 00000000000 15173770737 0015706 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/src/args.rs 0000664 0000000 0000000 00000006330 15173770737 0017212 0 ustar 00root root 0000000 0000000 use 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().to_string(),
eval_examples = r#"
eval "$(pay-respects bash)"
eval "$(pay-respects zsh)"
pay-respects fish | source
"#,
manual = "Nushell / PowerShell".bold().to_string(),
manual_examples = r#"
pay-respects nu
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 let Some(lib) = lib {
println!("Default lib directory: {}", lib);
}
let package_manager = option_env!("_DEF_PR_PACKAGE_MANAGER").map(|dir| dir.to_string());
if let Some(package_manager) = package_manager {
println!("Default package manager: {}", package_manager);
}
}
#[cfg(test)]
mod tests {
use super::{Status, handle_args};
#[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.8.8/core/src/config.rs 0000664 0000000 0000000 00000005242 15173770737 0017524 0 ustar 00root root 0000000 0000000 use pay_respects_utils::strings::print_error;
use serde::Deserialize;
use pay_respects_utils::files::config_files;
use pay_respects_utils::{merge, merge_option};
#[allow(dead_code)]
#[derive(Deserialize, Default)]
pub struct ConfigReader {
pub privilege: Option,
pub merge_commands: Option>>,
pub timeout: Option,
pub blocking_commands: Option>,
pub eval_method: Option,
pub package_manager: Option,
}
#[allow(dead_code)]
#[derive(Deserialize, Default)]
pub struct PackageManagerConfig {
pub package_manager: Option,
pub install_method: Option,
}
#[derive(Deserialize, Default, PartialEq)]
pub enum InstallMethod {
#[default]
Default,
System,
Shell, // only available for nix and guix
}
#[derive(Deserialize, Default, PartialEq)]
pub enum EvalMethod {
#[default]
Internal,
Shell,
}
pub struct Config {
pub privilege: Option,
pub merge_commands: Option>>,
pub timeout: u64,
pub blocking_commands: Option>,
pub eval_method: EvalMethod,
pub package_manager: Option,
pub install_method: InstallMethod,
}
impl Default for Config {
fn default() -> Self {
Self {
privilege: None,
merge_commands: None,
timeout: 3000,
blocking_commands: None,
eval_method: EvalMethod::Internal,
package_manager: None,
install_method: InstallMethod::Default,
}
}
}
impl Config {
pub fn merge(&mut self, reader: ConfigReader) {
merge_option!(self, reader, privilege, merge_commands, blocking_commands);
merge!(self, reader, timeout, eval_method);
if let Some(reader) = reader.package_manager {
merge_option!(self, reader, package_manager);
merge!(self, reader, install_method);
}
}
pub fn set_package_manager(&mut self, package_manager: &str) {
self.package_manager = Some(package_manager.to_string());
}
pub fn set_install_method(&mut self) {
let package_manager = self.package_manager.as_deref().unwrap();
if self.install_method == InstallMethod::Default {
match package_manager {
"nix" | "guix" => self.install_method = InstallMethod::Shell,
_ => self.install_method = InstallMethod::System,
}
}
}
}
pub fn load_config() -> Config {
if std::env::var("_PR_NO_CONFIG").is_ok() {
return Config::default();
}
let mut config = Config::default();
for file in config_files() {
let content = std::fs::read_to_string(&file).expect("Failed to read config file");
let reader: ConfigReader = toml::from_str(&content).unwrap_or_else(|_| {
print_error(&format!(
"Failed to parse config file at {}. Skipping.",
file
));
ConfigReader::default()
});
config.merge(reader);
}
config
}
pay-respects-0.8.8/core/src/data.rs 0000664 0000000 0000000 00000022207 15173770737 0017170 0 ustar 00root root 0000000 0000000 use pay_respects_utils::evals::split_command;
use pay_respects_utils::evals::split_comment;
use pay_respects_utils::files::get_path_files;
use pay_respects_utils::files::path_env_sep;
use pay_respects_utils::lists::privilege_list;
use pay_respects_utils::modes::Mode;
use pay_respects_utils::modes::run_mode;
use itertools::Itertools;
use pay_respects_utils::strings::remove_color_codes;
use std::process::exit;
use std::collections::HashMap;
#[cfg(windows)]
use pay_respects_utils::files::path_convert;
use crate::config::Config;
use crate::config::load_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;
pub struct Data {
pub shell: String,
pub env: Option,
pub prompt_prefix: Option,
pub input_command: String,
pub command: String,
pub target_rule: Option,
pub suggest: Option,
pub candidates: Vec,
pub split: Vec,
pub comments: Option,
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())
}
};
// let prompt_prefix = std::env::var("_PR_PREFIX").ok();
let prompt_prefix = match std::env::var("_PR_PREFIX") {
Ok(prefix) => {
let nocolor = remove_color_codes(&prefix).trim().to_string();
// get the last non-empty whitespace character
let char = nocolor
.chars()
.rev()
.find(|c| !c.is_whitespace() && !c.is_control());
char.map(|char| char.to_string())
}
Err(_) => None,
};
let input_command = if prompt_prefix.is_some() {
command.clone()
} else {
"".to_string()
};
#[cfg(debug_assertions)]
eprintln!("lib_dir: {:?}", lib_dir);
(executables, modules, fallbacks) = if let Some(lib_dir) = lib_dir {
let mut modules = vec![];
let mut fallbacks = vec![];
let mut executables = get_path_files();
if let Some(alias) = &alias {
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)
} else {
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 let Some(alias) = &alias {
for command in alias.keys() {
if executables.contains(command) {
continue;
}
executables.push(command.to_string());
}
}
(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,
prompt_prefix,
input_command,
command,
target_rule: None,
suggest: None,
candidates: vec![],
alias,
split: vec![],
comments: None,
privilege: None,
error: "".to_string(),
executables,
modules,
fallbacks,
config,
mode,
};
init.extract_privilege();
init.split();
init.extract_env();
init.expand_command();
if !(init.mode == Mode::Cnf || init.mode == Mode::Inline) {
init.update_error(None);
}
// setting utils functions
pay_respects_utils::shell::set_shell_type(&init.shell);
pay_respects_utils::settings::load_config();
#[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);
eprintln!("mode: {:?}", init.mode);
}
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.command = self.command.trim().to_string();
if self.command.is_empty() {
eprintln!("{}", t!("empty-command"));
exit(1);
}
let mut split = split_command(&self.command);
let comments = split_comment(&mut split);
if let Some(comments) = comments {
self.command = split.join(" ");
self.comments = Some(comments);
}
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;
}
};
let privileges = if let Some(privilege) = self.config.privilege.as_ref() {
privilege_list()
.iter()
.cloned()
.chain(std::iter::once(privilege.as_str()))
.collect::>()
} else {
privilege_list().to_vec()
};
if !privileges.contains(&command.as_str()) {
return;
}
// already with privilege, simply remove it from command
if self.privilege.as_ref().is_some() && privileges.contains(&command.as_str()) {
self.command = self.command.replacen(&command, "", 1).trim().to_string();
}
// set to user defined privilege
if let Some(privilege) = self.config.privilege.as_ref() {
self.privilege = Some(privilege.to_string());
self.command = self.command.replacen(&command, "", 1).trim().to_string();
return;
}
// set to default privilege
self.privilege = Some(command.to_string());
self.command = self.command.replacen(&command, "", 1).trim().to_string();
}
pub fn extract_env(&mut self) {
let mut envs = vec![];
loop {
if self.split.is_empty() {
break;
}
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 get_executable(&self) -> &str {
if self.split.is_empty() {
return "";
}
self.split[0]
.rsplit(std::path::MAIN_SEPARATOR)
.next()
.unwrap()
}
pub fn update_error(&mut self, error: Option) {
if let Some(error) = error {
self.error = error.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.extract_privilege();
self.split();
self.extract_env();
self.update_target_rule();
}
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).trim().to_string());
self.privilege = Some(split[0].clone())
} else {
self.suggest = Some(suggest.to_string());
};
}
pub fn update_target_rule(&mut self) {
if self.config.merge_commands.is_none() {
return;
}
let merge_commands = self.config.merge_commands.as_ref().unwrap();
let command = self.get_executable().to_string();
for merge_command in merge_commands {
if merge_command.contains(&command) {
self.target_rule = Some(merge_command[0].clone());
break;
}
}
}
pub fn get_target_rule(&self) -> &str {
if let Some(target_rule) = &self.target_rule {
target_rule
} else {
self.get_executable()
}
}
}
pay-respects-0.8.8/core/src/highlighting.rs 0000664 0000000 0000000 00000005340 15173770737 0020723 0 ustar 00root root 0000000 0000000 use 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, active: bool) -> 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(data, &split_suggested_command[0]);
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 skip = false;
'next: for entry in split_suggested_command.iter_mut() {
if entry == "#" {
skip = true;
continue;
}
if entry == "\n" {
skip = false;
continue;
}
if skip {
*entry = entry.normal().to_string();
continue;
}
for old in &old_entries {
if old == entry {
*entry = color_same(entry, active).to_string();
continue 'next;
}
}
*entry = color_diff(entry, active);
}
if privileged
&& (suggested_command.contains("&&")
|| suggested_command.contains("||")
|| suggested_command.contains('>'))
{
split_suggested_command[1] =
color_diff(&format!("{} -c \"\n", shell), active) + &split_suggested_command[1];
let len = split_suggested_command.len() - 1;
split_suggested_command[len] =
split_suggested_command[len].clone() + color_diff("\n\"", active).as_str();
}
if let Some(sudo) = data.privilege.clone() {
if suggested_command.contains("&&")
|| suggested_command.contains("||")
|| suggested_command.contains('>')
{
split_suggested_command[0] =
color_same(&format!("{} -c \"\n", shell), active) + &split_suggested_command[0];
let len = split_suggested_command.len() - 1;
split_suggested_command[len] =
split_suggested_command[len].clone() + color_same("\n\"", active).as_str();
}
split_suggested_command.insert(0, color_same(&sudo, active));
}
let highlighted = split_suggested_command.join(" ").replace(" \n ", "\n");
Some(highlighted)
}
fn color_same(str: &str, active: bool) -> String {
if active {
str.blue().to_string()
} else {
str.normal().to_string()
}
}
fn color_diff(str: &str, active: bool) -> String {
if active {
str.red().bold().to_string()
} else {
str.normal().bold().to_string()
}
}
pay-respects-0.8.8/core/src/init.rs 0000664 0000000 0000000 00000000406 15173770737 0017217 0 ustar 00root root 0000000 0000000 pub 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.8.8/core/src/integrations.rs 0000664 0000000 0000000 00000015437 15173770737 0020774 0 ustar 00root root 0000000 0000000 use pay_respects_utils::{
evals::{compare_string, fuzzy_best_n_substring},
settings::get_trigram_minimum_score,
shell::shell_path_post_processing,
strings::{print_error, remove_color_codes},
};
use crate::shell::command_output;
use tempfile::NamedTempFile;
#[allow(unreachable_code)]
#[allow(unused_variables)]
pub fn get_error_from_multiplexer(
shell: &str,
prompt_prefix: &Option,
command: &str,
) -> Option {
// in debug mode the output is not clear due to logs
#[cfg(debug_assertions)]
{
return None;
}
if std::env::var("_PR_NO_MULTIPLEXER").is_ok() {
return None;
}
let prefix = if let Some(prefix) = prompt_prefix {
prefix
} else {
return None;
};
// terminal multiplexers, higher priority
if let Some(error) = get_error_from_tmux(shell, prefix, command) {
#[cfg(debug_assertions)]
eprintln!("Error captured from tmux: '{}'", error);
return Some(error);
}
if let Some(error) = get_error_from_screen(shell, prefix, command) {
#[cfg(debug_assertions)]
eprintln!("Error captured from screen: '{}'", error);
return Some(error);
}
if let Some(error) = get_error_from_zellij(shell, prefix, command) {
#[cfg(debug_assertions)]
eprintln!("Error captured from zellij: '{}'", error);
return Some(error);
}
// terminals that support capturing output
if let Some(error) = get_error_from_kitty(shell, prefix, command) {
#[cfg(debug_assertions)]
eprintln!("Error captured from kitty: '{}'", error);
return Some(error);
}
if let Some(error) = get_error_from_wezterm(shell, prefix, command) {
#[cfg(debug_assertions)]
eprintln!("Error captured from wezterm: '{}'", error);
return Some(error);
}
None
}
fn get_error_from_tmux(shell: &str, prefix: &str, command: &str) -> Option {
if std::env::var("_PR_NO_TMUX").is_ok() {
return None;
}
if std::env::var("TMUX").is_err() {
return None;
}
if rust_i18n::locale().to_string() != "en" {
return None;
}
let capture_command = "tmux capture-pane -pS -";
let output = command_output(shell, capture_command);
parse_output(prefix, command, &output)
}
fn get_error_from_screen(shell: &str, prefix: &str, command: &str) -> Option {
if std::env::var("_PR_NO_SCREEN").is_ok() {
return None;
}
if std::env::var("STY").is_err() {
return None;
}
if rust_i18n::locale().to_string() != "en" {
return None;
}
let file = NamedTempFile::new().ok()?;
let path = file.path().to_str()?;
let capture_command = format!("screen -X hardcopy {}", path);
let _ = command_output(shell, &capture_command);
let output = std::fs::read_to_string(path).ok()?;
parse_output(prefix, command, &output)
}
fn get_error_from_zellij(shell: &str, prefix: &str, command: &str) -> Option {
if std::env::var("_PR_NO_ZELLIJ").is_ok() {
return None;
}
if std::env::var("ZELLIJ").is_err() {
return None;
}
if rust_i18n::locale().to_string() != "en" {
return None;
}
let capture_command = "zellij action dump-screen --full";
let output = command_output(shell, capture_command);
parse_output(prefix, command, &output)
}
fn get_error_from_kitty(shell: &str, prefix: &str, command: &str) -> Option {
if std::env::var("_PR_NO_KITTY").is_ok() {
return None;
}
if std::env::var("KITTY_PID").is_err() {
return None;
}
if rust_i18n::locale().to_string() != "en" {
return None;
}
let capture_command = "kitty @ get-text --extent=all";
let output = command_output(shell, capture_command);
parse_output(prefix, command, &output)
}
fn get_error_from_wezterm(shell: &str, prefix: &str, command: &str) -> Option {
if std::env::var("_PR_NO_WEZTERM").is_ok() {
return None;
}
if std::env::var("WEZTERM_PANE").is_err() {
return None;
}
if rust_i18n::locale().to_string() != "en" {
return None;
}
let capture_command = "wezterm cli get-text --start-line -10000";
let output = command_output(shell, capture_command);
parse_output(prefix, command, &output)
}
fn parse_output(prefix: &str, input_command: &str, capture: &str) -> Option {
// no space and newline, to make it more robust
let command = input_command.replace(|c: char| c.is_whitespace(), "");
let prefix = remove_color_codes(prefix);
let mut start_pos = capture.rfind(&prefix)?;
let mut end_pos = capture.len();
loop {
let tail =
capture[start_pos + prefix.len()..end_pos].replace(|c: char| c.is_whitespace(), "");
if tail.starts_with(&command) {
let cmderr = capture[start_pos + prefix.len()..].trim();
let error = cmderr[input_command.trim_start().len()..]
.trim()
.to_string();
return Some(error);
} else if let Some(pos) = capture[..start_pos].rfind(&prefix) {
end_pos = start_pos;
start_pos = pos;
} else {
print_error("Failed to capture output from multiplexer.");
break;
}
}
None
}
pub fn zoxide_integration(
shell: &str,
executables: &[String],
split: &[String],
candidates: &mut Vec,
) {
if std::env::var("_PR_NO_ZOXIDE").is_ok() {
return;
}
if !executables.contains(&"zoxide".to_string()) {
return;
}
let query_command = "zoxide query -l";
let hints = split[1..]
.iter()
.map(|s| s.to_lowercase())
.collect::>();
let zoxide_output = command_output(shell, query_command);
let directories = zoxide_output.lines();
if directories.clone().count() == 0 {
return;
}
let mut filtered_directories = Vec::new();
for directory in directories.clone() {
let mut should_add = true;
for hint in &hints {
if !directory.to_lowercase().contains(hint) {
should_add = false;
break;
}
}
if should_add {
filtered_directories.push(directory);
}
}
let current_dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(""));
let joined_hints = hints.join(" ");
if !filtered_directories.is_empty() {
let mut min_distance = usize::MAX;
let mut bests = Vec::new();
for directory in filtered_directories {
let distance = compare_string(&joined_hints, directory);
if distance < min_distance {
min_distance = distance;
bests.clear();
bests.push(directory.to_string());
} else if distance == min_distance {
bests.push(directory.to_string());
}
}
let mut valid = false;
for directory in bests {
if directory == current_dir.to_str().unwrap() {
continue;
}
valid = true;
let directory = shell_path_post_processing(&directory);
candidates.push(format!("cd {}", directory.clone()));
}
if valid {
return;
}
}
let match_candidates = directories.map(|s| s.to_string()).collect::>();
let directories = fuzzy_best_n_substring(
&joined_hints,
&match_candidates,
get_trigram_minimum_score(),
3,
);
if let Some(directories) = directories {
for directory in directories {
if directory == current_dir.to_str().unwrap() {
continue;
}
let directory = shell_path_post_processing(&directory);
candidates.push(format!("cd {}", directory.clone()));
}
}
}
pay-respects-0.8.8/core/src/main.rs 0000664 0000000 0000000 00000004605 15173770737 0017205 0 ustar 00root root 0000000 0000000 // 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 highlighting;
mod init;
mod integrations;
mod modes;
mod rules;
mod rules_function;
mod shell;
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 pay_respects_utils::modes::Mode::*;
match data.mode {
Suggestion => modes::suggestion(&mut data),
Inline => modes::inline(&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.8.8/core/src/modes.rs 0000664 0000000 0000000 00000015572 15173770737 0017375 0 ustar 00root root 0000000 0000000 use colored::Colorize;
use pay_respects_select::select_simple;
use pay_respects_utils::strings::{format_prefix, print_error, remove_color_codes};
use std::path::Path;
use std::process::exit;
use pay_respects_utils::evals::best_matches;
use pay_respects_utils::files::best_match_file;
use crate::data::Data;
use crate::highlighting::highlight_difference;
use crate::shell::{add_candidates_no_dup, shell_evaluated_commands};
use crate::suggestions::{inline_suggestion, 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::execute_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 inline(data: &mut Data) {
inline_suggestion(data);
if data.candidates.is_empty() {
return;
}
println!("{}", data.candidates[0]);
}
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();
let highlighted = highlight_difference(data, &candidate, true).unwrap();
let output = if let Some(prefix) = &data.prompt_prefix {
data.input_command = remove_color_codes(&highlighted);
format_prefix(prefix, &highlighted)
} else {
candidate.clone()
};
eprintln!("{}", output);
data.update_suggest(&candidate);
data.candidates.clear();
let execution = suggestions::execute_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 = data.split.clone();
let executable = split[0].clone();
let shell_msg = format!("{}:", shell);
eprintln!(
"{} {}: {}\n",
shell_msg.bold().red(),
t!("command-not-found"),
executable
);
let mut candidates: Vec = Vec::new();
// too aggresive
// desperate_fuzzy_recovery(&data.executables, &split, &mut candidates);
let best_matches = {
if executable.contains(std::path::MAIN_SEPARATOR) {
let file = best_match_file(&executable);
if let Some(file) = file {
let currrent_dir_prefix = format!(".{}", std::path::MAIN_SEPARATOR);
let file = if executable.starts_with(&currrent_dir_prefix) {
format!(".{}{}", std::path::MAIN_SEPARATOR, file)
} else {
file
};
Some(vec![file])
} else {
None
}
} else {
best_matches(&executable, &data.executables)
}
};
if let Some(best_matches) = best_matches {
for best_match in best_matches {
if best_match == executable {
continue;
}
split[0] = best_match;
let suggest = split.join(" ");
candidates.push(suggest);
}
}
add_candidates_no_dup(&data.command, &mut data.candidates, &candidates);
if !data.candidates.is_empty() {
suggestions::select_candidate(data);
let status = suggestions::execute_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;
}
};
data.config.set_package_manager(&package_manager);
#[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);
// change default install method based on package manager
data.config.set_install_method();
let packages = packages
.iter()
.map(|p| system::install_string(data, &package_manager, p))
.collect::>();
let msg = format!("{}:", t!("install-package")).bold().blue();
let confirm = format!("[{}]", t!("confirm-yes")).green();
let hint = format!("{} {} {}", "[↑/↓/j/k]".blue(), confirm, "[ESC]".red());
let prelude = format!("{}\n\r{}", msg, hint);
let selection = select_simple(&prelude, &packages).unwrap_or_else(|err| {
print_error(&format!("Selection failed: {}", err));
exit(1);
});
let package = packages[selection].to_string();
let install_method = &data.config.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::install_package_shell(data, &package_manager, &package)
);
return;
}
// retry after installing package
if system::install_package(data, &package_manager, &package) {
let output = if let Some(prefix) = &data.prompt_prefix {
format_prefix(prefix, &data.input_command)
} else {
data.input_command.clone()
};
eprintln!("\n{}", output.cyan());
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.8.8/core/src/rules.rs 0000664 0000000 0000000 00000002726 15173770737 0017415 0 ustar 00root root 0000000 0000000 use crate::data::Data;
use pay_respects_parser::{parse_inline_rules, parse_rules};
use pay_respects_utils::{evals::*, modes::Mode};
#[allow(unused)]
use crate::rules_function::{Functions::*, rules_function};
pub fn match_rule(executable: &str, data: &Data) -> Option> {
use Mode::*;
match data.mode {
Inline => match_inline(executable, data),
_ => match_pattern(executable, data),
}
}
fn match_pattern(executable: &str, data: &Data) -> Option> {
// variables to be used by parsed rules
let error_msg = &data.error;
let error_lower = error_msg.to_lowercase();
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 into rust code
parse_rules!("rules");
if candidates.is_empty() {
return None;
}
Some(candidates)
}
#[allow(dead_code)]
#[allow(unused)]
fn match_inline(executable: &str, data: &Data) -> Option> {
// variables to be used by parsed rules
// error variables are not used by inlines, they are here for reusing codes
let error_msg = &data.error;
let error_lower = error_msg.to_lowercase();
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 into rust code
parse_inline_rules!("rules");
if candidates.is_empty() {
return None;
}
Some(candidates)
}
pay-respects-0.8.8/core/src/rules_function.rs 0000664 0000000 0000000 00000013513 15173770737 0021316 0 ustar 00root root 0000000 0000000 use crate::{data::Data, integrations::zoxide_integration};
use pay_respects_utils::{
evals::{best_match, best_matches, segment, segment_1},
files::best_match_file,
lists::{commond_arguments, privilege_list},
settings::get_search_threshold,
};
pub enum Functions {
DesperateFileLookUp,
DesperateFuzzyRecovery,
SetPrivilege,
ZoxideIntegration,
}
use Functions::*;
#[allow(unused_variables)]
#[allow(clippy::too_many_arguments)]
pub fn rules_function(
function: Functions,
error_msg: &str,
error_lower: &str,
shell: &str,
last_command: &str,
executables: &[String],
split: &[String],
candidates: &mut Vec,
data: &Data,
) {
match function {
DesperateFileLookUp => desperate_file_look_up(split, candidates),
DesperateFuzzyRecovery => desperate_fuzzy_recovery(executables, split, candidates),
SetPrivilege => set_privilege(data, executables, last_command, candidates),
ZoxideIntegration => zoxide_integration(shell, executables, split, candidates),
}
}
fn set_privilege(
data: &Data,
executables: &[String],
last_command: &str,
candidates: &mut Vec,
) {
if data.privilege.is_some() {
return;
}
if let Some(privilege) = &data.config.privilege {
candidates.push(format!("{} {}", privilege, last_command));
return;
}
privilege_list().iter().for_each(|privilege| {
if executables.contains(&privilege.to_string()) {
candidates.push(format!("{} {}", privilege, last_command));
}
});
}
pub fn desperate_fuzzy_recovery(
executables: &[String],
split: &[String],
candidates: &mut Vec,
) {
// naive approach for executable only
if std::env::var("_PR_NO_DESPERATE").is_ok() {
if executables.contains(&split[0]) || split[0].contains(std::path::MAIN_SEPARATOR) {
return;
}
let best_matches = best_matches(&split[0], executables);
if let Some(best_matches) = best_matches {
for best_match in best_matches {
candidates.push(format!("{} {}", best_match, split[1..].join(" ")));
}
}
return;
}
let mut split = split.to_vec();
let mut segments: Vec = Vec::new();
let mut command: Vec = Vec::new();
let dict = commond_arguments()
.iter()
.map(|s| s.to_string())
.collect::>();
let mut valid_command =
executables.contains(&split[0]) || split[0].contains(std::path::MAIN_SEPARATOR);
let mut head = split[0].clone();
if !valid_command && head.len() < get_search_threshold() {
// append head until its length is greater than the threshold
for i in 2..split.len() + 1 {
head = split[..i].join("");
#[cfg(debug_assertions)]
eprintln!("i: {}, head: {}, lengh: {}", i, head, head.len());
if head.len() >= get_search_threshold() {
split = std::iter::once(&head)
.chain(split[i..].iter())
.cloned()
.collect::>();
#[cfg(debug_assertions)]
eprintln!("split: {:?}", split);
break;
}
}
valid_command = executables.contains(&split[0]);
}
for split in split[1..].iter() {
// don't segment if it's a string (quoted), or a flag that contains `-`, `=`, or `=` after the first two characters (e.g., `--flag=value` or `-f=value`)
let is_string = split.starts_with('"')
|| split.starts_with('\'')
|| split.starts_with('`')
|| split.contains(std::path::MAIN_SEPARATOR);
if is_string {
segments.push(split.to_string());
continue;
}
let prefix_dash_count = split.chars().take_while(|&c| c == '-').count();
let is_flag = prefix_dash_count > 0 && prefix_dash_count <= 2;
let is_flag_with_value = is_flag && split[2..].contains("=");
// if is_flag_with_value {
// segments.push(split.to_string());
// continue;
// }
if is_flag_with_value {
// split into flag and value, find the best match for the flag, and then rejoin them
let flag_part = &split[..split.find('=').unwrap()];
let value_part = &split[split.find('=').unwrap() + 1..];
let best_match = best_match(&flag_part[prefix_dash_count - 1..], &dict);
if let Some(best_match) = best_match {
segments.push(format!(
"{}{}={}",
&flag_part[..prefix_dash_count],
best_match,
value_part
));
} else {
segments.push(split.to_string());
}
} else if is_flag {
// don't segment but find the best match
let best_match = best_match(&split[prefix_dash_count - 1..], &dict);
if let Some(best_match) = best_match {
segments.push(format!("{}{}", &split[..prefix_dash_count], best_match));
} else {
segments.push(split.to_string());
}
} else {
let seg = segment(split, &dict);
for s in seg {
segments.push(s.to_string());
}
}
}
#[cfg(debug_assertions)]
eprintln!(
"split and segments:\n - split: {:?}\n - segments: {:?}",
split[0..].iter().collect::>(),
segments
);
if valid_command {
command.push(split[0].to_string());
} else {
// we have a problem with the command itself
if split[0].len() < get_search_threshold() {
return;
}
if let Some(best_matches) = best_matches(&split[0], executables) {
for best_match in best_matches {
command.push(best_match);
}
} else {
// introduces some false possitive
// gitpush -> git pwsh because pwsh is in executables
let command_segments = segment_1(&split[0], executables);
if !command_segments.is_empty() {
for segments in &command_segments {
command.push(segments.join(" "))
}
} else {
return;
}
}
}
for command in command.iter() {
let suggestion = format!("{} {}", command, segments.join(" "));
candidates.push(suggestion);
}
}
fn desperate_file_look_up(split: &[String], candidates: &mut Vec) {
if std::env::var("_PR_NO_DESPERATE").is_ok() {
return;
}
let hints = split[1..]
.iter()
.map(|s| {
if let Some(file) = best_match_file(s) {
file
} else {
s.to_string()
}
})
.collect::>();
let joined_hints = hints.join(" ");
let suggestion = format!("{} {}", split[0], joined_hints);
candidates.push(suggestion);
}
pay-respects-0.8.8/core/src/shell.rs 0000664 0000000 0000000 00000037325 15173770737 0017375 0 ustar 00root root 0000000 0000000 use askama::Template;
use pay_respects_utils::lists::{alias_skip_expand, blocking_commands, privilege_list};
use pay_respects_utils::log::dlog;
use std::process::{Stdio, exit};
use std::collections::HashMap;
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
use crate::data::Data;
use crate::init::Init;
use crate::integrations::get_error_from_multiplexer;
use pay_respects_utils::remove_env_var;
/// Run the command without any shell configuration files (noprofile, norc)
fn clean_shell_command(shell: &str, command: &str) -> std::process::Command {
let mut cmd = std::process::Command::new(shell);
match shell {
"bash" => {
cmd.arg("--noprofile").arg("--norc").arg("-c").arg(command);
}
"zsh" => {
cmd.arg("--no-rcs").arg("-c").arg(command);
}
"fish" => {
cmd.arg("--no-config").arg("-c").arg(command);
}
"pwsh" | "powershell" => {
// omg powershell
let invariant_culture_command = format!(
"$CurrentCulture = [System.Globalization.CultureInfo]::InvariantCulture; $CurrentUICulture = [System.Globalization.CultureInfo]::InvariantCulture; {}",
command
);
cmd.arg("-NoProfile")
.arg("-c")
.arg(invariant_culture_command);
}
"nu" => {
cmd.arg("--no-config-file").arg("-c").arg(command);
}
_ => {
cmd.arg("-c").arg(command);
}
}
cmd
}
pub fn elevate(data: &mut Data, command: &mut String) {
let first_command = command.split_whitespace().next().unwrap_or("");
if is_privileged(data, first_command) {
return;
}
if let Some(privilege) = &data.config.privilege {
*command = format!("{} {}", privilege, command);
return;
}
for privilege in privilege_list().iter() {
if data.executables.contains(&privilege.to_string()) {
*command = format!("{} {}", privilege, command);
break;
}
}
}
pub fn is_privileged(data: &Data, command: &str) -> bool {
if let Some(privilege) = &data.config.privilege {
return privilege == command;
}
privilege_list().contains(&command)
}
pub fn add_candidates_no_dup(
command: &str,
candidates: &mut Vec,
new_candidates: &[String],
) {
if new_candidates.is_empty() {
return;
}
#[cfg(debug_assertions)]
{
eprintln!("Adding candidates for command: '{}'", command);
for candidate in new_candidates {
eprintln!(" - '{}'", candidate.trim());
}
}
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 {
remove_env_var!("_PR_ERROR_MSG");
return error_msg;
} else {
let timeout = data.config.timeout;
#[cfg(debug_assertions)]
eprintln!("timeout: {}", timeout);
let executable = data.get_executable();
if executable.is_empty() {
return String::new();
}
if data.executables.contains(&executable.to_string()) {
if let Some(unrunnable) = &data.config.blocking_commands
&& unrunnable.contains(&executable.to_string())
{
return String::new();
}
if blocking_commands().contains(&executable) {
return String::new();
}
}
if let Some(error) =
get_error_from_multiplexer(shell, &data.prompt_prefix, &data.input_command)
{
let message = format!("Captured output from multiplexer: '{}'", error);
dlog(5, &message);
error
} else {
error_output_threaded(shell, command, timeout)
}
};
error.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(
clean_shell_command(shell, command)
.env("LC_ALL", "C")
.output()
.unwrap_or_else(|_| {
panic!(
"failed to execute process, is '{}' the correct executable?",
shell
)
}),
)
.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 = clean_shell_command(shell, command)
.env("LC_ALL", "C")
.output()
.unwrap_or_else(|_| {
panic!(
"failed to execute process, is '{}' the correct executable?",
shell
)
});
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 = clean_shell_command(shell, command)
.env("LC_ALL", "C")
.output()
.unwrap_or_else(|_| {
panic!(
"failed to execute process, is '{}' the correct executable?",
shell
)
});
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 mut last_command = data.command.clone();
let comments = data.comments.clone();
let error_msg = &data.error;
let executables = {
let exes = data.executables.clone().join(" ");
if exes.len() < 100_000 {
exes
} else {
"".to_string()
}
};
if let Some(comments) = comments {
last_command = format!("{} # {}", last_command, comments);
}
let output = clean_shell_command(shell, 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,
}
}
#[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" => {
// fix for multiline aliases
let lines = env.split("\nalias ").collect::>().into_iter();
for line in lines {
let (alias, command) = line.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());
}
}
"pwsh" | "powershell" | "ps" => {
for line in env.lines() {
if !line.starts_with("Alias ") {
continue;
}
let line = line.replacen("Alias ", "", 1);
let (alias, command) = line.split_once("->").unwrap();
let command = command.split_whitespace().next().unwrap_or("");
alias_map.insert(alias.trim().to_string(), command.trim().to_string());
}
}
"nu" | _ => {
for line in env.lines() {
let (alias, command) = line.split_once('=').unwrap();
alias_map.insert(alias.to_string(), command.to_string());
}
}
}
remove_env_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, "")
};
if alias_skip_expand().contains(&command) {
return None;
}
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> {
shell: &'a str,
alias: &'a str,
binary_path: &'a str,
cnf: bool,
}
#[derive(Template)]
#[template(path = "init.zsh", escape = "none")]
struct ZshTemplate<'a> {
shell: &'a str,
alias: &'a str,
binary_path: &'a str,
cnf: bool,
}
#[derive(Template)]
#[template(path = "init.fish", escape = "none")]
struct FishTemplate<'a> {
shell: &'a str,
alias: &'a str,
binary_path: &'a str,
cnf: bool,
}
#[derive(Template)]
#[template(path = "init.ps1", escape = "none")]
struct PowershellTemplate<'a> {
shell: &'a str,
alias: &'a str,
binary_path: &'a str,
cnf: bool,
}
#[derive(Template)]
#[template(path = "init.nu", escape = "none")]
struct NuTemplate<'a> {
shell: &'a str,
alias: &'a str,
binary_path: &'a str,
}
let initialize = match shell.as_str() {
"bash" => BashTemplate {
shell,
alias,
binary_path,
cnf,
}
.render()
.unwrap(),
"zsh" => ZshTemplate {
shell,
alias,
binary_path,
cnf,
}
.render()
.unwrap(),
"fish" => FishTemplate {
shell,
alias,
binary_path,
cnf,
}
.render()
.unwrap(),
"pwsh" | "powershell" | "ps" => PowershellTemplate {
shell,
alias,
binary_path,
cnf,
}
.render()
.unwrap(),
"nu" | "nush" | "nushell" => NuTemplate {
shell,
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('>')
|| 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 prefixes = vec!["cd ", "Set-Location "];
let cd = if success {
let dirs = {
let mut dirs = Vec::new();
for line in lines {
for prefix in &prefixes {
if let Some(dir) = line.strip_prefix(prefix) {
dirs.push(dir.to_string());
break;
}
}
}
dirs.join("")
};
if dirs.is_empty() {
None
} else if shell == "nu" {
Some(
dirs.trim_matches('`')
.trim_matches('"')
.trim_matches('\'')
.to_string(),
)
} 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> {
command: &'a str,
cd: &'a str,
}
#[derive(Template)]
#[template(path = "eval.ps1", escape = "none")]
struct PwshTemplate<'a> {
command: &'a str,
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" | "nush" | "nushell" => {
// JSON-escape the fields so init.nu can parse the output with `from json`
let escape_json = |s: &str| {
s.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t")
};
let command = escape_json(command);
let cd_escaped = cd.as_deref().map(escape_json).unwrap_or_default();
let template = NuTemplate {
command: &command,
cd: &cd_escaped,
};
template.render().unwrap()
}
"pwsh" | "powershell" | "ps" => {
// Single-quoted PowerShell string: only ' needs escaping (doubled).
let command = command.replace('\'', "''");
let template = PwshTemplate {
command: &command,
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.8.8/core/src/suggestions.rs 0000664 0000000 0000000 00000016732 15173770737 0020637 0 ustar 00root root 0000000 0000000 use std::io::stderr;
use std::process::{Stdio, exit};
use std::thread;
use std::time::{Duration, Instant};
use colored::Colorize;
use pay_respects_select::select;
use pay_respects_utils::log::dlog;
use pay_respects_utils::strings::{format_prefix, print_error, remove_color_codes};
use crate::config;
use crate::data::Data;
use crate::highlighting::highlight_difference;
use crate::integrations::get_error_from_multiplexer;
use crate::rules::match_rule;
use crate::shell::{
add_candidates_no_dup, add_privilege, module_output, shell_evaluated_commands, shell_syntax,
};
pub fn suggest_candidates(data: &mut Data) {
if data.split.is_empty() {
return;
}
let shell = &data.shell;
let command = &data.command;
let mut final_candidates = vec![];
let fallbacks = &data.fallbacks;
if let Some(candidates) = get_standard_suggestions(data) {
add_candidates_no_dup(command, &mut final_candidates, &candidates);
data.candidates = final_candidates
.iter()
.map(|s| shell_syntax(shell, s))
.collect();
}
if !final_candidates.is_empty() {
return;
}
for fallback in fallbacks {
let candidates = module_output(data, fallback);
if let Some(candidates) = candidates {
add_candidates_no_dup(command, &mut final_candidates, &candidates);
data.candidates = final_candidates
.iter()
.map(|s| shell_syntax(shell, s))
.collect();
return;
}
}
}
fn get_standard_suggestions(data: &Data) -> Option> {
let command = &data.command;
// likely comment only
if command.is_empty() {
return None;
}
let target_rule = data.get_target_rule();
let privilege = &data.privilege;
let mut suggest_candidates = vec![];
let mut module_candidates = vec![];
let mut final_candidates = vec![];
let modules = &data.modules;
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_rule(target_rule, data) {
add_candidates_no_dup(command, &mut suggest_candidates, &candidates);
}
if let Some(candidates) = match_rule("_PR_general", data) {
add_candidates_no_dup(command, &mut suggest_candidates, &candidates);
}
if privilege.is_none()
&& let Some(candidates) = match_rule("_PR_privilege", data)
{
add_candidates_no_dup(command, &mut suggest_candidates, &candidates);
}
});
add_candidates_no_dup(command, &mut final_candidates, &module_candidates);
add_candidates_no_dup(command, &mut final_candidates, &suggest_candidates);
if !final_candidates.is_empty() {
return Some(final_candidates);
}
if std::env::var("_PR_NO_DESPERATE").is_err()
&& let Some(candidates) = match_rule("_PR_fallback", data)
{
add_candidates_no_dup(command, &mut final_candidates, &candidates);
return Some(final_candidates);
}
None
}
pub fn select_candidate(data: &mut Data) {
let candidates = &data.candidates;
#[cfg(debug_assertions)]
eprintln!("candidates: {candidates:?}");
let mut active_candidates = candidates
.iter()
.map(|candidate| highlight_difference(data, candidate, true).unwrap())
.collect::>();
if active_candidates.iter().any(|x| x.contains('\n')) {
for candidate in active_candidates.iter_mut() {
*candidate = candidate.replace("\n", "\r\n ").to_string();
}
}
let mut inactive_candidates = candidates
.iter()
.map(|candidate| highlight_difference(data, candidate, false).unwrap())
.collect::>();
if inactive_candidates.iter().any(|x| x.contains('\n')) {
for candidate in inactive_candidates.iter_mut() {
*candidate = candidate.replace("\n", "\r\n ").to_string();
}
}
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());
let prelude = format!("{}\n\r{}", msg, hint);
let selection =
select(&prelude, &active_candidates, &inactive_candidates).unwrap_or_else(|err| {
print_error(&format!("Selection failed: {}", err));
exit(1);
});
let selected = active_candidates[selection].to_string();
let output = if let Some(prefix) = &data.prompt_prefix {
let output = format_prefix(prefix, &selected);
data.input_command = remove_color_codes(&output)
.trim_start_matches(prefix)
.to_string();
output
} else {
selected
};
eprintln!("{}", output);
let suggestion = candidates[selection].to_string();
data.update_suggest(&suggestion);
data.expand_suggest();
data.candidates.clear();
}
pub fn execute_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_execution(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);
}
get_suggestion_error(data, command)
}
}
pub fn inline_suggestion(data: &mut Data) {
if data.split.is_empty() {
return;
}
if let Some(candidates) = get_standard_suggestions(data) {
data.candidates = candidates
.iter()
.map(|s| shell_syntax(&data.shell, s))
.collect();
}
}
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_execution(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 get_suggestion_error(data: &Data, command: &str) -> Result<(), String> {
let shell = &data.shell;
if let Some(err) = get_error_from_multiplexer(shell, &data.prompt_prefix, &data.input_command) {
let message = format!("Captured output from multiplexer: '{}'", err);
dlog(5, &message);
return Err(err);
}
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),
false => String::from_utf8_lossy(&process.stderr),
};
Err(error_msg.to_string())
}
pay-respects-0.8.8/core/src/system.rs 0000664 0000000 0000000 00000017415 15173770737 0017610 0 ustar 00root root 0000000 0000000 use crate::data::Data;
use crate::shell::command_output_or_error;
use crate::shell::{command_output, elevate};
use pay_respects_utils::strings::{format_prefix, print_warning, unexpected_format};
use std::io::stderr;
use std::process::Command;
use std::process::Stdio;
use crate::config::InstallMethod;
use colored::*;
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.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()) {
print_warning("apt-file is required to find packages");
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| {
let bin = line.split_once(':');
if let Some((pkg, _)) = bin {
pkg.to_string()
} else {
unexpected_format(line);
"".to_string()
}
})
.filter(|s| !s.is_empty())
.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()) {
print_warning("pfl is required to find packages");
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" => {
let packages: Vec;
if data.executables.contains(&"nix-locate".to_string()) {
let result =
command_output(shell, &format!("nix-locate --regex 'bin/{}$'", executable));
if result.is_empty() {
return None;
}
packages = result
.lines()
.map(|line| {
let out = line.split_whitespace().next().unwrap().rsplit_once('.');
if let Some((pkg, _)) = out {
pkg.to_string()
} else {
unexpected_format(line);
"".to_string()
}
})
.filter(|s| !s.is_empty())
.collect();
} else if data.executables.contains(&"nix-search".to_string()) {
let result = command_output(shell, &format!("nix-search '{}'", executable));
if result.is_empty() {
return None;
}
packages = result
.lines()
.map(|line| line.split_whitespace().next().unwrap().to_string())
.collect()
} else {
print_warning("nix-locate or nix-search is required to find packages");
return None;
};
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")
|| result.contains("can be installed")
{
let packages = result
.lines()
.skip(1)
.map(|line| line.trim().to_string())
.collect();
return Some(packages);
}
None
}
false => {
print_warning("Unsupported package manager");
None
}
},
}
}
pub fn install_string(data: &mut Data, package_manager: &str, package: &str) -> String {
let method = &data.config.install_method;
match package_manager {
"apt" | "dnf" | "pkg" | "yum" | "zypper" => {
format!("{} install {}", package_manager, package)
}
"emerge" => format!("emerge {}", package),
"guix" => {
if method == &InstallMethod::Shell {
return format!("guix shell {}", package);
}
format!("guix package -i {}", package)
}
"nix" => {
if method == &InstallMethod::Shell {
return format!("nix-shell -p {}", package,);
}
format!("nix profile install nixpkgs#{}", package)
}
"pacman" => format!("pacman -S {}", package),
_ => match package_manager.ends_with("command-not-found") {
true => package.to_string(),
false => unreachable!("Unsupported package manager"),
},
}
}
pub fn install_package(data: &mut Data, package_manager: &str, install: &str) -> bool {
let shell = data.shell.clone();
let mut install = install.to_string();
if package_manager.ends_with("command-not-found") && install.starts_with("Command ") {
let split = install.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);
install = format!("apt install {}", package)
}
// 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 output = if let Some(prefix) = &data.prompt_prefix {
format_prefix(prefix, &install)
} else {
install.clone()
};
eprintln!("{}", output.cyan());
let result = Command::new(shell)
.arg("-c")
.arg(install)
.stdout(stderr())
.stderr(Stdio::inherit())
.status()
.expect("failed to execute process");
result.success()
}
pub fn install_package_shell(data: &Data, package_manager: &str, install: &str) -> String {
let command = data.command.clone();
let output = if let Some(prefix) = &data.prompt_prefix {
format_prefix(prefix, install)
} else {
install.to_string()
};
eprintln!("{}", output.cyan());
match package_manager {
"guix" => format!("{} -- {}", install, command),
"nix" => format!(r#"{} --command "{};return""#, install, command),
_ => unreachable!("Only `nix` and `guix` are supported for shell installation"),
}
}
pay-respects-0.8.8/core/templates/ 0000775 0000000 0000000 00000000000 15173770737 0017115 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/core/templates/eval.bash 0000664 0000000 0000000 00000000136 15173770737 0020703 0 ustar 00root root 0000000 0000000 builtin history -s "{{ command }}";
{%- if let Some(cd) = self.cd %}
cd {{ cd }}
{% endif %}
pay-respects-0.8.8/core/templates/eval.fish 0000664 0000000 0000000 00000000171 15173770737 0020716 0 ustar 00root root 0000000 0000000 builtin history append "{{ command }}";
builtin history merge;
{%- if let Some(cd) = self.cd %}
cd {{ cd }}
{% endif %}
pay-respects-0.8.8/core/templates/eval.nu 0000664 0000000 0000000 00000000061 15173770737 0020405 0 ustar 00root root 0000000 0000000 { "cd": "{{ cd }}", "command": "{{ command }}" }
pay-respects-0.8.8/core/templates/eval.ps1 0000664 0000000 0000000 00000000276 15173770737 0020476 0 ustar 00root root 0000000 0000000 {%- if !command.is_empty() %}
try { [Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory('{{ command }}') } catch {}
{%- endif %}
{%- if let Some(cd) = self.cd %}
cd {{ cd }}
{%- endif %}
pay-respects-0.8.8/core/templates/eval.sh 0000664 0000000 0000000 00000000071 15173770737 0020376 0 ustar 00root root 0000000 0000000 {%- if let Some(cd) = self.cd %}
cd {{ cd }}
{% endif %}
pay-respects-0.8.8/core/templates/eval.zsh 0000664 0000000 0000000 00000000134 15173770737 0020570 0 ustar 00root root 0000000 0000000 builtin print -s "{{ command }}";
{%- if let Some(cd) = self.cd %}
cd {{ cd }}
{% endif %}
pay-respects-0.8.8/core/templates/init.bash 0000664 0000000 0000000 00000001115 15173770737 0020715 0 ustar 00root root 0000000 0000000 alias {{ alias }}="__pr_main suggest"
__pr_main() {
eval $(__pr_base "$1" "$(fc -ln -1)")
}
__pr_base() {
prefix="${PS1@P}"
_PR_MODE="$1" _PR_PREFIX="$prefix" _PR_LAST_COMMAND="$2" _PR_ALIAS="`alias`" _PR_SHELL="{{ shell }}" "{{ binary_path }}"
}
__pr_inline() {
local input="$READLINE_LINE"
local output=$(__pr_base "inline" "$input")
{% raw %}
if [[ -n "$output" ]]; then
READLINE_LINE="$output"
READLINE_POINT=${#READLINE_LINE}
fi
{% endraw %}
}
bind -x '"\C-x\C-x":__pr_inline'
{%- if cnf %}
command_not_found_handle() {
eval $(__pr_base "cnf" "$*")
}
{% endif %}
pay-respects-0.8.8/core/templates/init.fish 0000664 0000000 0000000 00000001521 15173770737 0020732 0 ustar 00root root 0000000 0000000 function {{ alias }} -d "Suggest fixes to the previous command"
__pr_main suggest
end
function __pr_main -a mode
set command (builtin history | head -n 1)
eval (__pr_base "$mode" "$command")
end
function __pr_base -a mode last_command
set prefix (set -q SHELL_PROMPT_SUFFIX; and echo $SHELL_PROMPT_SUFFIX; or fish_prompt)
_PR_MODE="$mode" _PR_PREFIX="$prefix" _PR_LAST_COMMAND="$last_command" _PR_ALIAS="$(alias)" _PR_SHELL="{{ shell }}" "{{ binary_path }}"
end
function __pr_inline
set input (commandline)
set output (__pr_base "inline" "$input")
if test -n "$output"
commandline --replace "$output"
end
end
for mode in default insert
bind -M $mode \cx\cx __pr_inline
end
{%if cnf %}
if status is-interactive
function fish_command_not_found --on-event fish_command_not_found
eval (__pr_base "cnf" "$argv")
end
end
{% endif %}
pay-respects-0.8.8/core/templates/init.nu 0000664 0000000 0000000 00000002610 15173770737 0020423 0 ustar 00root root 0000000 0000000 def --env {{ alias }} [] {
__pr_main suggest
}
def --env __pr_main [mode: string] {
let command = (history | last).command
let output = (__pr_base $mode $command)
if ($output | str trim | is-empty) { return }
let wrapped = ('[' + ($output | str replace -r '}\s*{' '},{') + ']')
let data = (try { $wrapped | from json } catch { null })
if $data == null { return }
for d in $data {
if ($d.command != "") {
if $env.config.history.file_format == "plaintext" {
$"($d.command)\n" | save --append $nu.history-path
} else {
[$d.command] | history import
}
}
if ($d.cd != "") {
cd $d.cd
}
}
}
def __pr_base [mode: string, command: string] {
let alias = (help aliases | select name expansion | each ({ |row| $row.name + "=" + $row.expansion }) | str join (char nl))
let prefix = if ($env.PROMPT_INDICATOR | is-not-empty) { $env.PROMPT_INDICATOR } else { do $env.PROMPT_COMMAND }
with-env { _PR_MODE: $mode, _PR_PREFIX: $prefix, _PR_LAST_COMMAND: $command, _PR_ALIAS: $alias, _PR_SHELL: {{ shell }} } {
`{{ binary_path }}`
}
}
def __pr_inline [] {
let input = (commandline)
let output = (__pr_base inline $input)
if ($output | is-not-empty) {
commandline edit --replace $output
}
}
$env.config.keybindings ++= [
{
name: __pr_inline
modifier: control
keycode: char_x
mode: [emacs, vi_normal, vi_insert]
event: {
send: executehostcommand
cmd: "__pr_inline"
}
}
]
pay-respects-0.8.8/core/templates/init.ps1 0000664 0000000 0000000 00000003466 15173770737 0020516 0 ustar 00root root 0000000 0000000 function {{ alias }} {
__pr_main suggest
}
function __pr_main {
param(
[string]$mode
)
$Command = (Get-History -Count 1).CommandLine
__pr_base $mode $Command | Invoke-Expression
}
function __pr_base {
param(
[string]$mode,
[string]$Command
)
try {
$env:_PR_PREFIX = (prompt)
$env:_PR_MODE = $mode
$env:_PR_LAST_COMMAND = $Command
$env:_PR_ALIAS = (Get-Alias | Out-String)
$env:_PR_SHELL = "{{ shell }}"
& '{{ binary_path }}'
} finally {
$env_PR_PREFIX = $null;
$env:_PR_MODE = $null;
$env:_PR_LAST_COMMAND = $null;
$env:_PR_ALIAS = $null;
$env:_PR_SHELL = $null;
}
}
function __pr_inline {
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
$mode = 'inline'
$command = $line
$output = __pr_base $mode $command
if (-not [string]::IsNullOrWhiteSpace($output)) {
[Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, $line.Length, $output)
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($output.Length)
}
if ($env:_PR_MODE -eq 'inline') {
$env:_PR_MODE = $null;
}
}
Set-PSReadLineKeyHandler -Chord Ctrl+x,Ctrl+x -ScriptBlock { __pr_inline }
# Uncomment this block to enable command not found hook
# It's not very useful as we can't retrieve arguments,
{%- if cnf %}
# function __pr_invoke {
# try {
# &'{{ binary_path }}' | Invoke-Expression;
# } finally {
# $env:_PR_MODE = $env:null;
# $env:_PR_LAST_COMMAND = $env:null;
# $env:_PR_SHELL = $env:null;
# }
# }
# $ExecutionContext.InvokeCommand.CommandNotFoundAction = {
# param($commandName, $eventArgs)
# $env:_PR_LAST_COMMAND = $commandName -replace '^get-|\.\\','';
# $env:_PR_SHELL = 'pwsh';
# $env:_PR_MODE = 'cnf';
# $eventArgs.Command = (Get-Command __pr_invoke);
# $eventArgs.StopSearch = $True;
# }
{% endif %}
pay-respects-0.8.8/core/templates/init.zsh 0000664 0000000 0000000 00000001143 15173770737 0020605 0 ustar 00root root 0000000 0000000 alias {{ alias }}="__pr_main suggest"
function __pr_main() {
eval $(__pr_base "$1" "$(fc -ln -1)")
}
function __pr_base() {
prefix=$(print -P "$PROMPT")
_PR_MODE="$1" _PR_PREFIX="$prefix" _PR_LAST_COMMAND="$2" _PR_ALIAS="`alias`" _PR_SHELL="{{ shell }}" "{{ binary_path }}"
}
function __pr_inline() {
local input="$BUFFER"
local output=$(__pr_base "inline" "$input")
{% raw %}
if [[ -n "$output" ]]; then
BUFFER="$output"
CURSOR=${#BUFFER}
fi
{% endraw %}
}
zle -N __pr_inline
bindkey '^X^X' __pr_inline
{%- if cnf %}
command_not_found_handler() {
eval $(__pr_base "cnf" "$*")
}
{% endif %}
pay-respects-0.8.8/flake.lock 0000664 0000000 0000000 00000001071 15173770737 0016122 0 ustar 00root root 0000000 0000000 {
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1770141374,
"narHash": "sha256-yD4K/vRHPwXbJf5CK3JkptBA6nFWUKNX/jlFp2eKEQc=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "41965737c1797c1d83cfb0b644ed0840a6220bd1",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
pay-respects-0.8.8/flake.nix 0000664 0000000 0000000 00000002425 15173770737 0015774 0 ustar 00root root 0000000 0000000 {
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-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.8.8/flowchart.mmd 0000664 0000000 0000000 00000002475 15173770737 0016667 0 ustar 00root root 0000000 0000000 flowchart TD
init{{"Start"}}
err["Get error message"]
suggest["Match suggestion"]
found{"Got suggestions?"}
success{"Execution successful?"}
exit{{"Exit"}}
init --> err --> suggest --> found -->|Yes, prompt fixes| success -->|Yes| exit
%% subgraph "Main Flow"
%% init
%% err
%% suggest
%% found
%% success
%% exit
%% end
subgraph errsource["Error sources"]
direction TB
from_env["Environment variable"]
from_multiplexer["`Terminal multiplexer
(tmux, GNU Screen, Zellij)
(WezTerm, kitty)`"]
%% subgraph multiplexer["Terminal multiplexers"]
%% direction LR
%% from_tmux["tmux"]
%% from_screen["GNU Screen"]
%% from_zellij["Zellij"]
%% end
from_execution["Last command execution"]
end
from_env --> from_multiplexer --> from_execution
%% from_tmux --- from_screen --- from_zellij
errsource --> err
%% from_env["Enviroment variable"] --> err
%% from_tmux["`tmux`"] --> err
%% from_execution["Last command execution"] --> err
subgraph suggestsource["Suggestion sources"]
direction LR
builtin
module
fallback
end
%% suggestsource --> suggest
builtin["Compiled suggestions"] --> suggest
module["Module suggestions"] --> suggest
%% fallback modules loop
found -->|No| fallback["Fallback modules"]
fallback --> |If no suggestions| exit
fallback --> |If gives suggestions, prompt fixes| success
%% found -->|Yes| success
success -->|No| err
pay-respects-0.8.8/init.fish 0000664 0000000 0000000 00000000150 15173770737 0016001 0 ustar 00root root 0000000 0000000 if command -sq zoxide
pay-respects fish --alias | source
else
echo "pay-respects is not in $PATH"
end
pay-respects-0.8.8/install.ps1 0000664 0000000 0000000 00000004374 15173770737 0016272 0 ustar 00root root 0000000 0000000 $RepoOwner = "iffse"
$RepoName = "pay-respects"
$InstallDir = "$HOME\AppData\Roaming\pay-respects"
$SysArch = $env:PROCESSOR_ARCHITECTURE
$PackageArch = switch ($SysArch) {
"AMD64" { "x86_64" }
"ARM64" { "aarch64" }
Default { throw "Unsupported architecture: $SysArch" }
}
Write-Host "Detected Architecture: $SysArch" -ForegroundColor Cyan
$ApiUrl = "https://api.github.com/repos/$RepoOwner/$RepoName/releases/latest"
try {
$Release = Invoke-RestMethod -Uri $ApiUrl -Method Get -Headers @{"User-Agent"="PowerShell-Downloader"}
} catch {
throw "Failed to fetch release info: $_"
}
$Asset = $Release.assets | Where-Object { $_.name -like "*$PackageArch*" -and $_.name -like "*pc-windows*" }
if (-not $Asset) {
throw "Could not find a asset for $PackageArch in version $($Release.tag_name)"
}
$DownloadUrl = $Asset.browser_download_url
$ZipFile = Join-Path $env:TEMP $Asset.name
Write-Host "Downloading $($Asset.name)..." -ForegroundColor Yellow
Invoke-WebRequest -Uri $DownloadUrl -OutFile $ZipFile
if (-not (Test-Path $InstallDir)) {
New-Item -Path $InstallDir -ItemType Directory | Out-Null
}
Write-Host "Extracting to $InstallDir..." -ForegroundColor Yellow
Expand-Archive -Path $ZipFile -DestinationPath $InstallDir -Force
# add to user level PATH
Write-Host "Updating PATH environment variable..." -ForegroundColor Cyan
$CurrentPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($CurrentPath -notlike "*$InstallDir*") {
$NewPath = "$CurrentPath;$InstallDir"
[Environment]::SetEnvironmentVariable("Path", $NewPath, "User")
$env:Path = $NewPath # Update current session path
Write-Host "Successfully added $InstallDir to User PATH." -ForegroundColor Green
}
Write-Host "Installation of $($Release.tag_name) finished!"
Write-Host "pay-respects has an optional AI module to provide suggestions when no rules match"
Write-Host "The module works out-of-the-box with no data collection"
Write-Host "Do you want to keep the AI module? (Y/n)" -ForegroundColor Yellow
$Response = Read-Host
if ($Response -eq "n" -or $Response -eq "N") {
$AIModulePath = Join-Path $InstallDir "_pay-respects-fallback-100-request-ai.exe"
if (Test-Path $AIModulePath) {
Remove-Item -Path $AIModulePath -Recurse -Force
Write-Host "AI module removed." -ForegroundColor Green
}
}
pay-respects-0.8.8/install.sh 0000664 0000000 0000000 00000030352 15173770737 0016174 0 ustar 00root root 0000000 0000000 #!/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
if check_cmd zstd; then
ensure zstd -d -c "${_package}" | tar -x
else
ensure tar -xf "${_package}"
fi
;;
*.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}"
echo "Installed pay-respects to ${BIN_DIR}"
for _module in ${_modules}; do
ensure try_sudo cp -- "${_module}" "${BIN_DIR}/${_module}"
ensure try_sudo chmod +x "${BIN_DIR}/${_module}"
echo "Installed module (${_module}) to ${BIN_DIR}"
done
# 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
echo ""
echo "pay-respects has an optional AI module to provide suggestions when no rules match"
echo "The module works out-of-the-box with no data collection"
echo "Do you want to keep the AI module? [Y/n]"
read -r _keep_AI
if [ "${_keep_AI}" = "N" ] || [ "${_keep_AI}" = "n" ] ; then
for _module in ${_modules}; do
if echo "${_module}" | grep -q "request-ai"; then
ensure try_sudo rm -f -- "${BIN_DIR}/${_module}"
echo "AI module removed."
fi
done
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.8.8/man-src/ 0000775 0000000 0000000 00000000000 15173770737 0015527 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/man-src/pay-respects-modules.5.md 0000664 0000000 0000000 00000004237 15173770737 0022307 0 ustar 00root root 0000000 0000000 % PAY_RESPECTS(5) pay-respects 0.8.8 | Modules
% iff
% April 2026
# 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 after sorting. 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 ';'
```
# SEE ALSO
**pay-respects-rules**(5), **pay-respects**(1)
pay-respects-0.8.8/man-src/pay-respects-rules.5.md 0000664 0000000 0000000 00000012515 15173770737 0021767 0 ustar 00root root 0000000 0000000 % PAY_RESPECTS(5) pay-respects 0.8.8 | Rule File
% iff
% April 2026
# 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!
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
# If multiple commands could share the same rules, add it to extends
command = "hello"
extends = ["goodbye"]
# You can add as many `[[match_err]]` section as you want
[[match_err]]
# Note:
# - 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
# - This field is optional, always match if omitted
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}} '''
]
```
## Rust Functions
You can also write in Rust if the rule is very complex. This is only allowed
during compilation, by previously defining your function in
[`rules_functions.rs`](./core/src/rules_function.rs):
```toml
[[match_err]]
pattern = [
"pattern 1"
]
suggest = [
'''
#[FUNCTION]
MyRustFunction '''
]
```
## Placeholders
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
## Conditions
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 (using `,` requires escaping, i.e. `\,`)
- `err_contains`: Same as `cmd_contains` but for error message (all lowercase)
- `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
## Identifiers
Identifiers are used to reuse rules for specific purposes:
- `INLINE`: Reuse the rule for `inline` mode. Patterns are ignored.
## Other Considerations
When suggesting a chained command with `&&`, try to break it into multiple lines.
- More readable if the commands are long
- Automatic conversion to compatible syntax where `&&` is unavailable (e.g. nushell)
Example:
```toml
suggest = [
'''
command1 &&
command2 '''
]
```
# SEE ALSO
**pay-respects**(1), **pay-respects-modules**(5)
pay-respects-0.8.8/man-src/pay-respects.1.md 0000664 0000000 0000000 00000004505 15173770737 0020633 0 ustar 00root root 0000000 0000000 % PAY_RESPECTS(1) pay-respects 0.8.8 | User Commands
% iff
% April 2026
# NAME
pay-respects - Blazing fast terminal command suggestions
# SYNOPSIS
**pay-respects** *shell* [*options*]
# DESCRIPTION
pay-respects is a terminal suggestion tool that fixes your previous or current
typed command, with a sub-millisecond (<1ms) performance.
# OPTIONS
-h, --help
: Show help message and exit.
--alias
: Set a custom alias instead of `f`
--nocnf
: Disable command-not-found handler
# INITIALIZATION
## Bash / Zsh / Fish
Add the following line to your configuration file:
```sh
eval "$(pay-respects bash --alias)"
eval "$(pay-respects zsh --alias)"
pay-respects fish --alias | source
```
## Nushell / PowerShell
Add the following output to your configuration file. Replace the shell with the
actual executable name if needed.
```sh
pay-respects nu
pay-respects pwsh
```
# USAGE
Fix your previous command
```
f
```
Fix your current typed command
```
```
# Examples
```
gitcommit + + f + --> git commit
gitcommit + + --> git commit
```
# ENVIRONMENT VARIABLES
## Required
_PR_SHELL
: The binary name of the current working shell
_PR_LAST_COMMAND
: The last command
## Optional
_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
_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
_PR_MODE
: Execution mode.
## Configuration
_PR_PREFIX
: Shell prompt prefix, required for log capture from terminal multiplexers
_PR_NO_DESPERATE
: Disable desperate functions, which are slow but can give
better results
_PR_NO_CONFIG
: Don't load configurations
_PR_NO_ZOXIDE:
: Don't use zoxide
_PR_NO_MULTIPLEXER
: Equivalent of turning all the followings: `_PR_NO_TMUX`, `_PR_NO_SCREEN`, `_PR_NO_ZELLIJ`, `_PR_NO_WEZTERM`, `_PR_NO_KITTY`
# SEE ALSO
**pay-respects-rules**(5), **pay-respects-modules**(5)
pay-respects-0.8.8/man-src/pay-respects.5.md 0000664 0000000 0000000 00000005177 15173770737 0020645 0 ustar 00root root 0000000 0000000 % PAY_RESPECTS(5) pay-respects 0.8.8 | Configuration File
% iff
% April 2026
# Configuration File
User configuration file for `pay-respects` is located at:
- `$HOME/.config/pay-respects/config.toml` (*nix)
- `%APPDATA%/pay-respects/config.toml` (Windows)
Directories for system-wide configuration, which fields can be overwritten
individually by the user configuration file are searched on:
- `$XDG_CONFIG_DIRS` (*nix)
- If not set, `/etc/xdg`
- `$PROGRAMDATA` (Windows)
- If not set, `C:\ProgramData`
With the same directory structure, e.g. `/etc/xdg/pay-respects/config.toml`
## Options
All available options are listed in the following example file:
```toml
# Preferred command for privileged acesses
privilege = "sudo"
# Maximum time in milliseconds for getting previous output
timeout = 3000
# Apply existing rules to a set of commands. Every set will use the rule
# corresponding to the first entry
merge_commands = [
["ls", "exa"], # both using rules corresponding to `ls`
["grep", "rg"], # both using rules corresponding to `grep`
]
# Commands that won't return any message when run,
# which is most of the interactive commands
blocking_commands = ["vim", "nano"]
# 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"
# Algorithm used for fuzzy searching
# Options:
# - TrigramDamerauLevenshtein: More computationally expensive
# - DamerauLevenshtein: Fast
search_type = "TrigramDamerauLevenshtein"
# Minimum characters required to start seaching
# Avoids false positive when input strings are too short
search_threshold = 3
# Minimum score for the result to be valid: [0,1]
[trigram]
minimum_score = 0.5
# Configuring the linguistic distance (Damerau-Levenshtein)
# - Percentage: How many characters can be different in the suggestion, rounded
# to the nearest integer.
# - Threshold: How many characters are required for the reference string to
# start searching to avoid false positives when the reference string is too
# short.
# - Max: Maximum distance allowed between the reference and the suggestion.
# - Min: Minimum strating distance required. Seach only starts if the distance
# obtained after the percentage calculation is above or equal to this value.
[dl_distance]
percentage = 27.1828182845904523536028747135266250
max = 5
min = 1
[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.8.8/man/ 0000775 0000000 0000000 00000000000 15173770737 0014742 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/man/pay-respects-modules.5 0000664 0000000 0000000 00000005341 15173770737 0021120 0 ustar 00root root 0000000 0000000 .\" Automatically generated by Pandoc 3.9.0.2
.\"
.TH "PAY_RESPECTS" "5" "April 2026" "pay\-respects 0.8.8" "Modules"
.SH Creating a Module
There are 2 types of modules:
.IP \(bu 2
\f[B]Standard module\f[R]: Will always run to retrieve suggestions
.RS 2
.IP \(bu 2
Naming convention:
\f[CR]_pay\-respects\-module\-\-\f[R]
.RE
.IP \(bu 2
\f[B]Fallback module\f[R]: Will only be run if no previous suggestion
were found
.RS 2
.IP \(bu 2
\f[B]CAUTION\f[R]: Will immediately return if a suggestion is obtained
.IP \(bu 2
Naming convention:
\f[CR]_pay\-respects\-fallback\-\-\f[R]
.RE
.PP
Priority is used to retrieve suggestions in a specific order after
sorting.
Default modules have a priority of \f[CR]100\f[R].
.PP
When running your module, you will get the following environment
variables:
.IP \(bu 2
\f[CR]_PR_SHELL\f[R]: User shell
.IP \(bu 2
\f[CR]_PR_COMMAND\f[R]: The command, without arguments
.IP \(bu 2
\f[CR]_PR_LAST_COMMAND\f[R]: Full command with arguments
.IP \(bu 2
\f[CR]_PR_ERROR_MSG\f[R]: Error message from the command
.IP \(bu 2
\f[CR]_PR_EXECUTABLES\f[R]: A space (\f[CR]\f[R]) separated list of
executables in \f[CR]PATH\f[R].
Limited to 100k characters, empty if exceeded.
.PP
Your module should print:
.IP \(bu 2
\f[B]To \f[CB]stdout\f[B]\f[R]: Only suggestions.
.RS 2
.IP \(bu 2
At the end of each suggestion, append \f[CR]<_PR_BR>\f[R] so
pay\-respects knows you are either done or adding another suggestion
.RE
.IP \(bu 2
\f[B]To \f[CB]stderr\f[B]\f[R]: Any relevant information that should
display to the user (e.g, warning for AI generated content)
.PP
An example of a shell based module that always suggest adding a
\f[CR]sudo\f[R] or \f[CR]doas\f[R]:
.IP
.EX
\f[I]#!/bin/sh\f[R]
echo \(dqsudo $_PR_LAST_COMMAND\(dq
echo \(dq<_PR_BR>\(dq
echo \(dqdoas $_PR_LAST_COMMAND\(dq
.EE
.SH Adding a Module
Expose your module as executable (\f[CR]chmod u+x\f[R]) in
\f[CR]PATH\f[R], and done!
.SS \f[CR]LIB\f[R] directories
If exposing modules in \f[CR]PATH\f[R] annoys you, you can set the
\f[CR]_PR_LIB\f[R] environment variable to specify directories to find
the modules, separated by \f[CR]:\f[R] or \f[CR];\f[R] (analogous to
\f[CR]PATH\f[R]):
.PP
Example in a \c
.UR https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s06.html
FHS 3.0 compliant system
.UE \c
:
.IP
.EX
# compile\-time
export _DEF_PR_LIB=\(dq/usr/lib\(dq
# runtime
export _PR_LIB=\(dq/usr/lib:$HOME/.local/share\(dq
.EE
.PP
Example in Windows/DOS compliant systems
.IP
.EX
$env:_PR_LIB = \(at(
(Join\-Path $env:APPDATA \(dqpay\-respects\(dq \(dqmodules\(dq),
(Join\-Path $env:USERPROFILE \(dq.cargo\(dq \(dqbin\(dq)
) \-join \(aq;\(aq
.EE
.SH SEE ALSO
\f[B]pay\-respects\-rules\f[R](5), \f[B]pay\-respects\f[R](1)
.SH AUTHORS
iff.
pay-respects-0.8.8/man/pay-respects-rules.5 0000664 0000000 0000000 00000014663 15173770737 0020611 0 ustar 00root root 0000000 0000000 .\" Automatically generated by Pandoc 3.9.0.2
.\"
.TH "PAY_RESPECTS" "5" "April 2026" "pay\-respects 0.8.8" "Rule File"
.SH Writing Rules
Rule files placed under rules in the project directory are parsed at
compilation, everything is parsed to Rust code before compiling.
You don\(cqt have to know the project structure nor Rust to write
blazing fast rules!
.PP
Runtime\-rules support is provided by \f[CR]runtime\-rules\f[R] module.
Directories are searched with the following priority:
.IP \(bu 2
\f[CR]XDG_CONFIG_HOME\f[R], defaults to \f[CR]$HOME/.config\f[R].
.IP \(bu 2
\f[CR]XDG_CONFIG_DIRS\f[R], defaults to \f[CR]/etc/xdg\f[R].
.IP \(bu 2
\f[CR]XDG_DATA_DIRS\f[R], defaults to
\f[CR]/usr/local/share:/usr/share\f[R].
.PP
The actual rule file should be placed under
\f[CR]pay\-respects/rules/\f[R], for example:
\f[CR]\(ti/.config/pay\-respects/rules/cargo.toml\f[R].
Note that for runtime rules, the name of the file \f[B]MUST\f[R] match
the command name.
Except \f[CR]_PR_GENERAL.toml\f[R], that is always parsed.
.SS Syntax
Syntax of a rule file:
.IP
.EX
\f[I]# The name of the command\f[R]
\f[I]# If multiple commands could share the same rules, add it to extends\f[R]
command = \(dqhello\(dq
extends = [\(dqgoodbye\(dq]
\f[I]# You can add as many \(ga[[match_err]]\(ga section as you want\f[R]
\f[B][[match_err]]\f[R]
\f[I]# Note:\f[R]
\f[I]# \- Patterns should be the output with \(gaLC_ALL=C\(ga environment variable\f[R]
\f[I]# \- This is a first\-pass match. It should be quick so regex is not supported\f[R]
\f[I]# \- This field is optional, always match if omitted\f[R]
pattern = [
\(dqpattern 1\(dq,
\(dqpattern 2\(dq
]
\f[I]# If pattern is matched, suggest changing the first argument to fix:\f[R]
suggest = [
\(aq\(aq\(aq
{{command[0]}} fix {{command[2:]}} \(aq\(aq\(aq
]
\f[B][[match_err]]\f[R]
pattern = [
\(dqpattern 1\(dq
]
\f[I]# this will add a \(gasudo\(ga before the command if:\f[R]
\f[I]# \- the \(gasudo\(ga is found as executable\f[R]
\f[I]# \- the last command does not contain \(gasudo\(ga\f[R]
suggest = [
\(aq\(aq\(aq
#[executable(sudo), !cmd_contains(sudo)]
sudo {{command}} \(aq\(aq\(aq
]
.EE
.SS Rust Functions
You can also write in Rust if the rule is very complex.
This is only allowed during compilation, by previously defining your
function in \f[CR]rules_functions.rs\f[R]:
.IP
.EX
\f[B][[match_err]]\f[R]
pattern = [
\(dqpattern 1\(dq
]
suggest = [
\(aq\(aq\(aq
#[FUNCTION]
MyRustFunction \(aq\(aq\(aq
]
.EE
.SS Placeholders
The placeholder is evaluated as following:
.IP \(bu 2
\f[CR]{{command}}\f[R]: All the command without any modification
.IP \(bu 2
\f[CR]{{command[1]}}\f[R]: The first argument of the command (the
command itself has index of 0)
.RS 2
.IP \(bu 2
Negative values will count from reverse.
.RE
.IP \(bu 2
\f[CR]{{command[2:5]}}\f[R]: The second to fifth arguments
.RS 2
.IP \(bu 2
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)
.RE
.IP \(bu 2
\f[CR]{{typo[2](fix1, fix2)}}\f[R]: Try to change the second argument to
candidates in the parenthesis.
.RS 2
.IP \(bu 2
The argument in parentheses must have at least 2 values
.IP \(bu 2
Single arguments are reserved for specific matches, for instance,
\f[CR]path\f[R] to search all commands found in the \f[CR]$PATH\f[R]
environment, or the \f[CR]{{shell}}\f[R] placeholder, among others
.RE
.IP \(bu 2
\f[CR]{{select[3](selection1, selection2)}}\f[R]: A derivative of
\f[CR]typo\f[R] placeholder.
Will create a suggestion for each selection in the parenthesis
.RS 2
.IP \(bu 2
The argument in parentheses also must have at least 2 values
.IP \(bu 2
Single arguments are reserved for specific selections, for instance,
\f[CR]path\f[R] to search all commands found in the \f[CR]$PATH\f[R]
environment with the minimum shared linguistic distance, or the
\f[CR]{{shell}}\f[R] placeholder
.IP \(bu 2
To avoid permutations and combinations, only one instance is evaluated.
If you need to apply the same selection in multiple places, use
\f[CR]{{selection}}\f[R]
.IP \(bu 2
Index is optional as it only has effect when using with \f[CR]path\f[R],
and defaults to \f[CR]0\f[R]
.RE
.IP \(bu 2
\f[CR]{{opt::}}\f[R]: Optional patterns captured in
the command with RegEx (\c
.UR https://docs.rs/regex-lite/latest/regex_lite/#syntax
see regex crate for syntax
.UE \c
)
.RS 2
.IP \(bu 2
All patterns matching this placeholder will be removed from indexing
.RE
.IP \(bu 2
\f[CR]{{cmd::}}\f[R]: Get the matching captures from
the last command
.RS 2
.IP \(bu 2
Unlike \f[CR]{{opt}}\f[R], this won\(cqt remove the string after
matching
.RE
.IP \(bu 2
\f[CR]{{err::)}}\f[R]: Replace with the output of the
shell command
.RS 2
.IP \(bu 2
Can be used along \f[CR]{{typo}}\f[R] or \f[CR]{{select}}\f[R] as its
only argument, where each newline will be evaluated to a
candidate/selection
.RE
.SS Conditions
Suggestions can have additional conditions to check.
To specify conditions, add a \f[CR]#[...]\f[R] at the first line (just
like derive macros in Rust).
Available conditions:
.IP \(bu 2
\f[CR]executable\f[R]: Check if the argument can be found in path
.IP \(bu 2
\f[CR]cmd_contains\f[R]: Check if the last user input contains the
argument.
Regex supported (using \f[CR],\f[R] requires escaping,
i.e.\ \f[CR]\(rs,\f[R])
.IP \(bu 2
\f[CR]err_contains\f[R]: Same as \f[CR]cmd_contains\f[R] but for error
message (all lowercase)
.IP \(bu 2
\f[CR]length\f[R]: Check if the given command has the length of the
argument
.IP \(bu 2
\f[CR]min_length\f[R]: Check if the given command has at least the
length of the argument
.IP \(bu 2
\f[CR]max_length\f[R]: Check if the given command has at most the length
of the argument
.IP \(bu 2
\f[CR]shell\f[R]: Check if the current running shell is the argument
.SS Identifiers
Identifiers are used to reuse rules for specific purposes:
.IP \(bu 2
\f[CR]INLINE\f[R]: Reuse the rule for \f[CR]inline\f[R] mode.
Patterns are ignored.
.SS Other Considerations
When suggesting a chained command with \f[CR]&&\f[R], try to break it
into multiple lines.
.IP \(bu 2
More readable if the commands are long
.IP \(bu 2
Automatic conversion to compatible syntax where \f[CR]&&\f[R] is
unavailable (e.g.\ nushell)
.PP
Example:
.IP
.EX
suggest = [
\(aq\(aq\(aq
command1 &&
command2 \(aq\(aq\(aq
]
.EE
.SH SEE ALSO
\f[B]pay\-respects\f[R](1), \f[B]pay\-respects\-modules\f[R](5)
.SH AUTHORS
iff.
pay-respects-0.8.8/man/pay-respects.1 0000664 0000000 0000000 00000005201 15173770737 0017441 0 ustar 00root root 0000000 0000000 .\" Automatically generated by Pandoc 3.9.0.2
.\"
.TH "PAY_RESPECTS" "1" "April 2026" "pay\-respects 0.8.8" "User Commands"
.SH NAME
pay\-respects \- Blazing fast terminal command suggestions
.SH SYNOPSIS
\f[B]pay\-respects\f[R] \f[I]shell\f[R] [\f[I]options\f[R]]
.SH DESCRIPTION
pay\-respects is a terminal suggestion tool that fixes your previous or
current typed command, with a sub\-millisecond (<1ms) performance.
.SH OPTIONS
.TP
\-h, \(enhelp
Show help message and exit.
.TP
\(enalias
Set a custom alias instead of \f[CR]f\f[R]
.TP
\(ennocnf
Disable command\-not\-found handler
.SH INITIALIZATION
.SS Bash / Zsh / Fish
Add the following line to your configuration file:
.IP
.EX
eval \(dq$(pay\-respects bash \-\-alias)\(dq
eval \(dq$(pay\-respects zsh \-\-alias)\(dq
pay\-respects fish \-\-alias \f[B]|\f[R] source
.EE
.SS Nushell / PowerShell
Add the following output to your configuration file.
Replace the shell with the actual executable name if needed.
.IP
.EX
pay\-respects nu
pay\-respects pwsh
.EE
.SH USAGE
Fix your previous command
.IP
.EX
f
.EE
.PP
Fix your current typed command
.IP
.EX
.EE
.SH Examples
.IP
.EX
gitcommit + + f + \-\-> git commit
gitcommit + + \-\-> git commit
.EE
.SH ENVIRONMENT VARIABLES
.SS Required
.TP
_PR_SHELL
The binary name of the current working shell
.TP
_PR_LAST_COMMAND
The last command
.SS Optional
.TP
_PR_ALIAS
A list of aliases to commands.
Separated by newlines with zsh\-like formatting,
e.g.\ \f[CR]gc=git commit\f[R]
.TP
_PR_ERROR_MSG
Error message from the previous command.
\f[CR]pay\-respects\f[R] will rerun previous command to get the error
message if absent
.TP
_PR_EXECUTABLES
A space separated list of commands/executables.
\f[CR]pay\-respects\f[R] will search for \f[CR]$PATH\f[R] if absent
.TP
_PR_LIB
Directory of modules, analogous to \f[CR]PATH\f[R].
If not provided, search in \f[CR]PATH\f[R] or compile\-time provided
value
.TP
_PR_PACKAGE_MANAGER
Use defined package manager instead of auto\-detecting alphabetically.
Empty value disables package search functionality
.TP
_PR_MODE
Execution mode.
.SS Configuration
.TP
_PR_PREFIX
Shell prompt prefix, required for log capture from terminal multiplexers
.TP
_PR_NO_DESPERATE
Disable desperate functions, which are slow but can give better results
.TP
_PR_NO_CONFIG
Don\(cqt load configurations
.TP
_PR_NO_ZOXIDE:
Don\(cqt use zoxide
.TP
_PR_NO_MULTIPLEXER
Equivalent of turning all the followings: \f[CR]_PR_NO_TMUX\f[R],
\f[CR]_PR_NO_SCREEN\f[R], \f[CR]_PR_NO_ZELLIJ\f[R],
\f[CR]_PR_NO_WEZTERM\f[R], \f[CR]_PR_NO_KITTY\f[R]
.SH SEE ALSO
\f[B]pay\-respects\-rules\f[R](5), \f[B]pay\-respects\-modules\f[R](5)
.SH AUTHORS
iff.
pay-respects-0.8.8/man/pay-respects.5 0000664 0000000 0000000 00000006461 15173770737 0017456 0 ustar 00root root 0000000 0000000 .\" Automatically generated by Pandoc 3.9.0.2
.\"
.TH "PAY_RESPECTS" "5" "April 2026" "pay\-respects 0.8.8" "Configuration File"
.SH Configuration File
User configuration file for \f[CR]pay\-respects\f[R] is located at:
.IP \(bu 2
\f[CR]$HOME/.config/pay\-respects/config.toml\f[R] (*nix)
.IP \(bu 2
\f[CR]%APPDATA%/pay\-respects/config.toml\f[R] (Windows)
.PP
Directories for system\-wide configuration, which fields can be
overwritten individually by the user configuration file are searched on:
.IP \(bu 2
\f[CR]$XDG_CONFIG_DIRS\f[R] (*nix)
.RS 2
.IP \(bu 2
If not set, \f[CR]/etc/xdg\f[R]
.RE
.IP \(bu 2
\f[CR]$PROGRAMDATA\f[R] (Windows)
.RS 2
.IP \(bu 2
If not set, \f[CR]C:\(rsProgramData\f[R]
.RE
.PP
With the same directory structure,
e.g.\ \f[CR]/etc/xdg/pay\-respects/config.toml\f[R]
.SS Options
All available options are listed in the following example file:
.IP
.EX
\f[I]# Preferred command for privileged acesses\f[R]
privilege = \(dqsudo\(dq
\f[I]# Maximum time in milliseconds for getting previous output\f[R]
timeout = 3000
\f[I]# Apply existing rules to a set of commands. Every set will use the rule\f[R]
\f[I]# corresponding to the first entry\f[R]
merge_commands = [
[\(dqls\(dq, \(dqexa\(dq], \f[I]# both using rules corresponding to \(gals\(ga\f[R]
[\(dqgrep\(dq, \(dqrg\(dq], \f[I]# both using rules corresponding to \(gagrep\(ga\f[R]
]
\f[I]# Commands that won\(aqt return any message when run,\f[R]
\f[I]# which is most of the interactive commands\f[R]
blocking_commands = [\(dqvim\(dq, \(dqnano\(dq]
\f[I]# How suggestions are evaluated after being confirmed\f[R]
\f[I]# Options can be:\f[R]
\f[I]# \- Internal: Commands are evaluated inside \(gapay\-respects\(ga\f[R]
\f[I]# \- Shell: Current working shell is responsible for execution\f[R]
eval_method = \(dqInternal\(dq
\f[I]# Algorithm used for fuzzy searching\f[R]
\f[I]# Options:\f[R]
\f[I]# \- TrigramDamerauLevenshtein: More computationally expensive\f[R]
\f[I]# \- DamerauLevenshtein: Fast\f[R]
search_type = \(dqTrigramDamerauLevenshtein\(dq
\f[I]# Minimum characters required to start seaching\f[R]
\f[I]# Avoids false positive when input strings are too short\f[R]
search_threshold = 3
\f[I]# Minimum score for the result to be valid: [0,1]\f[R]
\f[B][trigram]\f[R]
minimum_score = 0.5
\f[I]# Configuring the linguistic distance (Damerau\-Levenshtein)\f[R]
\f[I]# \- Percentage: How many characters can be different in the suggestion, rounded\f[R]
\f[I]# to the nearest integer.\f[R]
\f[I]# \- Threshold: How many characters are required for the reference string to\f[R]
\f[I]# start searching to avoid false positives when the reference string is too\f[R]
\f[I]# short.\f[R]
\f[I]# \- Max: Maximum distance allowed between the reference and the suggestion.\f[R]
\f[I]# \- Min: Minimum strating distance required. Seach only starts if the distance\f[R]
\f[I]# obtained after the percentage calculation is above or equal to this value.\f[R]
\f[B][dl_distance]\f[R]
percentage = 27.1828182845904523536028747135266250
max = 5
min = 1
\f[B][package_manager]\f[R]
\f[I]# Preferred package manager\f[R]
package_manager = \(dqpacman\(dq
\f[I]# Preferred installation method, can be limited by the package manager\f[R]
\f[I]# Available options are:\f[R]
\f[I]# \- System\f[R]
\f[I]# \- Shell (nix and guix only)\f[R]
install_method = \(dqSystem\(dq
.EE
.SH AUTHORS
iff.
pay-respects-0.8.8/module-request-ai/ 0000775 0000000 0000000 00000000000 15173770737 0017531 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-request-ai/Cargo.toml 0000664 0000000 0000000 00000001506 15173770737 0021463 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects-module-request-ai"
version = "0.2.10"
edition = "2024"
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 = "4"
serde_json = { version = "1.0" }
serde = { version = "1.0", features = ["derive"]}
textwrap = "0.16"
terminal_size = "0.4"
askama = "0.15"
# reqwest = { version = "0.13", features = ["stream", "json"] }
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.8.8/module-request-ai/README.md 0000664 0000000 0000000 00000005756 15173770737 0021025 0 ustar 00root root 0000000 0000000 # 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/v1/chat/completions`: Local Ollama
- `_PR_AI_MODEL`: Model used. Reasoning models are also supported
- `_PR_AI_EXTRA`: Extra Json field requests, e.g. `"temperature" = 0.5`
- `_PR_AI_EXTRA_BODY`: A Json object for the `extra_body` field, e.g. `{"chat_template_kwargs": {"enable_thinking": false}}`
- `_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:
## 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
rustup # how do I setup nightly toolchain?
```
Or just a comment:
```sh
# git cache credential for 3 hours
```
pay-respects-0.8.8/module-request-ai/i18n/ 0000775 0000000 0000000 00000000000 15173770737 0020310 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-request-ai/i18n/i18n.toml 0000664 0000000 0000000 00000001106 15173770737 0021762 0 ustar 00root root 0000000 0000000 _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.8.8/module-request-ai/src/ 0000775 0000000 0000000 00000000000 15173770737 0020320 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-request-ai/src/buffer.rs 0000664 0000000 0000000 00000006671 15173770737 0022151 0 ustar 00root root 0000000 0000000 use std::io::Write;
use textwrap::fill as textwrap_fill;
fn termwidth() -> usize {
use terminal_size::{Height, Width, terminal_size};
let size = terminal_size();
if let Some((Width(w), Height(_))) = size {
std::cmp::min(w as usize, 80)
} else {
80
}
}
fn fill(str: &mut str) -> String {
let width = termwidth();
textwrap_fill(str, width)
}
fn clear_line() {
let width = termwidth();
let whitespace = " ".repeat(width);
eprint!("\r{}\r", whitespace);
}
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),
}
}
fn proc_write(&mut self, data: &str) {
self.buf.push_str(data);
fix_data(&mut self.buf);
self.buf = fill(&mut self.buf);
if !self.buf.contains("\n") {
eprint!("{}", data);
std::io::stderr().flush().unwrap();
return;
}
let slice = self.buf.split('\n').collect::>();
for (idx, line) in slice.iter().enumerate() {
clear_line();
match line.trim() {
"" => {
let warn = format!("{}:", t!("ai-suggestion"))
.bold()
.blue()
.to_string();
eprintln!("{}", warn);
}
"" | "" => {
self.state = State::Buf;
}
"" => {
self.state = State::Think;
let warn = format!("{}:", t!("ai-thinking")).bold().blue().to_string();
eprintln!("{}", warn);
}
"```" => {}
_ => {
// just a new line
if idx == slice.len() - 1 {
eprint!("{}", line);
} else {
eprintln!("{}", line);
}
}
}
std::io::stderr().flush().unwrap();
}
self.buf = slice.last().unwrap().to_string();
}
fn proc_think(&mut self, data: &str) {
self.buf.push_str(data);
fix_data(&mut self.buf);
self.buf = fill(&mut self.buf);
if !self.buf.contains("\n") {
eprint!("{}", data);
std::io::stderr().flush().unwrap();
return;
}
let slice = self.buf.split('\n').collect::>();
for (idx, line) in slice.iter().enumerate() {
clear_line();
match line.trim() {
"" => {
self.state = State::Write;
}
_ => {
// just a new line
if idx == slice.len() - 1 {
eprint!("{}", line);
} else {
eprintln!("{}", line);
}
}
}
std::io::stderr().flush().unwrap();
}
self.buf = slice.last().unwrap().to_string();
}
}
fn fix_data(data: &mut String) {
let tag_list = ["", "", "", "", "```"];
for tag in tag_list.iter() {
if data.contains(tag) {
let mut new_data = String::new();
let mut remaining = data.as_str();
while let Some(pos) = remaining.find(tag) {
let split_before = &remaining[..pos].trim_end();
let split_after = &remaining[pos + tag.len()..].trim_start();
new_data.push_str(split_before);
new_data.push('\n');
new_data.push_str(tag);
new_data.push('\n');
remaining = split_after;
}
new_data.push_str(remaining);
*data = new_data;
}
}
}
#[allow(unused)]
mod tests {
use super::*;
#[test]
fn test_fix_data() {
let mut data = "hellofoobar".to_string();
fix_data(&mut data);
let expected = "hello\n\nfoo\n\nbar".to_string();
assert_eq!(data, expected);
}
}
pay-respects-0.8.8/module-request-ai/src/main.rs 0000664 0000000 0000000 00000004214 15173770737 0021613 0 ustar 00root root 0000000 0000000 // 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
&& 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.8.8/module-request-ai/src/requests.rs 0000664 0000000 0000000 00000013176 15173770737 0022551 0 ustar 00root root 0000000 0000000 use askama::Template;
use serde_json::Value;
use futures_util::StreamExt;
use serde::Deserialize;
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,
// extra_body: Option,
// }
#[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,
}
#[derive(Template)]
#[template(path = "request.txt")]
struct Request {
extra: Option,
extra_body: Option,
}
pub async fn ai_suggestion(last_command: &str, error_msg: &str, locale: &str) {
let conf = match Conf::new() {
Some(conf) => conf,
None => {
return;
}
};
let char_limit = 500;
let error_msg = if error_msg.chars().count() > 500 + 3 {
let half = char_limit / 2;
format!(
"{}...{}",
error_msg.chars().take(half).collect::(),
error_msg
.chars()
.rev()
.take(half)
.collect::()
.chars()
.rev()
.collect::()
)
} else {
error_msg.to_string()
};
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: &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 extra: Option = std::env::var("_PR_AI_EXTRA").ok();
let extra_body: Option = std::env::var("_PR_AI_EXTRA_BODY").ok();
let body = Request { extra, extra_body };
let body = body.render().unwrap();
let mut json_body: Value = serde_json::from_str(&body).unwrap();
json_body["model"] = Value::String(conf.model);
json_body["messages"][0]["content"] = Value::String(ai_prompt);
json_body["stream"] = Value::Bool(true);
let client = reqwest::Client::new();
let res = client
.post(&conf.url)
.body(serde_json::to_string(&json_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();
json_buffer.push_str(str);
if !json_buffer.contains("\n\ndata: ") {
continue;
}
while json_buffer.contains("\n\ndata: ") {
proc_stream_buffer(&mut json_buffer, &mut buffer);
}
}
// remaining buffer
json_buffer.push_str("\n\ndata: "); // hackey
while json_buffer.contains("\n\ndata: ") {
proc_stream_buffer(&mut json_buffer, &mut buffer);
}
let suggestions = buffer
.buf
.trim()
.trim_end_matches("```")
.trim()
.trim_start_matches("")
.trim_end_matches("")
.replace(" ", "<_PR_BR>");
println!("{}", suggestions);
}
fn proc_stream_buffer(json_buffer: &mut String, buffer: &mut buffer::Buffer) {
let data_loc = json_buffer.find("\n\ndata: ").unwrap();
let binding = json_buffer.clone();
let split = binding.split_at(data_loc);
let json = split.0;
*json_buffer = split.1.trim_start().to_string();
proc_json(json, buffer);
}
fn proc_json(res: &str, buffer: &mut buffer::Buffer) {
if let Some(data) = res.trim().strip_prefix("data: ") {
if data == "[DONE]" {
return;
}
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);
}
}
}
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://pay-respects-serverless.iffse.eu.org/".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 {
"uwu".to_string()
}
}
};
if model.is_empty() {
return None;
}
Some(Conf { key, url, model })
}
}
pay-respects-0.8.8/module-request-ai/templates/ 0000775 0000000 0000000 00000000000 15173770737 0021527 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-request-ai/templates/prompt.txt 0000664 0000000 0000000 00000000731 15173770737 0023612 0 ustar 00root root 0000000 0000000 {{ 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.8.8/module-request-ai/templates/request.txt 0000664 0000000 0000000 00000000407 15173770737 0023761 0 ustar 00root root 0000000 0000000 {
"messages": [
{
"role": "user",
"content": ""
}
],
"model": "",
"stream": true
{%- if let Some(extra) = self.extra %}
,{{ extra }}
{%- endif %}
{%- if let Some(extra_body) = self.extra_body %}
, "extra_body": {{ extra_body }}
{%- endif %}
}
pay-respects-0.8.8/module-runtime-rules/ 0000775 0000000 0000000 00000000000 15173770737 0020265 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-runtime-rules/Cargo.toml 0000664 0000000 0000000 00000001106 15173770737 0022213 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects-module-runtime-rules"
version = "0.1.14"
edition = "2024"
# 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 = "1.0" }
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.8.8/module-runtime-rules/README.md 0000664 0000000 0000000 00000001427 15173770737 0021550 0 ustar 00root root 0000000 0000000 # 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.8.8/module-runtime-rules/src/ 0000775 0000000 0000000 00000000000 15173770737 0021054 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/module-runtime-rules/src/config.rs 0000664 0000000 0000000 00000002246 15173770737 0022673 0 ustar 00root root 0000000 0000000 use pay_respects_utils::strings::print_error;
use serde::Deserialize;
use pay_respects_utils::files::config_files;
use pay_respects_utils::merge_option;
#[derive(Deserialize, Default)]
pub struct ConfigReader {
pub merge_commands: Option>>,
}
#[derive(Default)]
pub struct Config {
pub merge_commands: Option>>,
}
impl Config {
pub fn merge(&mut self, reader: ConfigReader) {
merge_option!(self, reader, merge_commands);
}
}
pub fn load_config() -> Config {
let mut config = Config::default();
for file in config_files() {
let content = std::fs::read_to_string(&file).expect("Failed to read config file");
let reader: ConfigReader = toml::from_str(&content).unwrap_or_else(|_| {
print_error(&format!(
"Failed to parse config file at {}. Skipping.",
file
));
ConfigReader::default()
});
config.merge(reader);
}
config
}
pub fn get_target_rule(executable: &str, config: &Config) -> String {
if let Some(merge_commands) = &config.merge_commands {
for merge_command in merge_commands {
if merge_command.contains(&executable.to_string()) {
return merge_command[0].clone();
}
}
}
executable.to_string()
}
pay-respects-0.8.8/module-runtime-rules/src/main.rs 0000664 0000000 0000000 00000005025 15173770737 0022350 0 ustar 00root root 0000000 0000000 // 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 config;
mod replaces;
mod rules;
use pay_respects_utils::{
evals::{split_command, split_comment},
files::get_path_files,
modes::run_mode,
};
use crate::config::{get_target_rule, load_config};
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 mut 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();
let mode = run_mode();
#[cfg(debug_assertions)]
{
eprintln!("shell: {}", shell);
eprintln!("executable: {}", executable);
eprintln!("last_command: {}", last_command);
eprintln!("error_msg: {}", error_msg);
eprintln!("executables: {:?}", executables);
}
let mut split = split_command(&last_command);
if split_comment(&mut split).is_some() {
last_command = split.join(" ");
}
pay_respects_utils::shell::set_shell_type(&shell);
pay_respects_utils::settings::load_config();
let config = load_config();
let target_rule = get_target_rule(&executable, &config);
let mut runned_rules = vec![];
let mut pending_rules = vec![target_rule];
while let Some(executable) = pending_rules.pop() {
if runned_rules.contains(&executable) {
continue;
}
runned_rules.push(executable.clone());
let extends = rules::runtime_match(
&mode,
&executable,
&shell,
&last_command,
&error_msg,
&executables,
);
if let Some(extends) = extends {
for extend in extends {
if !runned_rules.contains(&extend) {
pending_rules.push(extend);
}
}
}
}
rules::runtime_match(
&mode,
"_PR_GENERAL",
&shell,
&last_command,
&error_msg,
&executables,
);
Ok(())
}
pay-respects-0.8.8/module-runtime-rules/src/replaces.rs 0000664 0000000 0000000 00000014225 15173770737 0023224 0 ustar 00root root 0000000 0000000 use 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 let Ok(end) = parsed_end {
end_index = end;
if end_index < 0 {
end_index += split_command.len() as i32 + 1;
} else {
end_index += 1;
}
} else {
end_index = split_command.len() as i32;
}
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 let Ok(end) = end {
if end < 0 {
split_command.len() as i32 + end + 1
} else {
end + 1
}
} else {
split_command.len() as i32
};
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.8.8/module-runtime-rules/src/rules.rs 0000664 0000000 0000000 00000021361 15173770737 0022557 0 ustar 00root root 0000000 0000000 use crate::replaces;
use pay_respects_utils::{evals::*, modes::Mode, strings::split_unescaped_character};
#[derive(serde::Deserialize)]
struct Rule {
extends: Option>,
match_err: Vec,
}
#[derive(serde::Deserialize)]
struct MatchError {
pattern: Option>,
suggest: Vec,
}
pub fn runtime_match(
mode: &Mode,
executable: &str,
shell: &str,
last_command: &str,
error_msg: &str,
executables: &[String],
) -> Option> {
match mode {
Mode::Suggestion => {
suggestion_match(executable, shell, last_command, error_msg, executables)
}
Mode::Inline => inline_match(executable, shell, last_command, error_msg, executables),
_ => suggestion_match(executable, shell, last_command, error_msg, executables),
}
}
pub fn suggestion_match(
executable: &str,
shell: &str,
last_command: &str,
error_msg: &str,
executables: &[String],
) -> Option> {
let file_path = get_rule(executable)?;
let file = match std::fs::read_to_string(&file_path) {
Ok(content) => content,
Err(e) => {
eprintln!("runtime-rules: Failed to read {}: {}", file_path, e);
return None;
}
};
let rule: Rule = match toml::from_str(&file) {
Ok(rule) => rule,
Err(e) => {
eprintln!("runtime-rules: Failed to parse {}: {}", file_path, e);
return None;
}
};
let split_command = split_command(last_command);
let error_lower = error_msg.to_lowercase();
let mut pure_suggest;
for match_err in rule.match_err {
let patterns = match match_err.pattern {
Some(patterns) => patterns,
None => vec!["".to_string()],
};
for pattern in patterns {
if error_lower.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(']');
let mut conditions = split_unescaped_character(conditions, ',');
conditions.retain(|c| c.trim() != "INLINE");
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_lower,
&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;
}
}
}
rule.extends
}
pub fn inline_match(
executable: &str,
shell: &str,
last_command: &str,
error_msg: &str,
executables: &[String],
) -> Option> {
let file_path = get_rule(executable)?;
let file = match std::fs::read_to_string(&file_path) {
Ok(content) => content,
Err(e) => {
eprintln!("runtime-rules: Failed to read {}: {}", file_path, e);
return None;
}
};
let rule: Rule = match toml::from_str(&file) {
Ok(rule) => rule,
Err(e) => {
eprintln!("runtime-rules: Failed to parse {}: {}", file_path, e);
return None;
}
};
let split_command = split_command(last_command);
let error_lower = error_msg.to_lowercase();
let mut pure_suggest;
for match_err in rule.match_err {
'suggest: for suggest in &match_err.suggest {
if !suggest.starts_with('#') {
continue 'suggest;
}
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(']');
let mut conditions = split_unescaped_character(conditions, ',');
for condition in &mut conditions {
*condition = condition.trim().to_string();
}
if !conditions.contains(&"INLINE".to_string()) {
continue 'suggest;
}
conditions.retain(|c| c != "INLINE");
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_lower,
&split_command,
executables,
) == reverse
{
continue 'suggest;
}
}
pure_suggest = lines.join("\n").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>");
}
}
}
rule.extends
}
fn eval_condition(
condition: &str,
arg: &str,
shell: &str,
last_command: &str,
error_lower: &str,
split_command: &[String],
executables: &[String],
) -> bool {
match condition {
"executable" => executables.contains(&arg.to_string()),
"err_contains" => regex_match(arg, error_lower),
"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.8.8/modules.md 0000664 0000000 0000000 00000006267 15173770737 0016174 0 ustar 00root root 0000000 0000000 # Modules
## 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 after sorting. 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.8.8/parser/ 0000775 0000000 0000000 00000000000 15173770737 0015463 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/parser/Cargo.toml 0000664 0000000 0000000 00000000772 15173770737 0017421 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects-parser"
version = "0.3.16"
edition = "2024"
# 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.9"
serde = { version = "1.0", features = ["derive"] }
itertools = "0.14.0"
pay-respects-utils = { version ="0.1", path = "../utils"}
pay-respects-0.8.8/parser/src/ 0000775 0000000 0000000 00000000000 15173770737 0016252 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/parser/src/lib.rs 0000664 0000000 0000000 00000022704 15173770737 0017373 0 ustar 00root root 0000000 0000000 // 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 itertools::sorted_unstable;
use pay_respects_utils::strings::split_unescaped_character;
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)
}
#[proc_macro]
pub fn parse_inline_rules(input: TokenStream) -> TokenStream {
let rules = get_rules(input.to_string().trim_matches('"'));
gen_inline_rules(&rules)
}
#[derive(serde::Deserialize)]
struct Rule {
command: String,
extends: Option>,
match_err: Vec,
}
#[derive(serde::Deserialize)]
struct MatchError {
pattern: Option>,
suggest: Vec,
}
fn get_rules(directory: &str) -> Vec {
let files = std::fs::read_dir(directory)
.expect("Failed to read directory.")
.map(|entry| {
let entry = entry.expect("Failed to read directory entry.");
entry
.path()
.to_str()
.expect("Failed to convert path to string.")
.to_string()
});
let files = sorted_unstable(files).collect::>();
let mut rules = Vec::new();
for path in files {
let rule_file = parse_file(Path::new(&path));
rules.push(rule_file);
}
rules
}
fn gen_match_rules(rules: &[Rule]) -> TokenStream {
let command = rule_commands(rules);
let command_matches = parse_match_err(rules);
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, mut conditions) = parse_conditions(&suggest);
if let Some(conditions) = &mut conditions {
conditions.retain(|x| x != "INLINE");
}
let suggestion = parse_suggestion(&suggestion_no_condition, conditions);
pattern_suggestions.push(suggestion);
}
let match_tokens = quote! {
#(#pattern_suggestions)*
};
suggestion_tokens.push(match_tokens);
if let Some(pattern) = pattern {
let string_patterns = pattern.join("\"###, r###\"");
let string_patterns: TokenStream2 =
format!("[r###\"{}\"###]", string_patterns).parse().unwrap();
patterns_tokens.push(string_patterns);
} else {
patterns_tokens.push("[\"\"]".parse().unwrap());
}
}
matches_tokens.push(quote! {
#(
for pattern in #patterns_tokens {
if error_lower.contains(pattern) {
#suggestion_tokens;
break;
};
})*
})
}
quote! {
let mut last_command = last_command.to_string();
match executable {
#(
#command => {
#matches_tokens
}
)*
_ => {}
};
}
.into()
}
fn gen_inline_rules(rules: &[Rule]) -> TokenStream {
let command = rule_commands(rules);
let command_matches = parse_match_err(rules);
let mut matches_tokens = Vec::new();
for match_err in command_matches {
let mut suggestion_tokens = Vec::new();
for (_, suggests) in match_err {
// let mut match_condition = Vec::new();
let mut pattern_suggestions = Vec::new();
for suggest in suggests {
let (suggestion_no_condition, mut conditions) = parse_conditions(&suggest);
if conditions.is_none() {
continue;
}
if let Some(conditions) = &mut conditions {
if !conditions.contains(&"INLINE".to_string()) {
continue;
}
conditions.retain(|x| {
x != "INLINE" && !x.starts_with("err") && !x.starts_with("!err")
});
}
let suggestion = parse_suggestion(&suggestion_no_condition, conditions);
pattern_suggestions.push(suggestion);
}
let match_tokens = quote! {
#(#pattern_suggestions)*
};
if match_tokens.is_empty() {
continue;
}
suggestion_tokens.push(match_tokens);
}
matches_tokens.push(quote! {
#(
#suggestion_tokens;
)*
})
}
quote! {
let mut last_command = last_command.to_string();
match executable {
#(
#command => {
#matches_tokens
}
)*
_ => {}
};
}
.into()
}
#[allow(clippy::type_complexity)]
fn parse_match_err(rules: &[Rule]) -> Vec>, Vec)>> {
rules
.iter()
.map(|x| {
x.match_err
.iter()
.map(|x| {
let pattern = if let Some(pattern) = &x.pattern {
let pattern = pattern
.iter()
.map(|x| x.to_lowercase())
.collect::>();
Some(pattern)
} else {
None
};
let suggests = x
.suggest
.iter()
.map(|x| x.to_string())
.collect::>();
(pattern, suggests)
})
.collect::>, Vec)>>()
})
.collect::>, Vec)>>>()
}
fn rule_commands(rules: &[Rule]) -> Vec {
rules
.iter()
.map(|x| {
if let Some(extends) = &x.extends {
format!(
"\"{}\"|{}",
x.command,
extends
.iter()
.map(|x| format!("\"{}\"", x))
.collect::>()
.join("|")
)
.parse()
.unwrap()
} else {
format!("\"{}\"", x.command).parse().unwrap()
}
})
.collect::>()
}
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, Option>) {
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(']');
let conditions = split_unescaped_character(conditions, ',')
.into_iter()
.map(|x| x.trim().to_string())
.collect::>();
let suggest = lines.join("\n");
return (suggest, Some(conditions));
}
(suggest.to_owned(), None)
}
fn tokenize_conditions(conditions: &[String]) -> Vec {
let mut eval_conditions = Vec::new();
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});
}
eval_conditions
}
fn parse_suggestion(suggestion: &str, conditions: Option>) -> TokenStream2 {
if conditions.is_none() {
return eval_suggest(suggestion);
}
let (conditions, is_function) = {
let mut conditions = conditions.unwrap();
if conditions.contains(&"FUNCTION".to_string()) {
conditions.retain(|x| x != "FUNCTION");
(conditions, true)
} else {
(conditions, false)
}
};
let suggest = if is_function {
let suggestion: TokenStream2 = suggestion.trim_matches('"').parse().unwrap();
quote! {
rules_function(#suggestion, &error_msg, &error_lower, &shell, &last_command, &executables, &split, &mut candidates, data);
}
} else {
eval_suggest(suggestion)
};
if conditions.is_empty() {
return suggest;
}
let conditions = tokenize_conditions(&conditions);
quote! {
if #(#conditions)&&* {
#suggest
}
}
}
fn eval_condition(condition: &str, arg: &str) -> TokenStream2 {
match condition {
"executable" => quote! {executables.contains(arg.to_string())},
"err_contains" => quote! {regex_match(#arg, &error_lower)},
"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.8.8/parser/src/replaces.rs 0000664 0000000 0000000 00000023523 15173770737 0020423 0 ustar 00root root 0000000 0000000 // 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 let Ok(end) = end {
if end < 0 {
format!("split.len() {}", end + 1)
} else {
(end + 1).to_string()
}
} else {
String::from("split.len()")
};
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(&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.8.8/pay-respects.plugin.zsh 0000664 0000000 0000000 00000000171 15173770737 0020630 0 ustar 00root root 0000000 0000000 if (( $+commands[pay-respects] )); then
eval "$(pay-respects zsh --alias)"
else
echo "pay-respects is not in $PATH"
fi
pay-respects-0.8.8/roadmap.md 0000664 0000000 0000000 00000001046 15173770737 0016135 0 ustar 00root root 0000000 0000000 # Roadmap
## Shell Integrations
- ✅: Working
- ⚠️: Partial working
- ❌: Not implemented / Cannot implement
| Feature | Bash | Zsh | Fish | Nush | Pwsh |
|-------------------|------|-----|------|------|--------|
| Inline mode | ✅ | ✅ | ✅ | ✅ | ✅ |
| 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.8.8/rules.md 0000664 0000000 0000000 00000012312 15173770737 0015642 0 ustar 00root root 0000000 0000000 # 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!
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
# If multiple commands could share the same rules, add it to extends
command = "hello"
extends = ["goodbye"]
# You can add as many `[[match_err]]` section as you want
[[match_err]]
# Note:
# - 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
# - This field is optional, always match if omitted
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}} '''
]
```
## Rust Functions
You can also write in Rust if the rule is very complex. This is only allowed
during compilation, by previously defining your function in
[`rules_functions.rs`](./core/src/rules_function.rs):
```toml
[[match_err]]
pattern = [
"pattern 1"
]
suggest = [
'''
#[FUNCTION]
MyRustFunction '''
]
```
## Placeholders
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
## Conditions
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 (using `,` requires escaping, i.e. `\,`)
- `err_contains`: Same as `cmd_contains` but for error message (all lowercase)
- `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
## Identifiers
Identifiers are used to reuse rules for specific purposes:
- `INLINE`: Reuse the rule for `inline` mode. Patterns are ignored.
## Other Considerations
When suggesting a chained command with `&&`, try to break it into multiple lines.
- More readable if the commands are long
- Automatic conversion to compatible syntax where `&&` is unavailable (e.g. nushell)
Example:
```toml
suggest = [
'''
command1 &&
command2 '''
]
```
pay-respects-0.8.8/rules/ 0000775 0000000 0000000 00000000000 15173770737 0015321 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/rules/_PR_FALLBACK.toml 0000664 0000000 0000000 00000000551 15173770737 0020116 0 ustar 00root root 0000000 0000000 command = "_PR_fallback"
[[match_err]]
pattern = [
"access",
"permission",
"permitted",
"privilege",
"protected",
"root",
"sudo",
"super-user",
"superuser",
]
suggest = [
'''
#[FUNCTION]
SetPrivilege
'''
]
[[match_err]]
suggest = [
'''
#[FUNCTION, min_length(2), INLINE]
DesperateFileLookUp
''',
'''
#[FUNCTION, INLINE]
DesperateFuzzyRecovery
''',
]
pay-respects-0.8.8/rules/_PR_GENERAL.toml 0000664 0000000 0000000 00000001167 15173770737 0020040 0 ustar 00root root 0000000 0000000 command = "_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:]}} ''',
# if command starts with `z `, it's likely using zoxide.
# zoxide defines a function, therefore the output is unobtainable in a non-interactive shell.
'''
#[FUNCTION, cmd_contains(^(z\s+)), min_length(2)]
ZoxideIntegration
'''
]
[[match_err]]
pattern = [
"permission denied",
"is not an executable file"
]
suggest = [
'''
#[cmd_contains((?m)^(\S*)\/(\S*))]
chmod +x {{command[0]}} &&
{{command}}'''
]
pay-respects-0.8.8/rules/_PR_PRIVILEGE.toml 0000664 0000000 0000000 00000001237 15173770737 0020307 0 ustar 00root root 0000000 0000000 command = "_PR_privilege"
[[match_err]]
pattern = [
"as root",
"as super-user",
"authentication is required",
"be root",
"be superuser",
"can not open a temporary file",
"cannot access",
"eacces",
"edspermissionerror",
"insufficient privileges",
"need root",
"non-root users cannot",
"not super-user",
"not superuser",
"only root can",
"operation not permitted",
"permission denied",
"requires root",
"root privilege",
"root user",
"sudorequirederror",
"superuser access",
"superuser privilege",
"unless you are root",
"use `sudo`",
"you don't have access",
"you don't have write permissions",
]
suggest = [
'''
#[FUNCTION]
SetPrivilege
'''
]
pay-respects-0.8.8/rules/brew.toml 0000664 0000000 0000000 00000002721 15173770737 0017157 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/c_typo.toml 0000664 0000000 0000000 00000000330 15173770737 0017507 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/cargo.toml 0000664 0000000 0000000 00000002324 15173770737 0017312 0 ustar 00root root 0000000 0000000 command = "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 = [
"requires the features",
]
suggest = [
'''
#[err_contains(consider enabling them by passing)]
{{command}} {{err::(?:`)(--features=.*")(?:`)}} ''',
]
[[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.8.8/rules/cat.toml 0000664 0000000 0000000 00000000337 15173770737 0016770 0 ustar 00root root 0000000 0000000 command = "cat"
extends = ["bat"]
[[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.8.8/rules/cd.toml 0000664 0000000 0000000 00000001701 15173770737 0016603 0 ustar 00root root 0000000 0000000 command = "cd"
extends = ["z", "__zoxide_z", "Set-Location"]
[[match_err]]
pattern = [
"no such file or directory",
"does not exist",
"no match found",
]
suggest = [
'''
#[INLINE, length(2)]
{{command[0]}} {{typo[1](file)}}
''',
'''
#[FUNCTION, !cmd_contains(^((z\s+)|(__zoxide_z\s+)))]
ZoxideIntegration
''',
'''
#[!shell(nu), length(2)]
mkdir --parents {{command[1]}} &&
cd {{command[1]}} ''',
]
[[match_err]]
pattern = [
"too many arguments", # bash
"string not in pwd", # zsh
"Too many args ", # fish
"nu::parser::extra_positional", #nu
"A positional parameter cannot be found that accepts argument", # pwsh
]
suggest = [
'''
#[FUNCTION, INLINE]
ZoxideIntegration
''',
]
[[match_err]]
suggest = [
'''
#[FUNCTION, INLINE, cmd_contains(^((z\s+)|(__zoxide_z\s+))), min_length(2)]
ZoxideIntegration
'''
]
[[match_err]]
pattern = [
"Directory not found"
]
suggest = [
'''
#[shell(nu), length(2)]
mkdir {{command[1]}} and \
cd {{command[1]}} '''
]
pay-respects-0.8.8/rules/cp.toml 0000664 0000000 0000000 00000000517 15173770737 0016623 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/git.toml 0000664 0000000 0000000 00000005437 15173770737 0017012 0 ustar 00root root 0000000 0000000 command = "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), INLINE]
{{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",
"No configured push destination.",
]
suggest = [
'''
#[cmd_contains(push)]
git push --set-upstream {{select({{shell(git remote)}})}} {{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 {{select({{shell(git remote)}})}} {{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}} --no-rebase '''
]
[[match_err]]
pattern = [
"is not fully merged"
]
suggest = [
'''
#[cmd_contains(branch -d)]
{{command[:1]}} -D {{command[3:]}} ''',
]
[[match_err]]
pattern = [
"Changes not staged for commit"
]
suggest = [
'''
git add . '''
]
[[match_err]]
pattern = [
"use \"git push\" to publish your local commits"
]
suggest = [
'''
git push ''',
]
[[match_err]]
pattern = [
"Nothing specified"
]
suggest = [
'''
#[cmd_contains(add)]
git add . ''',
]
[[match_err]]
pattern = [
"fatal: not a git repository"
]
suggest = [
'''
git init''',
]
[[match_err]]
pattern = [
"would clobber existing tag"
]
suggest = [
'''
#[cmd_contains(tag)]
{{command}} --force''',
]
pay-respects-0.8.8/rules/jj.toml 0000664 0000000 0000000 00000002026 15173770737 0016621 0 ustar 00root root 0000000 0000000 command = "jj"
[[match_err]]
pattern = [
"There is no jj repo in \".\"",
]
suggest = [
'''
{{command[0]}} git init
''',
]
[[match_err]]
pattern = [
"unrecognized subcommand",
]
suggest = [
'''
#[err_contains('git')]
{{command[0]}} git {{command[2:]}}
''',
'''
#[cmd_contains(\s((push)|(fetch)|(clone)|(init)|(remote))), INLINE]
{{command[0]}} git {{command[1:]}}
''',
'''
#[cmd_contains(\s(pull)), INLINE]
{{command[0]}} git fetch
''',
]
[[match_err]]
pattern = [
"error: commit",
"is immutable`",
"pass `--ignore-immutable`", # deprecated
]
suggest = [
'''
{{command}} --ignore-immutable
''',
]
[[match_err]]
pattern = [
"no bookmarks found in the default push revset",
]
suggest = [
'''
{{command}} --change @
''',
]
[[match_err]]
pattern = [
"hint: run",
"and try again",
]
suggest = [
'''
{{err::Hint: Run `(.*)` and try again.}} &&
{{command}}
''',
'''
{{err::Hint: Run `(.*)` and try again.}}
''',
]
# deprecated
[[match_err]]
pattern = [
"use --allow-new to push new bookmark"
]
suggest = [
'''
{{command}} --allow-new'''
]
pay-respects-0.8.8/rules/ls.toml 0000664 0000000 0000000 00000000305 15173770737 0016632 0 ustar 00root root 0000000 0000000 command = "ls"
extends = ["eza", "exa"]
[[match_err]]
pattern = [
"no such file or directory",
"does not exist"
]
suggest = [
'''
{{command[0]}} {{typo[1](file)}} {{opt::(?:\s)(-[\S]+)}}
''',
]
pay-respects-0.8.8/rules/make.toml 0000664 0000000 0000000 00000000324 15173770737 0017132 0 ustar 00root root 0000000 0000000 command = "make"
[[match_err]]
pattern = [
"No rule to make target"
]
suggest = [
'''
#[INLINE]
{{command[0]}} {{typo[1]({{shell(make -qp | awk -F: '/^[a-zA-Z0-9][^$#\\/\\t=]*:([^=]|$)/ {print $1}')}})}}''',
]
pay-respects-0.8.8/rules/mkdir.toml 0000664 0000000 0000000 00000000254 15173770737 0017325 0 ustar 00root root 0000000 0000000 command = "mkdir"
[[match_err]]
pattern = [
"cannot create directory"
]
suggest = [
'''
#[err_contains(no such file or directory)]
{{command[0]}} -p {{command[1:]}}'''
]
pay-respects-0.8.8/rules/mv.toml 0000664 0000000 0000000 00000000243 15173770737 0016637 0 ustar 00root root 0000000 0000000 command = "mv"
[[match_err]]
pattern = [
"no such file or directory",
"not a directory"
]
suggest = [
'''
mkdir --parents {{command[-1]}} &&
{{command}} '''
]
pay-respects-0.8.8/rules/npm.toml 0000664 0000000 0000000 00000001214 15173770737 0017006 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/pacman.toml 0000664 0000000 0000000 00000000506 15173770737 0017456 0 ustar 00root root 0000000 0000000 command = "pacman"
extends = ["paru", "yay"]
[[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.8.8/rules/rm.toml 0000664 0000000 0000000 00000000623 15173770737 0016635 0 ustar 00root root 0000000 0000000 command = "rm"
[[match_err]]
pattern = [
"is a directory",
"try --recursive"
]
suggest = [
'''
{{command[0]}} -r {{command[1:]}} '''
]
[[match_err]]
pattern = [
"write-protected",
]
suggest = [
'''
{{command[0]}} -f {{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.8.8/rules/size.toml 0000664 0000000 0000000 00000000326 15173770737 0017171 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/sl.toml 0000664 0000000 0000000 00000000142 15173770737 0016631 0 ustar 00root root 0000000 0000000 command = "sl"
[[match_err]]
suggest = [
'''
#[INLINE, !executable(sl)]
ls {{command[1:]}} '''
]
pay-respects-0.8.8/rules/snap.toml 0000664 0000000 0000000 00000000201 15173770737 0017150 0 ustar 00root root 0000000 0000000 command = "snap"
[[match_err]]
pattern = [
"published using classic confinement"
]
suggest = [
'''
{{command}} --classic '''
]
pay-respects-0.8.8/rules/touch.toml 0000664 0000000 0000000 00000000563 15173770737 0017344 0 ustar 00root root 0000000 0000000 command = "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.8.8/rules/vim.toml 0000664 0000000 0000000 00000000251 15173770737 0017007 0 ustar 00root root 0000000 0000000 command = "vim"
extends = ["vi", "nvim", "hx", "helix", "nano", "micro"]
[[match_err]]
suggest = [
'''
#[INLINE, min_length(2)]
{{command[0]}} {{typo[1:](file)}} '''
]
pay-respects-0.8.8/rules/yarn.toml 0000664 0000000 0000000 00000001206 15173770737 0017166 0 ustar 00root root 0000000 0000000 command = "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.8.8/select/ 0000775 0000000 0000000 00000000000 15173770737 0015446 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/select/Cargo.toml 0000664 0000000 0000000 00000000535 15173770737 0017401 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects-select"
version = "0.1.4"
edition = "2024"
# for crates.io
description = "Selection UI 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]
colored = "3.1.1"
crossterm = "0.29"
pay-respects-0.8.8/select/src/ 0000775 0000000 0000000 00000000000 15173770737 0016235 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/select/src/lib.rs 0000664 0000000 0000000 00000015410 15173770737 0017352 0 ustar 00root root 0000000 0000000 // 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 colored::Colorize;
use crossterm::{
cursor,
event::{self, Event, KeyCode},
execute,
terminal::{self, ClearType},
};
use std::io::{Write, stderr};
#[derive(Default)]
struct Page {
items: Vec,
lines: usize,
}
#[cfg(target_os = "windows")]
use crossterm::event::KeyEventKind;
const MAX_ITEMS: usize = 10;
pub fn select(
prelude: &str,
active_items: &[String],
inactive_items: &[String],
) -> Result> {
let height = terminal::size()?.1 as usize;
let prelude_lines = prelude.lines().count();
if height < prelude_lines + 1 {
terminal::disable_raw_mode()?;
eprintln!("Terminal height too small.");
std::process::exit(1);
}
let pages = get_pages(active_items, height - prelude_lines - 2);
terminal::enable_raw_mode()?;
drain_input();
execute!(stderr(), cursor::Hide)?;
eprint!("{}\r\n", prelude);
let mut current = 0;
let mut page_idx = 0;
let total_pages = pages.len();
macro_rules! page_range {
() => {
pages[page_idx].items[0]..pages[page_idx].items[pages[page_idx].items.len() - 1] + 1
};
}
macro_rules! page_len {
() => {
pages[page_idx].items.len()
};
}
macro_rules! next_page {
() => {
page_idx = (page_idx + 1) % pages.len();
current = 0;
};
}
macro_rules! prev_page {
() => {
page_idx = if page_idx == 0 {
pages.len() - 1
} else {
page_idx - 1
};
current = pages[page_idx].items.len() - 1;
};
}
macro_rules! clear_lines {
() => {
if pages.len() == 1 {
pages[page_idx].lines
} else {
pages[page_idx].lines + 1
}
};
}
// Initial draw
draw(
&active_items[page_range!()],
&inactive_items[page_range!()],
current,
page_idx,
total_pages,
)?;
loop {
if let Event::Key(key) = event::read()? {
// somehow windows receives two events
#[cfg(target_os = "windows")]
if key.kind != KeyEventKind::Press {
continue;
}
let clear_lines = clear_lines!();
match key.code {
// Navigation keys
KeyCode::Char('j') | KeyCode::Down => {
// current = (current + 1) % active_items.len();
if current + 1 >= page_len!() {
next_page!();
} else {
current += 1;
}
}
KeyCode::Char('k') | KeyCode::Up => {
if current == 0 {
prev_page!();
} else {
current -= 1
};
}
// Page navigation keys
KeyCode::Char('f') | KeyCode::PageDown => {
next_page!();
}
KeyCode::Char('b') | KeyCode::PageUp => {
prev_page!();
}
// Shortcut keys (1-0)
KeyCode::Char(c) if c.is_ascii_digit() => {
if c == '0' {
if page_len!() == 10 {
current = MAX_ITEMS - 1;
}
break;
}
let idx = c.to_digit(10).unwrap() as usize - 1;
if idx < pages[page_idx].items.len() {
current = idx;
break;
}
}
// Quit keys
KeyCode::Char('c') | KeyCode::Char('d') => {
if key.modifiers.contains(event::KeyModifiers::CONTROL) {
cleanup(pages[page_idx].lines)?;
quit();
}
}
KeyCode::Esc | KeyCode::Char('q') => {
cleanup(clear_lines!() + prelude_lines)?;
quit()
}
KeyCode::Enter => break,
_ => {}
}
redraw(
&active_items[page_range!()],
&inactive_items[page_range!()],
current,
clear_lines,
page_idx,
total_pages,
)?;
}
drain_input();
}
// Cleanup
cleanup(clear_lines!() + prelude_lines)?;
terminal::disable_raw_mode()?;
Ok(pages[page_idx].items[current])
}
pub fn select_simple(prelude: &str, items: &[String]) -> Result> {
let active_items = items
.iter()
.map(|s| s.cyan().to_string())
.collect::>();
select(prelude, &active_items, items)
}
fn select_idx(idx: usize) -> String {
let idx = idx + 1;
if idx < MAX_ITEMS {
format!("{}", idx)
} else if idx == MAX_ITEMS {
String::from("0")
} else {
String::from("-")
}
}
fn get_pages(active_items: &[String], max_height: usize) -> Vec {
let mut pages = Vec::new();
let mut current_page = Page::default();
for (idx, item) in active_items.iter().enumerate() {
let item_lines = item.lines().count();
if item_lines > max_height {
eprintln!("An item is too long to fit in the terminal.");
std::process::exit(1);
}
if current_page.lines + item_lines > max_height || current_page.items.len() >= MAX_ITEMS {
pages.push(current_page);
current_page = Page::default();
}
current_page.items.push(idx);
current_page.lines += item_lines;
}
if !current_page.items.is_empty() {
pages.push(current_page);
}
pages
}
fn print(str: &str) {
// TODO: Trimming long lines to fit terminal width
// Not working well due to color codes.
eprint!("{}\r\n", str);
}
fn draw(
active_items: &[String],
inactive_items: &[String],
selected: usize,
current_page: usize,
total_pages: usize,
) -> Result<(), Box> {
for (i, item) in active_items.iter().enumerate() {
execute!(stderr(), terminal::Clear(ClearType::CurrentLine))?;
if i == selected {
let prefix = format!("> {}) ", select_idx(i)).cyan().bold();
let line = format!("{}{}", prefix, item);
print(&line);
} else {
let prefix = format!(" {}) ", select_idx(i)).cyan();
let line = format!("{}{}", prefix, inactive_items.get(i).unwrap());
print(&line);
}
}
if total_pages > 1 {
execute!(stderr(), terminal::Clear(ClearType::CurrentLine))?;
let page_info = format!("[{}/{}]", current_page + 1, total_pages)
.cyan()
.to_string();
print(&page_info);
}
stderr().flush()?;
Ok(())
}
fn redraw(
active_items: &[String],
inactive_items: &[String],
selected: usize,
lines: usize,
currrent_page: usize,
total_pages: usize,
) -> Result<(), Box> {
execute!(stderr(), cursor::MoveUp(lines as u16))?;
for _ in 0..lines {
execute!(stderr(), terminal::Clear(ClearType::CurrentLine))?;
eprint!("\r\n");
}
execute!(stderr(), cursor::MoveUp(lines as u16))?;
draw(
active_items,
inactive_items,
selected,
currrent_page,
total_pages,
)
}
fn cleanup(lines: usize) -> Result<(), Box> {
execute!(stderr(), cursor::MoveUp(lines as u16))?;
for _ in 0..lines {
execute!(stderr(), terminal::Clear(ClearType::CurrentLine))?;
eprint!("\r\n");
}
execute!(stderr(), cursor::MoveUp(lines as u16))?;
stderr().flush()?;
execute!(stderr(), cursor::Show).unwrap();
Ok(())
}
fn quit() -> ! {
execute!(stderr(), cursor::Show).unwrap();
terminal::disable_raw_mode().unwrap();
let msg = "".red();
eprintln!("{}", msg);
std::process::exit(0);
}
fn drain_input() {
#[cfg(target_os = "windows")]
while event::poll(std::time::Duration::from_millis(10)).unwrap() {
event::read().unwrap();
}
}
pay-respects-0.8.8/tests/ 0000775 0000000 0000000 00000000000 15173770737 0015331 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/tests/benchmark.sh 0000775 0000000 0000000 00000001511 15173770737 0017620 0 ustar 00root root 0000000 0000000 #!/usr/bin/bash
export PR=$(realpath ../target/release/pay-respects)
export _PR_SHELL="bash"
export _PR_LIB=""
export _PR_MODE="echo"
export TMP=$(mktemp -d)
export _PR_EXECUTABLES=""
export _PR_NO_ZOXIDE=1
export _PR_NO_DESPERATE=1
export _PR_NO_CONFIG=1
export _PR_NO_MULTIPLEXER=1
benchmark() {
hyperfine --warmup 10 \
--shell none \
"$1"
}
run_test() {
export _PR_LAST_COMMAND=$command
export _PR_ERROR_MSG=$error
echo "Benchmark: $case"
benchmark $PR
}
run_case() {
(
source $1
run_test
)
}
main() {
echo "Starting benchmarking tests..."
echo "-----------------------------------------"
WORKDIR=$(pwd)
cd $TMP
echo "Benchmark: Initialization"
echo "$PR bash"
benchmark "$PR bash"
CASES=$(ls $WORKDIR/cases/* | sort -V)
for case in $CASES; do
run_case $case
rm -rf ./*
done
rm -rf $TMP
}
main "$@"
pay-respects-0.8.8/tests/cases/ 0000775 0000000 0000000 00000000000 15173770737 0016427 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/tests/cases/001 0000664 0000000 0000000 00000000243 15173770737 0016651 0 ustar 00root root 0000000 0000000 case="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.8.8/tests/cases/002 0000664 0000000 0000000 00000000114 15173770737 0016647 0 ustar 00root root 0000000 0000000 case="Typo: Command"
command="echp"
error="command not found"
expect="echo"
pay-respects-0.8.8/tests/cases/003 0000664 0000000 0000000 00000000163 15173770737 0016654 0 ustar 00root root 0000000 0000000 case="Typo: File path"
command="cd correc"
error="no such file or directory"
expect="cd correct"
mkdir -p correct
pay-respects-0.8.8/tests/cases/011 0000664 0000000 0000000 00000000176 15173770737 0016657 0 ustar 00root root 0000000 0000000 case="RegEx: command"
command="touch dir/file"
error="no such file or directory"
expect="\
mkdir -p dir/ &&
touch dir/file\
"
pay-respects-0.8.8/tests/cases/012 0000664 0000000 0000000 00000000203 15173770737 0016647 0 ustar 00root root 0000000 0000000 case="RegEx: Error"
command="cargo built"
error="
error: no such command: \`built\`
Did you mean \`build\`?
"
expect="cargo build"
pay-respects-0.8.8/tests/cases/013 0000664 0000000 0000000 00000000170 15173770737 0016653 0 ustar 00root root 0000000 0000000 case="RegEx: Options"
command="rm correc -r"
error="no such file or directory"
expect="rm -r correct"
mkdir -p correct
pay-respects-0.8.8/tests/cases/021 0000664 0000000 0000000 00000000236 15173770737 0016655 0 ustar 00root root 0000000 0000000 # helix is used to also check for extends
case="Blocking commands: vim"
command="hx filetobeopen"
error=""
expect="hx file-to-be-open"
touch file-to-be-open
pay-respects-0.8.8/tests/cases/101 0000664 0000000 0000000 00000000202 15173770737 0016645 0 ustar 00root root 0000000 0000000 case="Desperate: File look up"
command="foocommand imadethisup"
error=""
expect="foocommand i-made-this-up"
touch i-made-this-up
pay-respects-0.8.8/tests/cases/102 0000664 0000000 0000000 00000000161 15173770737 0016652 0 ustar 00root root 0000000 0000000 case="Desperate: Fuzzy recovery"
command="gi tcommit"
error=""
expect="git commit"
export _PR_EXECUTABLES="git"
pay-respects-0.8.8/tests/test.sh 0000775 0000000 0000000 00000002561 15173770737 0016653 0 ustar 00root root 0000000 0000000 #!/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)
# can take a while in debug builds
# required for desperate checks
# export _PR_NO_DESPERATE=1
# zoxide is too slow
export _PR_NO_ZOXIDE=1
export _PR_EXECUTABLES=""
export _PR_NO_CONFIG=1
export _PR_NO_MULTIPLEXER=1
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
)
if [[ $? == 0 ]]; then
PASSED=$((PASSED + 1))
else
FAILED=$((FAILED + 1))
fi
}
main() {
echo "Starting suggestion tests..."
echo "-----------------------------------------"
WORKDIR=$(pwd)
cd $TMP
CASES=$(ls $WORKDIR/cases/* | sort -V)
for case in $CASES; do
run_case $case
rm -rf ./*
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.8.8/utils/ 0000775 0000000 0000000 00000000000 15173770737 0015327 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/utils/Cargo.toml 0000664 0000000 0000000 00000000712 15173770737 0017257 0 ustar 00root root 0000000 0000000 [package]
name = "pay-respects-utils"
version = "0.1.18"
edition = "2024"
# 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"
colored = "3.1.1"
# config file
toml = { version = "1.0" }
serde = { version = "1.0", features = ["derive"] }
pay-respects-0.8.8/utils/src/ 0000775 0000000 0000000 00000000000 15173770737 0016116 5 ustar 00root root 0000000 0000000 pay-respects-0.8.8/utils/src/evals.rs 0000664 0000000 0000000 00000043131 15173770737 0017600 0 ustar 00root root 0000000 0000000 // 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 crate::settings::*;
use itertools::Itertools;
use regex_lite::Regex;
use std::cmp::Ordering;
use std::collections::HashSet;
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())
.filter(|s| !s.is_empty())
.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
// - surrounded by quotes
// - is surrrounded by backticks
let regex =
r#"([^\s"'`\\]+|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\\ )+|\\+|\n"#;
let regex = Regex::new(regex).unwrap();
regex
.find_iter(command)
.map(|cap| cap.as_str().to_owned())
.collect::>()
}
pub fn split_comment(split: &mut Vec) -> Option {
if !split.contains(&"#".to_string()) {
return None;
}
// remove everything after the first # and store it in comments
let index = split.iter().position(|s| s == "#").unwrap();
let comments_vec = split.split_off(index);
if split.is_empty() {
*split = vec!["".to_string()];
}
Some(comments_vec[1..].join(" "))
}
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) {
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) {
suggestions.push(suggest);
} else {
suggestions.push(typo.to_string());
}
}
suggestions.join(" ")
}
pub fn best_match(query: &str, dict: &[String]) -> Option {
find_similar(query, dict)
}
pub fn best_matches(query: &str, dict: &[String]) -> Option> {
find_similars(query, dict)
}
pub fn get_initial_distance(str: &str) -> Option {
let percentage = get_dl_distance_percentage();
let threshold = get_search_threshold();
let max = get_dl_distance_max();
let min = get_dl_distance_min();
if str.chars().count() < threshold {
return None;
}
let distance = (str.chars().count() as f32 * percentage / 100.0).round() as usize;
if distance < min {
return None;
}
Some(std::cmp::min(distance + 1, max + 1))
}
pub fn find_similar(typo: &str, candidates: &[String]) -> Option {
if typo.len() < get_search_threshold() {
return None;
}
match get_search_type() {
SearchType::DamerauLevenshtein => edit_distance_best(typo, candidates),
SearchType::TrigramDamerauLevenshtein => {
fuzzy_best(typo, candidates, get_trigram_minimum_score())
}
}
}
pub fn find_similars(typo: &str, candidates: &[String]) -> Option> {
if typo.len() < get_search_threshold() {
return None;
}
match get_search_type() {
SearchType::DamerauLevenshtein => edit_distance_bests(typo, candidates),
SearchType::TrigramDamerauLevenshtein => {
fuzzy_best_n(typo, candidates, get_trigram_minimum_score(), usize::MAX)
}
}
}
pub fn edit_distance_best(typo: &str, candidates: &[String]) -> Option {
let mut min_distance = get_initial_distance(typo)?;
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);
}
#[cfg(debug_assertions)]
eprintln!("comparing '{typo}' with '{candidate}': distance = {distance}");
// finding self, not a typo
if distance == 0 {
break;
}
}
if let Some(min_distance_index) = min_distance_index {
return Some(candidates[min_distance_index].to_string());
}
None
}
pub fn edit_distance_bests(typo: &str, candidates: &[String]) -> Option> {
let mut min_distance = get_initial_distance(typo)?;
let mut min_distance_index = vec![];
for (i, candidate) in candidates.iter().enumerate() {
if candidate.is_empty() {
continue;
}
let distance = compare_string(typo, candidate);
#[cfg(debug_assertions)]
eprintln!("comparing '{typo}' with '{candidate}': distance = {distance}");
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 between two strings
#[allow(clippy::needless_range_loop)]
pub fn compare_string(a: &str, b: &str) -> usize {
let a: Vec = a.chars().collect();
let b: Vec