diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..7014edc9 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,16 @@ + + +### What does this PR try to solve? + + +Fixes # + +### Notes to reviewers + + + +LLM involvement: diff --git a/.github/renovate.json5 b/.github/renovate.json5 index cc1fefc3..7dec7acd 100644 --- a/.github/renovate.json5 +++ b/.github/renovate.json5 @@ -1,11 +1,16 @@ { + extends: ["helpers:pinGitHubActionDigests"], schedule: [ 'before 5am on the first day of the month', ], + minimumReleaseAge: "3 days", + internalChecksFilter: "strict", semanticCommits: 'enabled', commitMessageLowerCase: 'never', configMigration: true, - dependencyDashboard: true, + dependencyDashboard: { + enabled: true, + }, "pre-commit": { enabled: true }, @@ -64,11 +69,19 @@ matchDepNames: [ 'prek', ], - extractVersion: '^(?\\d+\\.\\d+\\.\\d+)', - schedule: [ - '* * * * *', + extractVersion: '^v(?\\d+\\.\\d+\\.\\d+)', + automerge: true, + }, + { + matchManagers: [ + 'github-actions', + ], + matchUpdateTypes: [ + 'minor', + 'patch', ], automerge: true, + groupName: 'compatible (actions)', }, // Goals: // - Keep version reqs low, ignoring compatible normal/build dependencies diff --git a/.github/settings.yml b/.github/settings.yml index f8bcac4c..9b3763e4 100644 --- a/.github/settings.yml +++ b/.github/settings.yml @@ -1,7 +1,7 @@ # These settings are synced to GitHub by https://probot.github.io/apps/settings/ repository: - description: ".github/workflows/ci.yml" + description: "Interact with unix processes/bash the same way as pexpect or Don libes expect does" homepage: "https://docs.rs/rexpect" topics: "pexpect unix pty processes" has_issues: true diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml index 7446e08e..b070313e 100644 --- a/.github/workflows/audit.yml +++ b/.github/workflows/audit.yml @@ -1,13 +1,10 @@ -name: Security audit +name: Audit permissions: contents: read on: pull_request: - paths: - - '**/Cargo.toml' - - '**/Cargo.lock' push: branches: - main @@ -22,19 +19,38 @@ concurrency: cancel-in-progress: true jobs: - security_audit: + audit: + permissions: + contents: none + name: Audit + needs: [advisories, cargo_deny, actions] + runs-on: ubuntu-latest + if: "always()" + steps: + - name: Failed + run: exit 1 + if: "contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped')" + advisories: permissions: issues: write # to create issues (actions-rs/audit-check) checks: write # to create check (actions-rs/audit-check) runs-on: ubuntu-latest # Prevent sudden announcement of a new advisory from failing ci: continue-on-error: true + strategy: + matrix: + checks: + - advisories steps: - name: Checkout repository - uses: actions/checkout@v6 - - uses: actions-rs/audit-check@v1 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Lint advisories + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: - token: ${{ secrets.GITHUB_TOKEN }} + command: check ${{ matrix.checks }} + rust-version: stable cargo_deny: permissions: @@ -46,8 +62,29 @@ jobs: checks: - bans licenses sources steps: - - uses: actions/checkout@v6 - - uses: EmbarkStudios/cargo-deny-action@v2 + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Lint bans + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 with: command: check ${{ matrix.checks }} rust-version: stable + + actions: + runs-on: ubuntu-latest + permissions: + security-events: write + contents: read # only needed for private or internal repos + actions: read # only needed for private or internal repos + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Run zizmor + uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0 + with: + advanced-security: false + annotations: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5964cae7..d61f4433 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,8 @@ env: RUST_BACKTRACE: 1 CARGO_TERM_COLOR: always CLICOLOR: 1 + CARGO_INCREMENTAL: 0 + RUST_TOOLCHAIN_STABLE: "1.100" # STABLE concurrency: group: "${{ github.workflow }}-${{ github.ref }}" @@ -43,13 +45,17 @@ jobs: CARGO_PROFILE_DEV_DEBUG: line-tables-only steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@stable + run: rustup update --no-self-update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - name: Install cargo-hack + uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: - toolchain: ${{ matrix.rust }} - - uses: Swatinem/rust-cache@v2 - - uses: taiki-e/install-action@cargo-hack + tool: cargo-hack - name: Build run: cargo test --workspace --no-run - name: Test @@ -62,13 +68,17 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@stable + run: rustup update --no-self-update stable && rustup default stable + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - name: Install cargo-hack + uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - - uses: taiki-e/install-action@cargo-hack + tool: cargo-hack - name: Default features run: cargo hack check --each-feature --locked --rust-version --ignore-private --workspace --all-targets --keep-going minimal-versions: @@ -79,15 +89,13 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install stable Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: stable + persist-credentials: false + - name: Install stable Rust + run: rustup update --no-self-update stable && rustup default stable - name: Install nightly Rust - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly + run: rustup update --no-self-update nightly && rustup default nightly - name: Downgrade dependencies to minimal versions run: cargo +nightly generate-lockfile -Z minimal-versions - name: Compile with minimal versions @@ -96,12 +104,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 + persist-credentials: false + - name: Install Rust + run: rustup update --no-self-update stable && rustup default stable + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: "Is lockfile updated?" run: cargo update --workspace --locked docs: @@ -109,28 +118,31 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: "1.93" # STABLE - - uses: Swatinem/rust-cache@v2 + persist-credentials: false + - name: Install Rust + run: rustup update --no-self-update $RUST_TOOLCHAIN_STABLE && rustup default $RUST_TOOLCHAIN_STABLE + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Check documentation env: - RUSTDOCFLAGS: -D warnings + CARGO_BUILD_WARNINGS: deny run: cargo doc --workspace --all-features --no-deps --document-private-items --keep-going rustfmt: name: rustfmt runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: "1.93" # STABLE - components: rustfmt - - uses: Swatinem/rust-cache@v2 + persist-credentials: false + - name: Install Rust + run: rustup update --no-self-update $RUST_TOOLCHAIN_STABLE && rustup default $RUST_TOOLCHAIN_STABLE + - name: Install rustfmt + run: rustup component add rustfmt + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Check formatting run: cargo fmt --check clippy: @@ -140,13 +152,15 @@ jobs: security-events: write # to upload sarif results steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: "1.93" # STABLE - components: clippy - - uses: Swatinem/rust-cache@v2 + persist-credentials: false + - name: Install Rust + run: rustup update --no-self-update $RUST_TOOLCHAIN_STABLE && rustup default $RUST_TOOLCHAIN_STABLE + - name: Install clippy + run: rustup component add clippy + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Install SARIF tools run: cargo install clippy-sarif --locked - name: Install SARIF tools @@ -159,28 +173,37 @@ jobs: | sarif-fmt continue-on-error: true - name: Upload - uses: github/codeql-action/upload-sarif@v4 + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 with: sarif_file: clippy-results.sarif wait-for-processing: true - name: Report status - run: cargo clippy --workspace --all-features --all-targets --keep-going -- -D warnings --allow deprecated + env: + CARGO_BUILD_WARNINGS: deny + run: cargo clippy --workspace --all-features --all-targets --keep-going -- --allow deprecated --allow renamed_and_removed_lints coverage: name: Coverage runs-on: ubuntu-latest + permissions: + code-quality: write steps: - name: Checkout repository - uses: actions/checkout@v6 - - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 + persist-credentials: false + - name: Install Rust + run: rustup update --no-self-update stable && rustup default stable + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Install cargo-tarpaulin - run: cargo install cargo-tarpaulin + uses: taiki-e/install-action@37f7c5781271959fb65b6b35224e28652ff2b63d # v2.87.0 + with: + tool: cargo-tarpaulin - name: Gather coverage - run: cargo tarpaulin --output-dir coverage --out lcov - - name: Publish to Coveralls - uses: coverallsapp/github-action@master + run: cargo tarpaulin --out xml --timeout 120 + - name: Upload coverage report + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + uses: actions/upload-code-coverage@2b21a77928be8d5168c2b9581a67f2adbebacc52 # v1.4.4 with: - github-token: ${{ secrets.GITHUB_TOKEN }} + file: cobertura.xml + language: Rust diff --git a/.github/workflows/commit-lint.yml b/.github/workflows/commit-lint.yml deleted file mode 100644 index 1d7524bd..00000000 --- a/.github/workflows/commit-lint.yml +++ /dev/null @@ -1,25 +0,0 @@ -on: - pull_request: - -name: Pull Request Checks - -jobs: - block-fixup: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - name: Block fixup commit merge - uses: 13rac1/block-fixup-merge-action@v2.0.0 - - commit-lint: - runs-on: ubuntu-latest - if: github.event_name == 'pull_request' - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - uses: actions/setup-python@v6 - with: - python-version: '3.x' - - run: pip install gitlint - - run: gitlint --commits $(git merge-base origin/master HEAD)..HEAD diff --git a/.github/workflows/committed.yml b/.github/workflows/committed.yml index 9138a8e3..773fcd01 100644 --- a/.github/workflows/committed.yml +++ b/.github/workflows/committed.yml @@ -20,9 +20,11 @@ jobs: name: Lint Commits runs-on: ubuntu-latest steps: - - name: Checkout Actions Repository - uses: actions/checkout@v6 + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + filter: "tree:0" + persist-credentials: false - name: Lint Commits - uses: crate-ci/committed@master + uses: crate-ci/committed@faeed42f2e10c244533a01525f13c4d8b6ce383f # v1.1.11 diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index ef1a54ac..2b798597 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -22,7 +22,11 @@ jobs: contents: read runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: j178/prek-action@v1 + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - prek-version: '0.2.27' + persist-credentials: false + - name: prek + uses: j178/prek-action@44924fe9ef4a6f88253c4b6b1bf11c689d3ce53d # v3.1.0 + with: + prek-version: 'v0.5.9' diff --git a/.github/workflows/rust-next.yml b/.github/workflows/rust-next.yml index 2147daff..49d8f1a8 100644 --- a/.github/workflows/rust-next.yml +++ b/.github/workflows/rust-next.yml @@ -11,6 +11,7 @@ env: RUST_BACKTRACE: 1 CARGO_TERM_COLOR: always CLICOLOR: 1 + CARGO_INCREMENTAL: 0 concurrency: group: "${{ github.workflow }}-${{ github.ref }}" @@ -33,13 +34,17 @@ jobs: CARGO_PROFILE_DEV_DEBUG: line-tables-only steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@stable + run: rustup update --no-self-update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - name: Install cargo-hack + uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: - toolchain: ${{ matrix.rust }} - - uses: Swatinem/rust-cache@v2 - - uses: taiki-e/install-action@cargo-hack + tool: cargo-hack - name: Build run: cargo test --workspace --no-run - name: Test @@ -54,13 +59,17 @@ jobs: CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: allow steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install Rust - uses: dtolnay/rust-toolchain@stable + run: rustup update --no-self-update stable && rustup default stable + - name: Initialize cache + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - name: Install cargo-hack + uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - - uses: taiki-e/install-action@cargo-hack + tool: cargo-hack - name: Update dependencies run: cargo update - name: Build diff --git a/.github/workflows/spelling.yml b/.github/workflows/spelling.yml index cf4c1bfb..df7007d3 100644 --- a/.github/workflows/spelling.yml +++ b/.github/workflows/spelling.yml @@ -20,6 +20,8 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Actions Repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Spell Check Repo - uses: crate-ci/typos@master + uses: crate-ci/typos@7f9d0819ca1c008ade73f4b41fa9d258d48f605b # v1.51.1 diff --git a/.github/workflows/template.yml b/.github/workflows/template.yml index 1d4fd850..76121eef 100644 --- a/.github/workflows/template.yml +++ b/.github/workflows/template.yml @@ -28,12 +28,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + persist-credentials: true # to push the branch and create PR - name: Configure git run: | - git config --global user.name '${{ github.actor }}' + git config --global user.name '${GITHUB_ACTOR}' git config --global user.email '<>' - name: Fetch template run: "git remote add template ${{ env.TEMPLATE_URL }} && git fetch template ${{ env.TEMPLATE_BRANCH }}" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7aa56f78..49bc1555 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,10 +10,14 @@ repos: - id: check-case-conflict - id: detect-private-key - repo: https://github.com/crate-ci/typos - rev: v1.42.1 + rev: v1.50.0 hooks: - id: typos - repo: https://github.com/crate-ci/committed - rev: v1.1.10 + rev: v1.1.11 hooks: - id: committed + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.28.0 + hooks: + - id: zizmor diff --git a/AI_POLICY.md b/AI_POLICY.md new file mode 100644 index 00000000..b2ad65fd --- /dev/null +++ b/AI_POLICY.md @@ -0,0 +1,58 @@ +# AI policy + +Project maintainers are responsible for any code that is published as part of a release. +Contributors are responsible for their contributions, both in terms of communications and code. +This responsibility is for both understanding of and the quality of their contributions. + +## Personal use + +You are free to use an AI locally for your own purposes, +including to answer your questions, analyze, distill, refine, check, suggest, and review. + +## Communication + +**AI should not be used to generate comments when communicating with maintainers.** +We expect comments on our projects to be written by humans. +We may hide or delete any comments where we believe AI generation was involved. + +If you are opening an issue, +we expect you to have personally reproduced the problem and to describe it in your own words. + +If you are opening a pull request, +we expect you to be able to explain the proposed changes in your own words. +This includes the pull request body and responses to questions. +**Do not copy responses from an AI when replying to questions from maintainers.** +Do not run agents or bots on pull requests without first getting approval. + +We understand that AI is useful when communicating as a non-native English speaker. +If you are using AI to edit your comments for this purpose, +please take the time to ensure it reflects your own voice and ideas. +If using AI for translation, we recommend writing in your native language and including the AI translation in a [`
` block]. + +If you wish to include context from an interaction with AI in your comments, +it must be in a [`
` block] and disclosed as such. +The block must include human commentary explaining the relevance and implications of the context. +The content of your comment must stand on its own even without the quoted content. +Do not share long snippets. + +## Code + +Using AI as tools for coding requires receiving permission on the relevant issue before a PR is posted. + +This project requires a human in the loop who understands the work produced by AI. +**We do not allow autonomous agents to be used for contributing to this project**. +We will close any pull requests that we believe were created **without meaningful involvement** from the contributor. +Contributions should not "read" as being written by an AI. + +Some areas require specific expertise or care when touching. +AI generated code, even with human review, is prohibited for: +- none + +We view AI as providing a way to improve quality and will hold AI-assisted contributions to a higher standard. +We will be more free in asking for changes. + +The involvement of AI assistance must be disclosed in PRs. + +For documentation, including comments in code, see [Communication](#communication). + +[`
` block]: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-collapsed-sections) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bb2b6b1..f6649527 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] - ReleaseDate +## [0.7.2] - 2026-11-26 + +### Internal + +- Update dependencies + +## [0.7.1] - 2026-05-14 + +### Fixes + +- Avoid `char` boundary panics with `NBReader::try_read` + +## [0.7.0] - 2026-03-16 + +### Breaking Changes + +- Made fields private: `PtyReplSession`, `PtySession`, `StreamSession`, `Options` +- Made `non_exhaustive`: `Options`, `Error` +- Remove from the API: `find`, `process::wait`, `process::signal` + +## [0.6.4] - 2026-03-16 + +### Feature + +- Add builder methods to `Options` +- Add `PtySession::new` +- Add `PtySession::process` +- Add `PtyReplSession::new`, `PtyReplSession::echo_on`, `PtyReplSession::quit_command` + +### Fixes + +- Make `process::wait::WaitStatus` and `process::signal::Signal` available directly in `process` + +### Compatibility + +- MSRV is 1.85 + ## [0.6.3] - 2026-01-15 ### Fixes @@ -115,7 +152,11 @@ All `exp_*` methods now also return the yet unread string and/or the matched str - try_read was blocking when there was no char ready (!) -> fixed -[Unreleased]: https://github.com/rust-cli/rexpect/compare/v0.6.3...HEAD +[Unreleased]: https://github.com/rust-cli/rexpect/compare/v0.7.2...HEAD +[0.7.2]: https://github.com/rust-cli/rexpect/compare/v0.7.1...v0.7.2 +[0.7.1]: https://github.com/rust-cli/rexpect/compare/v0.7.0...v0.7.1 +[0.7.0]: https://github.com/rust-cli/rexpect/compare/v0.6.4...v0.7.0 +[0.6.4]: https://github.com/rust-cli/rexpect/compare/v0.6.3...v0.6.4 [0.6.3]: https://github.com/rust-cli/rexpect/compare/v0.6.2...v0.6.3 [0.6.2]: https://github.com/rust-cli/rexpect/compare/v0.6.1...v0.6.2 [0.6.1]: https://github.com/rust-cli/rexpect/compare/v0.6.0...v0.6.1 diff --git a/Cargo.lock b/Cargo.lock index e968809d..3dbcd985 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "aho-corasick" @@ -37,9 +37,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "comma" @@ -100,9 +100,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.172" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -124,9 +124,9 @@ checksum = "5486aed0026218e61b8a01d5fbd5a0a134649abb71a0e53b7bc088529dced86e" [[package]] name = "nix" -version = "0.30.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537bc3c4a347b87fd52ac6c03a02ab1302962cfd93373c5d7a112cdc337854cc" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ "bitflags 2.6.0", "cfg-if", @@ -192,7 +192,7 @@ checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] name = "rexpect" -version = "0.6.3" +version = "0.7.2" dependencies = [ "comma", "nix", diff --git a/Cargo.toml b/Cargo.toml index 42c253d6..ace15e2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,23 +1,26 @@ [workspace] -resolver = "2" +resolver = "3" [workspace.package] repository = "https://github.com/rust-cli/rexpect" license = "MIT OR Apache-2.0" -edition = "2021" -rust-version = "1.70.0" # MSRV +edition = "2024" +rust-version = "1.85.0" # MSRV include = [ - "build.rs", - "src/**/*", - "Cargo.toml", - "Cargo.lock", - "LICENSE*", - "README.md", - "examples/**/*" + "/build.rs", + "/src/**/*", + "/Cargo.toml", + "/Cargo.lock", + "/LICENSE*", + "/README.md", + "/examples/**/*" ] [workspace.lints.rust] rust_2018_idioms = { level = "warn", priority = -1 } + +non_ascii_idents = "warn" +trivial_numeric_casts = "warn" unnameable_types = "warn" unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" @@ -26,10 +29,17 @@ unused_macro_rules = "warn" unused_qualifications = "warn" [workspace.lints.clippy] +allow_attributes_without_reason = "warn" bool_assert_comparison = "allow" branches_sharing_code = "allow" +byte_char_slices = "allow" # sometimes explicit arrays are better +cast_possible_truncation = "warn" +cast_possible_wrap = "warn" +cast_sign_loss = "warn" checked_conversions = "warn" collapsible_else_if = "allow" +collapsible_match = "allow" +collection_is_never_read = "warn" create_dir = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" @@ -42,9 +52,10 @@ explicit_into_iter_loop = "warn" fallible_impl_from = "warn" filter_map_next = "warn" flat_map_option = "warn" +float_cmp = "warn" float_cmp_const = "warn" fn_params_excessive_bools = "warn" -from_iter_instead_of_collect = "warn" +fn_to_numeric_cast_any = "warn" if_same_then_else = "allow" implicit_clone = "warn" imprecise_flops = "warn" @@ -60,10 +71,12 @@ linkedlist = "warn" lossy_float_literal = "warn" macro_use_imports = "warn" mem_forget = "warn" +mismatching_type_param_order = "warn" mutex_integer = "warn" needless_continue = "allow" needless_for_each = "warn" negative_feature_names = "warn" +partial_pub_fields = "warn" path_buf_push_overwrite = "warn" ptr_as_ptr = "warn" rc_mutex = "warn" @@ -74,13 +87,19 @@ result_large_err = "allow" same_functions_in_if_condition = "warn" self_named_module_files = "warn" semicolon_if_nothing_returned = "warn" +should_panic_without_expect = "warn" str_to_string = "warn" string_add = "warn" string_add_assign = "warn" string_lit_as_bytes = "warn" todo = "warn" trait_duplication_in_bounds = "warn" +undocumented_unsafe_blocks = "warn" uninlined_format_args = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unseparated_literal_suffix = "warn" +use_self = "warn" verbose_file_reads = "warn" wildcard_imports = "warn" zero_sized_map_values = "warn" @@ -97,7 +116,7 @@ lto = true [package] name = "rexpect" description = "Interact with unix processes/bash the same way as pexpect or Don libes expect does" -version = "0.6.3" +version = "0.7.2" categories = ["os::unix-apis"] keywords = ["pty", "automation", "testing", "expect", "pexpect"] repository.workspace = true @@ -116,7 +135,7 @@ pre-release-replacements = [ {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1}, {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1}, {file="CHANGELOG.md", search="", replace="\n## [Unreleased] - ReleaseDate\n", exactly=1}, - {file="CHANGELOG.md", search="", replace="\n[Unreleased]: https://github.com/rust-cli/rexpect/compare/{{tag_name}}...HEAD", exactly=1}, + {file="CHANGELOG.md", search="", replace="\n[Unreleased]: {{repository}}/compare/{{tag_name}}...HEAD", exactly=1}, ] [features] @@ -125,7 +144,7 @@ which = ["dep:which"] [dependencies] comma = "1.0" -nix = { version = "0.30", features = ["fs", "process", "signal", "term"] } +nix = { version = "0.32", features = ["fs", "process", "signal", "term"] } regex = "1" tempfile = "3" thiserror = "2.0.0" diff --git a/LICENSE-APACHE b/LICENSE-APACHE index 8f71f43f..6aa81fe0 100644 --- a/LICENSE-APACHE +++ b/LICENSE-APACHE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright {yyyy} {name of copyright owner} + Copyright Individual contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 95451423..577b0640 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # rexpect -[![Documentation](https://img.shields.io/badge/docs-master-blue.svg)][Documentation] +[![Documentation](https://img.shields.io/badge/docs-main-blue.svg)][Documentation] ![License](https://img.shields.io/crates/l/rexpect.svg) [![Crates Status](https://img.shields.io/crates/v/rexpect.svg)][Crates.io] @@ -19,7 +19,7 @@ The goal is to offer a similar set of functionality as ## Examples -[For more examples, check the examples directory.](https://github.com/philippkeller/rexpect/tree/master/examples) +[For more examples, check the examples directory.](https://github.com/rust-cli/rexpect/tree/main/examples) ### Basic usage diff --git a/deny.toml b/deny.toml index 27bf59a8..c617b413 100644 --- a/deny.toml +++ b/deny.toml @@ -97,6 +97,7 @@ allow = [ "OpenSSL", "Zlib", "NCSA", + "CDLA-Permissive-2.0", ] # The confidence threshold for detecting a license from license text. # The higher the value, the more closely the license text must be to the diff --git a/examples/exit_code.rs b/examples/exit_code.rs index 67486de6..e341fd51 100644 --- a/examples/exit_code.rs +++ b/examples/exit_code.rs @@ -1,5 +1,5 @@ use rexpect::error::Error; -use rexpect::process::wait; +use rexpect::process::WaitStatus; use rexpect::spawn; /// The following code emits: @@ -8,15 +8,15 @@ use rexpect::spawn; /// Output (stdout and stderr): cat: /this/does/not/exist: No such file or directory fn main() -> Result<(), Error> { let p = spawn("cat /etc/passwd", Some(2000))?; - match p.process.wait() { - Ok(wait::WaitStatus::Exited(_, 0)) => println!("cat exited with code 0, all good!"), + match p.process().wait() { + Ok(WaitStatus::Exited(_, 0)) => println!("cat exited with code 0, all good!"), _ => println!("cat exited with code >0, or it was killed"), } let mut p = spawn("cat /this/does/not/exist", Some(2000))?; - match p.process.wait() { - Ok(wait::WaitStatus::Exited(_, 0)) => println!("cat succeeded"), - Ok(wait::WaitStatus::Exited(_, c)) => { + match p.process().wait() { + Ok(WaitStatus::Exited(_, 0)) => println!("cat succeeded"), + Ok(WaitStatus::Exited(_, c)) => { println!("Cat failed with exit code {c}"); println!("Output (stdout and stderr): {}", p.exp_eof()?); } diff --git a/examples/repl.rs b/examples/repl.rs index 4a305e46..674b4cbe 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -5,20 +5,15 @@ use rexpect::session::PtyReplSession; use rexpect::spawn; fn ed_session() -> Result { - let mut ed = PtyReplSession { + let mut ed = PtyReplSession::new(spawn("/bin/ed -p '> '", Some(2000))?, "> ".to_owned()) // for `echo_on` you need to figure that out by trial and error. // For bash and python repl it is false - echo_on: false, - - // used for `wait_for_prompt()` - prompt: "> ".to_owned(), - pty_session: spawn("/bin/ed -p '> '", Some(2000))?, + .echo_on(false) // command which is sent when the instance of this struct is dropped // in the below example this is not needed, but if you don't explicitly // exit a REPL then rexpect tries to send a SIGTERM and depending on the repl // this does not end the repl and would end up in an error - quit_command: Some("Q".to_owned()), - }; + .quit_command(Some("Q".to_owned())); ed.wait_for_prompt()?; Ok(ed) } diff --git a/src/error.rs b/src/error.rs index a64b906a..af8c1c4e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,7 @@ use std::time; #[derive(Debug, thiserror::Error)] +#[non_exhaustive] pub enum Error { #[error("EOF (End of File): Expected {:?} but got EOF after reading {:?} process terminated with {:?}", .expected, .got, .exit_code.as_ref().unwrap_or(&"unknown".to_owned()))] EOF { @@ -12,7 +13,7 @@ pub enum Error { #[error("PipeError")] BrokenPipe, - #[error("Timeout Error: Expected {:?} but got {:?} (after waiting {} ms)", .expected, .got, (.timeout.as_secs() * 1000) as u32 + .timeout.subsec_millis())] + #[error("Timeout Error: Expected {:?} but got {:?} (after waiting {} ms)", .expected, .got, (.timeout.as_secs() * 1000) + .timeout.subsec_millis() as u64)] Timeout { expected: String, got: String, diff --git a/src/lib.rs b/src/lib.rs index cc656a03..23843db9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,10 +7,10 @@ //! //! It's main components (depending on your need you can use either of those) //! -//! - [session](session/index.html): automate stuff in Rust -//! - [reader](reader/index.html): a non-blocking reader with buffering, matching on +//! - [session]: automate stuff in Rust +//! - [reader]: a non-blocking reader with buffering, matching on //! strings/regex/... -//! - [process](process/index.html): spawn a process in a pty +//! - [process]: spawn a process in a pty //! //! # Basic example //! diff --git a/src/process.rs b/src/process.rs index 63cfb498..bc50c730 100644 --- a/src/process.rs +++ b/src/process.rs @@ -2,13 +2,13 @@ use crate::error::Error; use nix; -use nix::fcntl::{open, OFlag}; +use nix::fcntl::{OFlag, open}; use nix::libc::STDERR_FILENO; -use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster}; -pub use nix::sys::{signal, wait}; +use nix::pty::{PtyMaster, grantpt, posix_openpt, unlockpt}; +use nix::sys::{signal, wait}; use nix::sys::{stat, termios}; use nix::unistd::{ - close, dup, dup2_stderr, dup2_stdin, dup2_stdout, fork, setsid, ForkResult, Pid, + ForkResult, Pid, close, dup, dup2_stderr, dup2_stdin, dup2_stdout, fork, setsid, }; use std; use std::fs::File; @@ -18,7 +18,10 @@ use std::os::unix::process::CommandExt; use std::process::Command; use std::{thread, time}; -/// Start a process in a forked tty so you can interact with it the same as you would +pub use signal::Signal; +pub use wait::WaitStatus; + +/// Start a process in a forked tty to interact with it like you would /// within a terminal /// /// The process and pty session are killed upon dropping `PtyProcess` @@ -42,8 +45,7 @@ use std::{thread, time}; /// # fn main() { /// /// let mut process = PtyProcess::new(Command::new("cat")).expect("could not execute cat"); -/// let fd = dup(&process.pty).unwrap(); -/// let f = File::from(fd); +/// let f = process.get_file_handle().unwrap(); /// let mut writer = LineWriter::new(&f); /// let mut reader = BufReader::new(&f); /// process.exit().expect("could not terminate process"); @@ -55,8 +57,8 @@ use std::{thread, time}; /// # } /// ``` pub struct PtyProcess { - pub pty: PtyMaster, - pub child_pid: Pid, + pty: PtyMaster, + pub(crate) child_pid: Pid, kill_timeout: Option, } @@ -64,16 +66,17 @@ pub struct PtyProcess { use nix::pty::ptsname_r; #[cfg(target_os = "macos")] -/// ptsname_r is a linux extension but ptsname isn't thread-safe +/// `ptsname_r` is a linux extension but ptsname isn't thread-safe /// instead of using a static mutex this calls ioctl with TIOCPTYGNAME directly -/// based on https://blog.tarq.io/ptsname-on-osx-with-rust/ +/// based on / fn ptsname_r(fd: &PtyMaster) -> nix::Result { - use nix::libc::{ioctl, TIOCPTYGNAME}; + use nix::libc::{TIOCPTYGNAME, ioctl}; use std::ffi::CStr; // the buffer size on OSX is 128, defined by sys/ttycom.h let mut buf: [i8; 128] = [0; 128]; + #[expect(clippy::undocumented_unsafe_blocks, reason = "TODO")] unsafe { match ioctl(fd.as_raw_fd(), TIOCPTYGNAME as u64, &mut buf) { 0 => { @@ -98,6 +101,7 @@ impl PtyProcess { // on Linux this is the libc function, on OSX this is our implementation of ptsname_r let slave_name = ptsname_r(&master_fd)?; + #[expect(clippy::undocumented_unsafe_blocks, reason = "TODO")] match unsafe { fork()? } { ForkResult::Child => { // Avoid leaking master fd @@ -129,7 +133,7 @@ impl PtyProcess { let _ = command.exec(); Err(Error::Nix(nix::Error::last())) } - ForkResult::Parent { child: child_pid } => Ok(PtyProcess { + ForkResult::Parent { child: child_pid } => Ok(Self { pty: master_fd, child_pid, kill_timeout: None, @@ -144,23 +148,24 @@ impl PtyProcess { Ok(fd.into()) } - /// At the drop of `PtyProcess` the running process is killed. This is blocking forever if - /// the process does not react to a normal kill. If `kill_timeout` is set the process is - /// `kill -9`ed after duration + /// At the drop of `PtyProcess` the running process is killed (blocking). + /// + /// This is blocking forever if the process does not react to a normal kill. + /// If `kill_timeout` is set the process is `kill -9`ed after duration. pub fn set_kill_timeout(&mut self, timeout_ms: Option) { self.kill_timeout = timeout_ms.map(time::Duration::from_millis); } - /// Get status of child process, non-blocking. + /// Get status of child process (non-blocking). /// - /// This method runs waitpid on the process. - /// This means: If you ran `exit()` before or `status()` this method will + /// This method runs waitpid on the process: + /// if you ran `exit()` before or `status()` this method will /// return `None` /// /// # Example /// ```rust,no_run /// - /// use rexpect::process::{self, wait::WaitStatus}; + /// use rexpect::process::{self, WaitStatus}; /// use std::process::Command; /// /// # fn main() { @@ -172,54 +177,59 @@ impl PtyProcess { /// # } /// ``` /// - pub fn status(&self) -> Option { + pub fn status(&self) -> Option { wait::waitpid(self.child_pid, Some(wait::WaitPidFlag::WNOHANG)).ok() } - /// Wait until process has exited. This is a blocking call. + /// Wait until process has exited (non-blocking). + /// /// If the process doesn't terminate this will block forever. - pub fn wait(&self) -> Result { + pub fn wait(&self) -> Result { wait::waitpid(self.child_pid, None).map_err(Error::from) } - /// Regularly exit the process, this method is blocking until the process is dead - pub fn exit(&mut self) -> Result { + /// Regularly exit the process (blocking). + /// + /// This method is blocking until the process is dead + pub fn exit(&mut self) -> Result { self.kill(signal::SIGTERM) } - /// Non-blocking variant of `kill()` (doesn't wait for process to be killed) - pub fn signal(&mut self, sig: signal::Signal) -> Result<(), Error> { + /// Kill the process with a specific signal (non-blocking). + pub fn signal(&mut self, sig: Signal) -> Result<(), Error> { signal::kill(self.child_pid, sig).map_err(Error::from) } - /// Kill the process with a specific signal. This method blocks, until the process is dead + /// Kill the process with a specific signal (blocking). + /// + /// This method blocks until the process is dead /// - /// repeatedly sends SIGTERM to the process until it died, + /// This repeatedly sends SIGTERM to the process until it died, /// the pty session is closed upon dropping `PtyMaster`, /// so we don't need to explicitly do that here. /// - /// if `kill_timeout` is set and a repeated sending of signal does not result in the process + /// If `kill_timeout` is set and a repeated sending of signal does not result in the process /// being killed, then `kill -9` is sent after the `kill_timeout` duration has elapsed. - pub fn kill(&mut self, sig: signal::Signal) -> Result { + pub fn kill(&mut self, sig: Signal) -> Result { let start = time::Instant::now(); loop { match signal::kill(self.child_pid, sig) { Ok(_) => {} // process was already killed before -> ignore Err(nix::errno::Errno::ESRCH) => { - return Ok(wait::WaitStatus::Exited(Pid::from_raw(0), 0)) + return Ok(WaitStatus::Exited(Pid::from_raw(0), 0)); } Err(e) => return Err(Error::from(e)), } match self.status() { - Some(status) if status != wait::WaitStatus::StillAlive => return Ok(status), + Some(status) if status != WaitStatus::StillAlive => return Ok(status), Some(_) | None => thread::sleep(time::Duration::from_millis(100)), } // kill -9 if timeout is reached if let Some(timeout) = self.kill_timeout { if start.elapsed() > timeout { - signal::kill(self.child_pid, signal::Signal::SIGKILL).map_err(Error::from)?; + signal::kill(self.child_pid, Signal::SIGKILL).map_err(Error::from)?; } } } @@ -228,7 +238,7 @@ impl PtyProcess { impl Drop for PtyProcess { fn drop(&mut self) { - if let Some(wait::WaitStatus::StillAlive) = self.status() { + if let Some(WaitStatus::StillAlive) = self.status() { self.exit().expect("cannot exit"); } } @@ -237,7 +247,7 @@ impl Drop for PtyProcess { #[cfg(test)] mod tests { use super::*; - use nix::sys::{signal, wait}; + use nix::sys::wait; use std::io::{BufRead, BufReader, LineWriter, Write}; #[test] @@ -257,7 +267,7 @@ mod tests { thread::sleep(time::Duration::from_millis(100)); writer.write_all(&[3])?; // send ^C writer.flush()?; - let should = wait::WaitStatus::Signaled(process.child_pid, signal::Signal::SIGINT, false); + let should = WaitStatus::Signaled(process.child_pid, Signal::SIGINT, false); assert_eq!(should, wait::waitpid(process.child_pid, None).unwrap()); Ok(()) } diff --git a/src/reader.rs b/src/reader.rs index 7a6a9443..af174e09 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -4,110 +4,35 @@ use crate::error::Error; pub use regex::Regex; use std::io::prelude::*; use std::io::{self, BufReader}; -use std::sync::mpsc::{channel, Receiver}; +use std::sync::mpsc::{Receiver, channel}; use std::thread; use std::{fmt, time}; -#[derive(Debug)] -enum PipeError { - IO(io::Error), -} - -#[derive(Debug)] -#[allow(clippy::upper_case_acronyms)] -enum PipedChar { - Char(u8), - EOF, -} - -pub enum ReadUntil { - String(String), - Regex(Regex), - EOF, - NBytes(usize), - Any(Vec), +/// Options for [`NBReader`] +#[derive(Default)] +pub struct Options { + /// `None`: `read_until` is blocking forever. This is probably not what you want + /// + /// `Some(millis)`: after millis milliseconds a timeout error is raised + pub(crate) timeout_ms: Option, + /// Whether to filter out escape codes, such as colors. + pub(crate) strip_ansi_escape_codes: bool, } -impl fmt::Display for ReadUntil { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let printable = match self { - ReadUntil::String(ref s) if s == "\n" => "\\n (newline)".to_owned(), - ReadUntil::String(ref s) if s == "\r" => "\\r (carriage return)".to_owned(), - ReadUntil::String(ref s) => format!("\"{s}\""), - ReadUntil::Regex(ref r) => format!("Regex: \"{r}\""), - ReadUntil::EOF => "EOF (End of File)".to_owned(), - ReadUntil::NBytes(n) => format!("reading {n} bytes"), - ReadUntil::Any(ref v) => { - let mut res = Vec::new(); - for r in v { - res.push(r.to_string()); - } - res.join(", ") - } - }; - write!(f, "{printable}") +impl Options { + pub fn new() -> Self { + Default::default() } -} -/// find first occurrence of needle within buffer -/// -/// # Arguments: -/// -/// - buffer: the currently read buffer from a process which will still grow in the future -/// - eof: if the process already sent an EOF or a HUP -/// -/// # Return -/// -/// Tuple with match positions: -/// 1. position before match (0 in case of EOF and Nbytes) -/// 2. position after match -pub fn find(needle: &ReadUntil, buffer: &str, eof: bool) -> Option<(usize, usize)> { - match needle { - ReadUntil::String(ref s) => buffer.find(s).map(|pos| (pos, pos + s.len())), - ReadUntil::Regex(ref pattern) => pattern.find(buffer).map(|mat| (mat.start(), mat.end())), - ReadUntil::EOF => { - if eof { - Some((0, buffer.len())) - } else { - None - } - } - ReadUntil::NBytes(n) => { - if *n <= buffer.len() { - Some((0, *n)) - } else if eof && !buffer.is_empty() { - // reached almost end of buffer, return string, even though it will be - // smaller than the wished n bytes - Some((0, buffer.len())) - } else { - None - } - } - ReadUntil::Any(ref anys) => anys - .iter() - // Filter matching needles - .filter_map(|any| find(any, buffer, eof)) - // Return the left-most match - .min_by(|(start1, end1), (start2, end2)| { - if start1 == start2 { - end1.cmp(end2) - } else { - start1.cmp(start2) - } - }), + pub fn timeout_ms(mut self, timeout_ms: Option) -> Self { + self.timeout_ms = timeout_ms; + self } -} -/// Options for `NBReader` -/// -/// - timeout: -/// + `None`: `read_until` is blocking forever. This is probably not what you want -/// + `Some(millis)`: after millis milliseconds a timeout error is raised -/// - `strip_ansi_escape_codes`: Whether to filter out escape codes, such as colors. -#[derive(Default)] -pub struct Options { - pub timeout_ms: Option, - pub strip_ansi_escape_codes: bool, + pub fn strip_ansi_escape_codes(mut self, yes: bool) -> Self { + self.strip_ansi_escape_codes = yes; + self + } } /// Non blocking reader @@ -125,17 +50,17 @@ pub struct NBReader { impl NBReader { /// Create a new reader instance /// - /// # Arguments: + /// # Arguments /// - /// - f: file like object - /// - options: see `Options` - pub fn new(f: R, options: Options) -> NBReader { + /// - `f`: file like object + /// - `options`: see [`Options`] + pub fn new(f: R, options: Options) -> Self { let (tx, rx) = channel(); // spawn a thread which reads one char and sends it to tx thread::spawn(move || -> Result<(), Error> { let mut reader = BufReader::new(f); - let mut byte = [0u8]; + let mut byte = [0_u8]; let mut in_escape_code = false; loop { @@ -169,7 +94,7 @@ impl NBReader { }); // allocate string with a initial capacity of 1024, so when appending chars // we don't need to reallocate memory often - NBReader { + Self { reader: rx, buffer: String::with_capacity(1024), eof: false, @@ -177,7 +102,7 @@ impl NBReader { } } - /// reads all available chars from the read channel and stores them in self.buffer + /// Reads all available chars from the read channel and stores them in [`Self::buffer`] fn read_into_buffer(&mut self) -> Result<(), Error> { if self.eof { return Ok(()); @@ -199,24 +124,13 @@ impl NBReader { Ok(()) } - /// Read until needle is found (blocking!) and return tuple with: - /// 1. yet unread string until and without needle - /// 2. matched needle + /// Read until needle is found (blocking!) /// /// This methods loops (while reading from the Cursor) until the needle is found. /// - /// There are different modes: - /// - /// - `ReadUntil::String` searches for string (use '\n'.`to_string()` to search for newline). - /// Returns not yet read data in first String, and needle in second String - /// - `ReadUntil::Regex` searches for regex - /// Returns not yet read data in first String and matched regex in second String - /// - `ReadUntil::NBytes` reads maximum n bytes - /// Returns n bytes in second String, first String is left empty - /// - `ReadUntil::EOF` reads until end of file is reached - /// Returns all bytes in second String, first is left empty - /// - /// Note that when used with a tty the lines end with \r\n + /// Returns a tuple with: + /// 1. yet unread string until and without needle + /// 2. matched needle /// /// Returns error if EOF is reached before the needle could be found. /// @@ -283,19 +197,125 @@ impl NBReader { } } - /// Try to read one char from internal buffer. Returns None if - /// no char is ready, Some(char) otherwise. This is non-blocking + /// Try to read one char from internal buffer (non-blocking). + /// + /// Returns `None` if no char is ready `Some(char)` otherwise. pub fn try_read(&mut self) -> Option { // discard eventual errors, EOF will be handled in read_until correctly let _ = self.read_into_buffer(); - if !self.buffer.is_empty() { - self.buffer.drain(..1).last() - } else { - None + let first = self.buffer.chars().next()?; + self.buffer.drain(..first.len_utf8()); + Some(first) + } +} + +/// See [`NBReader::read_until`] +/// +/// Note that when used with a tty the lines end with \r\n +#[non_exhaustive] +pub enum ReadUntil { + /// Searches for string (use '\n'.`to_string()` to search for newline). + /// + /// Returns not yet read data in first String, and needle in second String + String(String), + /// `ReadUntil::Regex` searches for regex + /// + /// Returns not yet read data in first String and matched regex in second String + Regex(Regex), + /// `ReadUntil::NBytes` reads maximum n bytes + /// + /// Returns n bytes in second String, first String is left empty + NBytes(usize), + /// `ReadUntil::EOF` reads until end of file is reached + /// + /// Returns all bytes in second String, first is left empty + EOF, + Any(Vec), +} + +impl fmt::Display for ReadUntil { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::String(s) if s == "\n" => write!(f, "\\n (newline)"), + Self::String(s) if s == "\r" => write!(f, "\\r (carriage return)"), + Self::String(s) => write!(f, "\"{s}\""), + Self::Regex(r) => write!(f, "Regex: \"{r}\""), + Self::NBytes(n) => write!(f, "reading {n} bytes"), + Self::EOF => write!(f, "EOF (End of File)"), + Self::Any(v) => { + for (i, r) in v.iter().enumerate() { + if i != 0 { + write!(f, ", ")?; + } + write!(f, "{r}")?; + } + Ok(()) + } } } } +/// Find first occurrence of needle within buffer +/// +/// # Arguments: +/// +/// - `buffer`: the currently read buffer from a process which will still grow in the future +/// - `eof`: if the process already sent an EOF or a HUP +/// +/// # Return +/// +/// Tuple with match positions: +/// 1. position before match (0 in case of EOF and Nbytes) +/// 2. position after match +fn find(needle: &ReadUntil, buffer: &str, eof: bool) -> Option<(usize, usize)> { + match needle { + ReadUntil::String(s) => buffer.find(s).map(|pos| (pos, pos + s.len())), + ReadUntil::Regex(pattern) => pattern.find(buffer).map(|mat| (mat.start(), mat.end())), + ReadUntil::EOF => { + if eof { + Some((0, buffer.len())) + } else { + None + } + } + ReadUntil::NBytes(n) => { + if *n <= buffer.len() { + Some((0, *n)) + } else if eof && !buffer.is_empty() { + // reached almost end of buffer, return string, even though it will be + // smaller than the wished n bytes + Some((0, buffer.len())) + } else { + None + } + } + ReadUntil::Any(anys) => anys + .iter() + // Filter matching needles + .filter_map(|any| find(any, buffer, eof)) + // Return the left-most match + .min_by(|(start1, end1), (start2, end2)| { + if start1 == start2 { + end1.cmp(end2) + } else { + start1.cmp(start2) + } + }), + } +} + +#[derive(Debug)] +enum PipeError { + IO(io::Error), +} + +#[derive(Debug)] +#[expect(clippy::upper_case_acronyms, reason = "compatibility")] +enum PipedChar { + Char(u8), + EOF, +} + #[cfg(test)] mod tests { use super::*; @@ -403,13 +423,7 @@ mod tests { #[test] fn test_skip_partial_ansi_code() { let f = io::Cursor::new("\x1b[31;1;4mHello\x1b[1"); - let mut r = NBReader::new( - f, - Options { - timeout_ms: None, - strip_ansi_escape_codes: true, - }, - ); + let mut r = NBReader::new(f, Options::new().strip_ansi_escape_codes(true)); let bytes = r .read_until(&ReadUntil::String("Hello".to_owned())) .unwrap(); @@ -420,13 +434,7 @@ mod tests { #[test] fn test_skip_ansi_codes() { let f = io::Cursor::new("\x1b[31;1;4mHello\x1b[0m"); - let mut r = NBReader::new( - f, - Options { - timeout_ms: None, - strip_ansi_escape_codes: true, - }, - ); + let mut r = NBReader::new(f, Options::new().strip_ansi_escape_codes(true)); let bytes = r .read_until(&ReadUntil::String("Hello".to_owned())) .unwrap(); @@ -447,4 +455,15 @@ mod tests { assert_eq!(None, r.try_read()); assert_eq!(None, r.try_read()); } + + #[test] + fn test_try_read_multibyte() { + // Filling `buffer` directly keeps the test fully synchronous. + let f = io::Cursor::new(""); + let mut r = NBReader::new(f, Options::default()); + r.buffer.push_str("\u{c3}\u{83}"); + assert_eq!(Some('\u{c3}'), r.try_read()); + assert_eq!(Some('\u{83}'), r.try_read()); + assert_eq!(None, r.try_read()); + } } diff --git a/src/session.rs b/src/session.rs index 52f2f41b..888ba0f8 100644 --- a/src/session.rs +++ b/src/session.rs @@ -5,15 +5,15 @@ use crate::process::PtyProcess; use crate::reader::{NBReader, Regex}; pub use crate::reader::{Options, ReadUntil}; use std::fs::File; -use std::io::prelude::*; use std::io::LineWriter; +use std::io::prelude::*; use std::ops::{Deref, DerefMut}; use std::process::Command; use tempfile; pub struct StreamSession { - pub writer: LineWriter, - pub reader: NBReader, + writer: LineWriter, + reader: NBReader, } impl StreamSession { @@ -24,9 +24,9 @@ impl StreamSession { } } - /// sends string and a newline to process + /// Sends string and a newline to process /// - /// this is guaranteed to be flushed to the process + /// This is guaranteed to be flushed to the process /// returns number of written bytes pub fn send_line(&mut self, line: &str) -> Result { let mut len = self.send(line)?; @@ -34,8 +34,10 @@ impl StreamSession { Ok(len) } - /// Send string to process. As stdin of the process is most likely buffered, you'd - /// need to call `flush()` after `send()` to make the process actually see your input. + /// Send string to process. + /// + /// As stdin of the process is most likely buffered, + /// you'd need to call `flush()` after `send()` to make the process actually see your input. /// /// Returns number of written bytes pub fn send(&mut self, s: &str) -> Result { @@ -45,7 +47,9 @@ impl StreamSession { /// Send a control code to the running process and consume resulting output line /// (which is empty because echo is off) /// - /// E.g. `send_control('c')` sends ctrl-c. Upper/smaller case does not matter. + /// Upper/smaller case does not matter. + /// + /// E.g. `send_control('c')` sends ctrl-c. pub fn send_control(&mut self, c: char) -> Result<(), Error> { let code = match c { 'a'..='z' => c as u8 + 1 - b'a', @@ -63,13 +67,16 @@ impl StreamSession { Ok(()) } - /// Make sure all bytes written via `send()` are sent to the process + /// Make sure all bytes written via [`Self::send()`] are sent to the process pub fn flush(&mut self) -> Result<(), Error> { self.writer.flush().map_err(Error::from) } - /// Read one line (blocking!) and return line without the newline - /// (waits until \n is in the output fetches the line and removes \r at the end if present) + /// Read one line (blocking). + /// + /// Return line without the newline + /// + /// Waits until \n is in the output fetches the line and removes \r at the end if present. pub fn read_line(&mut self) -> Result { match self.exp(&ReadUntil::String('\n'.to_string())) { Ok((mut line, _)) => { @@ -82,24 +89,22 @@ impl StreamSession { } } - /// Return `Some(c)` if a char is ready in the stdout stream of the process, return `None` - /// otherwise. This is non-blocking. + /// Return `Some(c)` if a char is ready in the stdout stream of the process (non-blocking). + /// + /// Return `None` otherwise. pub fn try_read(&mut self) -> Option { self.reader.try_read() } - // wrapper around reader::read_until to give more context for errors - fn exp(&mut self, needle: &ReadUntil) -> Result<(String, String), Error> { - self.reader.read_until(needle) - } - /// Wait until we see EOF (i.e. child process has terminated) + /// /// Return all the yet unread output pub fn exp_eof(&mut self) -> Result { self.exp(&ReadUntil::EOF).map(|(_, s)| s) } /// Wait until provided regex is seen on stdout of child process. + /// /// Return a tuple: /// 1. the yet unread output /// 2. the matched regex @@ -111,6 +116,7 @@ impl StreamSession { } /// Wait until provided string is seen on stdout of child process. + /// /// Return the yet unread output (without the matched string) pub fn exp_string(&mut self, needle: &str) -> Result { self.exp(&ReadUntil::String(needle.to_owned())) @@ -118,6 +124,7 @@ impl StreamSession { } /// Wait until provided char is seen on stdout of child process. + /// /// Return the yet unread output (without the matched char) pub fn exp_char(&mut self, needle: char) -> Result { self.exp(&ReadUntil::String(needle.to_string())) @@ -149,12 +156,17 @@ impl StreamSession { pub fn exp_any(&mut self, needles: Vec) -> Result<(String, String), Error> { self.exp(&ReadUntil::Any(needles)) } + + // wrapper around reader::read_until to give more context for errors + fn exp(&mut self, needle: &ReadUntil) -> Result<(String, String), Error> { + self.reader.read_until(needle) + } } + /// Interact with a process with read/write/signals, etc. -#[allow(dead_code)] pub struct PtySession { - pub process: PtyProcess, - pub stream: StreamSession, + process: PtyProcess, + stream: StreamSession, } // make StreamSession's methods available directly @@ -171,38 +183,40 @@ impl DerefMut for PtySession { } } -/// Start a process in a tty session, write and read from it -/// -/// # Example -/// -/// ``` -/// -/// use rexpect::spawn; -/// # use rexpect::error::Error; -/// -/// # fn main() { -/// # || -> Result<(), Error> { -/// let mut s = spawn("cat", Some(1000))?; -/// s.send_line("hello, polly!")?; -/// let line = s.read_line()?; -/// assert_eq!("hello, polly!", line); -/// # Ok(()) -/// # }().expect("test failed"); -/// # } -/// ``` impl PtySession { - fn new(process: PtyProcess, options: Options) -> Result { + /// Start a process in a tty session, write and read from it + /// + /// # Example + /// + /// ``` + /// + /// use rexpect::spawn; + /// # use rexpect::error::Error; + /// + /// # fn main() { + /// # || -> Result<(), Error> { + /// let mut s = spawn("cat", Some(1000))?; + /// s.send_line("hello, polly!")?; + /// let line = s.read_line()?; + /// assert_eq!("hello, polly!", line); + /// # Ok(()) + /// # }().expect("test failed"); + /// # } + /// ``` + pub fn new(process: PtyProcess, options: Options) -> Result { let f = process.get_file_handle()?; let reader = f.try_clone()?; let stream = StreamSession::new(reader, f, options); Ok(Self { process, stream }) } -} -/// Turn e.g. "prog arg1 arg2" into ["prog", "arg1", "arg2"] -/// Also takes care of single and double quotes -fn tokenize_command(program: &str) -> Result, Error> { - comma::parse_command(program).ok_or(Error::BadProgramArguments) + pub fn process(&self) -> &PtyProcess { + &self.process + } + + pub fn process_mut(&mut self) -> &mut PtyProcess { + &mut self.process + } } /// Start command in background in a pty session (pty fork) and return a struct @@ -230,18 +244,18 @@ pub fn spawn(program: &str, timeout_ms: Option) -> Result Result, Error> { + comma::parse_command(program).ok_or(Error::BadProgramArguments) +} + +/// See [`spawn`] pub fn spawn_command(command: Command, timeout_ms: Option) -> Result { - spawn_with_options( - command, - Options { - timeout_ms, - strip_ansi_escape_codes: false, - }, - ) + spawn_with_options(command, Options::new().timeout_ms(timeout_ms)) } -/// See `spawn` +/// See [`spawn`] pub fn spawn_with_options(command: Command, options: Options) -> Result { #[cfg(feature = "which")] { @@ -253,27 +267,50 @@ pub fn spawn_with_options(command: Command, options: Options) -> Result>> " for python - pub prompt: String, - - /// the `pty_session` you prepared before (initiating the shell, maybe set a custom prompt, etc.) - /// see `spawn_bash` for an example - pub pty_session: PtySession, - - /// if set, then the `quit_command` is called when this object is dropped - /// you need to provide this if the shell you're testing is not killed by just sending - /// SIGTERM - pub quit_command: Option, - - /// set this to true if the repl has echo on (i.e. sends user input to stdout) - /// although echo is set off at pty fork (see `PtyProcess::new`) a few repls still - /// seem to be able to send output. You may need to try with true first, and if - /// tests fail set this to false. - pub echo_on: bool, + pty_session: PtySession, + prompt: String, + quit_command: Option, + echo_on: bool, +} + +impl PtyReplSession { + /// Start a REPL session + /// + /// `prompt`: used for [`Self::wait_for_prompt`], e.g. ">>> " for python + /// + /// See [`spawn_bash`] for an example + pub fn new(pty_session: PtySession, prompt: String) -> Self { + Self { + pty_session, + prompt, + quit_command: None, + echo_on: false, + } + } + + /// Called when this object is dropped. + /// + /// You need to provide this if the shell you're testing is not killed by just sending + /// SIGTERM. + pub fn quit_command(mut self, cmd: Option) -> Self { + self.quit_command = cmd; + self + } + + /// Set this to true if the repl has echo on (i.e. sends user input to stdout) + /// + /// Although echo is set off at pty fork (see `PtyProcess::new`) a few repls still + /// seem to be able to send output. + /// You may need to try with true first, and if tests fail set this to false. + pub fn echo_on(mut self, yes: bool) -> Self { + self.echo_on = yes; + self + } } impl PtyReplSession { @@ -319,9 +356,11 @@ impl PtyReplSession { Ok(()) } - /// send line to repl (and flush output) and then, if `echo_on=true` wait for the - /// input to appear. - /// Return: number of bytes written + /// Send line to repl (and flush output) + /// + /// If `echo_on=true` wait for the input to appear. + /// + /// Returns number of bytes written pub fn send_line(&mut self, line: &str) -> Result { let bytes_written = self.pty_session.send_line(line)?; if self.echo_on { @@ -360,25 +399,25 @@ impl Drop for PtyReplSession { /// Spawn bash in a pty session, run programs and expect output /// +/// The difference to [`spawn`] and [`spawn_command`] is: /// -/// The difference to `spawn` and `spawn_command` is: -/// -/// - `spawn_bash` starts bash with a custom rcfile which guarantees +/// - [`spawn_bash`] starts bash with a custom rcfile which guarantees /// a certain prompt -/// - the `PtyBashSession` also provides `wait_for_prompt` and `execute` +/// - Provides [`PtyReplSession::wait_for_prompt`] and [`PtyReplSession::execute`] /// -/// timeout: the duration until which `exp_*` returns a timeout error, or None -/// additionally, when dropping the bash prompt while bash is still blocked by a program +/// `timeout`: the duration until which `exp_*` returns a timeout error, or `None`. +/// Additionally, when dropping the bash prompt while bash is still blocked by a program /// (e.g. `sleep 9999`) then the timeout is used as a timeout before a `kill -9` is issued -/// at the bash command. Use a timeout whenever possible because it makes -/// debugging a lot easier (otherwise the program just hangs and you -/// don't know where) +/// at the bash command. +/// Use a timeout whenever possible because it makes debugging a lot easier +/// (otherwise the program just hangs and you don't know where) /// -/// bash is started with echo off. That means you don't need to "read back" -/// what you wrote to bash. But what you need to do is a `wait_for_prompt` -/// after a process finished. +/// Bash is started with echo off. +/// That means you don't need to "read back" what you wrote to bash. +/// But what you need to do is a `wait_for_prompt` after a process finished. /// -/// Also: if you start a program you should use `execute` and not `send_line`. +/// Also: if you start a program you should use [`PtyReplSession::execute`] and not +/// [`PtyReplSession::send_line`]. /// /// For an example see the README pub fn spawn_bash(timeout: Option) -> Result { @@ -405,8 +444,8 @@ pub fn spawn_bash(timeout: Option) -> Result { spawn_command(c, timeout).and_then(|p| { let new_prompt = "[REXPECT_PROMPT>"; let mut pb = PtyReplSession { - prompt: new_prompt.to_owned(), pty_session: p, + prompt: new_prompt.to_owned(), quit_command: Some("quit".to_owned()), echo_on: false, }; @@ -438,30 +477,21 @@ pub fn spawn_stream( writer: W, timeout_ms: Option, ) -> StreamSession { - StreamSession::new( - reader, - writer, - Options { - timeout_ms, - strip_ansi_escape_codes: false, - }, - ) + StreamSession::new(reader, writer, Options::new().timeout_ms(timeout_ms)) } #[cfg(test)] mod tests { use super::*; + use nix::sys::wait; #[test] fn test_read_line() -> Result<(), Error> { let mut s = spawn("cat", Some(100000))?; s.send_line("hans")?; assert_eq!("hans", s.read_line()?); - let should = crate::process::wait::WaitStatus::Signaled( - s.process.child_pid, - crate::process::signal::Signal::SIGTERM, - false, - ); + let should = + wait::WaitStatus::Signaled(s.process.child_pid, crate::process::Signal::SIGTERM, false); assert_eq!(should, s.process.exit()?); Ok(()) }