Skip to content
Myr

cli: replace clap with lexopt and supporting code

Before adoption: this commit came in with the history the project adopted, so no landing records it.

ripgrep began it's life with docopt for argument parsing. Then it moved to Clap and stayed there for a number of years. Clap has served ripgrep well, and it probably could continue to serve ripgrep well, but I ended up deciding to move off of it. Why? The first time I had the thought of moving off of Clap was during the 2->3->4 transition. I thought the 3.x and 4.x releases were great, but for me, it ended up moving a little too quickly. Since the release of 4.x was telegraphed around when 3.x came out, I decided to just hold off and wait to migrate to 4.x instead of doing a 3.x migration followed shortly by another 4.x migration. Of course, I just never ended up doing the migration at all. I never got around to it and there just wasn't a compelling reason for me to upgrade. While I never investigated it, I saw an upgrade as a non-trivial amount of work in part because I didn't encapsulate the usage of Clap enough. The above is just what got me started thinking about it. It wasn't enough to get me to move off of it on its own. What ended up pushing me over the edge was a combination of factors: * As mentioned above, I didn't want to run on the migration treadmill. This has proven to not be much of an issue, but at the time of the 2->3->4 releases, I didn't know how long Clap 4.x would be out before a 5.x would come out. * The release of lexopt[1] caught my eye. IMO, that crate demonstrates exactly how something new can arrive on the scene and just thoroughly solve a problem minimalistically. It has the docs, the reasoning, the simple API, the tests and good judgment. It gets all the weird corner cases right that Clap also gets right (and is part of why I was originally attracted to Clap). * I have an overall desire to reduce the size of my dependency tree. In part because a smaller dependency tree tends to correlate with better compile times, but also in part because it reduces my reliance and trust on others. It lets me be the "master" of ripgrep's destiny by reducing the amount of behavior that is the result of someone else's decision (whether good or bad). * I perceived that Clap solves a more general problem than what I actually need solved. Despite the vast number of flags that ripgrep has, its requirements are actually pretty simple. We just need simple switches and flags that support one value. No multi-value flags. No sub-commands. And probably a lot of other functionality that Clap has that makes it so flexible for so many different use cases. (I'm being hand wavy on the last point.) With all that said, perhaps most importantly, the future of ripgrep possibly demands a more flexible CLI argument parser. In today's world, I would really like, for example, flags like `--type` and `--type-not` to be able to accumulate their repeated values into a single sequence while respecting the order they appear on the CLI. For example, prior to this migration, `rg regex-automata -Tlock -ttoml` would not return results in `Cargo.lock` in this repository because the `-Tlock` always took priority even though `-ttoml` appeared after it. But with this migration, `-ttoml` now correctly overrides `-Tlock`. We would like to do similar things for `-g/--glob` and `--iglob` and potentially even now introduce a `-G/--glob-not` flag instead of requiring users to use `!` to negate a glob. (Which I had done originally to work-around this problem.) And some day, I'd like to add some kind of boolean matching to ripgrep perhaps similar to how `git grep` does it. (Although I haven't thought too carefully on a design yet.) In order to do that, I perceive it would be difficult to implement correctly in Clap. I believe that this last point is possible to implement correctly in Clap 2.x, although it is awkward to do so. I have not looked closely enough at the Clap 4.x API to know whether it's still possible there. In any case, these were enough reasons to move off of Clap and own more of the argument parsing process myself. This did require a few things: * I had to write my own logic for how arguments are combined into one single state object. Of course, I wanted this. This was part of the upside. But it's still code I didn't have to write for Clap. * I had to write my own shell completion generator. * I had to write my own `-h/--help` output generator. * I also had to write my own man page generator. Well, I had to do this with Clap 2.x too, although my understanding is that Clap 4.x supports this. With that said, without having tried it, my guess is that I probably wouldn't have liked the output it generated because I ultimately had to write most of the roff by hand myself to get the man page I wanted. (This also had the benefit of dropping the build dependency on asciidoc/asciidoctor.) While this is definitely a fair bit of extra work, it overall only cost me a couple days. IMO, that's a good trade off given that this code is unlikely to change again in any substantial way. And it should also allow for more flexible semantics going forward. Fixes #884, Fixes #1648, Fixes #1701, Fixes #1814, Fixes #1966 [1]: https://docs.rs/lexopt/0.3.0/lexopt/index.html

authored by Andrew Gallant · committed by Andrew Gallant · parent c33f623 · Browse files · 51 files+13653 added−7070 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

51 files+13653 added−7070 removed

  • tests:+52 added−4 removed
  • other:+13601 added−7066 removed

51 files+13653 added−7070 removed

modified:.github/workflows/ci.yml+9 added-24 removed
51 unmodified lines
52 matrix:53 include:54 - build: pinned55 os: ubuntu-latest56 rust: 1.72.156 rust: 1.74.057 - build: stable58 os: ubuntu-latest59 rust: stable60 - build: beta
32 unmodified lines
93 os: windows-202294 rust: nightly-x86_64-gnu95 steps:96 - name: Checkout repository97 uses: actions/checkout@v397 uses: actions/checkout@v49899 - name: Install packages (Ubuntu)100 if: matrix.os == 'ubuntu-latest'101 run: |
28 unmodified lines
130 - name: Show command used for Cargo131 run: |132 echo "cargo command is: ${{ env.CARGO }}"133 echo "target flag is: ${{ env.TARGET_FLAGS }}"134 echo "target dir is: ${{ env.TARGET_DIR }}"135136 - name: Build ripgrep and all crates137 run: ${{ env.CARGO }} build --verbose --workspace ${{ env.TARGET_FLAGS }}138
25 unmodified lines
164 # regex engine and once with PCRE2.165 if: matrix.target != ''166 run: ${{ env.CARGO }} test --verbose --workspace ${{ env.TARGET_FLAGS }}167167 - name: Test for existence of build artifacts (Windows)168 if: matrix.os == 'windows-2022'169 shell: bash170 run: |171 outdir="$(ci/cargo-out-dir "${{ env.TARGET_DIR }}")"172 ls "$outdir/_rg.ps1" && file "$outdir/_rg.ps1"173174 - name: Test for existence of build artifacts (Unix)175 if: matrix.os != 'windows-2022'176 shell: bash177 run: |178 outdir="$(ci/cargo-out-dir "${{ env.TARGET_DIR }}")"179 # TODO: Check for the man page generation here. For whatever reason,180 # it seems to be intermittently failing in CI. No idea why.181 # for f in rg.bash rg.fish rg.1; do182 for f in rg.bash rg.fish; do183 # We could use file -E here, but it isn't supported on macOS.184 ls "$outdir/$f" && file "$outdir/$f"185 done186168 - name: Test zsh shell completions (Unix, sans cross)169 # We could test this when using Cross, but we'd have to execute the170 # 'rg' binary (done in test-complete) with qemu, which is a pain and171 # doesn't really gain us much. If shell completion works in one place,
5 unmodified lines
177 - name: Print hostname detected by grep-cli crate178 shell: bash179 run: ${{ env.CARGO }} test --manifest-path crates/cli/Cargo.toml ${{ env.TARGET_FLAGS }} --lib print_hostname -- --nocapture180181 - name: Print available short flags182 shell: bash183 run: ${{ env.CARGO }} test --bin rg ${{ env.TARGET_FLAGS }} flags::defs::tests::available_shorts -- --nocapture184185 rustfmt:186 runs-on: ubuntu-latest187 steps:188 - name: Checkout repository204 uses: actions/checkout@v3189 uses: actions/checkout@v4190 - name: Install Rust191 uses: dtolnay/rust-toolchain@master192 with:193 toolchain: stable
4 unmodified lines
198 docs:199 runs-on: ubuntu-latest200 steps:201 - name: Checkout repository217 uses: actions/checkout@v3202 uses: actions/checkout@v4203 - name: Install Rust204 uses: dtolnay/rust-toolchain@master205 with:206 toolchain: stable
4 unmodified lines
modified:.github/workflows/release.yml+164 added-69 removed
1# The way this works is the following:2#3# The create-release job runs purely to initialize the GitHub release itself4# and to output upload_url for the following job.5#6# The build-release job runs only once create-release is finished. It gets the7# release upload URL from create-release job outputs, then builds the release8# executables for each supported platform and attaches them as release assets9# to the previously created release.10#11# The key here is that we create the release only once.12#13# Reference:14# https://eugene-babichenko.github.io/blog/2020/05/09/github-actions-cross-platform-auto-releases/151name: release23# Only do the release on x.y.z tags.4on:5 push:19 # Enable when testing release infrastructure on a branch.20 # branches:21 # - ag/work6 tags:7 - "[0-9]+.[0-9]+.[0-9]+"89# We need this to be able to create releases.10permissions:11 contents: write1213jobs:14 # The create-release job runs purely to initialize the GitHub release itself,15 # and names the release after the `x.y.z` tag that was pushed. It's separate16 # from building the release so that we only create the release once.17 create-release:18 name: create-release19 runs-on: ubuntu-latest20 # env:21 # Set to force version number, e.g., when no tag exists.30 # RG_VERSION: TEST-0.0.031 outputs:32 rg_version: ${{ env.RG_VERSION }}22 # VERSION: TEST-0.0.023 steps:34 - uses: actions/checkout@v324 - uses: actions/checkout@v425 - name: Get the release version from the tag36 shell: bash37 if: env.RG_VERSION == ''26 if: env.VERSION == ''27 run: echo "VERSION=${{ github.ref_name }}" >> $GITHUB_ENV28 - name: Show the version29 run: |39 echo "RG_VERSION=$GITHUB_REF_NAME" >> $GITHUB_ENV40 echo "version is: ${{ env.RG_VERSION }}"30 echo "version is: $VERSION"31 - name: Create GitHub release32 env:43 GH_TOKEN: ${{ github.token }}44 run: gh release create ${{ env.RG_VERSION }}33 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}34 run: gh release create $VERSION --draft --verify-tag --title $VERSION35 outputs:36 version: ${{ env.VERSION }}3738 build-release:39 name: build-release40 needs: ['create-release']
2 unmodified lines
43 # For some builds, we use cross to test on 32-bit and big-endian44 # systems.45 CARGO: cargo46 # When CARGO is set to CROSS, this is set to `--target matrix.target`.55 TARGET_FLAGS: ""47 TARGET_FLAGS:48 # When CARGO is set to CROSS, TARGET_DIR includes matrix.target.49 TARGET_DIR: ./target50 # Bump this as appropriate. We pin to a version to make sure CI51 # continues to work as cross releases in the past have broken things52 # in subtle ways.53 CROSS_VERSION: v0.2.554 # Emit backtraces on panics.55 RUST_BACKTRACE: 156 # Build static releases with PCRE2.57 PCRE2_SYS_STATIC: 158 strategy:59 fail-fast: false60 matrix:64 build: [linux, linux-arm, macos, win-msvc, win-gnu, win32-msvc]61 include:62 - build: linux63 os: ubuntu-latest64 rust: nightly65 target: x86_64-unknown-linux-musl70 - build: linux-arm66 strip: x86_64-linux-musl-strip67 - build: stable-x8668 os: ubuntu-latest72 rust: nightly73 target: arm-unknown-linux-gnueabihf69 rust: stable70 target: i686-unknown-linux-gnu71 strip: x86_64-linux-gnu-strip72 qemu: i38673 - build: stable-aarch6474 os: ubuntu-latest75 rust: stable76 target: aarch64-unknown-linux-gnu77 strip: aarch64-linux-gnu-strip78 qemu: qemu-aarch6479 - build: stable-powerpc6480 os: ubuntu-latest81 rust: stable82 target: powerpc64-unknown-linux-gnu83 strip: powerpc64-linux-gnu-strip84 qemu: qemu-ppc6485 - build: stable-s390x86 os: ubuntu-latest87 rust: stable88 target: s390x-unknown-linux-gnu89 strip: s390x-linux-gnu-strip90 qemu: qemu-s390x91 - build: macos92 os: macos-latest93 rust: nightly94 target: x86_64-apple-darwin
11 unmodified lines
106 target: i686-pc-windows-msvc107108 steps:109 - name: Checkout repository93 uses: actions/checkout@v3110 uses: actions/checkout@v4111112 - name: Install packages (Ubuntu)113 if: matrix.os == 'ubuntu-latest'114 shell: bash115 run: |116 ci/ubuntu-install-packages117118 - name: Install packages (macOS)119 if: matrix.os == 'macos-latest'120 shell: bash121 run: |122 ci/macos-install-packages123124 - name: Install Rust
2 unmodified lines
127 toolchain: ${{ matrix.rust }}128 target: ${{ matrix.target }}129130 - name: Use Cross131 if: matrix.os == 'ubuntu-latest' && matrix.target != ''132 shell: bash133 run: |114 cargo install cross134 # In the past, new releases of 'cross' have broken CI. So for now, we135 # pin it. We also use their pre-compiled binary releases because cross136 # has over 100 dependencies and takes a bit to compile.137 dir="$RUNNER_TEMP/cross-download"138 mkdir "$dir"139 echo "$dir" >> $GITHUB_PATH140 cd "$dir"141 curl -LO "https://github.com/cross-rs/cross/releases/download/$CROSS_VERSION/cross-x86_64-unknown-linux-musl.tar.gz"142 tar xf cross-x86_64-unknown-linux-musl.tar.gz143 echo "CARGO=cross" >> $GITHUB_ENV144145 - name: Set target variables146 shell: bash147 run: |148 echo "TARGET_FLAGS=--target ${{ matrix.target }}" >> $GITHUB_ENV149 echo "TARGET_DIR=./target/${{ matrix.target }}" >> $GITHUB_ENV150151 - name: Show command used for Cargo152 shell: bash153 run: |154 echo "cargo command is: ${{ env.CARGO }}"155 echo "target flag is: ${{ env.TARGET_FLAGS }}"156 echo "target dir is: ${{ env.TARGET_DIR }}"157158 - name: Build release binary159 shell: bash160 run: |126 run: ${{ env.CARGO }} build --verbose --release --features pcre2 ${{ env.TARGET_FLAGS }}161 ${{ env.CARGO }} build --verbose --release --features pcre2 ${{ env.TARGET_FLAGS }}162 if [ "${{ matrix.os }}" = "windows-latest" ]; then163 bin="target/${{ matrix.target }}/release/rg.exe"164 else165 bin="target/${{ matrix.target }}/release/rg"166 fi167 echo "BIN=$bin" >> $GITHUB_ENV168128 - name: Strip release binary (linux, macos and macos-arm)129 if: matrix.build == 'linux' || matrix.os == 'macos'130 run: strip "target/${{ matrix.target }}/release/rg"169 - name: Strip release binary (macos)170 if: matrix.os == 'macos'171 shell: bash172 run: strip "$BIN"173132 - name: Strip release binary (arm)133 if: matrix.build == 'linux-arm'174 - name: Strip release binary (cross)175 if: env.CARGO == 'cross'176 shell: bash177 run: |178 docker run --rm -v \179 "$PWD/target:/target:Z" \137 rustembedded/cross:arm-unknown-linux-gnueabihf \138 arm-linux-gnueabihf-strip \139 /target/arm-unknown-linux-gnueabihf/release/rg180 "rustembedded/cross:${{ matrix.target }}" \181 "${{ matrix.strip }}" \182 "/target/${{ matrix.target }}/release/rg"183141 - name: Build archive184 - name: Determine archive name185 shell: bash186 run: |144 outdir="$(ci/cargo-out-dir "${{ env.TARGET_DIR }}")"145 staging="ripgrep-${{ needs.create-release.outputs.rg_version }}-${{ matrix.target }}"146 mkdir -p "$staging"/{complete,doc}187 version="${{ needs.create-release.outputs.version }}"188 echo "ARCHIVE=ripgrep-$version-${{ matrix.target }}" >> $GITHUB_ENV189148 cp {README.md,COPYING,UNLICENSE,LICENSE-MIT} "$staging/"149 cp {CHANGELOG.md,FAQ.md,GUIDE.md} "$staging/doc/"150 cp "$outdir"/{rg.bash,rg.fish,_rg.ps1} "$staging/complete/"151 cp complete/_rg "$staging/complete/"190 - name: Creating directory for archive191 shell: bash192 run: |193 mkdir -p "$ARCHIVE"/{complete,doc}194 cp "$BIN" "$ARCHIVE"/195 cp {README.md,COPYING,UNLICENSE,LICENSE-MIT} "$ARCHIVE"/196 cp {CHANGELOG.md,FAQ.md,GUIDE.md} "$ARCHIVE"/doc/197153 if [ "${{ matrix.os }}" = "windows-latest" ]; then154 cp "target/${{ matrix.target }}/release/rg.exe" "$staging/"155 7z a "$staging.zip" "$staging"156 certutil -hashfile "$staging.zip" SHA256 > "$staging.zip.sha256"157 echo "ASSET=$staging.zip" >> $GITHUB_ENV158 echo "ASSET_SUM=$staging.zip.sha256" >> $GITHUB_ENV159 else160 # The man page is only generated on Unix systems. ¯\_(ツ)_/¯161 cp "$outdir"/rg.1 "$staging/doc/"162 cp "target/${{ matrix.target }}/release/rg" "$staging/"163 tar czf "$staging.tar.gz" "$staging"164 shasum -a 256 "$staging.tar.gz" > "$staging.tar.gz.sha256"165 echo "ASSET=$staging.tar.gz" >> $GITHUB_ENV166 echo "ASSET_SUM=$staging.tar.gz.sha256" >> $GITHUB_ENV167 fi198 - name: Generate man page and completions (no emulation)199 if: matrix.qemu == ''200 shell: bash201 run: |202 "$BIN" --version203 "$BIN" --generate complete-bash > "$ARCHIVE/complete/rg.bash"204 "$BIN" --generate complete-fish > "$ARCHIVE/complete/rg.fish"205 "$BIN" --generate complete-powershell > "$ARCHIVE/complete/_rg.ps1"206 "$BIN" --generate complete-zsh > "$ARCHIVE/complete/_rg"207 "$BIN" --generate man > "$ARCHIVE/doc/rg.1"208209 - name: Generate man page and completions (emulation)210 if: matrix.qemu != ''211 shell: bash212 run: |213 docker run --rm -v \214 "$PWD/target:/target:Z" \215 "rustembedded/cross:${{ matrix.target }}" \216 "${{ matrix.qemu }}" "/$BIN" --version217 docker run --rm -v \218 "$PWD/target:/target:Z" \219 "rustembedded/cross:${{ matrix.target }}" \220 "${{ matrix.qemu }}" "/$BIN" \221 --generate complete-bash > "$ARCHIVE/complete/rg.bash"222 docker run --rm -v \223 "$PWD/target:/target:Z" \224 "rustembedded/cross:${{ matrix.target }}" \225 "${{ matrix.qemu }}" "/$BIN" \226 --generate complete-fish > "$ARCHIVE/complete/rg.fish"227 docker run --rm -v \228 "$PWD/target:/target:Z" \229 "rustembedded/cross:${{ matrix.target }}" \230 "${{ matrix.qemu }}" "/$BIN" \231 --generate complete-powershell > "$ARCHIVE/complete/_rg.ps1"232 docker run --rm -v \233 "$PWD/target:/target:Z" \234 "rustembedded/cross:${{ matrix.target }}" \235 "${{ matrix.qemu }}" "/$BIN" \236 --generate complete-zsh > "$ARCHIVE/complete/_rg"237 docker run --rm -v \238 "$PWD/target:/target:Z" \239 "rustembedded/cross:${{ matrix.target }}" \240 "${{ matrix.qemu }}" "/$BIN" \241 --generate man > "$ARCHIVE/doc/rg.1"242243 - name: Build archive (Windows)244 shell: bash245 if: matrix.os == 'windows-latest'246 run: |247 7z a "$ARCHIVE.zip" "$ARCHIVE"248 certutil -hashfile "$ARCHIVE.zip" SHA256 > "$ARCHIVE.zip.sha256"249 echo "ASSET=$ARCHIVE.zip" >> $GITHUB_ENV250 echo "ASSET_SUM=$ARCHIVE.zip.sha256" >> $GITHUB_ENV251252 - name: Build archive (Unix)253 shell: bash254 if: matrix.os != 'windows-latest'255 run: |256 tar czf "$ARCHIVE.tar.gz" "$ARCHIVE"257 shasum -a 256 "$ARCHIVE.tar.gz" > "$ARCHIVE.tar.gz.sha256"258 echo "ASSET=$ARCHIVE.tar.gz" >> $GITHUB_ENV259 echo "ASSET_SUM=$ARCHIVE.tar.gz.sha256" >> $GITHUB_ENV260261 - name: Upload release archive262 env:171 GH_TOKEN: ${{ github.token }}172 run: gh release upload ${{ needs.create-release.outputs.rg_version }} ${{ env.ASSET }} ${{ env.ASSET_SUM }}263 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}264 shell: bash265 run: |266 version="${{ needs.create-release.outputs.version }}"267 gh release upload "$version" ${{ env.ASSET }} ${{ env.ASSET_SUM }}
added:ci/build-and-publish-deb+55 added
1#!/bin/bash23set -e4D="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"56# This script builds a binary dpkg for Debian based distros. It does not7# currently run in CI, and is instead run manually and the resulting dpkg is8# uploaded to GitHub at the end of this script.9#10# Note that this requires 'cargo deb', which can be installed with11# 'cargo install cargo-deb'.12#13# This should be run from the root of the ripgrep repo.1415if ! command -V cargo-deb > /dev/null 2>&1; then16 echo "cargo-deb command missing" >&217 exit 118fi1920version="$1"21if [ -z "$version" ]; then22 echo "missing version" >&223 echo "Usage: "$(basename "$0")" <version>" >&224 exit 125fi26if ! grep -q "version = \"$version\"" Cargo.toml; then27 echo "version does not match Cargo.toml" >&228 exit 129fi3031# 'cargo deb' does not seem to provide a way to specify an asset that is32# created at build time, such as ripgrep's man page. To work around this,33# we force a debug build, copy out the man page (and shell completions)34# produced from that build, put it into a predictable location and then build35# the deb, which knows where to look.36cargo build3738DEPLOY_DIR=deployment/deb39mkdir -p "$DEPLOY_DIR"4041# Generate man page and shell completions. `cargo deb` knows how to find these42# files via the manifest configuration in `Cargo.toml`.43"target/debug/rg" --generate complete-bash > "$DEPLOY_DIR/rg.bash"44"target/debug/rg" --generate complete-fish > "$DEPLOY_DIR/rg.fish"45"target/debug/rg" --generate complete-zsh > "$DEPLOY_DIR/_rg"46"target/debug/rg" --generate man > "$DEPLOY_DIR/rg.1"4748# Since we're distributing the dpkg, we don't know whether the user will have49# PCRE2 installed, so just do a static build.50PCRE2_SYS_STATIC=1 cargo deb --target x86_64-unknown-linux-musl51target="target/x86_64-unknown-linux-musl/debian"52deb="$target/ripgrep_$version-1_amd64.deb"53debsum="$deb.sha256"54shasum -a 256 "$deb" > "$debsum"55gh release upload "$version" "$deb" "$debsum"
added:ci/build-and-publish-m2+34 added
1#!/bin/bash23set -e45version="$1"6if [ -z "$version" ]; then7 echo "missing version" >&28 echo "Usage: "$(basename "$0")" <version>" >&29 exit 110fi11if ! grep -q "version = \"$version\"" Cargo.toml; then12 echo "version does not match Cargo.toml" >&213 exit 114fi1516cargo build --release --features pcre217BIN=target/release/rg18NAME=ripgrep-$version-aarch64-apple-darwin19ARCHIVE="deployment/m2/$NAME"2021mkdir -p "$ARCHIVE"/{complete,doc}22cp target/release/rg "$ARCHIVE"/23strip "$ARCHIVE/rg"24cp {README.md,COPYING,UNLICENSE,LICENSE-MIT} "$ARCHIVE"/25cp {CHANGELOG.md,FAQ.md,GUIDE.md} "$ARCHIVE"/doc/26"$BIN" --generate complete-bash > "$ARCHIVE/complete/rg.bash"27"$BIN" --generate complete-fish > "$ARCHIVE/complete/rg.fish"28"$BIN" --generate complete-powershell > "$ARCHIVE/complete/_rg.ps1"29"$BIN" --generate complete-zsh > "$ARCHIVE/complete/_rg"30"$BIN" --generate man > "$ARCHIVE/doc/rg.1"3132tar c -C deployment/m2 -z -f "$ARCHIVE.tar.gz" "$NAME"33shasum -a 256 "$ARCHIVE.tar.gz" > "$ARCHIVE.tar.gz.sha256"34gh release upload "$version" "$ARCHIVE.tar.gz" "$ARCHIVE.tar.gz.sha256"
deleted:ci/build-deb-42 removed
1#!/bin/bash23set -e4D="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"56# This script builds a binary dpkg for Debian based distros. It does not7# currently run in CI, and is instead run manually and the resulting dpkg is8# uploaded to GitHub via the web UI.9#10# Note that this requires 'cargo deb', which can be installed with11# 'cargo install cargo-deb'.12#13# This should be run from the root of the ripgrep repo.1415if ! command -V cargo-deb > /dev/null 2>&1; then16 echo "cargo-deb command missing" >&217 exit 118fi1920if ! command -V asciidoctor > /dev/null 2>&1; then21 echo "asciidoctor command missing" >&222 exit 123fi2425# 'cargo deb' does not seem to provide a way to specify an asset that is26# created at build time, such as ripgrep's man page. To work around this,27# we force a debug build, copy out the man page (and shell completions)28# produced from that build, put it into a predictable location and then build29# the deb, which knows where to look.30cargo build3132DEPLOY_DIR=deployment/deb33OUT_DIR="$("$D"/cargo-out-dir target/debug/)"34mkdir -p "$DEPLOY_DIR"3536# Copy man page and shell completions.37cp "$OUT_DIR"/{rg.1,rg.bash,rg.fish} "$DEPLOY_DIR/"38cp complete/_rg "$DEPLOY_DIR/"3940# Since we're distributing the dpkg, we don't know whether the user will have41# PCRE2 installed, so just do a static build.42PCRE2_SYS_STATIC=1 cargo deb --target x86_64-unknown-linux-musl
deleted:ci/cargo-out-dir-19 removed
1#!/bin/bash23# Finds Cargo's `OUT_DIR` directory from the most recent build.4#5# This requires one parameter corresponding to the target directory6# to search for the build output.78if [ $# != 1 ]; then9 echo "Usage: $(basename "$0") <target-dir>" >&210 exit 211fi1213# This works by finding the most recent stamp file, which is produced by14# every ripgrep build.15target_dir="$1"16find "$target_dir" -name ripgrep-stamp -print0 \17 | xargs -0 ls -t \18 | head -n1 \19 | xargs dirname
modified:ci/test-complete+1 added-1 removed
17 unmodified lines
1819main() {20 local diff21 local rg="${0:a:h}/../${TARGET_DIR:-target}/release/rg"22 local _rg="${0:a:h}/../complete/_rg"22 local _rg="${0:a:h}/../crates/core/flags/complete/rg.zsh"23 local -a help_args comp_args2425 [[ -e $rg ]] || rg=${rg/%\/release\/rg/\/debug\/rg}26
71 unmodified lines
deleted:complete/_rg-647 removed
1#compdef rg23##4# zsh completion function for ripgrep5#6# Run ci/test-complete after building to ensure that the options supported by7# this function stay in synch with the `rg` binary.8#9# For convenience, a completion reference guide is included at the bottom of10# this file.11#12# Originally based on code from the zsh-users project — see copyright notice13# below.1415_rg() {16 local curcontext=$curcontext no='!' descr ret=117 local -a context line state state_descr args tmp suf18 local -A opt_args1920 # ripgrep has many options which negate the effect of a more common one — for21 # example, `--no-column` to negate `--column`, and `--messages` to negate22 # `--no-messages`. There are so many of these, and they're so infrequently23 # used, that some users will probably find it irritating if they're completed24 # indiscriminately, so let's not do that unless either the current prefix25 # matches one of those negation options or the user has the `complete-all`26 # style set. Note that this prefix check has to be updated manually to account27 # for all of the potential negation options listed below!28 if29 # We also want to list all of these options during testing30 [[ $_RG_COMPLETE_LIST_ARGS == (1|t*|y*) ]] ||31 # (--[imnp]* => --ignore*, --messages, --no-*, --pcre2-unicode)32 [[ $PREFIX$SUFFIX == --[imnp]* ]] ||33 zstyle -t ":completion:${curcontext}:" complete-all34 then35 no=36 fi3738 # We make heavy use of argument groups here to prevent the option specs from39 # growing unwieldy. These aren't supported in zsh <5.4, though, so we'll strip40 # them out below if necessary. This makes the exclusions inaccurate on those41 # older versions, but oh well — it's not that big a deal42 args=(43 + '(exclusive)' # Misc. fully exclusive options44 '(: * -)'{-h,--help}'[display help information]'45 '(: * -)'{-V,--version}'[display version information]'46 '(: * -)'--pcre2-version'[print the version of PCRE2 used by ripgrep, if available]'4748 + '(buffered)' # buffering options49 '--line-buffered[force line buffering]'50 $no"--no-line-buffered[don't force line buffering]"51 '--block-buffered[force block buffering]'52 $no"--no-block-buffered[don't force block buffering]"5354 + '(case)' # Case-sensitivity options55 {-i,--ignore-case}'[search case-insensitively]'56 {-s,--case-sensitive}'[search case-sensitively]'57 {-S,--smart-case}'[search case-insensitively if pattern is all lowercase]'5859 + '(context-a)' # Context (after) options60 '(context-c)'{-A+,--after-context=}'[specify lines to show after each match]:number of lines'6162 + '(context-b)' # Context (before) options63 '(context-c)'{-B+,--before-context=}'[specify lines to show before each match]:number of lines'6465 + '(context-c)' # Context (combined) options66 '(context-a context-b)'{-C+,--context=}'[specify lines to show before and after each match]:number of lines'6768 + '(column)' # Column options69 '--column[show column numbers for matches]'70 $no"--no-column[don't show column numbers for matches]"7172 + '(count)' # Counting options73 {-c,--count}'[only show count of matching lines for each file]'74 '--count-matches[only show count of individual matches for each file]'75 '--include-zero[include files with zero matches in summary]'7677 + '(encoding)' # Encoding options78 {-E+,--encoding=}'[specify text encoding of files to search]: :_rg_encodings'79 $no'--no-encoding[use default text encoding]'8081 + '(engine)' # Engine choice options82 '--engine=[select which regex engine to use]:when:((83 default\:"use default engine"84 pcre2\:"identical to --pcre2"85 auto\:"identical to --auto-hybrid-regex"86 ))'8788 + file # File-input options89 '(1)*'{-f+,--file=}'[specify file containing patterns to search for]: :_files'9091 + '(file-match)' # Files with/without match options92 '(stats)'{-l,--files-with-matches}'[only show names of files with matches]'93 '(stats)--files-without-match[only show names of files without matches]'9495 + '(file-name)' # File-name options96 {-H,--with-filename}'[show file name for matches]'97 {-I,--no-filename}"[don't show file name for matches]"9899 + '(file-system)' # File system options100 "--one-file-system[don't descend into directories on other file systems]"101 $no'--no-one-file-system[descend into directories on other file systems]'102103 + '(fixed)' # Fixed-string options104 {-F,--fixed-strings}'[treat pattern as literal string instead of regular expression]'105 $no"--no-fixed-strings[don't treat pattern as literal string]"106107 + '(follow)' # Symlink-following options108 {-L,--follow}'[follow symlinks]'109 $no"--no-follow[don't follow symlinks]"110111 + glob # File-glob options112 '*'{-g+,--glob=}'[include/exclude files matching specified glob]:glob'113 '*--iglob=[include/exclude files matching specified case-insensitive glob]:glob'114115 + '(glob-case-insensitive)' # File-glob case sensitivity options116 '--glob-case-insensitive[treat -g/--glob patterns case insensitively]'117 $no'--no-glob-case-insensitive[treat -g/--glob patterns case sensitively]'118119 + '(heading)' # Heading options120 '(pretty-vimgrep)--heading[show matches grouped by file name]'121 "(pretty-vimgrep)--no-heading[don't show matches grouped by file name]"122123 + '(hidden)' # Hidden-file options124 {-.,--hidden}'[search hidden files and directories]'125 $no"--no-hidden[don't search hidden files and directories]"126127 + '(hybrid)' # hybrid regex options128 '--auto-hybrid-regex[dynamically use PCRE2 if necessary]'129 $no"--no-auto-hybrid-regex[don't dynamically use PCRE2 if necessary]"130131 + '(ignore)' # Ignore-file options132 "(--no-ignore-global --no-ignore-parent --no-ignore-vcs --no-ignore-dot)--no-ignore[don't respect ignore files]"133 $no'(--ignore-global --ignore-parent --ignore-vcs --ignore-dot)--ignore[respect ignore files]'134135 + '(ignore-file-case-insensitive)' # Ignore-file case sensitivity options136 '--ignore-file-case-insensitive[process ignore files case insensitively]'137 $no'--no-ignore-file-case-insensitive[process ignore files case sensitively]'138139 + '(ignore-exclude)' # Local exclude (ignore)-file options140 "--no-ignore-exclude[don't respect local exclude (ignore) files]"141 $no'--ignore-exclude[respect local exclude (ignore) files]'142143 + '(ignore-global)' # Global ignore-file options144 "--no-ignore-global[don't respect global ignore files]"145 $no'--ignore-global[respect global ignore files]'146147 + '(ignore-parent)' # Parent ignore-file options148 "--no-ignore-parent[don't respect ignore files in parent directories]"149 $no'--ignore-parent[respect ignore files in parent directories]'150151 + '(ignore-vcs)' # VCS ignore-file options152 "--no-ignore-vcs[don't respect version control ignore files]"153 $no'--ignore-vcs[respect version control ignore files]'154155 + '(require-git)' # git specific settings156 "--no-require-git[don't require git repository to respect gitignore rules]"157 $no'--require-git[require git repository to respect gitignore rules]'158159 + '(ignore-dot)' # .ignore options160 "--no-ignore-dot[don't respect .ignore files]"161 $no'--ignore-dot[respect .ignore files]'162163 + '(ignore-files)' # custom global ignore file options164 "--no-ignore-files[don't respect --ignore-file flags]"165 $no'--ignore-files[respect --ignore-file files]'166167 + '(json)' # JSON options168 '--json[output results in JSON Lines format]'169 $no"--no-json[don't output results in JSON Lines format]"170171 + '(line-number)' # Line-number options172 {-n,--line-number}'[show line numbers for matches]'173 {-N,--no-line-number}"[don't show line numbers for matches]"174175 + '(line-terminator)' # Line-terminator options176 '--crlf[use CRLF as line terminator]'177 $no"--no-crlf[don't use CRLF as line terminator]"178 '(text)--null-data[use NUL as line terminator]'179180 + '(max-columns-preview)' # max column preview options181 '--max-columns-preview[show preview for long lines (with -M)]'182 $no"--no-max-columns-preview[don't show preview for long lines (with -M)]"183184 + '(max-depth)' # Directory-depth options185 '--max-depth=[specify max number of directories to descend]:number of directories'186 '!--maxdepth=:number of directories'187188 + '(messages)' # Error-message options189 '(--no-ignore-messages)--no-messages[suppress some error messages]'190 $no"--messages[don't suppress error messages affected by --no-messages]"191192 + '(messages-ignore)' # Ignore-error message options193 "--no-ignore-messages[don't show ignore-file parse error messages]"194 $no'--ignore-messages[show ignore-file parse error messages]'195196 + '(mmap)' # mmap options197 '--mmap[search using memory maps when possible]'198 "--no-mmap[don't search using memory maps]"199200 + '(multiline)' # Multiline options201 {-U,--multiline}'[permit matching across multiple lines]'202 $no'(multiline-dotall)--no-multiline[restrict matches to at most one line each]'203204 + '(multiline-dotall)' # Multiline DOTALL options205 '(--no-multiline)--multiline-dotall[allow "." to match newline (with -U)]'206 $no"(--no-multiline)--no-multiline-dotall[don't allow \".\" to match newline (with -U)]"207208 + '(only)' # Only-match options209 {-o,--only-matching}'[show only matching part of each line]'210211 + '(passthru)' # Pass-through options212 '(--vimgrep)--passthru[show both matching and non-matching lines]'213 '!(--vimgrep)--passthrough'214215 + '(pcre2)' # PCRE2 options216 {-P,--pcre2}'[enable matching with PCRE2]'217 $no'(pcre2-unicode)--no-pcre2[disable matching with PCRE2]'218219 + '(pcre2-unicode)' # PCRE2 Unicode options220 $no'(--no-pcre2 --no-pcre2-unicode)--pcre2-unicode[enable PCRE2 Unicode mode (with -P)]'221 '(--no-pcre2 --pcre2-unicode)--no-pcre2-unicode[disable PCRE2 Unicode mode (with -P)]'222223 + '(pre)' # Preprocessing options224 '(-z --search-zip)--pre=[specify preprocessor utility]:preprocessor utility:_command_names -e'225 $no'--no-pre[disable preprocessor utility]'226227 + pre-glob # Preprocessing glob options228 '*--pre-glob[include/exclude files for preprocessing with --pre]'229230 + '(pretty-vimgrep)' # Pretty/vimgrep display options231 '(heading)'{-p,--pretty}'[alias for --color=always --heading -n]'232 '(heading passthru)--vimgrep[show results in vim-compatible format]'233234 + regexp # Explicit pattern options235 '(1 file)*'{-e+,--regexp=}'[specify pattern]:pattern'236237 + '(replace)' # Replacement options238 {-r+,--replace=}'[specify string used to replace matches]:replace string'239240 + '(sort)' # File-sorting options241 '(threads)--sort=[sort results in ascending order (disables parallelism)]:sort method:((242 none\:"no sorting"243 path\:"sort by file path"244 modified\:"sort by last modified time"245 accessed\:"sort by last accessed time"246 created\:"sort by creation time"247 ))'248 '(threads)--sortr=[sort results in descending order (disables parallelism)]:sort method:((249 none\:"no sorting"250 path\:"sort by file path"251 modified\:"sort by last modified time"252 accessed\:"sort by last accessed time"253 created\:"sort by creation time"254 ))'255 '!(threads)--sort-files[sort results by file path (disables parallelism)]'256257 + '(stats)' # Statistics options258 '(--files file-match)--stats[show search statistics]'259 $no"--no-stats[don't show search statistics]"260261 + '(text)' # Binary-search options262 {-a,--text}'[search binary files as if they were text]'263 "--binary[search binary files, don't print binary data]"264 $no"--no-binary[don't search binary files]"265 $no"(--null-data)--no-text[don't search binary files as if they were text]"266267 + '(threads)' # Thread-count options268 '(sort)'{-j+,--threads=}'[specify approximate number of threads to use]:number of threads'269270 + '(trim)' # Trim options271 '--trim[trim any ASCII whitespace prefix from each line]'272 $no"--no-trim[don't trim ASCII whitespace prefix from each line]"273274 + type # Type options275 '*'{-t+,--type=}'[only search files matching specified type]: :_rg_types'276 '*--type-add=[add new glob for specified file type]: :->typespec'277 '*--type-clear=[clear globs previously defined for specified file type]: :_rg_types'278 # This should actually be exclusive with everything but other type options279 '(: *)--type-list[show all supported file types and their associated globs]'280 '*'{-T+,--type-not=}"[don't search files matching specified file type]: :_rg_types"281282 + '(word-line)' # Whole-word/line match options283 {-w,--word-regexp}'[only show matches surrounded by word boundaries]'284 {-x,--line-regexp}'[only show matches surrounded by line boundaries]'285286 + '(unicode)' # Unicode options287 $no'--unicode[enable Unicode mode]'288 '--no-unicode[disable Unicode mode]'289290 + '(zip)' # Compression options291 '(--pre)'{-z,--search-zip}'[search in compressed files]'292 $no"--no-search-zip[don't search in compressed files]"293294 + misc # Other options — no need to separate these at the moment295 '(-b --byte-offset)'{-b,--byte-offset}'[show 0-based byte offset for each matching line]'296 '--color=[specify when to use colors in output]:when:((297 never\:"never use colors"298 auto\:"use colors or not based on stdout, TERM, etc."299 always\:"always use colors"300 ansi\:"always use ANSI colors (even on Windows)"301 ))'302 '*--colors=[specify color and style settings]: :->colorspec'303 '--context-separator=[specify string used to separate non-continuous context lines in output]:separator'304 $no"--no-context-separator[don't print context separators]"305 '--debug[show debug messages]'306 '--field-context-separator[set string to delimit fields in context lines]'307 '--field-match-separator[set string to delimit fields in matching lines]'308 '--hostname-bin=[executable for getting system hostname]:hostname executable:_command_names -e'309 '--hyperlink-format=[specify pattern for hyperlinks]:pattern'310 '--trace[show more verbose debug messages]'311 '--dfa-size-limit=[specify upper size limit of generated DFA]:DFA size (bytes)'312 "(1 stats)--files[show each file that would be searched (but don't search)]"313 '*--ignore-file=[specify additional ignore file]:ignore file:_files'314 '(-v --invert-match)'{-v,--invert-match}'[invert matching]'315 '(-M --max-columns)'{-M+,--max-columns=}'[specify max length of lines to print]:number of bytes'316 '(-m --max-count)'{-m+,--max-count=}'[specify max number of matches per file]:number of matches'317 '--max-filesize=[specify size above which files should be ignored]:file size (bytes)'318 "--no-config[don't load configuration files]"319 '(-0 --null)'{-0,--null}'[print NUL byte after file names]'320 '--path-separator=[specify path separator to use when printing file names]:separator'321 '(-q --quiet)'{-q,--quiet}'[suppress normal output]'322 '--regex-size-limit=[specify upper size limit of compiled regex]:regex size (bytes)'323 '*'{-u,--unrestricted}'[reduce level of "smart" searching]'324 '--stop-on-nonmatch[stop on first non-matching line after a matching one]'325326 + operand # Operands327 '(--files --type-list file regexp)1: :_guard "^-*" pattern'328 '(--type-list)*: :_files'329 )330331 # This is used with test-complete to verify that there are no options332 # listed in the help output that aren't also defined here333 [[ $_RG_COMPLETE_LIST_ARGS == (1|t*|y*) ]] && {334 print -rl - $args335 return 0336 }337338 # Strip out argument groups where unsupported (see above)339 [[ $ZSH_VERSION == (4|5.<0-3>)(.*)# ]] &&340 args=( ${(@)args:#(#i)(+|[a-z0-9][a-z0-9_-]#|\([a-z0-9][a-z0-9_-]#\))} )341342 _arguments -C -s -S : $args && ret=0343344 case $state in345 colorspec)346 if [[ ${IPREFIX#--*=}$PREFIX == [^:]# ]]; then347 suf=( -qS: )348 tmp=(349 'column:specify coloring for column numbers'350 'line:specify coloring for line numbers'351 'match:specify coloring for match text'352 'path:specify coloring for file names'353 )354 descr='color/style type'355 elif [[ ${IPREFIX#--*=}$PREFIX == (column|line|match|path):[^:]# ]]; then356 suf=( -qS: )357 tmp=(358 'none:clear color/style for type'359 'bg:specify background color'360 'fg:specify foreground color'361 'style:specify text style'362 )363 descr='color/style attribute'364 elif [[ ${IPREFIX#--*=}$PREFIX == [^:]##:(bg|fg):[^:]# ]]; then365 tmp=( black blue green red cyan magenta yellow white )366 descr='color name or r,g,b'367 elif [[ ${IPREFIX#--*=}$PREFIX == [^:]##:style:[^:]# ]]; then368 tmp=( {,no}bold {,no}intense {,no}underline )369 descr='style name'370 else371 _message -e colorspec 'no more arguments'372 fi373374 (( $#tmp )) && {375 compset -P '*:'376 _describe -t colorspec $descr tmp $suf && ret=0377 }378 ;;379380 typespec)381 if compset -P '[^:]##:include:'; then382 _sequence -s , _rg_types && ret=0383 # @todo This bit in particular could be better, but it's a little384 # complex, and attempting to solve it seems to run us up against a crash385 # bug — zsh # 40362386 elif compset -P '[^:]##:'; then387 _message 'glob or include directive' && ret=1388 elif [[ ! -prefix *:* ]]; then389 _rg_types -qS : && ret=0390 fi391 ;;392 esac393394 return ret395}396397# Complete encodings398_rg_encodings() {399 local -a expl400 local -aU _encodings401402 # This is impossible to read, but these encodings rarely if ever change, so it403 # probably doesn't matter. They are derived from the list given here:404 # https://encoding.spec.whatwg.org/#concept-encoding-get405 _encodings=(406 {{,us-}ascii,arabic,chinese,cyrillic,greek{,8},hebrew,korean}407 logical visual mac {,cs}macintosh x-mac-{cyrillic,roman,ukrainian}408 866 ibm{819,866} csibm866409 big5{,-hkscs} {cn-,cs}big5 x-x-big5410 cp{819,866,125{0..8}} x-cp125{0..8}411 csiso2022{jp,kr} csiso8859{6,8}{e,i}412 csisolatin{{1..6},9} csisolatin{arabic,cyrillic,greek,hebrew}413 ecma-{114,118} asmo-708 elot_928 sun_eu_greek414 euc-{jp,kr} x-euc-jp cseuckr cseucpkdfmtjapanese415 {,x-}gbk csiso58gb231280 gb18030 {,cs}gb2312 gb_2312{,-80} hz-gb-2312416 iso-2022-{cn,cn-ext,jp,kr}417 iso8859{,-}{{1..11},13,14,15}418 iso-8859-{{1..11},{6,8}-{e,i},13,14,15,16} iso_8859-{{1..9},15}419 iso_8859-{1,2,6,7}:1987 iso_8859-{3,4,5,8}:1988 iso_8859-9:1989420 iso-ir-{58,100,101,109,110,126,127,138,144,148,149,157}421 koi{,8,8-r,8-ru,8-u,8_r} cskoi8r422 ks_c_5601-{1987,1989} ksc{,_}5691 csksc56011987423 latin{1..6} l{{1..6},9}424 shift{-,_}jis csshiftjis {,x-}sjis ms_kanji ms932425 utf{,-}8 utf-16{,be,le} unicode-1-1-utf-8426 windows-{31j,874,949,125{0..8}} dos-874 tis-620 ansi_x3.4-1968427 x-user-defined auto none428 )429430 _wanted encodings expl encoding compadd -a "$@" - _encodings431}432433# Complete file types434_rg_types() {435 local -a expl436 local -aU _types437438 _types=( ${(@)${(f)"$( _call_program types $words[1] --type-list )"}//:[[:space:]]##/:} )439440 if zstyle -t ":completion:${curcontext}:types" extra-verbose; then441 _describe -t types 'file type' _types442 else443 _wanted types expl 'file type' compadd "$@" - ${(@)_types%%:*}444 fi445}446447_rg "$@"448449################################################################################450# ZSH COMPLETION REFERENCE451#452# For the convenience of developers who aren't especially familiar with zsh453# completion functions, a brief reference guide follows. This is in no way454# comprehensive; it covers just enough of the basic structure, syntax, and455# conventions to help someone make simple changes like adding new options. For456# more complete documentation regarding zsh completion functions, please see the457# following:458#459# * http://zsh.sourceforge.net/Doc/Release/Completion-System.html460# * https://github.com/zsh-users/zsh/blob/master/Etc/completion-style-guide461#462# OVERVIEW463#464# Most zsh completion functions are defined in terms of `_arguments`, which is a465# shell function that takes a series of argument specifications. The specs for466# `rg` are stored in an array, which is common for more complex functions; the467# elements of the array are passed to `_arguments` on invocation.468#469# ARGUMENT-SPECIFICATION SYNTAX470#471# The following is a contrived example of the argument specs for a simple tool:472#473# '(: * -)'{-h,--help}'[display help information]'474# '(-q -v --quiet --verbose)'{-q,--quiet}'[decrease output verbosity]'475# '!(-q -v --quiet --verbose)--silent'476# '(-q -v --quiet --verbose)'{-v,--verbose}'[increase output verbosity]'477# '--color=[specify when to use colors]:when:(always never auto)'478# '*:example file:_files'479#480# Although there may appear to be six specs here, there are actually nine; we481# use brace expansion to combine specs for options that go by multiple names,482# like `-q` and `--quiet`. This is customary, and ties in with the fact that zsh483# merges completion possibilities together when they have the same description.484#485# The first line defines the option `-h`/`--help`. With most tools, it isn't486# useful to complete anything after `--help` because it effectively overrides487# all others; the `(: * -)` at the beginning of the spec tells zsh not to488# complete any other operands (`:` and `*`) or options (`-`) after this one has489# been used. The `[...]` at the end associates a description with `-h`/`--help`;490# as mentioned, zsh will see the identical descriptions and merge these options491# together when offering completion possibilities.492#493# The next line defines `-q`/`--quiet`. Here we don't want to suppress further494# completions entirely, but we don't want to offer `-q` if `--quiet` has been495# given (since they do the same thing), nor do we want to offer `-v` (since it496# doesn't make sense to be quiet and verbose at the same time). We don't need to497# tell zsh not to offer `--quiet` a second time, since that's the default498# behaviour, but since this line expands to two specs describing `-q` *and*499# `--quiet` we do need to explicitly list all of them here.500#501# The next line defines a hidden option `--silent` — maybe it's a deprecated502# synonym for `--quiet`. The leading `!` indicates that zsh shouldn't offer this503# option during completion. The benefit of providing a spec for an option that504# shouldn't be completed is that, if someone *does* use it, we can correctly505# suppress completion of other options afterwards.506#507# The next line defines `-v`/`--verbose`; this works just like `-q`/`--quiet`.508#509# The next line defines `--color`. In this example, `--color` doesn't have a510# corresponding short option, so we don't need to use brace expansion. Further,511# there are no other options it's exclusive with (just itself), so we don't need512# to define those at the beginning. However, it does take a mandatory argument.513# The `=` at the end of `--color=` indicates that the argument may appear either514# like `--color always` or like `--color=always`; this is how most GNU-style515# command-line tools work. The corresponding short option would normally use `+`516# — for example, `-c+` would allow either `-c always` or `-calways`. For this517# option, the arguments are known ahead of time, so we can simply list them in518# parentheses at the end (`when` is used as the description for the argument).519#520# The last line defines an operand (a non-option argument). In this example, the521# operand can be used any number of times (the leading `*`), and it should be a522# file path, so we tell zsh to call the `_files` function to complete it. The523# `example file` in the middle is the description to use for this operand; we524# could use a space instead to accept the default provided by `_files`.525#526# GROUPING ARGUMENT SPECIFICATIONS527#528# Newer versions of zsh support grouping argument specs together. All specs529# following a `+` and then a group name are considered to be members of the530# named group. Grouping is useful mostly for organisational purposes; it makes531# the relationship between different options more obvious, and makes it easier532# to specify exclusions.533#534# We could rewrite our example above using grouping as follows:535#536# '(: * -)'{-h,--help}'[display help information]'537# '--color=[specify when to use colors]:when:(always never auto)'538# '*:example file:_files'539# + '(verbosity)'540# {-q,--quiet}'[decrease output verbosity]'541# '!--silent'542# {-v,--verbose}'[increase output verbosity]'543#544# Here we take advantage of a useful feature of spec grouping — when the group545# name is surrounded by parentheses, as in `(verbosity)`, it tells zsh that all546# of the options in that group are exclusive with each other. As a result, we547# don't need to manually list out the exclusions at the beginning of each548# option.549#550# Groups can also be referred to by name in other argument specs; for example:551#552# '(xyz)--aaa' '*: :_files'553# + xyz --xxx --yyy --zzz554#555# Here we use the group name `xyz` to tell zsh that `--xxx`, `--yyy`, and556# `--zzz` are not to be completed after `--aaa`. This makes the exclusion list557# much more compact and reusable.558#559# CONVENTIONS560#561# zsh completion functions generally adhere to the following conventions:562#563# * Use two spaces for indentation564# * Combine specs for options with different names using brace expansion565# * In combined specs, list the short option first (as in `{-a,--text}`)566# * Use `+` or `=` as described above for options that take arguments567# * Provide a description for all options, option-arguments, and operands568# * Capitalise/punctuate argument descriptions as phrases, not complete569# sentences — 'display help information', never 'Display help information.'570# (but still capitalise acronyms and proper names)571# * Write argument descriptions as verb phrases — 'display x', 'enable y',572# 'use z'573# * Word descriptions to make it clear when an option expects an argument;574# usually this is done with the word 'specify', as in 'specify x' or575# 'use specified x')576# * Write argument descriptions as tersely as possible — for example, articles577# like 'a' and 'the' should be omitted unless it would be confusing578#579# Other conventions currently used by this function:580#581# * Order argument specs alphabetically by group name, then option name582# * Group options that are directly related, mutually exclusive, or frequently583# referenced by other argument specs584# * Use only characters in the set [a-z0-9_-] in group names585# * Order exclusion lists as follows: short options, long options, groups586# * Use American English in descriptions587# * Use 'don't' in descriptions instead of 'do not'588# * Word descriptions for related options as similarly as possible. For example,589# `--foo[enable foo]` and `--no-foo[disable foo]`, or `--foo[use foo]` and590# `--no-foo[don't use foo]`591# * Word descriptions to make it clear when an option only makes sense with592# another option, usually by adding '(with -x)' to the end593# * Don't quote strings or variables unnecessarily. When quotes are required,594# prefer single-quotes to double-quotes595# * Prefix option specs with `$no` when the option serves only to negate the596# behaviour of another option that must be provided explicitly by the user.597# This prevents rarely used options from cluttering up the completion menu598################################################################################599600# ------------------------------------------------------------------------------601# Copyright (c) 2011 Github zsh-users - http://github.com/zsh-users602# All rights reserved.603#604# Redistribution and use in source and binary forms, with or without605# modification, are permitted provided that the following conditions are met:606# * Redistributions of source code must retain the above copyright607# notice, this list of conditions and the following disclaimer.608# * Redistributions in binary form must reproduce the above copyright609# notice, this list of conditions and the following disclaimer in the610# documentation and/or other materials provided with the distribution.611# * Neither the name of the zsh-users nor the612# names of its contributors may be used to endorse or promote products613# derived from this software without specific prior written permission.614#615# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND616# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED617# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE618# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY619# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES620# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;621# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND622# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT623# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS624# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.625# ------------------------------------------------------------------------------626# Description627# -----------628#629# Completion script for ripgrep630#631# ------------------------------------------------------------------------------632# Authors633# -------634#635# * arcizan <ghostrevery@gmail.com>636# * MaskRay <i@maskray.me>637#638# ------------------------------------------------------------------------------639640# Local Variables:641# mode: shell-script642# coding: utf-8-unix643# indent-tabs-mode: nil644# sh-indentation: 2645# sh-basic-offset: 2646# End:647# vim: ft=zsh sw=2 ts=2 et
modified:crates/cli/src/wtr.rs+2 added
1 unmodified line
23use termcolor::{self, HyperlinkSpec};45/// A writer that supports coloring with either line or block buffering.6#[derive(Debug)]7pub struct StandardStream(StandardStreamKind);89/// Returns a possibly buffered writer to stdout for the given color choice.10///
46 unmodified lines
57 let out = termcolor::BufferedStandardStream::stdout(color_choice);58 StandardStream(StandardStreamKind::BlockBuffered(out))59}6061#[derive(Debug)]62enum StandardStreamKind {63 LineBuffered(termcolor::StandardStream),64 BlockBuffered(termcolor::BufferedStandardStream),65}
84 unmodified lines
added:crates/core/flags/complete/bash.rs+107 added
1/*!2Provides completions for ripgrep's CLI for the bash shell.3*/45use crate::flags::defs::FLAGS;67const TEMPLATE_FULL: &'static str = "8_rg() {9 local i cur prev opts cmds10 COMPREPLY=()11 cur=\"${COMP_WORDS[COMP_CWORD]}\"12 prev=\"${COMP_WORDS[COMP_CWORD-1]}\"13 cmd=\"\"14 opts=\"\"1516 for i in ${COMP_WORDS[@]}; do17 case \"${i}\" in18 rg)19 cmd=\"rg\"20 ;;21 *)22 ;;23 esac24 done2526 case \"${cmd}\" in27 rg)28 opts=\"!OPTS!\"29 if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then30 COMPREPLY=($(compgen -W \"${opts}\" -- \"${cur}\"))31 return 032 fi33 case \"${prev}\" in34!CASES!35 esac36 COMPREPLY=($(compgen -W \"${opts}\" -- \"${cur}\"))37 return 038 ;;39 esac40}4142complete -F _rg -o bashdefault -o default rg43";4445const TEMPLATE_CASE: &'static str = "46 !FLAG!)47 COMPREPLY=($(compgen -f \"${cur}\"))48 return 049 ;;50";5152const TEMPLATE_CASE_CHOICES: &'static str = "53 !FLAG!)54 COMPREPLY=($(compgen -W \"!CHOICES!\" -- \"${cur}\"))55 return 056 ;;57";5859/// Generate completions for Bash.60///61/// Note that these completions are based on what was produced for ripgrep <=1362/// using Clap 2.x. Improvements on this are welcome.63pub(crate) fn generate() -> String {64 let mut opts = String::new();65 for flag in FLAGS.iter() {66 opts.push_str("--");67 opts.push_str(flag.name_long());68 opts.push(' ');69 if let Some(short) = flag.name_short() {70 opts.push('-');71 opts.push(char::from(short));72 opts.push(' ');73 }74 if let Some(name) = flag.name_negated() {75 opts.push_str("--");76 opts.push_str(name);77 opts.push(' ');78 }79 }80 opts.push_str("<PATTERN> <PATH>...");8182 let mut cases = String::new();83 for flag in FLAGS.iter() {84 let template = if !flag.doc_choices().is_empty() {85 let choices = flag.doc_choices().join(" ");86 TEMPLATE_CASE_CHOICES.trim_end().replace("!CHOICES!", &choices)87 } else {88 TEMPLATE_CASE.trim_end().to_string()89 };90 let name = format!("--{}", flag.name_long());91 cases.push_str(&template.replace("!FLAG!", &name));92 if let Some(short) = flag.name_short() {93 let name = format!("-{}", char::from(short));94 cases.push_str(&template.replace("!FLAG!", &name));95 }96 if let Some(negated) = flag.name_negated() {97 let name = format!("--{negated}");98 cases.push_str(&template.replace("!FLAG!", &name));99 }100 }101102 TEMPLATE_FULL103 .replace("!OPTS!", &opts)104 .replace("!CASES!", &cases)105 .trim_start()106 .to_string()107}
added:crates/core/flags/complete/fish.rs+47 added
1/*!2Provides completions for ripgrep's CLI for the fish shell.3*/45use crate::flags::defs::FLAGS;67const TEMPLATE: &'static str =8 "complete -c rg -n '__fish_use_subcommand' !SHORT! !LONG! !DOC!\n";9const TEMPLATE_CHOICES: &'static str =10 "complete -c rg -n '__fish_use_subcommand' !SHORT! !LONG! !DOC! -r -f -a '!CHOICES!'\n";1112/// Generate completions for Fish.13///14/// Note that these completions are based on what was produced for ripgrep <=1315/// using Clap 2.x. Improvements on this are welcome.16pub(crate) fn generate() -> String {17 let mut out = String::new();18 for flag in FLAGS.iter() {19 let short = match flag.name_short() {20 None => "".to_string(),21 Some(byte) => format!("-s {}", char::from(byte)),22 };23 let long = format!("-l '{}'", flag.name_long().replace("'", "\\'"));24 let doc = format!("-d '{}'", flag.doc_short().replace("'", "\\'"));25 let template = if flag.doc_choices().is_empty() {26 TEMPLATE.to_string()27 } else {28 TEMPLATE_CHOICES29 .replace("!CHOICES!", &flag.doc_choices().join(" "))30 };31 out.push_str(32 &template33 .replace("!SHORT!", &short)34 .replace("!LONG!", &long)35 .replace("!DOC!", &doc),36 );37 if let Some(negated) = flag.name_negated() {38 out.push_str(39 &template40 .replace("!SHORT!", "")41 .replace("!LONG!", &negated)42 .replace("!DOC!", &doc),43 );44 }45 }46 out47}
added:crates/core/flags/complete/mod.rs+8 added
1/*!2Modules for generating completions for various shells.3*/45pub(super) mod bash;6pub(super) mod fish;7pub(super) mod powershell;8pub(super) mod zsh;
added:crates/core/flags/complete/powershell.rs+86 added
1/*!2Provides completions for ripgrep's CLI for PowerShell.3*/45use crate::flags::defs::FLAGS;67const TEMPLATE: &'static str = "8using namespace System.Management.Automation9using namespace System.Management.Automation.Language1011Register-ArgumentCompleter -Native -CommandName 'rg' -ScriptBlock {12 param($wordToComplete, $commandAst, $cursorPosition)13 $commandElements = $commandAst.CommandElements14 $command = @(15 'rg'16 for ($i = 1; $i -lt $commandElements.Count; $i++) {17 $element = $commandElements[$i]18 if ($element -isnot [StringConstantExpressionAst] -or19 $element.StringConstantType -ne [StringConstantType]::BareWord -or20 $element.Value.StartsWith('-')) {21 break22 }23 $element.Value24 }) -join ';'2526 $completions = @(switch ($command) {27 'rg' {28!FLAGS!29 }30 })3132 $completions.Where{ $_.CompletionText -like \"$wordToComplete*\" } |33 Sort-Object -Property ListItemText34}35";3637const TEMPLATE_FLAG: &'static str =38 "[CompletionResult]::new('!DASH_NAME!', '!NAME!', [CompletionResultType]::ParameterName, '!DOC!')";3940/// Generate completions for PowerShell.41///42/// Note that these completions are based on what was produced for ripgrep <=1343/// using Clap 2.x. Improvements on this are welcome.44pub(crate) fn generate() -> String {45 let mut flags = String::new();46 for (i, flag) in FLAGS.iter().enumerate() {47 let doc = flag.doc_short().replace("'", "''");4849 let dash_name = format!("--{}", flag.name_long());50 let name = flag.name_long();51 if i > 0 {52 flags.push('\n');53 }54 flags.push_str(" ");55 flags.push_str(56 &TEMPLATE_FLAG57 .replace("!DASH_NAME!", &dash_name)58 .replace("!NAME!", &name)59 .replace("!DOC!", &doc),60 );6162 if let Some(byte) = flag.name_short() {63 let dash_name = format!("-{}", char::from(byte));64 let name = char::from(byte).to_string();65 flags.push_str("\n ");66 flags.push_str(67 &TEMPLATE_FLAG68 .replace("!DASH_NAME!", &dash_name)69 .replace("!NAME!", &name)70 .replace("!DOC!", &doc),71 );72 }7374 if let Some(negated) = flag.name_negated() {75 let dash_name = format!("--{}", negated);76 flags.push_str("\n ");77 flags.push_str(78 &TEMPLATE_FLAG79 .replace("!DASH_NAME!", &dash_name)80 .replace("!NAME!", &negated)81 .replace("!DOC!", &doc),82 );83 }84 }85 TEMPLATE.trim_start().replace("!FLAGS!", &flags)86}
added:crates/core/flags/complete/rg.zsh+661 added
1#compdef rg23##4# zsh completion function for ripgrep5#6# Run ci/test-complete after building to ensure that the options supported by7# this function stay in synch with the `rg` binary.8#9# For convenience, a completion reference guide is included at the bottom of10# this file.11#12# Originally based on code from the zsh-users project — see copyright notice13# below.1415_rg() {16 local curcontext=$curcontext no='!' descr ret=117 local -a context line state state_descr args tmp suf18 local -A opt_args1920 # ripgrep has many options which negate the effect of a more common one — for21 # example, `--no-column` to negate `--column`, and `--messages` to negate22 # `--no-messages`. There are so many of these, and they're so infrequently23 # used, that some users will probably find it irritating if they're completed24 # indiscriminately, so let's not do that unless either the current prefix25 # matches one of those negation options or the user has the `complete-all`26 # style set. Note that this prefix check has to be updated manually to account27 # for all of the potential negation options listed below!28 if29 # We also want to list all of these options during testing30 [[ $_RG_COMPLETE_LIST_ARGS == (1|t*|y*) ]] ||31 # (--[imnp]* => --ignore*, --messages, --no-*, --pcre2-unicode)32 [[ $PREFIX$SUFFIX == --[imnp]* ]] ||33 zstyle -t ":completion:${curcontext}:" complete-all34 then35 no=36 fi3738 # We make heavy use of argument groups here to prevent the option specs from39 # growing unwieldy. These aren't supported in zsh <5.4, though, so we'll strip40 # them out below if necessary. This makes the exclusions inaccurate on those41 # older versions, but oh well — it's not that big a deal42 args=(43 + '(exclusive)' # Misc. fully exclusive options44 '(: * -)'{-h,--help}'[display help information]'45 '(: * -)'{-V,--version}'[display version information]'46 '(: * -)'--pcre2-version'[print the version of PCRE2 used by ripgrep, if available]'4748 + '(buffered)' # buffering options49 '--line-buffered[force line buffering]'50 $no"--no-line-buffered[don't force line buffering]"51 '--block-buffered[force block buffering]'52 $no"--no-block-buffered[don't force block buffering]"5354 + '(case)' # Case-sensitivity options55 {-i,--ignore-case}'[search case-insensitively]'56 {-s,--case-sensitive}'[search case-sensitively]'57 {-S,--smart-case}'[search case-insensitively if pattern is all lowercase]'5859 + '(context-a)' # Context (after) options60 '(context-c)'{-A+,--after-context=}'[specify lines to show after each match]:number of lines'6162 + '(context-b)' # Context (before) options63 '(context-c)'{-B+,--before-context=}'[specify lines to show before each match]:number of lines'6465 + '(context-c)' # Context (combined) options66 '(context-a context-b)'{-C+,--context=}'[specify lines to show before and after each match]:number of lines'6768 + '(column)' # Column options69 '--column[show column numbers for matches]'70 $no"--no-column[don't show column numbers for matches]"7172 + '(count)' # Counting options73 {-c,--count}'[only show count of matching lines for each file]'74 '--count-matches[only show count of individual matches for each file]'75 '--include-zero[include files with zero matches in summary]'76 $no"--no-include-zero[don't include files with zero matches in summary]"7778 + '(encoding)' # Encoding options79 {-E+,--encoding=}'[specify text encoding of files to search]: :_rg_encodings'80 $no'--no-encoding[use default text encoding]'8182 + '(engine)' # Engine choice options83 '--engine=[select which regex engine to use]:when:((84 default\:"use default engine"85 pcre2\:"identical to --pcre2"86 auto\:"identical to --auto-hybrid-regex"87 ))'8889 + file # File-input options90 '(1)*'{-f+,--file=}'[specify file containing patterns to search for]: :_files'9192 + '(file-match)' # Files with/without match options93 '(stats)'{-l,--files-with-matches}'[only show names of files with matches]'94 '(stats)--files-without-match[only show names of files without matches]'9596 + '(file-name)' # File-name options97 {-H,--with-filename}'[show file name for matches]'98 {-I,--no-filename}"[don't show file name for matches]"99100 + '(file-system)' # File system options101 "--one-file-system[don't descend into directories on other file systems]"102 $no'--no-one-file-system[descend into directories on other file systems]'103104 + '(fixed)' # Fixed-string options105 {-F,--fixed-strings}'[treat pattern as literal string instead of regular expression]'106 $no"--no-fixed-strings[don't treat pattern as literal string]"107108 + '(follow)' # Symlink-following options109 {-L,--follow}'[follow symlinks]'110 $no"--no-follow[don't follow symlinks]"111112 + '(generate)' # Options for generating ancillary data113 '--generate=[generate man page or completion scripts]:when:((114 man\:"man page"115 complete-bash\:"shell completions for bash"116 complete-zsh\:"shell completions for zsh"117 complete-fish\:"shell completions for fish"118 complete-powershell\:"shell completions for PowerShell"119 ))'120121 + glob # File-glob options122 '*'{-g+,--glob=}'[include/exclude files matching specified glob]:glob'123 '*--iglob=[include/exclude files matching specified case-insensitive glob]:glob'124125 + '(glob-case-insensitive)' # File-glob case sensitivity options126 '--glob-case-insensitive[treat -g/--glob patterns case insensitively]'127 $no'--no-glob-case-insensitive[treat -g/--glob patterns case sensitively]'128129 + '(heading)' # Heading options130 '(pretty-vimgrep)--heading[show matches grouped by file name]'131 "(pretty-vimgrep)--no-heading[don't show matches grouped by file name]"132133 + '(hidden)' # Hidden-file options134 {-.,--hidden}'[search hidden files and directories]'135 $no"--no-hidden[don't search hidden files and directories]"136137 + '(hybrid)' # hybrid regex options138 '--auto-hybrid-regex[DEPRECATED: dynamically use PCRE2 if necessary]'139 $no"--no-auto-hybrid-regex[DEPRECATED: don't dynamically use PCRE2 if necessary]"140141 + '(ignore)' # Ignore-file options142 "(--no-ignore-global --no-ignore-parent --no-ignore-vcs --no-ignore-dot)--no-ignore[don't respect ignore files]"143 $no'(--ignore-global --ignore-parent --ignore-vcs --ignore-dot)--ignore[respect ignore files]'144145 + '(ignore-file-case-insensitive)' # Ignore-file case sensitivity options146 '--ignore-file-case-insensitive[process ignore files case insensitively]'147 $no'--no-ignore-file-case-insensitive[process ignore files case sensitively]'148149 + '(ignore-exclude)' # Local exclude (ignore)-file options150 "--no-ignore-exclude[don't respect local exclude (ignore) files]"151 $no'--ignore-exclude[respect local exclude (ignore) files]'152153 + '(ignore-global)' # Global ignore-file options154 "--no-ignore-global[don't respect global ignore files]"155 $no'--ignore-global[respect global ignore files]'156157 + '(ignore-parent)' # Parent ignore-file options158 "--no-ignore-parent[don't respect ignore files in parent directories]"159 $no'--ignore-parent[respect ignore files in parent directories]'160161 + '(ignore-vcs)' # VCS ignore-file options162 "--no-ignore-vcs[don't respect version control ignore files]"163 $no'--ignore-vcs[respect version control ignore files]'164165 + '(require-git)' # git specific settings166 "--no-require-git[don't require git repository to respect gitignore rules]"167 $no'--require-git[require git repository to respect gitignore rules]'168169 + '(ignore-dot)' # .ignore options170 "--no-ignore-dot[don't respect .ignore files]"171 $no'--ignore-dot[respect .ignore files]'172173 + '(ignore-files)' # custom global ignore file options174 "--no-ignore-files[don't respect --ignore-file flags]"175 $no'--ignore-files[respect --ignore-file files]'176177 + '(json)' # JSON options178 '--json[output results in JSON Lines format]'179 $no"--no-json[don't output results in JSON Lines format]"180181 + '(line-number)' # Line-number options182 {-n,--line-number}'[show line numbers for matches]'183 {-N,--no-line-number}"[don't show line numbers for matches]"184185 + '(line-terminator)' # Line-terminator options186 '--crlf[use CRLF as line terminator]'187 $no"--no-crlf[don't use CRLF as line terminator]"188 '(text)--null-data[use NUL as line terminator]'189190 + '(max-columns-preview)' # max column preview options191 '--max-columns-preview[show preview for long lines (with -M)]'192 $no"--no-max-columns-preview[don't show preview for long lines (with -M)]"193194 + '(max-depth)' # Directory-depth options195 '--max-depth=[specify max number of directories to descend]:number of directories'196 '--maxdepth=[alias for --max-depth]:number of directories'197 '!--maxdepth=:number of directories'198199 + '(messages)' # Error-message options200 '(--no-ignore-messages)--no-messages[suppress some error messages]'201 $no"--messages[don't suppress error messages affected by --no-messages]"202203 + '(messages-ignore)' # Ignore-error message options204 "--no-ignore-messages[don't show ignore-file parse error messages]"205 $no'--ignore-messages[show ignore-file parse error messages]'206207 + '(mmap)' # mmap options208 '--mmap[search using memory maps when possible]'209 "--no-mmap[don't search using memory maps]"210211 + '(multiline)' # Multiline options212 {-U,--multiline}'[permit matching across multiple lines]'213 $no'(multiline-dotall)--no-multiline[restrict matches to at most one line each]'214215 + '(multiline-dotall)' # Multiline DOTALL options216 '(--no-multiline)--multiline-dotall[allow "." to match newline (with -U)]'217 $no"(--no-multiline)--no-multiline-dotall[don't allow \".\" to match newline (with -U)]"218219 + '(only)' # Only-match options220 {-o,--only-matching}'[show only matching part of each line]'221222 + '(passthru)' # Pass-through options223 '(--vimgrep)--passthru[show both matching and non-matching lines]'224 '(--vimgrep)--passthrough[alias for --passthru]'225226 + '(pcre2)' # PCRE2 options227 {-P,--pcre2}'[enable matching with PCRE2]'228 $no'(pcre2-unicode)--no-pcre2[disable matching with PCRE2]'229230 + '(pcre2-unicode)' # PCRE2 Unicode options231 $no'(--no-pcre2 --no-pcre2-unicode)--pcre2-unicode[DEPRECATED: enable PCRE2 Unicode mode (with -P)]'232 '(--no-pcre2 --pcre2-unicode)--no-pcre2-unicode[DEPRECATED: disable PCRE2 Unicode mode (with -P)]'233234 + '(pre)' # Preprocessing options235 '(-z --search-zip)--pre=[specify preprocessor utility]:preprocessor utility:_command_names -e'236 $no'--no-pre[disable preprocessor utility]'237238 + pre-glob # Preprocessing glob options239 '*--pre-glob[include/exclude files for preprocessing with --pre]'240241 + '(pretty-vimgrep)' # Pretty/vimgrep display options242 '(heading)'{-p,--pretty}'[alias for --color=always --heading -n]'243 '(heading passthru)--vimgrep[show results in vim-compatible format]'244245 + regexp # Explicit pattern options246 '(1 file)*'{-e+,--regexp=}'[specify pattern]:pattern'247248 + '(replace)' # Replacement options249 {-r+,--replace=}'[specify string used to replace matches]:replace string'250251 + '(sort)' # File-sorting options252 '(threads)--sort=[sort results in ascending order (disables parallelism)]:sort method:((253 none\:"no sorting"254 path\:"sort by file path"255 modified\:"sort by last modified time"256 accessed\:"sort by last accessed time"257 created\:"sort by creation time"258 ))'259 '(threads)--sortr=[sort results in descending order (disables parallelism)]:sort method:((260 none\:"no sorting"261 path\:"sort by file path"262 modified\:"sort by last modified time"263 accessed\:"sort by last accessed time"264 created\:"sort by creation time"265 ))'266 '(threads)--sort-files[DEPRECATED: sort results by file path (disables parallelism)]'267 $no"--no-sort-files[DEPRECATED: do not sort results]"268269 + '(stats)' # Statistics options270 '(--files file-match)--stats[show search statistics]'271 $no"--no-stats[don't show search statistics]"272273 + '(text)' # Binary-search options274 {-a,--text}'[search binary files as if they were text]'275 "--binary[search binary files, don't print binary data]"276 $no"--no-binary[don't search binary files]"277 $no"(--null-data)--no-text[don't search binary files as if they were text]"278279 + '(threads)' # Thread-count options280 '(sort)'{-j+,--threads=}'[specify approximate number of threads to use]:number of threads'281282 + '(trim)' # Trim options283 '--trim[trim any ASCII whitespace prefix from each line]'284 $no"--no-trim[don't trim ASCII whitespace prefix from each line]"285286 + type # Type options287 '*'{-t+,--type=}'[only search files matching specified type]: :_rg_types'288 '*--type-add=[add new glob for specified file type]: :->typespec'289 '*--type-clear=[clear globs previously defined for specified file type]: :_rg_types'290 # This should actually be exclusive with everything but other type options291 '(: *)--type-list[show all supported file types and their associated globs]'292 '*'{-T+,--type-not=}"[don't search files matching specified file type]: :_rg_types"293294 + '(word-line)' # Whole-word/line match options295 {-w,--word-regexp}'[only show matches surrounded by word boundaries]'296 {-x,--line-regexp}'[only show matches surrounded by line boundaries]'297298 + '(unicode)' # Unicode options299 $no'--unicode[enable Unicode mode]'300 '--no-unicode[disable Unicode mode]'301302 + '(zip)' # Compression options303 '(--pre)'{-z,--search-zip}'[search in compressed files]'304 $no"--no-search-zip[don't search in compressed files]"305306 + misc # Other options — no need to separate these at the moment307 '(-b --byte-offset)'{-b,--byte-offset}'[show 0-based byte offset for each matching line]'308 $no"--no-byte-offset[don't show byte offsets for each matching line]"309 '--color=[specify when to use colors in output]:when:((310 never\:"never use colors"311 auto\:"use colors or not based on stdout, TERM, etc."312 always\:"always use colors"313 ansi\:"always use ANSI colors (even on Windows)"314 ))'315 '*--colors=[specify color and style settings]: :->colorspec'316 '--context-separator=[specify string used to separate non-continuous context lines in output]:separator'317 $no"--no-context-separator[don't print context separators]"318 '--debug[show debug messages]'319 '--field-context-separator[set string to delimit fields in context lines]'320 '--field-match-separator[set string to delimit fields in matching lines]'321 '--hostname-bin=[executable for getting system hostname]:hostname executable:_command_names -e'322 '--hyperlink-format=[specify pattern for hyperlinks]:pattern'323 '--trace[show more verbose debug messages]'324 '--dfa-size-limit=[specify upper size limit of generated DFA]:DFA size (bytes)'325 "(1 stats)--files[show each file that would be searched (but don't search)]"326 '*--ignore-file=[specify additional ignore file]:ignore file:_files'327 '(-v --invert-match)'{-v,--invert-match}'[invert matching]'328 $no"--no-invert-match[do not invert matching]"329 '(-M --max-columns)'{-M+,--max-columns=}'[specify max length of lines to print]:number of bytes'330 '(-m --max-count)'{-m+,--max-count=}'[specify max number of matches per file]:number of matches'331 '--max-filesize=[specify size above which files should be ignored]:file size (bytes)'332 "--no-config[don't load configuration files]"333 '(-0 --null)'{-0,--null}'[print NUL byte after file names]'334 '--path-separator=[specify path separator to use when printing file names]:separator'335 '(-q --quiet)'{-q,--quiet}'[suppress normal output]'336 '--regex-size-limit=[specify upper size limit of compiled regex]:regex size (bytes)'337 '*'{-u,--unrestricted}'[reduce level of "smart" searching]'338 '--stop-on-nonmatch[stop on first non-matching line after a matching one]'339340 + operand # Operands341 '(--files --type-list file regexp)1: :_guard "^-*" pattern'342 '(--type-list)*: :_files'343 )344345 # This is used with test-complete to verify that there are no options346 # listed in the help output that aren't also defined here347 [[ $_RG_COMPLETE_LIST_ARGS == (1|t*|y*) ]] && {348 print -rl - $args349 return 0350 }351352 # Strip out argument groups where unsupported (see above)353 [[ $ZSH_VERSION == (4|5.<0-3>)(.*)# ]] &&354 args=( ${(@)args:#(#i)(+|[a-z0-9][a-z0-9_-]#|\([a-z0-9][a-z0-9_-]#\))} )355356 _arguments -C -s -S : $args && ret=0357358 case $state in359 colorspec)360 if [[ ${IPREFIX#--*=}$PREFIX == [^:]# ]]; then361 suf=( -qS: )362 tmp=(363 'column:specify coloring for column numbers'364 'line:specify coloring for line numbers'365 'match:specify coloring for match text'366 'path:specify coloring for file names'367 )368 descr='color/style type'369 elif [[ ${IPREFIX#--*=}$PREFIX == (column|line|match|path):[^:]# ]]; then370 suf=( -qS: )371 tmp=(372 'none:clear color/style for type'373 'bg:specify background color'374 'fg:specify foreground color'375 'style:specify text style'376 )377 descr='color/style attribute'378 elif [[ ${IPREFIX#--*=}$PREFIX == [^:]##:(bg|fg):[^:]# ]]; then379 tmp=( black blue green red cyan magenta yellow white )380 descr='color name or r,g,b'381 elif [[ ${IPREFIX#--*=}$PREFIX == [^:]##:style:[^:]# ]]; then382 tmp=( {,no}bold {,no}intense {,no}underline )383 descr='style name'384 else385 _message -e colorspec 'no more arguments'386 fi387388 (( $#tmp )) && {389 compset -P '*:'390 _describe -t colorspec $descr tmp $suf && ret=0391 }392 ;;393394 typespec)395 if compset -P '[^:]##:include:'; then396 _sequence -s , _rg_types && ret=0397 # @todo This bit in particular could be better, but it's a little398 # complex, and attempting to solve it seems to run us up against a crash399 # bug — zsh # 40362400 elif compset -P '[^:]##:'; then401 _message 'glob or include directive' && ret=1402 elif [[ ! -prefix *:* ]]; then403 _rg_types -qS : && ret=0404 fi405 ;;406 esac407408 return ret409}410411# Complete encodings412_rg_encodings() {413 local -a expl414 local -aU _encodings415416 # This is impossible to read, but these encodings rarely if ever change, so it417 # probably doesn't matter. They are derived from the list given here:418 # https://encoding.spec.whatwg.org/#concept-encoding-get419 _encodings=(420 {{,us-}ascii,arabic,chinese,cyrillic,greek{,8},hebrew,korean}421 logical visual mac {,cs}macintosh x-mac-{cyrillic,roman,ukrainian}422 866 ibm{819,866} csibm866423 big5{,-hkscs} {cn-,cs}big5 x-x-big5424 cp{819,866,125{0..8}} x-cp125{0..8}425 csiso2022{jp,kr} csiso8859{6,8}{e,i}426 csisolatin{{1..6},9} csisolatin{arabic,cyrillic,greek,hebrew}427 ecma-{114,118} asmo-708 elot_928 sun_eu_greek428 euc-{jp,kr} x-euc-jp cseuckr cseucpkdfmtjapanese429 {,x-}gbk csiso58gb231280 gb18030 {,cs}gb2312 gb_2312{,-80} hz-gb-2312430 iso-2022-{cn,cn-ext,jp,kr}431 iso8859{,-}{{1..11},13,14,15}432 iso-8859-{{1..11},{6,8}-{e,i},13,14,15,16} iso_8859-{{1..9},15}433 iso_8859-{1,2,6,7}:1987 iso_8859-{3,4,5,8}:1988 iso_8859-9:1989434 iso-ir-{58,100,101,109,110,126,127,138,144,148,149,157}435 koi{,8,8-r,8-ru,8-u,8_r} cskoi8r436 ks_c_5601-{1987,1989} ksc{,_}5691 csksc56011987437 latin{1..6} l{{1..6},9}438 shift{-,_}jis csshiftjis {,x-}sjis ms_kanji ms932439 utf{,-}8 utf-16{,be,le} unicode-1-1-utf-8440 windows-{31j,874,949,125{0..8}} dos-874 tis-620 ansi_x3.4-1968441 x-user-defined auto none442 )443444 _wanted encodings expl encoding compadd -a "$@" - _encodings445}446447# Complete file types448_rg_types() {449 local -a expl450 local -aU _types451452 _types=( ${(@)${(f)"$( _call_program types $words[1] --type-list )"}//:[[:space:]]##/:} )453454 if zstyle -t ":completion:${curcontext}:types" extra-verbose; then455 _describe -t types 'file type' _types456 else457 _wanted types expl 'file type' compadd "$@" - ${(@)_types%%:*}458 fi459}460461_rg "$@"462463################################################################################464# ZSH COMPLETION REFERENCE465#466# For the convenience of developers who aren't especially familiar with zsh467# completion functions, a brief reference guide follows. This is in no way468# comprehensive; it covers just enough of the basic structure, syntax, and469# conventions to help someone make simple changes like adding new options. For470# more complete documentation regarding zsh completion functions, please see the471# following:472#473# * http://zsh.sourceforge.net/Doc/Release/Completion-System.html474# * https://github.com/zsh-users/zsh/blob/master/Etc/completion-style-guide475#476# OVERVIEW477#478# Most zsh completion functions are defined in terms of `_arguments`, which is a479# shell function that takes a series of argument specifications. The specs for480# `rg` are stored in an array, which is common for more complex functions; the481# elements of the array are passed to `_arguments` on invocation.482#483# ARGUMENT-SPECIFICATION SYNTAX484#485# The following is a contrived example of the argument specs for a simple tool:486#487# '(: * -)'{-h,--help}'[display help information]'488# '(-q -v --quiet --verbose)'{-q,--quiet}'[decrease output verbosity]'489# '!(-q -v --quiet --verbose)--silent'490# '(-q -v --quiet --verbose)'{-v,--verbose}'[increase output verbosity]'491# '--color=[specify when to use colors]:when:(always never auto)'492# '*:example file:_files'493#494# Although there may appear to be six specs here, there are actually nine; we495# use brace expansion to combine specs for options that go by multiple names,496# like `-q` and `--quiet`. This is customary, and ties in with the fact that zsh497# merges completion possibilities together when they have the same description.498#499# The first line defines the option `-h`/`--help`. With most tools, it isn't500# useful to complete anything after `--help` because it effectively overrides501# all others; the `(: * -)` at the beginning of the spec tells zsh not to502# complete any other operands (`:` and `*`) or options (`-`) after this one has503# been used. The `[...]` at the end associates a description with `-h`/`--help`;504# as mentioned, zsh will see the identical descriptions and merge these options505# together when offering completion possibilities.506#507# The next line defines `-q`/`--quiet`. Here we don't want to suppress further508# completions entirely, but we don't want to offer `-q` if `--quiet` has been509# given (since they do the same thing), nor do we want to offer `-v` (since it510# doesn't make sense to be quiet and verbose at the same time). We don't need to511# tell zsh not to offer `--quiet` a second time, since that's the default512# behaviour, but since this line expands to two specs describing `-q` *and*513# `--quiet` we do need to explicitly list all of them here.514#515# The next line defines a hidden option `--silent` — maybe it's a deprecated516# synonym for `--quiet`. The leading `!` indicates that zsh shouldn't offer this517# option during completion. The benefit of providing a spec for an option that518# shouldn't be completed is that, if someone *does* use it, we can correctly519# suppress completion of other options afterwards.520#521# The next line defines `-v`/`--verbose`; this works just like `-q`/`--quiet`.522#523# The next line defines `--color`. In this example, `--color` doesn't have a524# corresponding short option, so we don't need to use brace expansion. Further,525# there are no other options it's exclusive with (just itself), so we don't need526# to define those at the beginning. However, it does take a mandatory argument.527# The `=` at the end of `--color=` indicates that the argument may appear either528# like `--color always` or like `--color=always`; this is how most GNU-style529# command-line tools work. The corresponding short option would normally use `+`530# — for example, `-c+` would allow either `-c always` or `-calways`. For this531# option, the arguments are known ahead of time, so we can simply list them in532# parentheses at the end (`when` is used as the description for the argument).533#534# The last line defines an operand (a non-option argument). In this example, the535# operand can be used any number of times (the leading `*`), and it should be a536# file path, so we tell zsh to call the `_files` function to complete it. The537# `example file` in the middle is the description to use for this operand; we538# could use a space instead to accept the default provided by `_files`.539#540# GROUPING ARGUMENT SPECIFICATIONS541#542# Newer versions of zsh support grouping argument specs together. All specs543# following a `+` and then a group name are considered to be members of the544# named group. Grouping is useful mostly for organisational purposes; it makes545# the relationship between different options more obvious, and makes it easier546# to specify exclusions.547#548# We could rewrite our example above using grouping as follows:549#550# '(: * -)'{-h,--help}'[display help information]'551# '--color=[specify when to use colors]:when:(always never auto)'552# '*:example file:_files'553# + '(verbosity)'554# {-q,--quiet}'[decrease output verbosity]'555# '!--silent'556# {-v,--verbose}'[increase output verbosity]'557#558# Here we take advantage of a useful feature of spec grouping — when the group559# name is surrounded by parentheses, as in `(verbosity)`, it tells zsh that all560# of the options in that group are exclusive with each other. As a result, we561# don't need to manually list out the exclusions at the beginning of each562# option.563#564# Groups can also be referred to by name in other argument specs; for example:565#566# '(xyz)--aaa' '*: :_files'567# + xyz --xxx --yyy --zzz568#569# Here we use the group name `xyz` to tell zsh that `--xxx`, `--yyy`, and570# `--zzz` are not to be completed after `--aaa`. This makes the exclusion list571# much more compact and reusable.572#573# CONVENTIONS574#575# zsh completion functions generally adhere to the following conventions:576#577# * Use two spaces for indentation578# * Combine specs for options with different names using brace expansion579# * In combined specs, list the short option first (as in `{-a,--text}`)580# * Use `+` or `=` as described above for options that take arguments581# * Provide a description for all options, option-arguments, and operands582# * Capitalise/punctuate argument descriptions as phrases, not complete583# sentences — 'display help information', never 'Display help information.'584# (but still capitalise acronyms and proper names)585# * Write argument descriptions as verb phrases — 'display x', 'enable y',586# 'use z'587# * Word descriptions to make it clear when an option expects an argument;588# usually this is done with the word 'specify', as in 'specify x' or589# 'use specified x')590# * Write argument descriptions as tersely as possible — for example, articles591# like 'a' and 'the' should be omitted unless it would be confusing592#593# Other conventions currently used by this function:594#595# * Order argument specs alphabetically by group name, then option name596# * Group options that are directly related, mutually exclusive, or frequently597# referenced by other argument specs598# * Use only characters in the set [a-z0-9_-] in group names599# * Order exclusion lists as follows: short options, long options, groups600# * Use American English in descriptions601# * Use 'don't' in descriptions instead of 'do not'602# * Word descriptions for related options as similarly as possible. For example,603# `--foo[enable foo]` and `--no-foo[disable foo]`, or `--foo[use foo]` and604# `--no-foo[don't use foo]`605# * Word descriptions to make it clear when an option only makes sense with606# another option, usually by adding '(with -x)' to the end607# * Don't quote strings or variables unnecessarily. When quotes are required,608# prefer single-quotes to double-quotes609# * Prefix option specs with `$no` when the option serves only to negate the610# behaviour of another option that must be provided explicitly by the user.611# This prevents rarely used options from cluttering up the completion menu612################################################################################613614# ------------------------------------------------------------------------------615# Copyright (c) 2011 Github zsh-users - http://github.com/zsh-users616# All rights reserved.617#618# Redistribution and use in source and binary forms, with or without619# modification, are permitted provided that the following conditions are met:620# * Redistributions of source code must retain the above copyright621# notice, this list of conditions and the following disclaimer.622# * Redistributions in binary form must reproduce the above copyright623# notice, this list of conditions and the following disclaimer in the624# documentation and/or other materials provided with the distribution.625# * Neither the name of the zsh-users nor the626# names of its contributors may be used to endorse or promote products627# derived from this software without specific prior written permission.628#629# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND630# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED631# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE632# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY633# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES634# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;635# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND636# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT637# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS638# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.639# ------------------------------------------------------------------------------640# Description641# -----------642#643# Completion script for ripgrep644#645# ------------------------------------------------------------------------------646# Authors647# -------648#649# * arcizan <ghostrevery@gmail.com>650# * MaskRay <i@maskray.me>651#652# ------------------------------------------------------------------------------653654# Local Variables:655# mode: shell-script656# coding: utf-8-unix657# indent-tabs-mode: nil658# sh-indentation: 2659# sh-basic-offset: 2660# End:661# vim: ft=zsh sw=2 ts=2 et
added:crates/core/flags/complete/zsh.rs+23 added
1/*!2Provides completions for ripgrep's CLI for the zsh shell.34Unlike completion short for other shells (at time of writing), zsh's5completions for ripgrep are maintained by hand. This is because:671. They are lovingly written by an expert in such things.82. Are much higher in quality than the ones below that are auto-generated.9Namely, the zsh completions take application level context about flag10compatibility into account.113. There is a CI script that fails if a new flag is added to ripgrep that12isn't included in the zsh completions.134. There is a wealth of documentation in the zsh script explaining how it14works and how it can be extended.1516In principle, I'd be open to maintaining any completion script by hand so17long as it meets criteria 3 and 4 above.18*/1920/// Generate completions for zsh.21pub(crate) fn generate() -> String {22 include_str!("rg.zsh").to_string()23}
added:crates/core/flags/doc/help.rs+259 added
1/*!2Provides routines for generating ripgrep's "short" and "long" help3documentation.45The short version is used when the `-h` flag is given, while the long version6is used when the `--help` flag is given.7*/89use std::{collections::BTreeMap, fmt::Write};1011use crate::flags::{defs::FLAGS, doc::version, Category, Flag};1213const TEMPLATE_SHORT: &'static str = include_str!("template.short.help");14const TEMPLATE_LONG: &'static str = include_str!("template.long.help");1516/// Wraps `std::write!` and asserts there is no failure.17///18/// We only write to `String` in this module.19macro_rules! write {20 ($($tt:tt)*) => { std::write!($($tt)*).unwrap(); }21}2223/// Generate short documentation, i.e., for `-h`.24pub(crate) fn generate_short() -> String {25 let mut cats: BTreeMap<Category, (Vec<String>, Vec<String>)> =26 BTreeMap::new();27 let (mut maxcol1, mut maxcol2) = (0, 0);28 for flag in FLAGS.iter().copied() {29 let columns =30 cats.entry(flag.doc_category()).or_insert((vec![], vec![]));31 let (col1, col2) = generate_short_flag(flag);32 maxcol1 = maxcol1.max(col1.len());33 maxcol2 = maxcol2.max(col2.len());34 columns.0.push(col1);35 columns.1.push(col2);36 }37 let mut out =38 TEMPLATE_SHORT.replace("!!VERSION!!", &version::generate_digits());39 for (cat, (col1, col2)) in cats.iter() {40 let var = format!("!!{name}!!", name = cat.as_str());41 let val = format_short_columns(col1, col2, maxcol1, maxcol2);42 out = out.replace(&var, &val);43 }44 out45}4647/// Generate short for a single flag.48///49/// The first element corresponds to the flag name while the second element50/// corresponds to the documentation string.51fn generate_short_flag(flag: &dyn Flag) -> (String, String) {52 let (mut col1, mut col2) = (String::new(), String::new());5354 // Some of the variable names are fine for longer form55 // docs, but they make the succinct short help very noisy.56 // So just shorten some of them.57 let var = flag.doc_variable().map(|s| {58 let mut s = s.to_string();59 s = s.replace("SEPARATOR", "SEP");60 s = s.replace("REPLACEMENT", "TEXT");61 s = s.replace("NUM+SUFFIX?", "NUM");62 s63 });6465 // Generate the first column, the flag name.66 if let Some(byte) = flag.name_short() {67 let name = char::from(byte);68 write!(col1, r"-{name}");69 write!(col1, r", ");70 }71 write!(col1, r"--{name}", name = flag.name_long());72 if let Some(var) = var.as_ref() {73 write!(col1, r"={var}");74 }7576 // And now the second column, with the description.77 write!(col2, "{}", flag.doc_short());7879 (col1, col2)80}8182/// Write two columns of documentation.83///84/// `maxcol1` should be the maximum length (in bytes) of the first column,85/// while `maxcol2` should be the maximum length (in bytes) of the second86/// column.87fn format_short_columns(88 col1: &[String],89 col2: &[String],90 maxcol1: usize,91 _maxcol2: usize,92) -> String {93 assert_eq!(col1.len(), col2.len(), "columns must have equal length");94 const PAD: usize = 2;95 let mut out = String::new();96 for (i, (c1, c2)) in col1.iter().zip(col2.iter()).enumerate() {97 if i > 0 {98 write!(out, "\n");99 }100101 let pad = maxcol1 - c1.len() + PAD;102 write!(out, " ");103 write!(out, "{c1}");104 write!(out, "{}", " ".repeat(pad));105 write!(out, "{c2}");106 }107 out108}109110/// Generate long documentation, i.e., for `--help`.111pub(crate) fn generate_long() -> String {112 let mut cats = BTreeMap::new();113 for flag in FLAGS.iter().copied() {114 let mut cat = cats.entry(flag.doc_category()).or_insert(String::new());115 if !cat.is_empty() {116 write!(cat, "\n\n");117 }118 generate_long_flag(flag, &mut cat);119 }120121 let mut out =122 TEMPLATE_LONG.replace("!!VERSION!!", &version::generate_digits());123 for (cat, value) in cats.iter() {124 let var = format!("!!{name}!!", name = cat.as_str());125 out = out.replace(&var, value);126 }127 out128}129130/// Write generated documentation for `flag` to `out`.131fn generate_long_flag(flag: &dyn Flag, out: &mut String) {132 if let Some(byte) = flag.name_short() {133 let name = char::from(byte);134 write!(out, r" -{name}");135 if let Some(var) = flag.doc_variable() {136 write!(out, r" {var}");137 }138 write!(out, r", ");139 } else {140 write!(out, r" ");141 }142143 let name = flag.name_long();144 write!(out, r"--{name}");145 if let Some(var) = flag.doc_variable() {146 write!(out, r"={var}");147 }148 write!(out, "\n");149150 let doc = flag.doc_long().trim();151 let doc = super::render_custom_markup(doc, "flag", |name, out| {152 let Some(flag) = crate::flags::parse::lookup(name) else {153 unreachable!(r"found unrecognized \flag{{{name}}} in --help docs")154 };155 if let Some(name) = flag.name_short() {156 write!(out, r"-{}/", char::from(name));157 }158 write!(out, r"--{}", flag.name_long());159 });160 let doc = super::render_custom_markup(&doc, "flag-negate", |name, out| {161 let Some(flag) = crate::flags::parse::lookup(name) else {162 unreachable!(163 r"found unrecognized \flag-negate{{{name}}} in --help docs"164 )165 };166 let Some(name) = flag.name_negated() else {167 let long = flag.name_long();168 unreachable!(169 "found \\flag-negate{{{long}}} in --help docs but \170 {long} does not have a negation"171 );172 };173 write!(out, r"--{name}");174 });175176 let mut cleaned = remove_roff(&doc);177 if let Some(negated) = flag.name_negated() {178 // Flags that can be negated that aren't switches, like179 // --context-separator, are somewhat weird. Because of that, the docs180 // for those flags should discuss the semantics of negation explicitly.181 // But for switches, the behavior is always the same.182 if flag.is_switch() {183 write!(cleaned, "\n\nThis flag can be disabled with --{negated}.");184 }185 }186 let indent = " ".repeat(8);187 let wrapopts = textwrap::Options::new(71)188 // Normally I'd be fine with breaking at hyphens, but ripgrep's docs189 // includes a lot of flag names, and they in turn contain hyphens.190 // Breaking flag names across lines is not great.191 .word_splitter(textwrap::WordSplitter::NoHyphenation);192 for (i, paragraph) in cleaned.split("\n\n").enumerate() {193 if i > 0 {194 write!(out, "\n\n");195 }196 let mut new = paragraph.to_string();197 if paragraph.lines().all(|line| line.starts_with(" ")) {198 // Re-indent but don't refill so as to preserve line breaks199 // in code/shell example snippets.200 new = textwrap::indent(&new, &indent);201 } else {202 new = new.replace("\n", " ");203 new = textwrap::refill(&new, &wrapopts);204 new = textwrap::indent(&new, &indent);205 }206 write!(out, "{}", new.trim_end());207 }208}209210/// Removes roff syntax from `v` such that the result is approximately plain211/// text readable.212///213/// This is basically a mish mash of heuristics based on the specific roff used214/// in the docs for the flags in this tool. If new kinds of roff are used in215/// the docs, then this may need to be updated to handle them.216fn remove_roff(v: &str) -> String {217 let mut lines = vec![];218 for line in v.trim().lines() {219 assert!(!line.is_empty(), "roff should have no empty lines");220 if line.starts_with(".") {221 if line.starts_with(".IP ") {222 let item_label = line223 .split(" ")224 .nth(1)225 .expect("first argument to .IP")226 .replace(r"\(bu", r"•")227 .replace(r"\fB", "")228 .replace(r"\fP", ":");229 lines.push(format!("{item_label}"));230 } else if line.starts_with(".IB ") || line.starts_with(".BI ") {231 let pieces = line232 .split_whitespace()233 .skip(1)234 .collect::<Vec<_>>()235 .concat();236 lines.push(format!("{pieces}"));237 } else if line.starts_with(".sp")238 || line.starts_with(".PP")239 || line.starts_with(".TP")240 {241 lines.push("".to_string());242 }243 } else if line.starts_with(r"\fB") && line.ends_with(r"\fP") {244 let line = line.replace(r"\fB", "").replace(r"\fP", "");245 lines.push(format!("{line}:"));246 } else {247 lines.push(line.to_string());248 }249 }250 // Squash multiple adjacent paragraph breaks into one.251 lines.dedup_by(|l1, l2| l1.is_empty() && l2.is_empty());252 lines253 .join("\n")254 .replace(r"\fB", "")255 .replace(r"\fI", "")256 .replace(r"\fP", "")257 .replace(r"\-", "-")258 .replace(r"\\", r"\")259}
added:crates/core/flags/doc/man.rs+110 added
1/*!2Provides routines for generating ripgrep's man page in `roff` format.3*/45use std::{collections::BTreeMap, fmt::Write};67use crate::flags::{defs::FLAGS, doc::version, Flag};89const TEMPLATE: &'static str = include_str!("template.rg.1");1011/// Wraps `std::write!` and asserts there is no failure.12///13/// We only write to `String` in this module.14macro_rules! write {15 ($($tt:tt)*) => { std::write!($($tt)*).unwrap(); }16}1718/// Wraps `std::writeln!` and asserts there is no failure.19///20/// We only write to `String` in this module.21macro_rules! writeln {22 ($($tt:tt)*) => { std::writeln!($($tt)*).unwrap(); }23}2425/// Returns a `roff` formatted string corresponding to ripgrep's entire man26/// page.27pub(crate) fn generate() -> String {28 let mut cats = BTreeMap::new();29 for flag in FLAGS.iter().copied() {30 let mut cat = cats.entry(flag.doc_category()).or_insert(String::new());31 if !cat.is_empty() {32 writeln!(cat, ".sp");33 }34 generate_flag(flag, &mut cat);35 }3637 let mut out = TEMPLATE.replace("!!VERSION!!", &version::generate_digits());38 for (cat, value) in cats.iter() {39 let var = format!("!!{name}!!", name = cat.as_str());40 out = out.replace(&var, value);41 }42 out43}4445/// Writes `roff` formatted documentation for `flag` to `out`.46fn generate_flag(flag: &'static dyn Flag, out: &mut String) {47 if let Some(byte) = flag.name_short() {48 let name = char::from(byte);49 write!(out, r"\fB\-{name}\fP");50 if let Some(var) = flag.doc_variable() {51 write!(out, r" \fI{var}\fP");52 }53 write!(out, r", ");54 }5556 let name = flag.name_long();57 write!(out, r"\fB\-\-{name}\fP");58 if let Some(var) = flag.doc_variable() {59 write!(out, r"=\fI{var}\fP");60 }61 write!(out, "\n");6263 writeln!(out, ".RS 4");64 let doc = flag.doc_long().trim();65 // Convert \flag{foo} into something nicer.66 let doc = super::render_custom_markup(doc, "flag", |name, out| {67 let Some(flag) = crate::flags::parse::lookup(name) else {68 unreachable!(r"found unrecognized \flag{{{name}}} in roff docs")69 };70 out.push_str(r"\fB");71 if let Some(name) = flag.name_short() {72 write!(out, r"\-{}/", char::from(name));73 }74 write!(out, r"\-\-{}", flag.name_long());75 out.push_str(r"\fP");76 });77 // Convert \flag-negate{foo} into something nicer.78 let doc = super::render_custom_markup(&doc, "flag-negate", |name, out| {79 let Some(flag) = crate::flags::parse::lookup(name) else {80 unreachable!(81 r"found unrecognized \flag-negate{{{name}}} in roff docs"82 )83 };84 let Some(name) = flag.name_negated() else {85 let long = flag.name_long();86 unreachable!(87 "found \\flag-negate{{{long}}} in roff docs but \88 {long} does not have a negation"89 );90 };91 out.push_str(r"\fB");92 write!(out, r"\-\-{name}");93 out.push_str(r"\fP");94 });95 writeln!(out, "{doc}");96 if let Some(negated) = flag.name_negated() {97 // Flags that can be negated that aren't switches, like98 // --context-separator, are somewhat weird. Because of that, the docs99 // for those flags should discuss the semantics of negation explicitly.100 // But for switches, the behavior is always the same.101 if flag.is_switch() {102 writeln!(out, ".sp");103 writeln!(104 out,105 r"This flag can be disabled with \fB\-\-{negated}\fP."106 );107 }108 }109 writeln!(out, ".RE");110}
added:crates/core/flags/doc/mod.rs+38 added
1/*!2Modules for generating documentation for ripgrep's flags.3*/45pub(crate) mod help;6pub(crate) mod man;7pub(crate) mod version;89/// Searches for `\tag{...}` occurrences in `doc` and calls `replacement` for10/// each such tag found.11///12/// The first argument given to `replacement` is the tag value, `...`. The13/// second argument is the buffer that accumulates the full replacement text.14///15/// Since this function is only intended to be used on doc strings written into16/// the program source code, callers should panic in `replacement` if there are17/// any errors or unexpected circumstances.18fn render_custom_markup(19 mut doc: &str,20 tag: &str,21 mut replacement: impl FnMut(&str, &mut String),22) -> String {23 let mut out = String::with_capacity(doc.len());24 let tag_prefix = format!(r"\{tag}{{");25 while let Some(offset) = doc.find(&tag_prefix) {26 out.push_str(&doc[..offset]);2728 let start = offset + tag_prefix.len();29 let Some(end) = doc[start..].find('}').map(|i| start + i) else {30 unreachable!(r"found {tag_prefix} without closing }}");31 };32 let name = &doc[start..end];33 replacement(name, &mut out);34 doc = &doc[end + 1..];35 }36 out.push_str(doc);37 out38}
added:crates/core/flags/doc/template.long.help+61 added
1ripgrep !!VERSION!!2Andrew Gallant <jamslam@gmail.com>34ripgrep (rg) recursively searches the current directory for a regex pattern.5By default, ripgrep will respect gitignore rules and automatically skip hidden6files/directories and binary files.78Use -h for short descriptions and --help for more details.910Project home page: https://github.com/BurntSushi/ripgrep1112USAGE:13 rg [OPTIONS] PATTERN [PATH ...]14 rg [OPTIONS] -e PATTERN ... [PATH ...]15 rg [OPTIONS] -f PATTERNFILE ... [PATH ...]16 rg [OPTIONS] --files [PATH ...]17 rg [OPTIONS] --type-list18 command | rg [OPTIONS] PATTERN19 rg [OPTIONS] --help20 rg [OPTIONS] --version2122POSITIONAL ARGUMENTS:23 <PATTERN>24 A regular expression used for searching. To match a pattern beginning25 with a dash, use the -e/--regexp flag.2627 For example, to search for the literal '-foo', you can use this flag:2829 rg -e -foo3031 You can also use the special '--' delimiter to indicate that no more32 flags will be provided. Namely, the following is equivalent to the33 above:3435 rg -- -foo3637 <PATH>...38 A file or directory to search. Directories are searched recursively.39 File paths specified on the command line override glob and ignore40 rules.4142INPUT OPTIONS:43!!input!!4445SEARCH OPTIONS:46!!search!!4748FILTER OPTIONS:49!!filter!!5051OUTPUT OPTIONS:52!!output!!5354OUTPUT MODES:55!!output-modes!!5657LOGGING OPTIONS:58!!logging!!5960OTHER BEHAVIORS:61!!other-behaviors!!
added:crates/core/flags/doc/template.rg.1+415 added
1.TH RG 1 2023-11-13 "!!VERSION!!" "User Commands"2.3.4.SH NAME5rg \- recursively search the current directory for lines matching a pattern6.7.8.SH SYNOPSIS9.\" I considered using GNU troff's .SY and .YS "synopsis" macros here, but it10.\" looks like they aren't portable. Specifically, they don't appear to be in11.\" BSD's mdoc used on macOS.12.sp13\fBrg\fP [\fIOPTIONS\fP] \fIPATTERN\fP [\fIPATH\fP...]14.sp15\fBrg\fP [\fIOPTIONS\fP] \fB\-e\fP \fIPATTERN\fP... [\fIPATH\fP...]16.sp17\fBrg\fP [\fIOPTIONS\fP] \fB\-f\fP \fIPATTERNFILE\fP... [\fIPATH\fP...]18.sp19\fBrg\fP [\fIOPTIONS\fP] \fB\-\-files\fP [\fIPATH\fP...]20.sp21\fBrg\fP [\fIOPTIONS\fP] \fB\-\-type\-list\fP22.sp23\fIcommand\fP | \fBrg\fP [\fIOPTIONS\fP] \fIPATTERN\fP24.sp25\fBrg\fP [\fIOPTIONS\fP] \fB\-\-help\fP26.sp27\fBrg\fP [\fIOPTIONS\fP] \fB\-\-version\fP28.29.30.SH DESCRIPTION31ripgrep (rg) recursively searches the current directory for a regex pattern.32By default, ripgrep will respect your \fB.gitignore\fP and automatically skip33hidden files/directories and binary files.34.sp35ripgrep's default regex engine uses finite automata and guarantees linear36time searching. Because of this, features like backreferences and arbitrary37look-around are not supported. However, if ripgrep is built with PCRE2,38then the \fB\-P/\-\-pcre2\fP flag can be used to enable backreferences and39look-around.40.sp41ripgrep supports configuration files. Set \fBRIPGREP_CONFIG_PATH\fP to a42configuration file. The file can specify one shell argument per line. Lines43starting with \fB#\fP are ignored. For more details, see \fBCONFIGURATION44FILES\fP below.45.sp46ripgrep will automatically detect if stdin exists and search stdin for a regex47pattern, e.g. \fBls | rg foo\fP. In some environments, stdin may exist when48it shouldn't. To turn off stdin detection, one can explicitly specify the49directory to search, e.g. \fBrg foo ./\fP.50.sp51Tip: to disable all smart filtering and make ripgrep behave a bit more like52classical grep, use \fBrg -uuu\fP.53.54.55.SH REGEX SYNTAX56ripgrep uses Rust's regex engine by default, which documents its syntax:57\fIhttps://docs.rs/regex/1.*/regex/#syntax\fP58.sp59ripgrep uses byte-oriented regexes, which has some additional documentation:60\fIhttps://docs.rs/regex/1.*/regex/bytes/index.html#syntax\fP61.sp62To a first approximation, ripgrep uses Perl-like regexes without look-around or63backreferences. This makes them very similar to the "extended" (ERE) regular64expressions supported by *egrep*, but with a few additional features like65Unicode character classes.66.sp67If you're using ripgrep with the \fB\-P/\-\-pcre2\fP flag, then please consult68\fIhttps://www.pcre.org\fP or the PCRE2 man pages for documentation on the69supported syntax.70.71.72.SH POSITIONAL ARGUMENTS73.TP 1274\fIPATTERN\fP75A regular expression used for searching. To match a pattern beginning with a76dash, use the \fB\-e/\-\-regexp\fP option.77.TP 1278\fIPATH\fP79A file or directory to search. Directories are searched recursively. File paths80specified explicitly on the command line override glob and ignore rules.81.82.83.SH OPTIONS84This section documents all flags that ripgrep accepts. Flags are grouped into85categories below according to their function.86.sp87Note that many options can be turned on and off. In some cases, those flags are88not listed explicitly below. For example, the \fB\-\-column\fP flag (listed89below) enables column numbers in ripgrep's output, but the \fB\-\-no\-column\fP90flag (not listed below) disables them. The reverse can also exist. For example,91the \fB\-\-no\-ignore\fP flag (listed below) disables ripgrep's \fBgitignore\fP92logic, but the \fB\-\-ignore\fP flag (not listed below) enables it. These93flags are useful for overriding a ripgrep configuration file (or alias) on the94command line. Each flag's documentation notes whether an inverted flag exists.95In all cases, the flag specified last takes precedence.96.97.SS INPUT OPTIONS98!!input!!99.100.SS SEARCH OPTIONS101!!search!!102.103.SS FILTER OPTIONS104!!filter!!105.106.SS OUTPUT OPTIONS107!!output!!108.109.SS OUTPUT MODES110!!output-modes!!111.112.SS LOGGING OPTIONS113!!logging!!114.115.SS OTHER BEHAVIORS116!!other-behaviors!!117.118.119.SH EXIT STATUS120If ripgrep finds a match, then the exit status of the program is \fB0\fP.121If no match could be found, then the exit status is \fB1\fP. If an error122occurred, then the exit status is always \fB2\fP unless ripgrep was run with123the \fB\-q/\-\-quiet\fP flag and a match was found. In summary:124.sp125.IP \(bu 3n126\fB0\fP exit status occurs only when at least one match was found, and if127no error occurred, unless \fB\-q/\-\-quiet\fP was given.128.129.IP \(bu 3n130\fB1\fP exit status occurs only when no match was found and no error occurred.131.132.IP \(bu 3n133\fB2\fP exit status occurs when an error occurred. This is true for both134catastrophic errors (e.g., a regex syntax error) and for soft errors (e.g.,135unable to read a file).136.137.138.SH AUTOMATIC FILTERING139ripgrep does a fair bit of automatic filtering by default. This section140describes that filtering and how to control it.141.sp142\fBTIP\fP: To disable automatic filtering, use \fBrg -uuu\fP.143.sp144ripgrep's automatic "smart" filtering is one of the most apparent145differentiating features between ripgrep and other tools like \fBgrep\fP. As146such, its behavior may be surprising to users that aren't expecting it.147.sp148ripgrep does four types of filtering automatically:149.sp150.151.IP 1. 3n152Files and directories that match ignore rules are not searched.153.IP 2. 3n154Hidden files and directories are not searched.155.IP 3. 3n156Binary files (files with a \fBNUL\fP byte) are not searched.157.IP 4. 3n158Symbolic links are not followed.159.PP160The first type of filtering is the most sophisticated. ripgrep will attempt to161respect your \fBgitignore\fP rules as faithfully as possible. In particular,162this includes the following:163.164.IP \(bu 3n165Any global rules, e.g., in \fB$HOME/.config/git/ignore\fP.166.167.IP \(bu 3n168Any rules in relevant \fB.gitignore\fP files.169.170.IP \(bu 3n171Any local rules, e.g., in \fB.git/info/exclude\fP.172.PP173In some cases, ripgrep and \fBgit\fP will not always be in sync in terms174of which files are ignored. For example, a file that is ignored via175\fB.gitignore\fP but is tracked by \fBgit\fP would not be searched by ripgrep176even though \fBgit\fP tracks it. This is unlikely to ever be fixed. Instead,177you should either make sure your exclude rules match the files you track178precisely, or otherwise use \fBgit grep\fP for search.179.sp180Additional ignore rules can be provided outside of a \fBgit\fP context:181.182.IP \(bu 3n183Any rules in \fB.ignore\fP.184.185.IP \(bu 3n186Any rules in \fB.rgignore\fP.187.188.IP \(bu 3n189Any rules in files specified with the \fB\-\-ignore\-file\fP flag.190.PP191The precedence of ignore rules is as follows, with later items overriding192earlier items:193.194.IP \(bu 3n195Files given by \fB\-\-ignore\-file\fP.196.197.IP \(bu 3n198Global gitignore rules, e.g., from \fB$HOME/.config/git/ignore\fP.199.200.IP \(bu 3n201Local rules from \fB.git/info/exclude\fP.202.203.IP \(bu 3n204Rules from \fB.gitignore\fP.205.206.IP \(bu 3n207Rules from \fB.ignore\fP.208.209.IP \(bu 3n210Rules from \fB.rgignore\fP.211.PP212So for example, if \fIfoo\fP were in a \fB.gitignore\fP and \fB!\fP\fIfoo\fP213were in an \fB.rgignore\fP, then \fIfoo\fP would not be ignored since214\fB.rgignore\fP takes precedence over \fB.gitignore\fP.215.sp216Each of the types of filtering can be configured via command line flags:217.218.IP \(bu 3n219There are several flags starting with \fB\-\-no\-ignore\fP that toggle which,220if any, ignore rules are respected. \fB\-\-no\-ignore\fP by itself will disable221all222of them.223.224.IP \(bu 3n225\fB\-./\-\-hidden\fP will force ripgrep to search hidden files and directories.226.227.IP \(bu 3n228\fB\-\-binary\fP will force ripgrep to search binary files.229.230.IP \(bu 3n231\fB\-L/\-\-follow\fP will force ripgrep to follow symlinks.232.PP233As a special short hand, the \fB\-u\fP flag can be specified up to three times.234Each additional time incrementally decreases filtering:235.236.IP \(bu 3n237\fB\-u\fP is equivalent to \fB\-\-no\-ignore\fP.238.239.IP \(bu 3n240\fB\-uu\fP is equivalent to \fB\-\-no\-ignore \-\-hidden\fP.241.242.IP \(bu 3n243\fB\-uuu\fP is equivalent to \fB\-\-no\-ignore \-\-hidden \-\-binary\fP.244.PP245In particular, \fBrg -uuu\fP should search the same exact content as \fBgrep246-r\fP.247.248.249.SH CONFIGURATION FILES250ripgrep supports reading configuration files that change ripgrep's default251behavior. The format of the configuration file is an "rc" style and is very252simple. It is defined by two rules:253.254.IP 1. 3n255Every line is a shell argument, after trimming whitespace.256.257.IP 2. 3n258Lines starting with \fB#\fP (optionally preceded by any amount of whitespace)259are ignored.260.PP261ripgrep will look for a single configuration file if and only if the262\fBRIPGREP_CONFIG_PATH\fP environment variable is set and is non-empty.263ripgrep will parse arguments from this file on startup and will behave as if264the arguments in this file were prepended to any explicit arguments given to265ripgrep on the command line. Note though that the \fBrg\fP command you run266must still be valid. That is, it must always contain at least one pattern at267the command line, even if the configuration file uses the \fB\-e/\-\-regexp\fP268flag.269.sp270For example, if your ripgreprc file contained a single line:271.sp272.EX273 \-\-smart\-case274.EE275.sp276then the following command277.sp278.EX279 RIPGREP_CONFIG_PATH=wherever/.ripgreprc rg foo280.EE281.sp282would behave identically to the following command:283.sp284.EX285 rg \-\-smart-case foo286.EE287.sp288Another example is adding types, like so:289.sp290.EX291 \-\-type-add292 web:*.{html,css,js}*293.EE294.sp295The above would behave identically to the following command:296.sp297.EX298 rg \-\-type\-add 'web:*.{html,css,js}*' foo299.EE300.sp301The same applies to using globs. This:302.sp303.EX304 \-\-glob=!.git305.EE306.sp307or this:308.sp309.EX310 \-\-glob311 !.git312.EE313.sp314would behave identically to the following command:315.sp316.EX317 rg \-\-glob '!.git' foo318.EE319.sp320The bottom line is that every shell argument needs to be on its own line. So321for example, a config file containing322.sp323.EX324 \-j 4325.EE326.sp327is probably not doing what you intend. Instead, you want328.sp329.EX330 \-j331 4332.EE333.sp334or335.sp336.EX337 \-j4338.EE339.sp340ripgrep also provides a flag, \fB\-\-no\-config\fP, that when present will341suppress any and all support for configuration. This includes any future342support for auto-loading configuration files from pre-determined paths.343.sp344Conflicts between configuration files and explicit arguments are handled345exactly like conflicts in the same command line invocation. That is, assuming346your config file contains only \fB\-\-smart\-case\fP, then this command:347.sp348.EX349 RIPGREP_CONFIG_PATH=wherever/.ripgreprc rg foo \-\-case\-sensitive350.EE351.sp352is exactly equivalent to353.sp354.EX355 rg \-\-smart\-case foo \-\-case\-sensitive356.EE357.sp358in which case, the \fB\-\-case\-sensitive\fP flag would override the359\fB\-\-smart\-case\fP flag.360.361.362.SH SHELL COMPLETION363Shell completion files are included in the release tarball for Bash, Fish, Zsh364and PowerShell.365.sp366For \fBbash\fP, move \fBrg.bash\fP to \fB$XDG_CONFIG_HOME/bash_completion\fP or367\fB/etc/bash_completion.d/\fP.368.sp369For \fBfish\fP, move \fBrg.fish\fP to \fB$HOME/.config/fish/completions\fP.370.sp371For \fBzsh\fP, move \fB_rg\fP to one of your \fB$fpath\fP directories.372.373.374.SH CAVEATS375ripgrep may abort unexpectedly when using default settings if it searches a376file that is simultaneously truncated. This behavior can be avoided by passing377the \fB\-\-no\-mmap\fP flag which will forcefully disable the use of memory378maps in all cases.379.sp380ripgrep may use a large amount of memory depending on a few factors. Firstly,381if ripgrep uses parallelism for search (the default), then the entire382output for each individual file is buffered into memory in order to prevent383interleaving matches in the output. To avoid this, you can disable parallelism384with the \fB\-j1\fP flag. Secondly, ripgrep always needs to have at least a385single line in memory in order to execute a search. A file with a very long386line can thus cause ripgrep to use a lot of memory. Generally, this only occurs387when searching binary data with the \fB\-a/\-\-text\fP flag enabled. (When the388\fB\-a/\-\-text\fP flag isn't enabled, ripgrep will replace all NUL bytes with389line terminators, which typically prevents exorbitant memory usage.) Thirdly,390when ripgrep searches a large file using a memory map, the process will likely391report its resident memory usage as the size of the file. However, this does392not mean ripgrep actually needed to use that much heap memory; the operating393system will generally handle this for you.394.395.396.SH VERSION397!!VERSION!!398.399.400.SH HOMEPAGE401\fIhttps://github.com/BurntSushi/ripgrep\fP402.sp403Please report bugs and feature requests to the issue tracker. Please do your404best to provide a reproducible test case for bugs. This should include the405corpus being searched, the \fBrg\fP command, the actual output and the expected406output. Please also include the output of running the same \fBrg\fP command but407with the \fB\-\-debug\fP flag.408.sp409If you have questions that don't obviously fall into the "bug" or "feature410request" category, then they are welcome in the Discussions section of the411issue tracker: \fIhttps://github.com/BurntSushi/ripgrep/discussions\fP.412.413.414.SH AUTHORS415Andrew Gallant <\fIjamslam@gmail.com\fP>
added:crates/core/flags/doc/template.short.help+38 added
1ripgrep !!VERSION!!2Andrew Gallant <jamslam@gmail.com>34ripgrep (rg) recursively searches the current directory for a regex pattern.5By default, ripgrep will respect gitignore rules and automatically skip hidden6files/directories and binary files.78Use -h for short descriptions and --help for more details.910Project home page: https://github.com/BurntSushi/ripgrep1112USAGE:13 rg [OPTIONS] PATTERN [PATH ...]1415POSITIONAL ARGUMENTS:16 <PATTERN> A regular expression used for searching.17 <PATH>... A file or directory to search.1819INPUT OPTIONS:20!!input!!2122SEARCH OPTIONS:23!!search!!2425FILTER OPTIONS:26!!filter!!2728OUTPUT OPTIONS:29!!output!!3031OUTPUT MODES:32!!output-modes!!3334LOGGING OPTIONS:35!!logging!!3637OTHER BEHAVIORS:38!!other-behaviors!!
added:crates/core/flags/doc/version.rs+148 added
1/*!2Provides routines for generating version strings.34Version strings can be just the digits, an overall short one-line description5or something more verbose that includes things like CPU target feature support.6*/78use std::fmt::Write;910/// Generates just the numerical part of the version of ripgrep.11///12/// This includes the git revision hash.13pub(crate) fn generate_digits() -> String {14 let semver = option_env!("CARGO_PKG_VERSION").unwrap_or("N/A");15 match option_env!("RIPGREP_BUILD_GIT_HASH") {16 None => semver.to_string(),17 Some(hash) => format!("{semver} (rev {hash})"),18 }19}2021/// Generates a short version string of the form `ripgrep x.y.z`.22pub(crate) fn generate_short() -> String {23 let digits = generate_digits();24 format!("ripgrep {digits}")25}2627/// Generates a longer multi-line version string.28///29/// This includes not only the version of ripgrep but some other information30/// about its build. For example, SIMD support and PCRE2 support.31pub(crate) fn generate_long() -> String {32 let (compile, runtime) = (compile_cpu_features(), runtime_cpu_features());3334 let mut out = String::new();35 writeln!(out, "{}", generate_short()).unwrap();36 writeln!(out, "features:{}", features().join(",")).unwrap();37 if !compile.is_empty() {38 writeln!(out, "simd(compile):{}", compile.join(",")).unwrap();39 }40 if !runtime.is_empty() {41 writeln!(out, "simd(runtime):{}", runtime.join(",")).unwrap();42 }43 out44}4546/// Returns the relevant SIMD features supported by the CPU at runtime.47///48/// This is kind of a dirty violation of abstraction, since it assumes49/// knowledge about what specific SIMD features are being used by various50/// components.51fn runtime_cpu_features() -> Vec<String> {52 #[cfg(target_arch = "x86_64")]53 {54 let mut features = vec![];5556 let sse2 = is_x86_feature_detected!("sse2");57 features.push(format!("{sign}SSE2", sign = sign(sse2)));5859 let ssse3 = is_x86_feature_detected!("ssse3");60 features.push(format!("{sign}SSSE3", sign = sign(ssse3)));6162 let avx2 = is_x86_feature_detected!("avx2");63 features.push(format!("{sign}AVX2", sign = sign(avx2)));6465 features66 }67 #[cfg(target_arch = "aarch64")]68 {69 let mut features = vec![];7071 // memchr and aho-corasick only use NEON when it is available at72 // compile time. This isn't strictly necessary, but NEON is supposed73 // to be available for all aarch64 targets. If this isn't true, please74 // file an issue at https://github.com/BurntSushi/memchr.75 let neon = cfg!(target_feature = "neon");76 features.push(format!("{sign}NEON", sign = sign(neon)));7778 features79 }80 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]81 {82 vec![]83 }84}8586/// Returns the SIMD features supported while compiling ripgrep.87///88/// In essence, any features listed here are required to run ripgrep correctly.89///90/// This is kind of a dirty violation of abstraction, since it assumes91/// knowledge about what specific SIMD features are being used by various92/// components.93///94/// An easy way to enable everything available on your current CPU is to95/// compile ripgrep with `RUSTFLAGS="-C target-cpu=native"`. But note that96/// the binary produced by this will not be portable.97fn compile_cpu_features() -> Vec<String> {98 #[cfg(target_arch = "x86_64")]99 {100 let mut features = vec![];101102 let sse2 = cfg!(target_feature = "sse2");103 features.push(format!("{sign}SSE2", sign = sign(sse2)));104105 let ssse3 = cfg!(target_feature = "ssse3");106 features.push(format!("{sign}SSSE3", sign = sign(ssse3)));107108 let avx2 = cfg!(target_feature = "avx2");109 features.push(format!("{sign}AVX2", sign = sign(avx2)));110111 features112 }113 #[cfg(target_arch = "aarch64")]114 {115 let mut features = vec![];116117 let neon = cfg!(target_feature = "neon");118 features.push(format!("{sign}NEON", sign = sign(neon)));119120 features121 }122 #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]123 {124 vec![]125 }126}127128/// Returns a list of "features" supported (or not) by this build of ripgrpe.129fn features() -> Vec<String> {130 let mut features = vec![];131132 let simd_accel = cfg!(feature = "simd-accel");133 features.push(format!("{sign}simd-accel", sign = sign(simd_accel)));134135 let pcre2 = cfg!(feature = "pcre2");136 features.push(format!("{sign}pcre2", sign = sign(pcre2)));137138 features139}140141/// Returns `+` when `enabled` is `true` and `-` otherwise.142fn sign(enabled: bool) -> &'static str {143 if enabled {144 "+"145 } else {146 "-"147 }148}
added:crates/core/flags/config.rs+170 added
1/*!2This module provides routines for reading ripgrep config "rc" files.34The primary output of these routines is a sequence of arguments, where each5argument corresponds precisely to one shell argument.6*/78use std::{9 ffi::OsString,10 path::{Path, PathBuf},11};1213use bstr::{io::BufReadExt, ByteSlice};1415/// Return a sequence of arguments derived from ripgrep rc configuration files.16pub fn args() -> Vec<OsString> {17 let config_path = match std::env::var_os("RIPGREP_CONFIG_PATH") {18 None => return vec![],19 Some(config_path) => {20 if config_path.is_empty() {21 return vec![];22 }23 PathBuf::from(config_path)24 }25 };26 let (args, errs) = match parse(&config_path) {27 Ok((args, errs)) => (args, errs),28 Err(err) => {29 message!(30 "failed to read the file specified in RIPGREP_CONFIG_PATH: {}",31 err32 );33 return vec![];34 }35 };36 if !errs.is_empty() {37 for err in errs {38 message!("{}:{}", config_path.display(), err);39 }40 }41 log::debug!(42 "{}: arguments loaded from config file: {:?}",43 config_path.display(),44 args45 );46 args47}4849/// Parse a single ripgrep rc file from the given path.50///51/// On success, this returns a set of shell arguments, in order, that should52/// be pre-pended to the arguments given to ripgrep at the command line.53///54/// If the file could not be read, then an error is returned. If there was55/// a problem parsing one or more lines in the file, then errors are returned56/// for each line in addition to successfully parsed arguments.57fn parse<P: AsRef<Path>>(58 path: P,59) -> anyhow::Result<(Vec<OsString>, Vec<anyhow::Error>)> {60 let path = path.as_ref();61 match std::fs::File::open(&path) {62 Ok(file) => parse_reader(file),63 Err(err) => anyhow::bail!("{}: {}", path.display(), err),64 }65}6667/// Parse a single ripgrep rc file from the given reader.68///69/// Callers should not provided a buffered reader, as this routine will use its70/// own buffer internally.71///72/// On success, this returns a set of shell arguments, in order, that should73/// be pre-pended to the arguments given to ripgrep at the command line.74///75/// If the reader could not be read, then an error is returned. If there was a76/// problem parsing one or more lines, then errors are returned for each line77/// in addition to successfully parsed arguments.78fn parse_reader<R: std::io::Read>(79 rdr: R,80) -> anyhow::Result<(Vec<OsString>, Vec<anyhow::Error>)> {81 let mut bufrdr = std::io::BufReader::new(rdr);82 let (mut args, mut errs) = (vec![], vec![]);83 let mut line_number = 0;84 bufrdr.for_byte_line_with_terminator(|line| {85 line_number += 1;8687 let line = line.trim();88 if line.is_empty() || line[0] == b'#' {89 return Ok(true);90 }91 match line.to_os_str() {92 Ok(osstr) => {93 args.push(osstr.to_os_string());94 }95 Err(err) => {96 errs.push(anyhow::anyhow!("{line_number}: {err}"));97 }98 }99 Ok(true)100 })?;101 Ok((args, errs))102}103104#[cfg(test)]105mod tests {106 use super::parse_reader;107 use std::ffi::OsString;108109 #[test]110 fn basic() {111 let (args, errs) = parse_reader(112 &b"\113# Test114--context=0115 --smart-case116-u117118119 # --bar120--foo121"[..],122 )123 .unwrap();124 assert!(errs.is_empty());125 let args: Vec<String> =126 args.into_iter().map(|s| s.into_string().unwrap()).collect();127 assert_eq!(args, vec!["--context=0", "--smart-case", "-u", "--foo",]);128 }129130 // We test that we can handle invalid UTF-8 on Unix-like systems.131 #[test]132 #[cfg(unix)]133 fn error() {134 use std::os::unix::ffi::OsStringExt;135136 let (args, errs) = parse_reader(137 &b"\138quux139foo\xFFbar140baz141"[..],142 )143 .unwrap();144 assert!(errs.is_empty());145 assert_eq!(146 args,147 vec![148 OsString::from("quux"),149 OsString::from_vec(b"foo\xFFbar".to_vec()),150 OsString::from("baz"),151 ]152 );153 }154155 // ... but test that invalid UTF-8 fails on Windows.156 #[test]157 #[cfg(not(unix))]158 fn error() {159 let (args, errs) = parse_reader(160 &b"\161quux162foo\xFFbar163baz164"[..],165 )166 .unwrap();167 assert_eq!(errs.len(), 1);168 assert_eq!(args, vec![OsString::from("quux"), OsString::from("baz"),]);169 }170}
added:crates/core/flags/defs.rs+7625 added
1/*!2Defines all of the flags available in ripgrep.34Each flag corresponds to a unit struct with a corresponding implementation5of `Flag`. Note that each implementation of `Flag` might actually have many6possible manifestations of the same "flag." That is, each implementation of7`Flag` can have the following flags available to an end user of ripgrep:89* The long flag name.10* An optional short flag name.11* An optional negated long flag name.12* An arbitrarily long list of aliases.1314The idea is that even though there are multiple flags that a user can type,15one implementation of `Flag` corresponds to a single _logical_ flag inside of16ripgrep. For example, `-E`, `--encoding` and `--no-encoding` all manipulate the17same encoding state in ripgrep.18*/1920use std::path::PathBuf;2122use {anyhow::Context as AnyhowContext, bstr::ByteVec};2324use crate::flags::{25 lowargs::{26 BinaryMode, BoundaryMode, BufferMode, CaseMode, ColorChoice,27 ContextMode, EncodingMode, EngineChoice, GenerateMode, LoggingMode,28 LowArgs, MmapMode, Mode, PatternSource, SearchMode, SortMode,29 SortModeKind, SpecialMode, TypeChange,30 },31 Category, Flag, FlagValue,32};3334#[cfg(test)]35use crate::flags::parse::parse_low_raw;3637/// A list of all flags in ripgrep via implementations of `Flag`.38///39/// The order of these flags matter. It determines the order of the flags in40/// the generated documentation (`-h`, `--help` and the man page) within each41/// category. (This is why the deprecated flags are last.)42pub(super) const FLAGS: &[&dyn Flag] = &[43 // -e/--regexp and -f/--file should come before anything else in the44 // same category.45 &Regexp,46 &File,47 &AfterContext,48 &BeforeContext,49 &Binary,50 &BlockBuffered,51 &ByteOffset,52 &CaseSensitive,53 &Color,54 &Colors,55 &Column,56 &Context,57 &ContextSeparator,58 &Count,59 &CountMatches,60 &Crlf,61 &Debug,62 &DfaSizeLimit,63 &Encoding,64 &Engine,65 &FieldContextSeparator,66 &FieldMatchSeparator,67 &Files,68 &FilesWithMatches,69 &FilesWithoutMatch,70 &FixedStrings,71 &Follow,72 &Generate,73 &Glob,74 &GlobCaseInsensitive,75 &Heading,76 &Help,77 &Hidden,78 &HostnameBin,79 &HyperlinkFormat,80 &IGlob,81 &IgnoreCase,82 &IgnoreFile,83 &IgnoreFileCaseInsensitive,84 &IncludeZero,85 &InvertMatch,86 &JSON,87 &LineBuffered,88 &LineNumber,89 &LineNumberNo,90 &LineRegexp,91 &MaxColumns,92 &MaxColumnsPreview,93 &MaxCount,94 &MaxDepth,95 &MaxFilesize,96 &Mmap,97 &Multiline,98 &MultilineDotall,99 &NoConfig,100 &NoIgnore,101 &NoIgnoreDot,102 &NoIgnoreExclude,103 &NoIgnoreFiles,104 &NoIgnoreGlobal,105 &NoIgnoreMessages,106 &NoIgnoreParent,107 &NoIgnoreVcs,108 &NoMessages,109 &NoRequireGit,110 &NoUnicode,111 &Null,112 &NullData,113 &OneFileSystem,114 &OnlyMatching,115 &PathSeparator,116 &Passthru,117 &PCRE2,118 &PCRE2Version,119 &Pre,120 &PreGlob,121 &Pretty,122 &Quiet,123 &RegexSizeLimit,124 &Replace,125 &SearchZip,126 &SmartCase,127 &Sort,128 &Sortr,129 &Stats,130 &StopOnNonmatch,131 &Text,132 &Threads,133 &Trace,134 &Trim,135 &Type,136 &TypeNot,137 &TypeAdd,138 &TypeClear,139 &TypeList,140 &Unrestricted,141 &Version,142 &Vimgrep,143 &WithFilename,144 &WithFilenameNo,145 &WordRegexp,146 // DEPRECATED (make them show up last in their respective categories)147 &AutoHybridRegex,148 &NoPcre2Unicode,149 &SortFiles,150];151152/// -A/--after-context153#[derive(Debug)]154struct AfterContext;155156impl Flag for AfterContext {157 fn is_switch(&self) -> bool {158 false159 }160 fn name_short(&self) -> Option<u8> {161 Some(b'A')162 }163 fn name_long(&self) -> &'static str {164 "after-context"165 }166 fn doc_variable(&self) -> Option<&'static str> {167 Some("NUM")168 }169 fn doc_category(&self) -> Category {170 Category::Output171 }172 fn doc_short(&self) -> &'static str {173 "Show NUM lines after each match."174 }175 fn doc_long(&self) -> &'static str {176 r"177Show \fINUM\fP lines after each match.178.sp179This overrides the \flag{passthru} flag and partially overrides the180\flag{context} flag.181"182 }183184 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {185 args.context.set_after(convert::usize(&v.unwrap_value())?);186 Ok(())187 }188}189190#[cfg(test)]191#[test]192fn test_after_context() {193 let mkctx = |lines| {194 let mut mode = ContextMode::default();195 mode.set_after(lines);196 mode197 };198199 let args = parse_low_raw(None::<&str>).unwrap();200 assert_eq!(ContextMode::default(), args.context);201202 let args = parse_low_raw(["--after-context", "5"]).unwrap();203 assert_eq!(mkctx(5), args.context);204205 let args = parse_low_raw(["--after-context=5"]).unwrap();206 assert_eq!(mkctx(5), args.context);207208 let args = parse_low_raw(["-A", "5"]).unwrap();209 assert_eq!(mkctx(5), args.context);210211 let args = parse_low_raw(["-A5"]).unwrap();212 assert_eq!(mkctx(5), args.context);213214 let args = parse_low_raw(["-A5", "-A10"]).unwrap();215 assert_eq!(mkctx(10), args.context);216217 let args = parse_low_raw(["-A5", "-A0"]).unwrap();218 assert_eq!(mkctx(0), args.context);219220 let args = parse_low_raw(["-A5", "--passthru"]).unwrap();221 assert_eq!(ContextMode::Passthru, args.context);222223 let args = parse_low_raw(["--passthru", "-A5"]).unwrap();224 assert_eq!(mkctx(5), args.context);225226 let n = usize::MAX.to_string();227 let args = parse_low_raw(["--after-context", n.as_str()]).unwrap();228 assert_eq!(mkctx(usize::MAX), args.context);229230 #[cfg(target_pointer_width = "64")]231 {232 let n = (u128::from(u64::MAX) + 1).to_string();233 let result = parse_low_raw(["--after-context", n.as_str()]);234 assert!(result.is_err(), "{result:?}");235 }236}237238/// --auto-hybrid-regex239#[derive(Debug)]240struct AutoHybridRegex;241242impl Flag for AutoHybridRegex {243 fn is_switch(&self) -> bool {244 true245 }246 fn name_long(&self) -> &'static str {247 "auto-hybrid-regex"248 }249 fn name_negated(&self) -> Option<&'static str> {250 Some("no-auto-hybrid-regex")251 }252 fn doc_category(&self) -> Category {253 Category::Search254 }255 fn doc_short(&self) -> &'static str {256 "(DEPRECATED) Use PCRE2 if appropriate."257 }258 fn doc_long(&self) -> &'static str {259 r"260DEPRECATED. Use \flag{engine} instead.261.sp262When this flag is used, ripgrep will dynamically choose between supported regex263engines depending on the features used in a pattern. When ripgrep chooses a264regex engine, it applies that choice for every regex provided to ripgrep (e.g.,265via multiple \flag{regexp} or \flag{file} flags).266.sp267As an example of how this flag might behave, ripgrep will attempt to use268its default finite automata based regex engine whenever the pattern can be269successfully compiled with that regex engine. If PCRE2 is enabled and if the270pattern given could not be compiled with the default regex engine, then PCRE2271will be automatically used for searching. If PCRE2 isn't available, then this272flag has no effect because there is only one regex engine to choose from.273.sp274In the future, ripgrep may adjust its heuristics for how it decides which275regex engine to use. In general, the heuristics will be limited to a static276analysis of the patterns, and not to any specific runtime behavior observed277while searching files.278.sp279The primary downside of using this flag is that it may not always be obvious280which regex engine ripgrep uses, and thus, the match semantics or performance281profile of ripgrep may subtly and unexpectedly change. However, in many cases,282all regex engines will agree on what constitutes a match and it can be nice283to transparently support more advanced regex features like look-around and284backreferences without explicitly needing to enable them.285"286 }287288 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {289 let mode = if v.unwrap_switch() {290 EngineChoice::Auto291 } else {292 EngineChoice::Default293 };294 args.engine = mode;295 Ok(())296 }297}298299#[cfg(test)]300#[test]301fn test_auto_hybrid_regex() {302 let args = parse_low_raw(None::<&str>).unwrap();303 assert_eq!(EngineChoice::Default, args.engine);304305 let args = parse_low_raw(["--auto-hybrid-regex"]).unwrap();306 assert_eq!(EngineChoice::Auto, args.engine);307308 let args =309 parse_low_raw(["--auto-hybrid-regex", "--no-auto-hybrid-regex"])310 .unwrap();311 assert_eq!(EngineChoice::Default, args.engine);312313 let args =314 parse_low_raw(["--no-auto-hybrid-regex", "--auto-hybrid-regex"])315 .unwrap();316 assert_eq!(EngineChoice::Auto, args.engine);317318 let args = parse_low_raw(["--auto-hybrid-regex", "-P"]).unwrap();319 assert_eq!(EngineChoice::PCRE2, args.engine);320321 let args = parse_low_raw(["-P", "--auto-hybrid-regex"]).unwrap();322 assert_eq!(EngineChoice::Auto, args.engine);323324 let args =325 parse_low_raw(["--engine=auto", "--auto-hybrid-regex"]).unwrap();326 assert_eq!(EngineChoice::Auto, args.engine);327328 let args =329 parse_low_raw(["--engine=default", "--auto-hybrid-regex"]).unwrap();330 assert_eq!(EngineChoice::Auto, args.engine);331332 let args =333 parse_low_raw(["--auto-hybrid-regex", "--engine=default"]).unwrap();334 assert_eq!(EngineChoice::Default, args.engine);335}336337/// -B/--before-context338#[derive(Debug)]339struct BeforeContext;340341impl Flag for BeforeContext {342 fn is_switch(&self) -> bool {343 false344 }345 fn name_short(&self) -> Option<u8> {346 Some(b'B')347 }348 fn name_long(&self) -> &'static str {349 "before-context"350 }351 fn doc_variable(&self) -> Option<&'static str> {352 Some("NUM")353 }354 fn doc_category(&self) -> Category {355 Category::Output356 }357 fn doc_short(&self) -> &'static str {358 "Show NUM lines before each match."359 }360 fn doc_long(&self) -> &'static str {361 r"362Show \fINUM\fP lines before each match.363.sp364This overrides the \flag{passthru} flag and partially overrides the365\flag{context} flag.366"367 }368369 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {370 args.context.set_before(convert::usize(&v.unwrap_value())?);371 Ok(())372 }373}374375#[cfg(test)]376#[test]377fn test_before_context() {378 let mkctx = |lines| {379 let mut mode = ContextMode::default();380 mode.set_before(lines);381 mode382 };383384 let args = parse_low_raw(None::<&str>).unwrap();385 assert_eq!(ContextMode::default(), args.context);386387 let args = parse_low_raw(["--before-context", "5"]).unwrap();388 assert_eq!(mkctx(5), args.context);389390 let args = parse_low_raw(["--before-context=5"]).unwrap();391 assert_eq!(mkctx(5), args.context);392393 let args = parse_low_raw(["-B", "5"]).unwrap();394 assert_eq!(mkctx(5), args.context);395396 let args = parse_low_raw(["-B5"]).unwrap();397 assert_eq!(mkctx(5), args.context);398399 let args = parse_low_raw(["-B5", "-B10"]).unwrap();400 assert_eq!(mkctx(10), args.context);401402 let args = parse_low_raw(["-B5", "-B0"]).unwrap();403 assert_eq!(mkctx(0), args.context);404405 let args = parse_low_raw(["-B5", "--passthru"]).unwrap();406 assert_eq!(ContextMode::Passthru, args.context);407408 let args = parse_low_raw(["--passthru", "-B5"]).unwrap();409 assert_eq!(mkctx(5), args.context);410411 let n = usize::MAX.to_string();412 let args = parse_low_raw(["--before-context", n.as_str()]).unwrap();413 assert_eq!(mkctx(usize::MAX), args.context);414415 #[cfg(target_pointer_width = "64")]416 {417 let n = (u128::from(u64::MAX) + 1).to_string();418 let result = parse_low_raw(["--before-context", n.as_str()]);419 assert!(result.is_err(), "{result:?}");420 }421}422423/// --binary424#[derive(Debug)]425struct Binary;426427impl Flag for Binary {428 fn is_switch(&self) -> bool {429 true430 }431 fn name_long(&self) -> &'static str {432 "binary"433 }434 fn name_negated(&self) -> Option<&'static str> {435 Some("no-binary")436 }437 fn doc_category(&self) -> Category {438 Category::Filter439 }440 fn doc_short(&self) -> &'static str {441 "Search binary files."442 }443 fn doc_long(&self) -> &'static str {444 r"445Enabling this flag will cause ripgrep to search binary files. By default,446ripgrep attempts to automatically skip binary files in order to improve the447relevance of results and make the search faster.448.sp449Binary files are heuristically detected based on whether they contain a450\fBNUL\fP byte or not. By default (without this flag set), once a \fBNUL\fP451byte is seen, ripgrep will stop searching the file. Usually, \fBNUL\fP bytes452occur in the beginning of most binary files. If a \fBNUL\fP byte occurs after453a match, then ripgrep will not print the match, stop searching that file, and454emit a warning that some matches are being suppressed.455.sp456In contrast, when this flag is provided, ripgrep will continue searching a457file even if a \fBNUL\fP byte is found. In particular, if a \fBNUL\fP byte is458found then ripgrep will continue searching until either a match is found or459the end of the file is reached, whichever comes sooner. If a match is found,460then ripgrep will stop and print a warning saying that the search stopped461prematurely.462.sp463If you want ripgrep to search a file without any special \fBNUL\fP byte464handling at all (and potentially print binary data to stdout), then you should465use the \flag{text} flag.466.sp467The \flag{binary} flag is a flag for controlling ripgrep's automatic filtering468mechanism. As such, it does not need to be used when searching a file469explicitly or when searching stdin. That is, it is only applicable when470recursively searching a directory.471.sp472When the \flag{unrestricted} flag is provided for a third time, then this flag473is automatically enabled.474.sp475This flag overrides the \flag{text} flag.476"477 }478479 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {480 args.binary = if v.unwrap_switch() {481 BinaryMode::SearchAndSuppress482 } else {483 BinaryMode::Auto484 };485 Ok(())486 }487}488489#[cfg(test)]490#[test]491fn test_binary() {492 let args = parse_low_raw(None::<&str>).unwrap();493 assert_eq!(BinaryMode::Auto, args.binary);494495 let args = parse_low_raw(["--binary"]).unwrap();496 assert_eq!(BinaryMode::SearchAndSuppress, args.binary);497498 let args = parse_low_raw(["--binary", "--no-binary"]).unwrap();499 assert_eq!(BinaryMode::Auto, args.binary);500501 let args = parse_low_raw(["--no-binary", "--binary"]).unwrap();502 assert_eq!(BinaryMode::SearchAndSuppress, args.binary);503504 let args = parse_low_raw(["--binary", "-a"]).unwrap();505 assert_eq!(BinaryMode::AsText, args.binary);506507 let args = parse_low_raw(["-a", "--binary"]).unwrap();508 assert_eq!(BinaryMode::SearchAndSuppress, args.binary);509510 let args = parse_low_raw(["-a", "--no-binary"]).unwrap();511 assert_eq!(BinaryMode::Auto, args.binary);512}513514/// --block-buffered515#[derive(Debug)]516struct BlockBuffered;517518impl Flag for BlockBuffered {519 fn is_switch(&self) -> bool {520 true521 }522 fn name_long(&self) -> &'static str {523 "block-buffered"524 }525 fn name_negated(&self) -> Option<&'static str> {526 Some("no-block-buffered")527 }528 fn doc_category(&self) -> Category {529 Category::Output530 }531 fn doc_short(&self) -> &'static str {532 "Force block buffering."533 }534 fn doc_long(&self) -> &'static str {535 r"536When enabled, ripgrep will use block buffering. That is, whenever a matching537line is found, it will be written to an in-memory buffer and will not be538written to stdout until the buffer reaches a certain size. This is the default539when ripgrep's stdout is redirected to a pipeline or a file. When ripgrep's540stdout is connected to a terminal, line buffering will be used by default.541Forcing block buffering can be useful when dumping a large amount of contents542to a terminal.543.sp544This overrides the \flag{line-buffered} flag.545"546 }547548 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {549 args.buffer = if v.unwrap_switch() {550 BufferMode::Block551 } else {552 BufferMode::Auto553 };554 Ok(())555 }556}557558#[cfg(test)]559#[test]560fn test_block_buffered() {561 let args = parse_low_raw(None::<&str>).unwrap();562 assert_eq!(BufferMode::Auto, args.buffer);563564 let args = parse_low_raw(["--block-buffered"]).unwrap();565 assert_eq!(BufferMode::Block, args.buffer);566567 let args =568 parse_low_raw(["--block-buffered", "--no-block-buffered"]).unwrap();569 assert_eq!(BufferMode::Auto, args.buffer);570571 let args = parse_low_raw(["--block-buffered", "--line-buffered"]).unwrap();572 assert_eq!(BufferMode::Line, args.buffer);573}574575/// --byte-offset576#[derive(Debug)]577struct ByteOffset;578579impl Flag for ByteOffset {580 fn is_switch(&self) -> bool {581 true582 }583 fn name_short(&self) -> Option<u8> {584 Some(b'b')585 }586 fn name_long(&self) -> &'static str {587 "byte-offset"588 }589 fn name_negated(&self) -> Option<&'static str> {590 Some("no-byte-offset")591 }592 fn doc_category(&self) -> Category {593 Category::Output594 }595 fn doc_short(&self) -> &'static str {596 "Print the byte offset for each matching line."597 }598 fn doc_long(&self) -> &'static str {599 r"600Print the 0-based byte offset within the input file before each line of output.601If \flag{only-matching} is specified, print the offset of the matched text602itself.603.sp604If ripgrep does transcoding, then the byte offset is in terms of the result605of transcoding and not the original data. This applies similarly to other606transformations on the data, such as decompression or a \flag{pre} filter.607"608 }609610 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {611 args.byte_offset = v.unwrap_switch();612 Ok(())613 }614}615616#[cfg(test)]617#[test]618fn test_byte_offset() {619 let args = parse_low_raw(None::<&str>).unwrap();620 assert_eq!(false, args.byte_offset);621622 let args = parse_low_raw(["--byte-offset"]).unwrap();623 assert_eq!(true, args.byte_offset);624625 let args = parse_low_raw(["-b"]).unwrap();626 assert_eq!(true, args.byte_offset);627628 let args = parse_low_raw(["--byte-offset", "--no-byte-offset"]).unwrap();629 assert_eq!(false, args.byte_offset);630631 let args = parse_low_raw(["--no-byte-offset", "-b"]).unwrap();632 assert_eq!(true, args.byte_offset);633}634635/// -s/--case-sensitive636#[derive(Debug)]637struct CaseSensitive;638639impl Flag for CaseSensitive {640 fn is_switch(&self) -> bool {641 true642 }643 fn name_short(&self) -> Option<u8> {644 Some(b's')645 }646 fn name_long(&self) -> &'static str {647 "case-sensitive"648 }649 fn doc_category(&self) -> Category {650 Category::Search651 }652 fn doc_short(&self) -> &'static str {653 r"Search case sensitively (default)."654 }655 fn doc_long(&self) -> &'static str {656 r"657Execute the search case sensitively. This is the default mode.658.sp659This is a global option that applies to all patterns given to ripgrep.660Individual patterns can still be matched case insensitively by using inline661regex flags. For example, \fB(?i)abc\fP will match \fBabc\fP case insensitively662even when this flag is used.663.sp664This flag overrides the \flag{ignore-case} and \flag{smart-case} flags.665"666 }667668 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {669 assert!(v.unwrap_switch(), "flag has no negation");670 args.case = CaseMode::Sensitive;671 Ok(())672 }673}674675#[cfg(test)]676#[test]677fn test_case_sensitive() {678 let args = parse_low_raw(None::<&str>).unwrap();679 assert_eq!(CaseMode::Sensitive, args.case);680681 let args = parse_low_raw(["--case-sensitive"]).unwrap();682 assert_eq!(CaseMode::Sensitive, args.case);683684 let args = parse_low_raw(["-s"]).unwrap();685 assert_eq!(CaseMode::Sensitive, args.case);686}687688/// --color689#[derive(Debug)]690struct Color;691692impl Flag for Color {693 fn is_switch(&self) -> bool {694 false695 }696 fn name_long(&self) -> &'static str {697 "color"698 }699 fn doc_variable(&self) -> Option<&'static str> {700 Some("WHEN")701 }702 fn doc_category(&self) -> Category {703 Category::Output704 }705 fn doc_short(&self) -> &'static str {706 "When to use color."707 }708 fn doc_long(&self) -> &'static str {709 r"710This flag controls when to use colors. The default setting is \fBauto\fP, which711means ripgrep will try to guess when to use colors. For example, if ripgrep is712printing to a terminal, then it will use colors, but if it is redirected to a713file or a pipe, then it will suppress color output.714.sp715ripgrep will suppress color output by default in some other circumstances as716well. These include, but are not limited to:717.sp718.IP \(bu 3n719When the \fBTERM\fP environment variable is not set or set to \fBdumb\fP.720.sp721.IP \(bu 3n722When the \fBNO_COLOR\fP environment variable is set (regardless of value).723.sp724.IP \(bu 3n725When flags that imply no use for colors are given. For example,726\flag{vimgrep} and \flag{json}.727.728.PP729The possible values for this flag are:730.sp731.IP \fBnever\fP 10n732Colors will never be used.733.sp734.IP \fBauto\fP 10n735The default. ripgrep tries to be smart.736.sp737.IP \fBalways\fP 10n738Colors will always be used regardless of where output is sent.739.sp740.IP \fBansi\fP 10n741Like 'always', but emits ANSI escapes (even in a Windows console).742.743.PP744This flag also controls whether hyperlinks are emitted. For example, when745a hyperlink format is specified, hyperlinks won't be used when color is746suppressed. If one wants to emit hyperlinks but no colors, then one must use747the \flag{colors} flag to manually set all color styles to \fBnone\fP:748.sp749.EX750 \-\-colors 'path:none' \\751 \-\-colors 'line:none' \\752 \-\-colors 'column:none' \\753 \-\-colors 'match:none'754.EE755.sp756"757 }758 fn doc_choices(&self) -> &'static [&'static str] {759 &["never", "auto", "always", "ansi"]760 }761762 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {763 args.color = match convert::str(&v.unwrap_value())? {764 "never" => ColorChoice::Never,765 "auto" => ColorChoice::Auto,766 "always" => ColorChoice::Always,767 "ansi" => ColorChoice::Ansi,768 unk => anyhow::bail!("choice '{unk}' is unrecognized"),769 };770 Ok(())771 }772}773774#[cfg(test)]775#[test]776fn test_color() {777 let args = parse_low_raw(None::<&str>).unwrap();778 assert_eq!(ColorChoice::Auto, args.color);779780 let args = parse_low_raw(["--color", "never"]).unwrap();781 assert_eq!(ColorChoice::Never, args.color);782783 let args = parse_low_raw(["--color", "auto"]).unwrap();784 assert_eq!(ColorChoice::Auto, args.color);785786 let args = parse_low_raw(["--color", "always"]).unwrap();787 assert_eq!(ColorChoice::Always, args.color);788789 let args = parse_low_raw(["--color", "ansi"]).unwrap();790 assert_eq!(ColorChoice::Ansi, args.color);791792 let args = parse_low_raw(["--color=never"]).unwrap();793 assert_eq!(ColorChoice::Never, args.color);794795 let args =796 parse_low_raw(["--color", "always", "--color", "never"]).unwrap();797 assert_eq!(ColorChoice::Never, args.color);798799 let args =800 parse_low_raw(["--color", "never", "--color", "always"]).unwrap();801 assert_eq!(ColorChoice::Always, args.color);802803 let result = parse_low_raw(["--color", "foofoo"]);804 assert!(result.is_err(), "{result:?}");805806 let result = parse_low_raw(["--color", "Always"]);807 assert!(result.is_err(), "{result:?}");808}809810/// --colors811#[derive(Debug)]812struct Colors;813814impl Flag for Colors {815 fn is_switch(&self) -> bool {816 false817 }818 fn name_long(&self) -> &'static str {819 "colors"820 }821 fn doc_variable(&self) -> Option<&'static str> {822 Some("COLOR_SPEC")823 }824 fn doc_category(&self) -> Category {825 Category::Output826 }827 fn doc_short(&self) -> &'static str {828 "Configure color settings and styles."829 }830 fn doc_long(&self) -> &'static str {831 r"832This flag specifies color settings for use in the output. This flag may be833provided multiple times. Settings are applied iteratively. Pre-existing color834labels are limited to one of eight choices: \fBred\fP, \fBblue\fP, \fBgreen\fP,835\fBcyan\fP, \fBmagenta\fP, \fByellow\fP, \fBwhite\fP and \fBblack\fP. Styles836are limited to \fBnobold\fP, \fBbold\fP, \fBnointense\fP, \fBintense\fP,837\fBnounderline\fP or \fBunderline\fP.838.sp839The format of the flag is840\fB{\fP\fItype\fP\fB}:{\fP\fIattribute\fP\fB}:{\fP\fIvalue\fP\fB}\fP.841\fItype\fP should be one of \fBpath\fP, \fBline\fP, \fBcolumn\fP or842\fBmatch\fP. \fIattribute\fP can be \fBfg\fP, \fBbg\fP or \fBstyle\fP.843\fIvalue\fP is either a color (for \fBfg\fP and \fBbg\fP) or a text style. A844special format, \fB{\fP\fItype\fP\fB}:none\fP, will clear all color settings845for \fItype\fP.846.sp847For example, the following command will change the match color to magenta and848the background color for line numbers to yellow:849.sp850.EX851 rg \-\-colors 'match:fg:magenta' \-\-colors 'line:bg:yellow'852.EE853.sp854Extended colors can be used for \fIvalue\fP when the terminal supports855ANSI color sequences. These are specified as either \fIx\fP (256-color) or856.IB x , x , x857(24-bit truecolor) where \fIx\fP is a number between \fB0\fP and \fB255\fP858inclusive. \fIx\fP may be given as a normal decimal number or a hexadecimal859number, which is prefixed by \fB0x\fP.860.sp861For example, the following command will change the match background color to862that represented by the rgb value (0,128,255):863.sp864.EX865 rg \-\-colors 'match:bg:0,128,255'866.EE867.sp868or, equivalently,869.sp870.EX871 rg \-\-colors 'match:bg:0x0,0x80,0xFF'872.EE873.sp874Note that the \fBintense\fP and \fBnointense\fP styles will have no effect when875used alongside these extended color codes.876"877 }878879 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {880 let v = v.unwrap_value();881 let v = convert::str(&v)?;882 args.colors.push(v.parse()?);883 Ok(())884 }885}886887#[cfg(test)]888#[test]889fn test_colors() {890 let args = parse_low_raw(None::<&str>).unwrap();891 assert!(args.colors.is_empty());892893 let args = parse_low_raw(["--colors", "match:fg:magenta"]).unwrap();894 assert_eq!(args.colors, vec!["match:fg:magenta".parse().unwrap()]);895896 let args = parse_low_raw([897 "--colors",898 "match:fg:magenta",899 "--colors",900 "line:bg:yellow",901 ])902 .unwrap();903 assert_eq!(904 args.colors,905 vec![906 "match:fg:magenta".parse().unwrap(),907 "line:bg:yellow".parse().unwrap()908 ]909 );910}911912/// --column913#[derive(Debug)]914struct Column;915916impl Flag for Column {917 fn is_switch(&self) -> bool {918 true919 }920 fn name_long(&self) -> &'static str {921 "column"922 }923 fn name_negated(&self) -> Option<&'static str> {924 Some("no-column")925 }926 fn doc_category(&self) -> Category {927 Category::Output928 }929 fn doc_short(&self) -> &'static str {930 "Show column numbers."931 }932 fn doc_long(&self) -> &'static str {933 r"934Show column numbers (1-based). This only shows the column numbers for the first935match on each line. This does not try to account for Unicode. One byte is equal936to one column. This implies \flag{line-number}.937.sp938When \flag{only-matching} is used, then the column numbers written correspond939to the start of each match.940"941 }942943 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {944 args.column = Some(v.unwrap_switch());945 Ok(())946 }947}948949#[cfg(test)]950#[test]951fn test_column() {952 let args = parse_low_raw(None::<&str>).unwrap();953 assert_eq!(None, args.column);954955 let args = parse_low_raw(["--column"]).unwrap();956 assert_eq!(Some(true), args.column);957958 let args = parse_low_raw(["--column", "--no-column"]).unwrap();959 assert_eq!(Some(false), args.column);960961 let args = parse_low_raw(["--no-column", "--column"]).unwrap();962 assert_eq!(Some(true), args.column);963}964965/// -C/--context966#[derive(Debug)]967struct Context;968969impl Flag for Context {970 fn is_switch(&self) -> bool {971 false972 }973 fn name_short(&self) -> Option<u8> {974 Some(b'C')975 }976 fn name_long(&self) -> &'static str {977 "context"978 }979 fn doc_variable(&self) -> Option<&'static str> {980 Some("NUM")981 }982 fn doc_category(&self) -> Category {983 Category::Output984 }985 fn doc_short(&self) -> &'static str {986 r"Show NUM lines before and after each match."987 }988 fn doc_long(&self) -> &'static str {989 r"990Show \fINUM\fP lines before and after each match. This is equivalent to991providing both the \flag{before-context} and \flag{after-context} flags with992the same value.993.sp994This overrides the \flag{passthru} flag. The \flag{after-context} and995\flag{before-context} flags both partially override this flag, regardless of996the order. For example, \fB\-A2 \-C1\fP is equivalent to \fB\-A2 \-B1\fP.997"998 }9991000 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1001 args.context.set_both(convert::usize(&v.unwrap_value())?);1002 Ok(())1003 }1004}10051006#[cfg(test)]1007#[test]1008fn test_context() {1009 let mkctx = |lines| {1010 let mut mode = ContextMode::default();1011 mode.set_both(lines);1012 mode1013 };10141015 let args = parse_low_raw(None::<&str>).unwrap();1016 assert_eq!(ContextMode::default(), args.context);10171018 let args = parse_low_raw(["--context", "5"]).unwrap();1019 assert_eq!(mkctx(5), args.context);10201021 let args = parse_low_raw(["--context=5"]).unwrap();1022 assert_eq!(mkctx(5), args.context);10231024 let args = parse_low_raw(["-C", "5"]).unwrap();1025 assert_eq!(mkctx(5), args.context);10261027 let args = parse_low_raw(["-C5"]).unwrap();1028 assert_eq!(mkctx(5), args.context);10291030 let args = parse_low_raw(["-C5", "-C10"]).unwrap();1031 assert_eq!(mkctx(10), args.context);10321033 let args = parse_low_raw(["-C5", "-C0"]).unwrap();1034 assert_eq!(mkctx(0), args.context);10351036 let args = parse_low_raw(["-C5", "--passthru"]).unwrap();1037 assert_eq!(ContextMode::Passthru, args.context);10381039 let args = parse_low_raw(["--passthru", "-C5"]).unwrap();1040 assert_eq!(mkctx(5), args.context);10411042 let n = usize::MAX.to_string();1043 let args = parse_low_raw(["--context", n.as_str()]).unwrap();1044 assert_eq!(mkctx(usize::MAX), args.context);10451046 #[cfg(target_pointer_width = "64")]1047 {1048 let n = (u128::from(u64::MAX) + 1).to_string();1049 let result = parse_low_raw(["--context", n.as_str()]);1050 assert!(result.is_err(), "{result:?}");1051 }10521053 // Test the interaction between -A/-B and -C. Basically, -A/-B always1054 // partially overrides -C, regardless of where they appear relative to1055 // each other. This behavior is also how GNU grep works, and it also makes1056 // logical sense to me: -A/-B are the more specific flags.1057 let args = parse_low_raw(["-A1", "-C5"]).unwrap();1058 let mut mode = ContextMode::default();1059 mode.set_after(1);1060 mode.set_both(5);1061 assert_eq!(mode, args.context);1062 assert_eq!((5, 1), args.context.get_limited());10631064 let args = parse_low_raw(["-B1", "-C5"]).unwrap();1065 let mut mode = ContextMode::default();1066 mode.set_before(1);1067 mode.set_both(5);1068 assert_eq!(mode, args.context);1069 assert_eq!((1, 5), args.context.get_limited());10701071 let args = parse_low_raw(["-A1", "-B2", "-C5"]).unwrap();1072 let mut mode = ContextMode::default();1073 mode.set_before(2);1074 mode.set_after(1);1075 mode.set_both(5);1076 assert_eq!(mode, args.context);1077 assert_eq!((2, 1), args.context.get_limited());10781079 // These next three are like the ones above, but with -C before -A/-B. This1080 // tests that -A and -B only partially override -C. That is, -C1 -A2 is1081 // equivalent to -B1 -A2.1082 let args = parse_low_raw(["-C5", "-A1"]).unwrap();1083 let mut mode = ContextMode::default();1084 mode.set_after(1);1085 mode.set_both(5);1086 assert_eq!(mode, args.context);1087 assert_eq!((5, 1), args.context.get_limited());10881089 let args = parse_low_raw(["-C5", "-B1"]).unwrap();1090 let mut mode = ContextMode::default();1091 mode.set_before(1);1092 mode.set_both(5);1093 assert_eq!(mode, args.context);1094 assert_eq!((1, 5), args.context.get_limited());10951096 let args = parse_low_raw(["-C5", "-A1", "-B2"]).unwrap();1097 let mut mode = ContextMode::default();1098 mode.set_before(2);1099 mode.set_after(1);1100 mode.set_both(5);1101 assert_eq!(mode, args.context);1102 assert_eq!((2, 1), args.context.get_limited());1103}11041105/// --context-separator1106#[derive(Debug)]1107struct ContextSeparator;11081109impl Flag for ContextSeparator {1110 fn is_switch(&self) -> bool {1111 false1112 }1113 fn name_long(&self) -> &'static str {1114 "context-separator"1115 }1116 fn name_negated(&self) -> Option<&'static str> {1117 Some("no-context-separator")1118 }1119 fn doc_variable(&self) -> Option<&'static str> {1120 Some("SEPARATOR")1121 }1122 fn doc_category(&self) -> Category {1123 Category::Output1124 }1125 fn doc_short(&self) -> &'static str {1126 r"Set the separator for contextual chunks."1127 }1128 fn doc_long(&self) -> &'static str {1129 r"1130The string used to separate non-contiguous context lines in the output. This is1131only used when one of the context flags is used (that is, \flag{after-context},1132\flag{before-context} or \flag{context}). Escape sequences like \fB\\x7F\fP or1133\fB\\t\fP may be used. The default value is \fB\-\-\fP.1134.sp1135When the context separator is set to an empty string, then a line break1136is still inserted. To completely disable context separators, use the1137\flag-negate{context-separator} flag.1138"1139 }11401141 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1142 use crate::flags::lowargs::ContextSeparator as Separator;11431144 args.context_separator = match v {1145 FlagValue::Switch(true) => {1146 unreachable!("flag can only be disabled")1147 }1148 FlagValue::Switch(false) => Separator::disabled(),1149 FlagValue::Value(v) => Separator::new(&v)?,1150 };1151 Ok(())1152 }1153}11541155#[cfg(test)]1156#[test]1157fn test_context_separator() {1158 use bstr::BString;11591160 use crate::flags::lowargs::ContextSeparator as Separator;11611162 let getbytes = |ctxsep: Separator| ctxsep.into_bytes().map(BString::from);11631164 let args = parse_low_raw(None::<&str>).unwrap();1165 assert_eq!(Some(BString::from("--")), getbytes(args.context_separator));11661167 let args = parse_low_raw(["--context-separator", "XYZ"]).unwrap();1168 assert_eq!(Some(BString::from("XYZ")), getbytes(args.context_separator));11691170 let args = parse_low_raw(["--no-context-separator"]).unwrap();1171 assert_eq!(None, getbytes(args.context_separator));11721173 let args = parse_low_raw([1174 "--context-separator",1175 "XYZ",1176 "--no-context-separator",1177 ])1178 .unwrap();1179 assert_eq!(None, getbytes(args.context_separator));11801181 let args = parse_low_raw([1182 "--no-context-separator",1183 "--context-separator",1184 "XYZ",1185 ])1186 .unwrap();1187 assert_eq!(Some(BString::from("XYZ")), getbytes(args.context_separator));11881189 // This checks that invalid UTF-8 can be used. This case isn't too tricky1190 // to handle, because it passes the invalid UTF-8 as an escape sequence1191 // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after1192 // the argument is parsed and then unescaped.1193 let args = parse_low_raw(["--context-separator", r"\xFF"]).unwrap();1194 assert_eq!(Some(BString::from(b"\xFF")), getbytes(args.context_separator));11951196 // In this case, we specifically try to pass an invalid UTF-8 argument to1197 // the flag. In theory we might be able to support this, but because we do1198 // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check1199 // on the value. Since we pass invalid UTF-8, it fails. This demonstrates1200 // that the only way to use an invalid UTF-8 separator is by specifying an1201 // escape sequence that is itself valid UTF-8.1202 #[cfg(unix)]1203 {1204 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};12051206 let result = parse_low_raw([1207 OsStr::from_bytes(b"--context-separator"),1208 OsStr::from_bytes(&[0xFF]),1209 ]);1210 assert!(result.is_err(), "{result:?}");1211 }1212}12131214/// -c/--count1215#[derive(Debug)]1216struct Count;12171218impl Flag for Count {1219 fn is_switch(&self) -> bool {1220 true1221 }1222 fn name_short(&self) -> Option<u8> {1223 Some(b'c')1224 }1225 fn name_long(&self) -> &'static str {1226 "count"1227 }1228 fn doc_category(&self) -> Category {1229 Category::OutputModes1230 }1231 fn doc_short(&self) -> &'static str {1232 r"Show count of matching lines for each file."1233 }1234 fn doc_long(&self) -> &'static str {1235 r"1236This flag suppresses normal output and shows the number of lines that match the1237given patterns for each file searched. Each file containing a match has its1238path and count printed on each line. Note that unless \flag{multiline}1239is enabled, this reports the number of lines that match and not the total1240number of matches. In multiline mode, \flag{count} is equivalent to1241\flag{count-matches}.1242.sp1243If only one file is given to ripgrep, then only the count is printed if there1244is a match. The \flag{with-filename} flag can be used to force printing the1245file path in this case. If you need a count to be printed regardless of whether1246there is a match, then use \flag{include-zero}.1247.sp1248This overrides the \flag{count-matches} flag. Note that when \flag{count}1249is combined with \flag{only-matching}, then ripgrep behaves as if1250\flag{count-matches} was given.1251"1252 }12531254 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1255 assert!(v.unwrap_switch(), "--count can only be enabled");1256 args.mode.update(Mode::Search(SearchMode::Count));1257 Ok(())1258 }1259}12601261#[cfg(test)]1262#[test]1263fn test_count() {1264 let args = parse_low_raw(None::<&str>).unwrap();1265 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);12661267 let args = parse_low_raw(["--count"]).unwrap();1268 assert_eq!(Mode::Search(SearchMode::Count), args.mode);12691270 let args = parse_low_raw(["-c"]).unwrap();1271 assert_eq!(Mode::Search(SearchMode::Count), args.mode);12721273 let args = parse_low_raw(["--count-matches", "--count"]).unwrap();1274 assert_eq!(Mode::Search(SearchMode::Count), args.mode);12751276 let args = parse_low_raw(["--count-matches", "-c"]).unwrap();1277 assert_eq!(Mode::Search(SearchMode::Count), args.mode);1278}12791280/// --count-matches1281#[derive(Debug)]1282struct CountMatches;12831284impl Flag for CountMatches {1285 fn is_switch(&self) -> bool {1286 true1287 }1288 fn name_long(&self) -> &'static str {1289 "count-matches"1290 }1291 fn doc_variable(&self) -> Option<&'static str> {1292 None1293 }1294 fn doc_category(&self) -> Category {1295 Category::OutputModes1296 }1297 fn doc_short(&self) -> &'static str {1298 r"Show count of every match for each file."1299 }1300 fn doc_long(&self) -> &'static str {1301 r"1302This flag suppresses normal output and shows the number of individual matches1303of the given patterns for each file searched. Each file containing matches has1304its path and match count printed on each line. Note that this reports the total1305number of individual matches and not the number of lines that match.1306.sp1307If only one file is given to ripgrep, then only the count is printed if there1308is a match. The \flag{with-filename} flag can be used to force printing the1309file path in this case.1310.sp1311This overrides the \flag{count} flag. Note that when \flag{count} is combined1312with \flag{only-matching}, then ripgrep behaves as if \flag{count-matches} was1313given.1314"1315 }13161317 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1318 assert!(v.unwrap_switch(), "--count-matches can only be enabled");1319 args.mode.update(Mode::Search(SearchMode::CountMatches));1320 Ok(())1321 }1322}13231324#[cfg(test)]1325#[test]1326fn test_count_matches() {1327 let args = parse_low_raw(None::<&str>).unwrap();1328 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);13291330 let args = parse_low_raw(["--count-matches"]).unwrap();1331 assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);13321333 let args = parse_low_raw(["--count", "--count-matches"]).unwrap();1334 assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);13351336 let args = parse_low_raw(["-c", "--count-matches"]).unwrap();1337 assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);1338}13391340/// --crlf1341#[derive(Debug)]1342struct Crlf;13431344impl Flag for Crlf {1345 fn is_switch(&self) -> bool {1346 true1347 }1348 fn name_long(&self) -> &'static str {1349 "crlf"1350 }1351 fn name_negated(&self) -> Option<&'static str> {1352 Some("no-crlf")1353 }1354 fn doc_category(&self) -> Category {1355 Category::Search1356 }1357 fn doc_short(&self) -> &'static str {1358 r"Use CRLF line terminators (nice for Windows)."1359 }1360 fn doc_long(&self) -> &'static str {1361 r"1362When enabled, ripgrep will treat CRLF (\fB\\r\\n\fP) as a line terminator1363instead of just \fB\\n\fP.1364.sp1365Principally, this permits the line anchor assertions \fB^\fP and \fB$\fP in1366regex patterns to treat CRLF, CR or LF as line terminators instead of just LF.1367Note that they will never match between a CR and a LF. CRLF is treated as one1368single line terminator.1369.sp1370When using the default regex engine, CRLF support can also be enabled inside1371the pattern with the \fBR\fP flag. For example, \fB(?R:$)\fP will match just1372before either CR or LF, but never between CR and LF.1373.sp1374This flag overrides \flag{null-data}.1375"1376 }13771378 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1379 args.crlf = v.unwrap_switch();1380 if args.crlf {1381 args.null_data = false;1382 }1383 Ok(())1384 }1385}13861387#[cfg(test)]1388#[test]1389fn test_crlf() {1390 let args = parse_low_raw(None::<&str>).unwrap();1391 assert_eq!(false, args.crlf);13921393 let args = parse_low_raw(["--crlf"]).unwrap();1394 assert_eq!(true, args.crlf);1395 assert_eq!(false, args.null_data);13961397 let args = parse_low_raw(["--crlf", "--null-data"]).unwrap();1398 assert_eq!(false, args.crlf);1399 assert_eq!(true, args.null_data);14001401 let args = parse_low_raw(["--null-data", "--crlf"]).unwrap();1402 assert_eq!(true, args.crlf);1403 assert_eq!(false, args.null_data);14041405 let args = parse_low_raw(["--null-data", "--no-crlf"]).unwrap();1406 assert_eq!(false, args.crlf);1407 assert_eq!(true, args.null_data);14081409 let args = parse_low_raw(["--null-data", "--crlf", "--no-crlf"]).unwrap();1410 assert_eq!(false, args.crlf);1411 assert_eq!(false, args.null_data);1412}14131414/// --debug1415#[derive(Debug)]1416struct Debug;14171418impl Flag for Debug {1419 fn is_switch(&self) -> bool {1420 true1421 }1422 fn name_long(&self) -> &'static str {1423 "debug"1424 }1425 fn doc_category(&self) -> Category {1426 Category::Logging1427 }1428 fn doc_short(&self) -> &'static str {1429 r"Show debug messages."1430 }1431 fn doc_long(&self) -> &'static str {1432 r"1433Show debug messages. Please use this when filing a bug report.1434.sp1435The \flag{debug} flag is generally useful for figuring out why ripgrep skipped1436searching a particular file. The debug messages should mention all files1437skipped and why they were skipped.1438.sp1439To get even more debug output, use the \flag{trace} flag, which implies1440\flag{debug} along with additional trace data.1441"1442 }14431444 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1445 assert!(v.unwrap_switch(), "--debug can only be enabled");1446 args.logging = Some(LoggingMode::Debug);1447 Ok(())1448 }1449}14501451#[cfg(test)]1452#[test]1453fn test_debug() {1454 let args = parse_low_raw(None::<&str>).unwrap();1455 assert_eq!(None, args.logging);14561457 let args = parse_low_raw(["--debug"]).unwrap();1458 assert_eq!(Some(LoggingMode::Debug), args.logging);14591460 let args = parse_low_raw(["--trace", "--debug"]).unwrap();1461 assert_eq!(Some(LoggingMode::Debug), args.logging);1462}14631464/// --dfa-size-limit1465#[derive(Debug)]1466struct DfaSizeLimit;14671468impl Flag for DfaSizeLimit {1469 fn is_switch(&self) -> bool {1470 false1471 }1472 fn name_long(&self) -> &'static str {1473 "dfa-size-limit"1474 }1475 fn doc_variable(&self) -> Option<&'static str> {1476 Some("NUM+SUFFIX?")1477 }1478 fn doc_category(&self) -> Category {1479 Category::Search1480 }1481 fn doc_short(&self) -> &'static str {1482 r"The upper size limit of the regex DFA."1483 }1484 fn doc_long(&self) -> &'static str {1485 r"1486The upper size limit of the regex DFA. The default limit is something generous1487for any single pattern or for many smallish patterns. This should only be1488changed on very large regex inputs where the (slower) fallback regex engine may1489otherwise be used if the limit is reached.1490.sp1491The input format accepts suffixes of \fBK\fP, \fBM\fP or \fBG\fP which1492correspond to kilobytes, megabytes and gigabytes, respectively. If no suffix is1493provided the input is treated as bytes.1494"1495 }14961497 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1498 let v = v.unwrap_value();1499 args.dfa_size_limit = Some(convert::human_readable_usize(&v)?);1500 Ok(())1501 }1502}15031504#[cfg(test)]1505#[test]1506fn test_dfa_size_limit() {1507 let args = parse_low_raw(None::<&str>).unwrap();1508 assert_eq!(None, args.dfa_size_limit);15091510 #[cfg(target_pointer_width = "64")]1511 {1512 let args = parse_low_raw(["--dfa-size-limit", "9G"]).unwrap();1513 assert_eq!(Some(9 * (1 << 30)), args.dfa_size_limit);15141515 let args = parse_low_raw(["--dfa-size-limit=9G"]).unwrap();1516 assert_eq!(Some(9 * (1 << 30)), args.dfa_size_limit);15171518 let args =1519 parse_low_raw(["--dfa-size-limit=9G", "--dfa-size-limit=0"])1520 .unwrap();1521 assert_eq!(Some(0), args.dfa_size_limit);1522 }15231524 let args = parse_low_raw(["--dfa-size-limit=0K"]).unwrap();1525 assert_eq!(Some(0), args.dfa_size_limit);15261527 let args = parse_low_raw(["--dfa-size-limit=0M"]).unwrap();1528 assert_eq!(Some(0), args.dfa_size_limit);15291530 let args = parse_low_raw(["--dfa-size-limit=0G"]).unwrap();1531 assert_eq!(Some(0), args.dfa_size_limit);15321533 let result = parse_low_raw(["--dfa-size-limit", "9999999999999999999999"]);1534 assert!(result.is_err(), "{result:?}");15351536 let result = parse_low_raw(["--dfa-size-limit", "9999999999999999G"]);1537 assert!(result.is_err(), "{result:?}");1538}15391540/// -E/--encoding1541#[derive(Debug)]1542struct Encoding;15431544impl Flag for Encoding {1545 fn is_switch(&self) -> bool {1546 false1547 }1548 fn name_short(&self) -> Option<u8> {1549 Some(b'E')1550 }1551 fn name_long(&self) -> &'static str {1552 "encoding"1553 }1554 fn name_negated(&self) -> Option<&'static str> {1555 Some("no-encoding")1556 }1557 fn doc_variable(&self) -> Option<&'static str> {1558 Some("ENCODING")1559 }1560 fn doc_category(&self) -> Category {1561 Category::Search1562 }1563 fn doc_short(&self) -> &'static str {1564 r"Specify the text encoding of files to search."1565 }1566 fn doc_long(&self) -> &'static str {1567 r"1568Specify the text encoding that ripgrep will use on all files searched. The1569default value is \fBauto\fP, which will cause ripgrep to do a best effort1570automatic detection of encoding on a per-file basis. Automatic detection in1571this case only applies to files that begin with a UTF-8 or UTF-16 byte-order1572mark (BOM). No other automatic detection is performed. One can also specify1573\fBnone\fP which will then completely disable BOM sniffing and always result1574in searching the raw bytes, including a BOM if it's present, regardless of its1575encoding.1576.sp1577Other supported values can be found in the list of labels here:1578\fIhttps://encoding.spec.whatwg.org/#concept-encoding-get\fP.1579.sp1580For more details on encoding and how ripgrep deals with it, see \fBGUIDE.md\fP.1581.sp1582The encoding detection that ripgrep uses can be reverted to its automatic mode1583via the \flag-negate{encoding} flag.1584"1585 }15861587 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1588 let value = match v {1589 FlagValue::Value(v) => v,1590 FlagValue::Switch(true) => {1591 unreachable!("--encoding must accept a value")1592 }1593 FlagValue::Switch(false) => {1594 args.encoding = EncodingMode::Auto;1595 return Ok(());1596 }1597 };1598 let label = convert::str(&value)?;1599 args.encoding = match label {1600 "auto" => EncodingMode::Auto,1601 "none" => EncodingMode::Disabled,1602 _ => EncodingMode::Some(grep::searcher::Encoding::new(label)?),1603 };1604 Ok(())1605 }1606}16071608#[cfg(test)]1609#[test]1610fn test_encoding() {1611 let args = parse_low_raw(None::<&str>).unwrap();1612 assert_eq!(EncodingMode::Auto, args.encoding);16131614 let args = parse_low_raw(["--encoding", "auto"]).unwrap();1615 assert_eq!(EncodingMode::Auto, args.encoding);16161617 let args = parse_low_raw(["--encoding", "none"]).unwrap();1618 assert_eq!(EncodingMode::Disabled, args.encoding);16191620 let args = parse_low_raw(["--encoding=none"]).unwrap();1621 assert_eq!(EncodingMode::Disabled, args.encoding);16221623 let args = parse_low_raw(["-E", "none"]).unwrap();1624 assert_eq!(EncodingMode::Disabled, args.encoding);16251626 let args = parse_low_raw(["-Enone"]).unwrap();1627 assert_eq!(EncodingMode::Disabled, args.encoding);16281629 let args = parse_low_raw(["-E", "none", "--no-encoding"]).unwrap();1630 assert_eq!(EncodingMode::Auto, args.encoding);16311632 let args = parse_low_raw(["--no-encoding", "-E", "none"]).unwrap();1633 assert_eq!(EncodingMode::Disabled, args.encoding);16341635 let args = parse_low_raw(["-E", "utf-16"]).unwrap();1636 let enc = grep::searcher::Encoding::new("utf-16").unwrap();1637 assert_eq!(EncodingMode::Some(enc), args.encoding);16381639 let args = parse_low_raw(["-E", "utf-16", "--no-encoding"]).unwrap();1640 assert_eq!(EncodingMode::Auto, args.encoding);16411642 let result = parse_low_raw(["-E", "foo"]);1643 assert!(result.is_err(), "{result:?}");1644}16451646/// --engine1647#[derive(Debug)]1648struct Engine;16491650impl Flag for Engine {1651 fn is_switch(&self) -> bool {1652 false1653 }1654 fn name_long(&self) -> &'static str {1655 "engine"1656 }1657 fn doc_variable(&self) -> Option<&'static str> {1658 Some("ENGINE")1659 }1660 fn doc_category(&self) -> Category {1661 Category::Search1662 }1663 fn doc_short(&self) -> &'static str {1664 r"Specify which regex engine to use."1665 }1666 fn doc_long(&self) -> &'static str {1667 r"1668Specify which regular expression engine to use. When you choose a regex engine,1669it applies that choice for every regex provided to ripgrep (e.g., via multiple1670\flag{regexp} or \flag{file} flags).1671.sp1672Accepted values are \fBdefault\fP, \fBpcre2\fP, or \fBauto\fP.1673.sp1674The default value is \fBdefault\fP, which is usually the fastest and should be1675good for most use cases. The \fBpcre2\fP engine is generally useful when you1676want to use features such as look-around or backreferences. \fBauto\fP will1677dynamically choose between supported regex engines depending on the features1678used in a pattern on a best effort basis.1679.sp1680Note that the \fBpcre2\fP engine is an optional ripgrep feature. If PCRE21681wasn't included in your build of ripgrep, then using this flag will result in1682ripgrep printing an error message and exiting.1683.sp1684This overrides previous uses of the \flag{pcre2} and \flag{auto-hybrid-regex}1685flags.1686"1687 }1688 fn doc_choices(&self) -> &'static [&'static str] {1689 &["default", "pcre2", "auto"]1690 }16911692 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1693 let v = v.unwrap_value();1694 let string = convert::str(&v)?;1695 args.engine = match string {1696 "default" => EngineChoice::Default,1697 "pcre2" => EngineChoice::PCRE2,1698 "auto" => EngineChoice::Auto,1699 _ => anyhow::bail!("unrecognized regex engine '{string}'"),1700 };1701 Ok(())1702 }1703}17041705#[cfg(test)]1706#[test]1707fn test_engine() {1708 let args = parse_low_raw(None::<&str>).unwrap();1709 assert_eq!(EngineChoice::Default, args.engine);17101711 let args = parse_low_raw(["--engine", "pcre2"]).unwrap();1712 assert_eq!(EngineChoice::PCRE2, args.engine);17131714 let args = parse_low_raw(["--engine=pcre2"]).unwrap();1715 assert_eq!(EngineChoice::PCRE2, args.engine);17161717 let args =1718 parse_low_raw(["--auto-hybrid-regex", "--engine=pcre2"]).unwrap();1719 assert_eq!(EngineChoice::PCRE2, args.engine);17201721 let args =1722 parse_low_raw(["--engine=pcre2", "--auto-hybrid-regex"]).unwrap();1723 assert_eq!(EngineChoice::Auto, args.engine);17241725 let args =1726 parse_low_raw(["--auto-hybrid-regex", "--engine=auto"]).unwrap();1727 assert_eq!(EngineChoice::Auto, args.engine);17281729 let args =1730 parse_low_raw(["--auto-hybrid-regex", "--engine=default"]).unwrap();1731 assert_eq!(EngineChoice::Default, args.engine);17321733 let args =1734 parse_low_raw(["--engine=pcre2", "--no-auto-hybrid-regex"]).unwrap();1735 assert_eq!(EngineChoice::Default, args.engine);1736}17371738/// --field-context-separator1739#[derive(Debug)]1740struct FieldContextSeparator;17411742impl Flag for FieldContextSeparator {1743 fn is_switch(&self) -> bool {1744 false1745 }1746 fn name_long(&self) -> &'static str {1747 "field-context-separator"1748 }1749 fn doc_variable(&self) -> Option<&'static str> {1750 Some("SEPARATOR")1751 }1752 fn doc_category(&self) -> Category {1753 Category::Output1754 }1755 fn doc_short(&self) -> &'static str {1756 r"Set the field context separator."1757 }1758 fn doc_long(&self) -> &'static str {1759 r"1760Set the field context separator. This separator is only used when printing1761contextual lines. It is used to delimit file paths, line numbers, columns and1762the contextual line itself. The separator may be any number of bytes, including1763zero. Escape sequences like \fB\\x7F\fP or \fB\\t\fP may be used.1764.sp1765The \fB-\fP character is the default value.1766"1767 }17681769 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1770 use crate::flags::lowargs::FieldContextSeparator as Separator;17711772 args.field_context_separator = Separator::new(&v.unwrap_value())?;1773 Ok(())1774 }1775}17761777#[cfg(test)]1778#[test]1779fn test_field_context_separator() {1780 use bstr::BString;17811782 let args = parse_low_raw(None::<&str>).unwrap();1783 assert_eq!(BString::from("-"), args.field_context_separator.into_bytes());17841785 let args = parse_low_raw(["--field-context-separator", "XYZ"]).unwrap();1786 assert_eq!(1787 BString::from("XYZ"),1788 args.field_context_separator.into_bytes()1789 );17901791 let args = parse_low_raw(["--field-context-separator=XYZ"]).unwrap();1792 assert_eq!(1793 BString::from("XYZ"),1794 args.field_context_separator.into_bytes()1795 );17961797 let args = parse_low_raw([1798 "--field-context-separator",1799 "XYZ",1800 "--field-context-separator",1801 "ABC",1802 ])1803 .unwrap();1804 assert_eq!(1805 BString::from("ABC"),1806 args.field_context_separator.into_bytes()1807 );18081809 let args = parse_low_raw(["--field-context-separator", r"\t"]).unwrap();1810 assert_eq!(BString::from("\t"), args.field_context_separator.into_bytes());18111812 let args = parse_low_raw(["--field-context-separator", r"\x00"]).unwrap();1813 assert_eq!(1814 BString::from("\x00"),1815 args.field_context_separator.into_bytes()1816 );18171818 // This checks that invalid UTF-8 can be used. This case isn't too tricky1819 // to handle, because it passes the invalid UTF-8 as an escape sequence1820 // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after1821 // the argument is parsed and then unescaped.1822 let args = parse_low_raw(["--field-context-separator", r"\xFF"]).unwrap();1823 assert_eq!(1824 BString::from(b"\xFF"),1825 args.field_context_separator.into_bytes()1826 );18271828 // In this case, we specifically try to pass an invalid UTF-8 argument to1829 // the flag. In theory we might be able to support this, but because we do1830 // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check1831 // on the value. Since we pass invalid UTF-8, it fails. This demonstrates1832 // that the only way to use an invalid UTF-8 separator is by specifying an1833 // escape sequence that is itself valid UTF-8.1834 #[cfg(unix)]1835 {1836 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};18371838 let result = parse_low_raw([1839 OsStr::from_bytes(b"--field-context-separator"),1840 OsStr::from_bytes(&[0xFF]),1841 ]);1842 assert!(result.is_err(), "{result:?}");1843 }1844}18451846/// --field-match-separator1847#[derive(Debug)]1848struct FieldMatchSeparator;18491850impl Flag for FieldMatchSeparator {1851 fn is_switch(&self) -> bool {1852 false1853 }1854 fn name_long(&self) -> &'static str {1855 "field-match-separator"1856 }1857 fn doc_variable(&self) -> Option<&'static str> {1858 Some("SEPARATOR")1859 }1860 fn doc_category(&self) -> Category {1861 Category::Output1862 }1863 fn doc_short(&self) -> &'static str {1864 r"Set the field match separator."1865 }1866 fn doc_long(&self) -> &'static str {1867 r"1868Set the field match separator. This separator is only used when printing1869matching lines. It is used to delimit file paths, line numbers, columns and the1870matching line itself. The separator may be any number of bytes, including zero.1871Escape sequences like \fB\\x7F\fP or \fB\\t\fP may be used.1872.sp1873The \fB:\fP character is the default value.1874"1875 }18761877 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1878 use crate::flags::lowargs::FieldMatchSeparator as Separator;18791880 args.field_match_separator = Separator::new(&v.unwrap_value())?;1881 Ok(())1882 }1883}18841885#[cfg(test)]1886#[test]1887fn test_field_match_separator() {1888 use bstr::BString;18891890 let args = parse_low_raw(None::<&str>).unwrap();1891 assert_eq!(BString::from(":"), args.field_match_separator.into_bytes());18921893 let args = parse_low_raw(["--field-match-separator", "XYZ"]).unwrap();1894 assert_eq!(BString::from("XYZ"), args.field_match_separator.into_bytes());18951896 let args = parse_low_raw(["--field-match-separator=XYZ"]).unwrap();1897 assert_eq!(BString::from("XYZ"), args.field_match_separator.into_bytes());18981899 let args = parse_low_raw([1900 "--field-match-separator",1901 "XYZ",1902 "--field-match-separator",1903 "ABC",1904 ])1905 .unwrap();1906 assert_eq!(BString::from("ABC"), args.field_match_separator.into_bytes());19071908 let args = parse_low_raw(["--field-match-separator", r"\t"]).unwrap();1909 assert_eq!(BString::from("\t"), args.field_match_separator.into_bytes());19101911 let args = parse_low_raw(["--field-match-separator", r"\x00"]).unwrap();1912 assert_eq!(BString::from("\x00"), args.field_match_separator.into_bytes());19131914 // This checks that invalid UTF-8 can be used. This case isn't too tricky1915 // to handle, because it passes the invalid UTF-8 as an escape sequence1916 // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after1917 // the argument is parsed and then unescaped.1918 let args = parse_low_raw(["--field-match-separator", r"\xFF"]).unwrap();1919 assert_eq!(1920 BString::from(b"\xFF"),1921 args.field_match_separator.into_bytes()1922 );19231924 // In this case, we specifically try to pass an invalid UTF-8 argument to1925 // the flag. In theory we might be able to support this, but because we do1926 // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check1927 // on the value. Since we pass invalid UTF-8, it fails. This demonstrates1928 // that the only way to use an invalid UTF-8 separator is by specifying an1929 // escape sequence that is itself valid UTF-8.1930 #[cfg(unix)]1931 {1932 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};19331934 let result = parse_low_raw([1935 OsStr::from_bytes(b"--field-match-separator"),1936 OsStr::from_bytes(&[0xFF]),1937 ]);1938 assert!(result.is_err(), "{result:?}");1939 }1940}19411942/// -f/--file1943#[derive(Debug)]1944struct File;19451946impl Flag for File {1947 fn is_switch(&self) -> bool {1948 false1949 }1950 fn name_short(&self) -> Option<u8> {1951 Some(b'f')1952 }1953 fn name_long(&self) -> &'static str {1954 "file"1955 }1956 fn doc_variable(&self) -> Option<&'static str> {1957 Some("PATTERNFILE")1958 }1959 fn doc_category(&self) -> Category {1960 Category::Input1961 }1962 fn doc_short(&self) -> &'static str {1963 r"Search for patterns from the given file."1964 }1965 fn doc_long(&self) -> &'static str {1966 r"1967Search for patterns from the given file, with one pattern per line. When this1968flag is used multiple times or in combination with the \flag{regexp} flag, then1969all patterns provided are searched. Empty pattern lines will match all input1970lines, and the newline is not counted as part of the pattern.1971.sp1972A line is printed if and only if it matches at least one of the patterns.1973.sp1974When \fIPATTERNFILE\fP is \fB-\fP, then \fBstdin\fP will be read for the1975patterns.1976.sp1977When \flag{file} or \flag{regexp} is used, then ripgrep treats all positional1978arguments as files or directories to search.1979"1980 }19811982 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {1983 let path = PathBuf::from(v.unwrap_value());1984 args.patterns.push(PatternSource::File(path));1985 Ok(())1986 }1987}19881989#[cfg(test)]1990#[test]1991fn test_file() {1992 let args = parse_low_raw(None::<&str>).unwrap();1993 assert_eq!(Vec::<PatternSource>::new(), args.patterns);19941995 let args = parse_low_raw(["--file", "foo"]).unwrap();1996 assert_eq!(vec![PatternSource::File(PathBuf::from("foo"))], args.patterns);19971998 let args = parse_low_raw(["--file=foo"]).unwrap();1999 assert_eq!(vec![PatternSource::File(PathBuf::from("foo"))], args.patterns);20002001 let args = parse_low_raw(["-f", "foo"]).unwrap();2002 assert_eq!(vec![PatternSource::File(PathBuf::from("foo"))], args.patterns);20032004 let args = parse_low_raw(["-ffoo"]).unwrap();2005 assert_eq!(vec![PatternSource::File(PathBuf::from("foo"))], args.patterns);20062007 let args = parse_low_raw(["--file", "-foo"]).unwrap();2008 assert_eq!(2009 vec![PatternSource::File(PathBuf::from("-foo"))],2010 args.patterns2011 );20122013 let args = parse_low_raw(["--file=-foo"]).unwrap();2014 assert_eq!(2015 vec![PatternSource::File(PathBuf::from("-foo"))],2016 args.patterns2017 );20182019 let args = parse_low_raw(["-f", "-foo"]).unwrap();2020 assert_eq!(2021 vec![PatternSource::File(PathBuf::from("-foo"))],2022 args.patterns2023 );20242025 let args = parse_low_raw(["-f-foo"]).unwrap();2026 assert_eq!(2027 vec![PatternSource::File(PathBuf::from("-foo"))],2028 args.patterns2029 );20302031 let args = parse_low_raw(["--file=foo", "--file", "bar"]).unwrap();2032 assert_eq!(2033 vec![2034 PatternSource::File(PathBuf::from("foo")),2035 PatternSource::File(PathBuf::from("bar"))2036 ],2037 args.patterns2038 );20392040 // We permit path arguments to be invalid UTF-8. So test that. Some of2041 // these cases are tricky and depend on lexopt doing the right thing.2042 //2043 // We probably should add tests for this handling on Windows too, but paths2044 // that are invalid UTF-16 appear incredibly rare in the Windows world.2045 #[cfg(unix)]2046 {2047 use std::{2048 ffi::{OsStr, OsString},2049 os::unix::ffi::{OsStrExt, OsStringExt},2050 };20512052 let bytes = &[b'A', 0xFF, b'Z'][..];2053 let path = PathBuf::from(OsString::from_vec(bytes.to_vec()));20542055 let args = parse_low_raw([2056 OsStr::from_bytes(b"--file"),2057 OsStr::from_bytes(bytes),2058 ])2059 .unwrap();2060 assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);20612062 let args = parse_low_raw([2063 OsStr::from_bytes(b"-f"),2064 OsStr::from_bytes(bytes),2065 ])2066 .unwrap();2067 assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);20682069 let mut bytes = b"--file=A".to_vec();2070 bytes.push(0xFF);2071 bytes.push(b'Z');2072 let args = parse_low_raw([OsStr::from_bytes(&bytes)]).unwrap();2073 assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);20742075 let mut bytes = b"-fA".to_vec();2076 bytes.push(0xFF);2077 bytes.push(b'Z');2078 let args = parse_low_raw([OsStr::from_bytes(&bytes)]).unwrap();2079 assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);2080 }2081}20822083/// --files2084#[derive(Debug)]2085struct Files;20862087impl Flag for Files {2088 fn is_switch(&self) -> bool {2089 true2090 }2091 fn name_long(&self) -> &'static str {2092 "files"2093 }2094 fn doc_category(&self) -> Category {2095 Category::OtherBehaviors2096 }2097 fn doc_short(&self) -> &'static str {2098 r"Print each file that would be searched."2099 }2100 fn doc_long(&self) -> &'static str {2101 r"2102Print each file that would be searched without actually performing the search.2103This is useful to determine whether a particular file is being searched or not.2104.sp2105This overrides \flag{type-list}.2106"2107 }21082109 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2110 assert!(v.unwrap_switch());2111 args.mode.update(Mode::Files);2112 Ok(())2113 }2114}21152116#[cfg(test)]2117#[test]2118fn test_files() {2119 let args = parse_low_raw(None::<&str>).unwrap();2120 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);21212122 let args = parse_low_raw(["--files"]).unwrap();2123 assert_eq!(Mode::Files, args.mode);2124}21252126/// -l/--files-with-matches2127#[derive(Debug)]2128struct FilesWithMatches;21292130impl Flag for FilesWithMatches {2131 fn is_switch(&self) -> bool {2132 true2133 }2134 fn name_short(&self) -> Option<u8> {2135 Some(b'l')2136 }2137 fn name_long(&self) -> &'static str {2138 "files-with-matches"2139 }2140 fn doc_category(&self) -> Category {2141 Category::OutputModes2142 }2143 fn doc_short(&self) -> &'static str {2144 r"Print the paths with at least one match."2145 }2146 fn doc_long(&self) -> &'static str {2147 r"2148Print only the paths with at least one match and suppress match contents.2149.sp2150This overrides \flag{files-without-match}.2151"2152 }21532154 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2155 assert!(v.unwrap_switch(), "--files-with-matches can only be enabled");2156 args.mode.update(Mode::Search(SearchMode::FilesWithMatches));2157 Ok(())2158 }2159}21602161#[cfg(test)]2162#[test]2163fn test_files_with_matches() {2164 let args = parse_low_raw(None::<&str>).unwrap();2165 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);21662167 let args = parse_low_raw(["--files-with-matches"]).unwrap();2168 assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);21692170 let args = parse_low_raw(["-l"]).unwrap();2171 assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);2172}21732174/// -l/--files-without-match2175#[derive(Debug)]2176struct FilesWithoutMatch;21772178impl Flag for FilesWithoutMatch {2179 fn is_switch(&self) -> bool {2180 true2181 }2182 fn name_long(&self) -> &'static str {2183 "files-without-match"2184 }2185 fn doc_category(&self) -> Category {2186 Category::OutputModes2187 }2188 fn doc_short(&self) -> &'static str {2189 r"Print the paths that contain zero matches."2190 }2191 fn doc_long(&self) -> &'static str {2192 r"2193Print the paths that contain zero matches and suppress match contents.2194.sp2195This overrides \flag{files-with-matches}.2196"2197 }21982199 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2200 assert!(2201 v.unwrap_switch(),2202 "--files-without-match can only be enabled"2203 );2204 args.mode.update(Mode::Search(SearchMode::FilesWithoutMatch));2205 Ok(())2206 }2207}22082209#[cfg(test)]2210#[test]2211fn test_files_without_match() {2212 let args = parse_low_raw(None::<&str>).unwrap();2213 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);22142215 let args = parse_low_raw(["--files-without-match"]).unwrap();2216 assert_eq!(Mode::Search(SearchMode::FilesWithoutMatch), args.mode);22172218 let args =2219 parse_low_raw(["--files-with-matches", "--files-without-match"])2220 .unwrap();2221 assert_eq!(Mode::Search(SearchMode::FilesWithoutMatch), args.mode);22222223 let args =2224 parse_low_raw(["--files-without-match", "--files-with-matches"])2225 .unwrap();2226 assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);2227}22282229/// -F/--fixed-strings2230#[derive(Debug)]2231struct FixedStrings;22322233impl Flag for FixedStrings {2234 fn is_switch(&self) -> bool {2235 true2236 }2237 fn name_short(&self) -> Option<u8> {2238 Some(b'F')2239 }2240 fn name_long(&self) -> &'static str {2241 "fixed-strings"2242 }2243 fn name_negated(&self) -> Option<&'static str> {2244 Some("no-fixed-strings")2245 }2246 fn doc_category(&self) -> Category {2247 Category::Search2248 }2249 fn doc_short(&self) -> &'static str {2250 r"Treat all patterns as literals."2251 }2252 fn doc_long(&self) -> &'static str {2253 r"2254Treat all patterns as literals instead of as regular expressions. When this2255flag is used, special regular expression meta characters such as \fB.(){}*+\fP2256should not need be escaped.2257"2258 }22592260 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2261 args.fixed_strings = v.unwrap_switch();2262 Ok(())2263 }2264}22652266#[cfg(test)]2267#[test]2268fn test_fixed_strings() {2269 let args = parse_low_raw(None::<&str>).unwrap();2270 assert_eq!(false, args.fixed_strings);22712272 let args = parse_low_raw(["--fixed-strings"]).unwrap();2273 assert_eq!(true, args.fixed_strings);22742275 let args = parse_low_raw(["-F"]).unwrap();2276 assert_eq!(true, args.fixed_strings);22772278 let args = parse_low_raw(["-F", "--no-fixed-strings"]).unwrap();2279 assert_eq!(false, args.fixed_strings);22802281 let args = parse_low_raw(["--no-fixed-strings", "-F"]).unwrap();2282 assert_eq!(true, args.fixed_strings);2283}22842285/// -L/--follow2286#[derive(Debug)]2287struct Follow;22882289impl Flag for Follow {2290 fn is_switch(&self) -> bool {2291 true2292 }2293 fn name_short(&self) -> Option<u8> {2294 Some(b'L')2295 }2296 fn name_long(&self) -> &'static str {2297 "follow"2298 }2299 fn name_negated(&self) -> Option<&'static str> {2300 Some("no-follow")2301 }2302 fn doc_category(&self) -> Category {2303 Category::Filter2304 }2305 fn doc_short(&self) -> &'static str {2306 r"Follow symbolic links."2307 }2308 fn doc_long(&self) -> &'static str {2309 r"2310This flag instructs ripgrep to follow symbolic links while traversing2311directories. This behavior is disabled by default. Note that ripgrep will2312check for symbolic link loops and report errors if it finds one. ripgrep will2313also report errors for broken links. To suppress error messages, use the2314\flag{no-messages} flag.2315"2316 }23172318 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2319 args.follow = v.unwrap_switch();2320 Ok(())2321 }2322}23232324#[cfg(test)]2325#[test]2326fn test_follow() {2327 let args = parse_low_raw(None::<&str>).unwrap();2328 assert_eq!(false, args.follow);23292330 let args = parse_low_raw(["--follow"]).unwrap();2331 assert_eq!(true, args.follow);23322333 let args = parse_low_raw(["-L"]).unwrap();2334 assert_eq!(true, args.follow);23352336 let args = parse_low_raw(["-L", "--no-follow"]).unwrap();2337 assert_eq!(false, args.follow);23382339 let args = parse_low_raw(["--no-follow", "-L"]).unwrap();2340 assert_eq!(true, args.follow);2341}23422343/// --generate2344#[derive(Debug)]2345struct Generate;23462347impl Flag for Generate {2348 fn is_switch(&self) -> bool {2349 false2350 }2351 fn name_long(&self) -> &'static str {2352 "generate"2353 }2354 fn doc_variable(&self) -> Option<&'static str> {2355 Some("KIND")2356 }2357 fn doc_category(&self) -> Category {2358 Category::OtherBehaviors2359 }2360 fn doc_short(&self) -> &'static str {2361 r"Generate man pages and completion scripts."2362 }2363 fn doc_long(&self) -> &'static str {2364 r"2365This flag instructs ripgrep to generate some special kind of output identified2366by \fIKIND\fP and then quit without searching. \fIKIND\fP can be one of the2367following values:2368.sp2369.TP 152370\fBman\fP2371Generates a manual page for ripgrep in the \fBroff\fP format.2372.TP 152373\fBcomplete\-bash\fP2374Generates a completion script for the \fBbash\fP shell.2375.TP 152376\fBcomplete\-zsh\fP2377Generates a completion script for the \fBzsh\fP shell.2378.TP 152379\fBcomplete\-fish\fP2380Generates a completion script for the \fBfish\fP shell.2381.TP 152382\fBcomplete\-powershell\fP2383Generates a completion script for PowerShell.2384.PP2385The output is written to \fBstdout\fP. The list above may expand over time.2386"2387 }2388 fn doc_choices(&self) -> &'static [&'static str] {2389 &[2390 "man",2391 "complete-bash",2392 "complete-zsh",2393 "complete-fish",2394 "complete-powershell",2395 ]2396 }23972398 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2399 let genmode = match convert::str(&v.unwrap_value())? {2400 "man" => GenerateMode::Man,2401 "complete-bash" => GenerateMode::CompleteBash,2402 "complete-zsh" => GenerateMode::CompleteZsh,2403 "complete-fish" => GenerateMode::CompleteFish,2404 "complete-powershell" => GenerateMode::CompletePowerShell,2405 unk => anyhow::bail!("choice '{unk}' is unrecognized"),2406 };2407 args.mode.update(Mode::Generate(genmode));2408 Ok(())2409 }2410}24112412#[cfg(test)]2413#[test]2414fn test_generate() {2415 let args = parse_low_raw(None::<&str>).unwrap();2416 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);24172418 let args = parse_low_raw(["--generate", "man"]).unwrap();2419 assert_eq!(Mode::Generate(GenerateMode::Man), args.mode);24202421 let args = parse_low_raw(["--generate", "complete-bash"]).unwrap();2422 assert_eq!(Mode::Generate(GenerateMode::CompleteBash), args.mode);24232424 let args = parse_low_raw(["--generate", "complete-zsh"]).unwrap();2425 assert_eq!(Mode::Generate(GenerateMode::CompleteZsh), args.mode);24262427 let args = parse_low_raw(["--generate", "complete-fish"]).unwrap();2428 assert_eq!(Mode::Generate(GenerateMode::CompleteFish), args.mode);24292430 let args = parse_low_raw(["--generate", "complete-powershell"]).unwrap();2431 assert_eq!(Mode::Generate(GenerateMode::CompletePowerShell), args.mode);24322433 let args =2434 parse_low_raw(["--generate", "complete-bash", "--generate=man"])2435 .unwrap();2436 assert_eq!(Mode::Generate(GenerateMode::Man), args.mode);24372438 let args = parse_low_raw(["--generate", "man", "-l"]).unwrap();2439 assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);24402441 // An interesting quirk of how the modes override each other that lets2442 // you get back to the "default" mode of searching.2443 let args =2444 parse_low_raw(["--generate", "man", "--json", "--no-json"]).unwrap();2445 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);2446}24472448/// -g/--glob2449#[derive(Debug)]2450struct Glob;24512452impl Flag for Glob {2453 fn is_switch(&self) -> bool {2454 false2455 }2456 fn name_short(&self) -> Option<u8> {2457 Some(b'g')2458 }2459 fn name_long(&self) -> &'static str {2460 "glob"2461 }2462 fn doc_variable(&self) -> Option<&'static str> {2463 Some("GLOB")2464 }2465 fn doc_category(&self) -> Category {2466 Category::Filter2467 }2468 fn doc_short(&self) -> &'static str {2469 r"Include or exclude file paths."2470 }2471 fn doc_long(&self) -> &'static str {2472 r#"2473Include or exclude files and directories for searching that match the given2474glob. This always overrides any other ignore logic. Multiple glob flags may2475be used. Globbing rules match \fB.gitignore\fP globs. Precede a glob with a2476\fB!\fP to exclude it. If multiple globs match a file or directory, the glob2477given later in the command line takes precedence.2478.sp2479As an extension, globs support specifying alternatives:2480.BI "\-g '" ab{c,d}* '2481is equivalent to2482.BI "\-g " "abc " "\-g " abd.2483Empty alternatives like2484.BI "\-g '" ab{,c} '2485are not currently supported. Note that this syntax extension is also currently2486enabled in \fBgitignore\fP files, even though this syntax isn't supported by2487git itself. ripgrep may disable this syntax extension in gitignore files, but2488it will always remain available via the \flag{glob} flag.2489.sp2490When this flag is set, every file and directory is applied to it to test for2491a match. For example, if you only want to search in a particular directory2492\fIfoo\fP, then2493.BI "\-g " foo2494is incorrect because \fIfoo/bar\fP does not match2495the glob \fIfoo\fP. Instead, you should use2496.BI "\-g '" foo/** '.2497"#2498 }24992500 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2501 let glob = convert::string(v.unwrap_value())?;2502 args.globs.push(glob);2503 Ok(())2504 }2505}25062507#[cfg(test)]2508#[test]2509fn test_glob() {2510 let args = parse_low_raw(None::<&str>).unwrap();2511 assert_eq!(Vec::<String>::new(), args.globs);25122513 let args = parse_low_raw(["--glob", "foo"]).unwrap();2514 assert_eq!(vec!["foo".to_string()], args.globs);25152516 let args = parse_low_raw(["--glob=foo"]).unwrap();2517 assert_eq!(vec!["foo".to_string()], args.globs);25182519 let args = parse_low_raw(["-g", "foo"]).unwrap();2520 assert_eq!(vec!["foo".to_string()], args.globs);25212522 let args = parse_low_raw(["-gfoo"]).unwrap();2523 assert_eq!(vec!["foo".to_string()], args.globs);25242525 let args = parse_low_raw(["--glob", "-foo"]).unwrap();2526 assert_eq!(vec!["-foo".to_string()], args.globs);25272528 let args = parse_low_raw(["--glob=-foo"]).unwrap();2529 assert_eq!(vec!["-foo".to_string()], args.globs);25302531 let args = parse_low_raw(["-g", "-foo"]).unwrap();2532 assert_eq!(vec!["-foo".to_string()], args.globs);25332534 let args = parse_low_raw(["-g-foo"]).unwrap();2535 assert_eq!(vec!["-foo".to_string()], args.globs);2536}25372538/// --glob-case-insensitive2539#[derive(Debug)]2540struct GlobCaseInsensitive;25412542impl Flag for GlobCaseInsensitive {2543 fn is_switch(&self) -> bool {2544 true2545 }2546 fn name_long(&self) -> &'static str {2547 "glob-case-insensitive"2548 }2549 fn name_negated(&self) -> Option<&'static str> {2550 Some("no-glob-case-insensitive")2551 }2552 fn doc_category(&self) -> Category {2553 Category::Filter2554 }2555 fn doc_short(&self) -> &'static str {2556 r"Process all glob patterns case insensitively."2557 }2558 fn doc_long(&self) -> &'static str {2559 r"2560Process all glob patterns given with the \flag{glob} flag case insensitively.2561This effectively treats \flag{glob} as \flag{iglob}.2562"2563 }25642565 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2566 args.glob_case_insensitive = v.unwrap_switch();2567 Ok(())2568 }2569}25702571#[cfg(test)]2572#[test]2573fn test_glob_case_insensitive() {2574 let args = parse_low_raw(None::<&str>).unwrap();2575 assert_eq!(false, args.glob_case_insensitive);25762577 let args = parse_low_raw(["--glob-case-insensitive"]).unwrap();2578 assert_eq!(true, args.glob_case_insensitive);25792580 let args = parse_low_raw([2581 "--glob-case-insensitive",2582 "--no-glob-case-insensitive",2583 ])2584 .unwrap();2585 assert_eq!(false, args.glob_case_insensitive);25862587 let args = parse_low_raw([2588 "--no-glob-case-insensitive",2589 "--glob-case-insensitive",2590 ])2591 .unwrap();2592 assert_eq!(true, args.glob_case_insensitive);2593}25942595/// --heading2596#[derive(Debug)]2597struct Heading;25982599impl Flag for Heading {2600 fn is_switch(&self) -> bool {2601 true2602 }2603 fn name_long(&self) -> &'static str {2604 "heading"2605 }2606 fn name_negated(&self) -> Option<&'static str> {2607 Some("no-heading")2608 }2609 fn doc_category(&self) -> Category {2610 Category::Output2611 }2612 fn doc_short(&self) -> &'static str {2613 r"Print matches grouped by each file."2614 }2615 fn doc_long(&self) -> &'static str {2616 r"2617This flag prints the file path above clusters of matches from each file instead2618of printing the file path as a prefix for each matched line. This is the2619default mode when printing to a terminal.2620.sp2621When \fBstdout\fP is not a terminal, then ripgrep will default to the standard2622grep-like format. Once can force this format in Unix-like environments by2623piping the output of ripgrep to \fBcat\fP. For example, \fBrg\fP \fIfoo\fP \fB|2624cat\fP.2625"2626 }26272628 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2629 args.heading = Some(v.unwrap_switch());2630 Ok(())2631 }2632}26332634#[cfg(test)]2635#[test]2636fn test_heading() {2637 let args = parse_low_raw(None::<&str>).unwrap();2638 assert_eq!(None, args.heading);26392640 let args = parse_low_raw(["--heading"]).unwrap();2641 assert_eq!(Some(true), args.heading);26422643 let args = parse_low_raw(["--no-heading"]).unwrap();2644 assert_eq!(Some(false), args.heading);26452646 let args = parse_low_raw(["--heading", "--no-heading"]).unwrap();2647 assert_eq!(Some(false), args.heading);26482649 let args = parse_low_raw(["--no-heading", "--heading"]).unwrap();2650 assert_eq!(Some(true), args.heading);2651}26522653/// -h/--help2654#[derive(Debug)]2655struct Help;26562657impl Flag for Help {2658 fn is_switch(&self) -> bool {2659 true2660 }2661 fn name_long(&self) -> &'static str {2662 "help"2663 }2664 fn name_short(&self) -> Option<u8> {2665 Some(b'h')2666 }2667 fn doc_category(&self) -> Category {2668 Category::Output2669 }2670 fn doc_short(&self) -> &'static str {2671 r"Show help output."2672 }2673 fn doc_long(&self) -> &'static str {2674 r"2675This flag prints the help output for ripgrep.2676.sp2677Unlike most other flags, the behavior of the short flag, \fB\-h\fP, and the2678long flag, \fB\-\-help\fP, is different. The short flag will show a condensed2679help output while the long flag will show a verbose help output. The verbose2680help output has complete documentation, where as the condensed help output will2681show only a single line for every flag.2682"2683 }26842685 fn update(&self, v: FlagValue, _: &mut LowArgs) -> anyhow::Result<()> {2686 assert!(v.unwrap_switch(), "--help has no negation");2687 // Since this flag has different semantics for -h and --help and the2688 // Flag trait doesn't support encoding this sort of thing, we handle it2689 // as a special case in the parser.2690 Ok(())2691 }2692}26932694#[cfg(test)]2695#[test]2696fn test_help() {2697 let args = parse_low_raw(None::<&str>).unwrap();2698 assert_eq!(None, args.special);26992700 let args = parse_low_raw(["-h"]).unwrap();2701 assert_eq!(Some(SpecialMode::HelpShort), args.special);27022703 let args = parse_low_raw(["--help"]).unwrap();2704 assert_eq!(Some(SpecialMode::HelpLong), args.special);27052706 let args = parse_low_raw(["-h", "--help"]).unwrap();2707 assert_eq!(Some(SpecialMode::HelpLong), args.special);27082709 let args = parse_low_raw(["--help", "-h"]).unwrap();2710 assert_eq!(Some(SpecialMode::HelpShort), args.special);2711}27122713/// -./--hidden2714#[derive(Debug)]2715struct Hidden;27162717impl Flag for Hidden {2718 fn is_switch(&self) -> bool {2719 true2720 }2721 fn name_short(&self) -> Option<u8> {2722 Some(b'.')2723 }2724 fn name_long(&self) -> &'static str {2725 "hidden"2726 }2727 fn name_negated(&self) -> Option<&'static str> {2728 Some("no-hidden")2729 }2730 fn doc_category(&self) -> Category {2731 Category::Filter2732 }2733 fn doc_short(&self) -> &'static str {2734 r"Search hidden files and directories."2735 }2736 fn doc_long(&self) -> &'static str {2737 r#"2738Search hidden files and directories. By default, hidden files and directories2739are skipped. Note that if a hidden file or a directory is whitelisted in2740an ignore file, then it will be searched even if this flag isn't provided.2741Similarly if a hidden file or directory is given explicitly as an argumnet to2742ripgrep.2743.sp2744A file or directory is considered hidden if its base name starts with a dot2745character (\fB.\fP). On operating systems which support a "hidden" file2746attribute, like Windows, files with this attribute are also considered hidden.2747"#2748 }27492750 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2751 args.hidden = v.unwrap_switch();2752 Ok(())2753 }2754}27552756#[cfg(test)]2757#[test]2758fn test_hidden() {2759 let args = parse_low_raw(None::<&str>).unwrap();2760 assert_eq!(false, args.hidden);27612762 let args = parse_low_raw(["--hidden"]).unwrap();2763 assert_eq!(true, args.hidden);27642765 let args = parse_low_raw(["-."]).unwrap();2766 assert_eq!(true, args.hidden);27672768 let args = parse_low_raw(["-.", "--no-hidden"]).unwrap();2769 assert_eq!(false, args.hidden);27702771 let args = parse_low_raw(["--no-hidden", "-."]).unwrap();2772 assert_eq!(true, args.hidden);2773}27742775/// --hostname-bin2776#[derive(Debug)]2777struct HostnameBin;27782779impl Flag for HostnameBin {2780 fn is_switch(&self) -> bool {2781 false2782 }2783 fn name_long(&self) -> &'static str {2784 "hostname-bin"2785 }2786 fn doc_variable(&self) -> Option<&'static str> {2787 Some("COMMAND")2788 }2789 fn doc_category(&self) -> Category {2790 Category::Output2791 }2792 fn doc_short(&self) -> &'static str {2793 r"Run a program to get this system's hostname."2794 }2795 fn doc_long(&self) -> &'static str {2796 r#"2797This flag controls how ripgrep determines this system's hostname. The flag's2798value should correspond to an executable (either a path or something that can2799be found via your system's \fBPATH\fP environment variable). When set, ripgrep2800will run this executable, with no arguments, and treat its output (with leading2801and trailing whitespace stripped) as your system's hostname.2802.sp2803When not set (the default, or the empty string), ripgrep will try to2804automatically detect your system's hostname. On Unix, this corresponds2805to calling \fBgethostname\fP. On Windows, this corresponds to calling2806\fBGetComputerNameExW\fP to fetch the system's "physical DNS hostname."2807.sp2808ripgrep uses your system's hostname for producing hyperlinks.2809"#2810 }28112812 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2813 let path = PathBuf::from(v.unwrap_value());2814 args.hostname_bin =2815 if path.as_os_str().is_empty() { None } else { Some(path) };2816 Ok(())2817 }2818}28192820#[cfg(test)]2821#[test]2822fn test_hostname_bin() {2823 let args = parse_low_raw(None::<&str>).unwrap();2824 assert_eq!(None, args.hostname_bin);28252826 let args = parse_low_raw(["--hostname-bin", "foo"]).unwrap();2827 assert_eq!(Some(PathBuf::from("foo")), args.hostname_bin);28282829 let args = parse_low_raw(["--hostname-bin=foo"]).unwrap();2830 assert_eq!(Some(PathBuf::from("foo")), args.hostname_bin);2831}28322833/// --hyperlink-format2834#[derive(Debug)]2835struct HyperlinkFormat;28362837impl Flag for HyperlinkFormat {2838 fn is_switch(&self) -> bool {2839 false2840 }2841 fn name_long(&self) -> &'static str {2842 "hyperlink-format"2843 }2844 fn doc_variable(&self) -> Option<&'static str> {2845 Some("FORMAT")2846 }2847 fn doc_category(&self) -> Category {2848 Category::Output2849 }2850 fn doc_short(&self) -> &'static str {2851 r"Set the format of hyperlinks."2852 }2853 fn doc_long(&self) -> &'static str {2854 r#"2855Set the format of hyperlinks to use when printing results. Hyperlinks make2856certain elements of ripgrep's output, such as file paths, clickable. This2857generally only works in terminal emulators that support OSC-8 hyperlinks. For2858example, the format \fBfile://{host}{path}\fP will emit an RFC 8089 hyperlink.2859To see the format that ripgrep is using, pass the \flag{debug} flag.2860.sp2861Alternatively, a format string may correspond to one of the following aliases:2862\fBdefault\fP, \fBnone\fP, \fBfile\fP, \fBgrep+\fP, \fBkitty\fP, \fBmacvim\fP,2863\fBtextmate\fP, \fBvscode\fP, \fBvscode-insiders\fP, \fBvscodium\fP. The2864alias will be replaced with a format string that is intended to work for the2865corresponding application.2866.sp2867The following variables are available in the format string:2868.sp2869.TP 122870\fB{path}\fP2871Required. This is replaced with a path to a matching file. The path is2872guaranteed to be absolute and percent encoded such that it is valid to put into2873a URI. Note that a path is guaranteed to start with a /.2874.TP 122875\fB{host}\fP2876Optional. This is replaced with your system's hostname. On Unix, this2877corresponds to calling \fBgethostname\fP. On Windows, this corresponds to2878calling \fBGetComputerNameExW\fP to fetch the system's "physical DNS hostname."2879Alternatively, if \flag{hostname-bin} was provided, then the hostname returned2880from the output of that program will be returned. If no hostname could be2881found, then this variable is replaced with the empty string.2882.TP 122883\fB{line}\fP2884Optional. If appropriate, this is replaced with the line number of a match. If2885no line number is available (for example, if \fB\-\-no\-line\-number\fP was2886given), then it is automatically replaced with the value 1.2887.TP 122888\fB{column}\fP2889Optional, but requires the presence of \fB{line}\fP. If appropriate, this is2890replaced with the column number of a match. If no column number is available2891(for example, if \fB\-\-no\-column\fP was given), then it is automatically2892replaced with the value 1.2893.TP 122894\fB{wslprefix}\fP2895Optional. This is a special value that is set to2896\fBwsl$/\fP\fIWSL_DISTRO_NAME\fP, where \fIWSL_DISTRO_NAME\fP corresponds to2897the value of the equivalent environment variable. If the system is not Unix2898or if the \fIWSL_DISTRO_NAME\fP environment variable is not set, then this is2899replaced with the empty string.2900.PP2901A format string may be empty. An empty format string is equivalent to the2902\fBnone\fP alias. In this case, hyperlinks will be disabled.2903.sp2904At present, ripgrep does not enable hyperlinks by default. Users must opt into2905them. If you aren't sure what format to use, try \fBdefault\fP.2906.sp2907Like colors, when ripgrep detects that stdout is not connected to a tty, then2908hyperlinks are automatically disabled, regardless of the value of this flag.2909Users can pass \fB\-\-color=always\fP to forcefully emit hyperlinks.2910.sp2911Note that hyperlinks are only written when a path is also in the output2912and colors are enabled. To write hyperlinks without colors, you'll need to2913configure ripgrep to not colorize anything without actually disabling all ANSI2914escape codes completely:2915.sp2916.EX2917 \-\-colors 'path:none' \\2918 \-\-colors 'line:none' \\2919 \-\-colors 'column:none' \\2920 \-\-colors 'match:none'2921.EE2922.sp2923ripgrep works this way because it treats the \flag{color} flag as a proxy for2924whether ANSI escape codes should be used at all. This means that environment2925variables like \fBNO_COLOR=1\fP and \fBTERM=dumb\fP not only disable colors,2926but hyperlinks as well. Similarly, colors and hyperlinks are disabled when2927ripgrep is not writing to a tty. (Unless one forces the issue by setting2928\fB\-\-color=always\fP.)2929.sp2930If you're searching a file directly, for example:2931.sp2932.EX2933 rg foo path/to/file2934.EE2935.sp2936then hyperlinks will not be emitted since the path given does not appear2937in the output. To make the path appear, and thus also a hyperlink, use the2938\flag{with-filename} flag.2939.sp2940For more information on hyperlinks in terminal emulators, see:2941https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda2942"#2943 }29442945 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {2946 let v = v.unwrap_value();2947 let string = convert::str(&v)?;2948 let format = string.parse().context("invalid hyperlink format")?;2949 args.hyperlink_format = format;2950 Ok(())2951 }2952}29532954#[cfg(test)]2955#[test]2956fn test_hyperlink_format() {2957 let parseformat = |format: &str| {2958 format.parse::<grep::printer::HyperlinkFormat>().unwrap()2959 };29602961 let args = parse_low_raw(None::<&str>).unwrap();2962 assert_eq!(parseformat("none"), args.hyperlink_format);29632964 let args = parse_low_raw(["--hyperlink-format", "default"]).unwrap();2965 #[cfg(windows)]2966 assert_eq!(parseformat("file://{path}"), args.hyperlink_format);2967 #[cfg(not(windows))]2968 assert_eq!(parseformat("file://{host}{path}"), args.hyperlink_format);29692970 let args = parse_low_raw(["--hyperlink-format", "file"]).unwrap();2971 assert_eq!(parseformat("file://{host}{path}"), args.hyperlink_format);29722973 let args = parse_low_raw([2974 "--hyperlink-format",2975 "file",2976 "--hyperlink-format=grep+",2977 ])2978 .unwrap();2979 assert_eq!(parseformat("grep+://{path}:{line}"), args.hyperlink_format);29802981 let args =2982 parse_low_raw(["--hyperlink-format", "file://{host}{path}#{line}"])2983 .unwrap();2984 assert_eq!(2985 parseformat("file://{host}{path}#{line}"),2986 args.hyperlink_format2987 );29882989 let result = parse_low_raw(["--hyperlink-format", "file://heythere"]);2990 assert!(result.is_err(), "{result:?}");2991}29922993/// --iglob2994#[derive(Debug)]2995struct IGlob;29962997impl Flag for IGlob {2998 fn is_switch(&self) -> bool {2999 false3000 }3001 fn name_long(&self) -> &'static str {3002 "iglob"3003 }3004 fn doc_variable(&self) -> Option<&'static str> {3005 Some("GLOB")3006 }3007 fn doc_category(&self) -> Category {3008 Category::Filter3009 }3010 fn doc_short(&self) -> &'static str {3011 r"Include/exclude paths case insensitively."3012 }3013 fn doc_long(&self) -> &'static str {3014 r"3015Include or exclude files and directories for searching that match the given3016glob. This always overrides any other ignore logic. Multiple glob flags may3017be used. Globbing rules match \fB.gitignore\fP globs. Precede a glob with a3018\fB!\fP to exclude it. If multiple globs match a file or directory, the glob3019given later in the command line takes precedence. Globs used via this flag are3020matched case insensitively.3021"3022 }30233024 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3025 let glob = convert::string(v.unwrap_value())?;3026 args.iglobs.push(glob);3027 Ok(())3028 }3029}30303031#[cfg(test)]3032#[test]3033fn test_iglob() {3034 let args = parse_low_raw(None::<&str>).unwrap();3035 assert_eq!(Vec::<String>::new(), args.iglobs);30363037 let args = parse_low_raw(["--iglob", "foo"]).unwrap();3038 assert_eq!(vec!["foo".to_string()], args.iglobs);30393040 let args = parse_low_raw(["--iglob=foo"]).unwrap();3041 assert_eq!(vec!["foo".to_string()], args.iglobs);30423043 let args = parse_low_raw(["--iglob", "-foo"]).unwrap();3044 assert_eq!(vec!["-foo".to_string()], args.iglobs);30453046 let args = parse_low_raw(["--iglob=-foo"]).unwrap();3047 assert_eq!(vec!["-foo".to_string()], args.iglobs);3048}30493050/// -i/--ignore-case3051#[derive(Debug)]3052struct IgnoreCase;30533054impl Flag for IgnoreCase {3055 fn is_switch(&self) -> bool {3056 true3057 }3058 fn name_short(&self) -> Option<u8> {3059 Some(b'i')3060 }3061 fn name_long(&self) -> &'static str {3062 "ignore-case"3063 }3064 fn doc_category(&self) -> Category {3065 Category::Search3066 }3067 fn doc_short(&self) -> &'static str {3068 r"Case insensitive search."3069 }3070 fn doc_long(&self) -> &'static str {3071 r#"3072When this flag is provided, all patterns will be searched case insensitively.3073The case insensitivity rules used by ripgrep's default regex engine conform to3074Unicode's "simple" case folding rules.3075.sp3076This is a global option that applies to all patterns given to ripgrep.3077Individual patterns can still be matched case sensitively by using3078inline regex flags. For example, \fB(?\-i)abc\fP will match \fBabc\fP3079case sensitively even when this flag is used.3080.sp3081This flag overrides \flag{case-sensitive} and flag{smart-case}.3082"#3083 }30843085 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3086 assert!(v.unwrap_switch(), "flag has no negation");3087 args.case = CaseMode::Insensitive;3088 Ok(())3089 }3090}30913092#[cfg(test)]3093#[test]3094fn test_ignore_case() {3095 let args = parse_low_raw(None::<&str>).unwrap();3096 assert_eq!(CaseMode::Sensitive, args.case);30973098 let args = parse_low_raw(["--ignore-case"]).unwrap();3099 assert_eq!(CaseMode::Insensitive, args.case);31003101 let args = parse_low_raw(["-i"]).unwrap();3102 assert_eq!(CaseMode::Insensitive, args.case);31033104 let args = parse_low_raw(["-i", "-s"]).unwrap();3105 assert_eq!(CaseMode::Sensitive, args.case);31063107 let args = parse_low_raw(["-s", "-i"]).unwrap();3108 assert_eq!(CaseMode::Insensitive, args.case);3109}31103111/// --ignore-file3112#[derive(Debug)]3113struct IgnoreFile;31143115impl Flag for IgnoreFile {3116 fn is_switch(&self) -> bool {3117 false3118 }3119 fn name_long(&self) -> &'static str {3120 "ignore-file"3121 }3122 fn doc_variable(&self) -> Option<&'static str> {3123 Some("PATH")3124 }3125 fn doc_category(&self) -> Category {3126 Category::Filter3127 }3128 fn doc_short(&self) -> &'static str {3129 r"Specify additional ignore files."3130 }3131 fn doc_long(&self) -> &'static str {3132 r"3133Specifies a path to one or more \fBgitignore\fP formatted rules files.3134These patterns are applied after the patterns found in \fB.gitignore\fP,3135\fB.rgignore\fP and \fB.ignore\fP are applied and are matched relative to the3136current working directory. Multiple additional ignore files can be specified3137by using this flag repeatedly. When specifying multiple ignore files, earlier3138files have lower precedence than later files.3139.sp3140If you are looking for a way to include or exclude files and directories3141directly on the command line, then use \flag{glob} instead.3142"3143 }31443145 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3146 let path = PathBuf::from(v.unwrap_value());3147 args.ignore_file.push(path);3148 Ok(())3149 }3150}31513152#[cfg(test)]3153#[test]3154fn test_ignore_file() {3155 let args = parse_low_raw(None::<&str>).unwrap();3156 assert_eq!(Vec::<PathBuf>::new(), args.ignore_file);31573158 let args = parse_low_raw(["--ignore-file", "foo"]).unwrap();3159 assert_eq!(vec![PathBuf::from("foo")], args.ignore_file);31603161 let args = parse_low_raw(["--ignore-file", "foo", "--ignore-file", "bar"])3162 .unwrap();3163 assert_eq!(3164 vec![PathBuf::from("foo"), PathBuf::from("bar")],3165 args.ignore_file3166 );3167}31683169/// --ignore-file-case-insensitive3170#[derive(Debug)]3171struct IgnoreFileCaseInsensitive;31723173impl Flag for IgnoreFileCaseInsensitive {3174 fn is_switch(&self) -> bool {3175 true3176 }3177 fn name_long(&self) -> &'static str {3178 "ignore-file-case-insensitive"3179 }3180 fn name_negated(&self) -> Option<&'static str> {3181 Some("no-ignore-file-case-insensitive")3182 }3183 fn doc_category(&self) -> Category {3184 Category::Filter3185 }3186 fn doc_short(&self) -> &'static str {3187 r"Process ignore files case insensitively."3188 }3189 fn doc_long(&self) -> &'static str {3190 r"3191Process ignore files (\fB.gitignore\fP, \fB.ignore\fP, etc.) case3192insensitively. Note that this comes with a performance penalty and is most3193useful on case insensitive file systems (such as Windows).3194"3195 }31963197 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3198 args.ignore_file_case_insensitive = v.unwrap_switch();3199 Ok(())3200 }3201}32023203#[cfg(test)]3204#[test]3205fn test_ignore_file_case_insensitive() {3206 let args = parse_low_raw(None::<&str>).unwrap();3207 assert_eq!(false, args.ignore_file_case_insensitive);32083209 let args = parse_low_raw(["--ignore-file-case-insensitive"]).unwrap();3210 assert_eq!(true, args.ignore_file_case_insensitive);32113212 let args = parse_low_raw([3213 "--ignore-file-case-insensitive",3214 "--no-ignore-file-case-insensitive",3215 ])3216 .unwrap();3217 assert_eq!(false, args.ignore_file_case_insensitive);32183219 let args = parse_low_raw([3220 "--no-ignore-file-case-insensitive",3221 "--ignore-file-case-insensitive",3222 ])3223 .unwrap();3224 assert_eq!(true, args.ignore_file_case_insensitive);3225}32263227/// --include-zero3228#[derive(Debug)]3229struct IncludeZero;32303231impl Flag for IncludeZero {3232 fn is_switch(&self) -> bool {3233 true3234 }3235 fn name_long(&self) -> &'static str {3236 "include-zero"3237 }3238 fn name_negated(&self) -> Option<&'static str> {3239 Some("no-include-zero")3240 }3241 fn doc_category(&self) -> Category {3242 Category::Output3243 }3244 fn doc_short(&self) -> &'static str {3245 r"Include zero matches in summary output."3246 }3247 fn doc_long(&self) -> &'static str {3248 r"3249When used with \flag{count} or \flag{count-matches}, this causes ripgrep to3250print the number of matches for each file even if there were zero matches. This3251is disabled by default but can be enabled to make ripgrep behave more like3252grep.3253"3254 }32553256 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3257 args.include_zero = v.unwrap_switch();3258 Ok(())3259 }3260}32613262#[cfg(test)]3263#[test]3264fn test_include_zero() {3265 let args = parse_low_raw(None::<&str>).unwrap();3266 assert_eq!(false, args.include_zero);32673268 let args = parse_low_raw(["--include-zero"]).unwrap();3269 assert_eq!(true, args.include_zero);32703271 let args = parse_low_raw(["--include-zero", "--no-include-zero"]).unwrap();3272 assert_eq!(false, args.include_zero);3273}32743275/// -v/--invert-match3276#[derive(Debug)]3277struct InvertMatch;32783279impl Flag for InvertMatch {3280 fn is_switch(&self) -> bool {3281 true3282 }3283 fn name_short(&self) -> Option<u8> {3284 Some(b'v')3285 }3286 fn name_long(&self) -> &'static str {3287 "invert-match"3288 }3289 fn name_negated(&self) -> Option<&'static str> {3290 Some("no-invert-match")3291 }3292 fn doc_category(&self) -> Category {3293 Category::Search3294 }3295 fn doc_short(&self) -> &'static str {3296 r"Invert matching."3297 }3298 fn doc_long(&self) -> &'static str {3299 r"3300This flag inverts matching. That is, instead of printing lines that match,3301ripgrep will print lines that don't match.3302.sp3303Note that this only inverts line-by-line matching. For example, combining this3304flag with \flag{files-with-matches} will emit files that contain any lines3305that do not match the patterns given. That's not the same as, for example,3306\flag{files-without-match}, which will emit files that do not contain any3307matching lines.3308"3309 }33103311 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3312 args.invert_match = v.unwrap_switch();3313 Ok(())3314 }3315}33163317#[cfg(test)]3318#[test]3319fn test_invert_match() {3320 let args = parse_low_raw(None::<&str>).unwrap();3321 assert_eq!(false, args.invert_match);33223323 let args = parse_low_raw(["--invert-match"]).unwrap();3324 assert_eq!(true, args.invert_match);33253326 let args = parse_low_raw(["-v"]).unwrap();3327 assert_eq!(true, args.invert_match);33283329 let args = parse_low_raw(["-v", "--no-invert-match"]).unwrap();3330 assert_eq!(false, args.invert_match);3331}33323333/// --json3334#[derive(Debug)]3335struct JSON;33363337impl Flag for JSON {3338 fn is_switch(&self) -> bool {3339 true3340 }3341 fn name_long(&self) -> &'static str {3342 "json"3343 }3344 fn name_negated(&self) -> Option<&'static str> {3345 Some("no-json")3346 }3347 fn doc_category(&self) -> Category {3348 Category::OutputModes3349 }3350 fn doc_short(&self) -> &'static str {3351 r"Show search results in a JSON Lines format."3352 }3353 fn doc_long(&self) -> &'static str {3354 r"3355Enable printing results in a JSON Lines format.3356.sp3357When this flag is provided, ripgrep will emit a sequence of messages, each3358encoded as a JSON object, where there are five different message types:3359.sp3360.TP 123361\fBbegin\fP3362A message that indicates a file is being searched and contains at least one3363match.3364.TP 123365\fBend\fP3366A message the indicates a file is done being searched. This message also3367include summary statistics about the search for a particular file.3368.TP 123369\fBmatch\fP3370A message that indicates a match was found. This includes the text and offsets3371of the match.3372.TP 123373\fBcontext\fP3374A message that indicates a contextual line was found. This includes the text of3375the line, along with any match information if the search was inverted.3376.TP 123377\fBsummary\fP3378The final message emitted by ripgrep that contains summary statistics about the3379search across all files.3380.PP3381Since file paths or the contents of files are not guaranteed to be valid3382UTF-8 and JSON itself must be representable by a Unicode encoding, ripgrep3383will emit all data elements as objects with one of two keys: \fBtext\fP or3384\fBbytes\fP. \fBtext\fP is a normal JSON string when the data is valid UTF-83385while \fBbytes\fP is the base64 encoded contents of the data.3386.sp3387The JSON Lines format is only supported for showing search results. It cannot3388be used with other flags that emit other types of output, such as \flag{files},3389\flag{files-with-matches}, \flag{files-without-match}, \flag{count} or3390\flag{count-matches}. ripgrep will report an error if any of the aforementioned3391flags are used in concert with \flag{json}.3392.sp3393Other flags that control aspects of the standard output such as3394\flag{only-matching}, \flag{heading}, \flag{replace}, \flag{max-columns}, etc.,3395have no effect when \flag{json} is set.3396.sp3397A more complete description of the JSON format used can be found here:3398\fIhttps://docs.rs/grep-printer/*/grep_printer/struct.JSON.html\fP.3399"3400 }34013402 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3403 if v.unwrap_switch() {3404 args.mode.update(Mode::Search(SearchMode::JSON));3405 } else if matches!(args.mode, Mode::Search(SearchMode::JSON)) {3406 // --no-json only reverts to the default mode if the mode is3407 // JSON, otherwise it's a no-op.3408 args.mode.update(Mode::Search(SearchMode::Standard));3409 }3410 Ok(())3411 }3412}34133414#[cfg(test)]3415#[test]3416fn test_json() {3417 let args = parse_low_raw(None::<&str>).unwrap();3418 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);34193420 let args = parse_low_raw(["--json"]).unwrap();3421 assert_eq!(Mode::Search(SearchMode::JSON), args.mode);34223423 let args = parse_low_raw(["--json", "--no-json"]).unwrap();3424 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);34253426 let args = parse_low_raw(["--json", "--files", "--no-json"]).unwrap();3427 assert_eq!(Mode::Files, args.mode);34283429 let args = parse_low_raw(["--json", "-l", "--no-json"]).unwrap();3430 assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);3431}34323433/// --line-buffered3434#[derive(Debug)]3435struct LineBuffered;34363437impl Flag for LineBuffered {3438 fn is_switch(&self) -> bool {3439 true3440 }3441 fn name_long(&self) -> &'static str {3442 "line-buffered"3443 }3444 fn name_negated(&self) -> Option<&'static str> {3445 Some("no-line-buffered")3446 }3447 fn doc_category(&self) -> Category {3448 Category::Output3449 }3450 fn doc_short(&self) -> &'static str {3451 r"Force line buffering."3452 }3453 fn doc_long(&self) -> &'static str {3454 r"3455When enabled, ripgrep will always use line buffering. That is, whenever a3456matching line is found, it will be flushed to stdout immediately. This is3457the default when ripgrep's stdout is connected to a terminal, but otherwise,3458ripgrep will use block buffering, which is typically faster. This flag forces3459ripgrep to use line buffering even if it would otherwise use block buffering.3460This is typically useful in shell pipelines, for example:3461.sp3462.EX3463 tail -f something.log | rg foo --line-buffered | rg bar3464.EE3465.sp3466This overrides the \flag{block-buffered} flag.3467"3468 }34693470 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3471 args.buffer = if v.unwrap_switch() {3472 BufferMode::Line3473 } else {3474 BufferMode::Auto3475 };3476 Ok(())3477 }3478}34793480#[cfg(test)]3481#[test]3482fn test_line_buffered() {3483 let args = parse_low_raw(None::<&str>).unwrap();3484 assert_eq!(BufferMode::Auto, args.buffer);34853486 let args = parse_low_raw(["--line-buffered"]).unwrap();3487 assert_eq!(BufferMode::Line, args.buffer);34883489 let args =3490 parse_low_raw(["--line-buffered", "--no-line-buffered"]).unwrap();3491 assert_eq!(BufferMode::Auto, args.buffer);34923493 let args = parse_low_raw(["--line-buffered", "--block-buffered"]).unwrap();3494 assert_eq!(BufferMode::Block, args.buffer);3495}34963497/// -n/--line-number3498#[derive(Debug)]3499struct LineNumber;35003501impl Flag for LineNumber {3502 fn is_switch(&self) -> bool {3503 true3504 }3505 fn name_short(&self) -> Option<u8> {3506 Some(b'n')3507 }3508 fn name_long(&self) -> &'static str {3509 "line-number"3510 }3511 fn doc_category(&self) -> Category {3512 Category::Output3513 }3514 fn doc_short(&self) -> &'static str {3515 r"Show line numbers."3516 }3517 fn doc_long(&self) -> &'static str {3518 r"3519Show line numbers (1-based). This is enabled by default stdout is connected to3520a tty.3521.sp3522This flag can be disabled by \flag{no-line-number}.3523"3524 }35253526 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3527 assert!(v.unwrap_switch(), "--line-number has no automatic negation");3528 args.line_number = Some(true);3529 Ok(())3530 }3531}35323533#[cfg(test)]3534#[test]3535fn test_line_number() {3536 let args = parse_low_raw(None::<&str>).unwrap();3537 assert_eq!(None, args.line_number);35383539 let args = parse_low_raw(["--line-number"]).unwrap();3540 assert_eq!(Some(true), args.line_number);35413542 let args = parse_low_raw(["-n"]).unwrap();3543 assert_eq!(Some(true), args.line_number);35443545 let args = parse_low_raw(["-n", "--no-line-number"]).unwrap();3546 assert_eq!(Some(false), args.line_number);3547}35483549/// -N/--no-line-number3550#[derive(Debug)]3551struct LineNumberNo;35523553impl Flag for LineNumberNo {3554 fn is_switch(&self) -> bool {3555 true3556 }3557 fn name_short(&self) -> Option<u8> {3558 Some(b'N')3559 }3560 fn name_long(&self) -> &'static str {3561 "no-line-number"3562 }3563 fn doc_category(&self) -> Category {3564 Category::Output3565 }3566 fn doc_short(&self) -> &'static str {3567 r"Suppress line numbers."3568 }3569 fn doc_long(&self) -> &'static str {3570 r"3571Suppress line numbers. Line numbers are off by default when stdout is not3572connected to a tty.3573.sp3574Line numbers can be forcefully turned on by \flag{line-number}.3575"3576 }35773578 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3579 assert!(3580 v.unwrap_switch(),3581 "--no-line-number has no automatic negation"3582 );3583 args.line_number = Some(false);3584 Ok(())3585 }3586}35873588#[cfg(test)]3589#[test]3590fn test_no_line_number() {3591 let args = parse_low_raw(None::<&str>).unwrap();3592 assert_eq!(None, args.line_number);35933594 let args = parse_low_raw(["--no-line-number"]).unwrap();3595 assert_eq!(Some(false), args.line_number);35963597 let args = parse_low_raw(["-N"]).unwrap();3598 assert_eq!(Some(false), args.line_number);35993600 let args = parse_low_raw(["-N", "--line-number"]).unwrap();3601 assert_eq!(Some(true), args.line_number);3602}36033604/// -x/--line-regexp3605#[derive(Debug)]3606struct LineRegexp;36073608impl Flag for LineRegexp {3609 fn is_switch(&self) -> bool {3610 true3611 }3612 fn name_short(&self) -> Option<u8> {3613 Some(b'x')3614 }3615 fn name_long(&self) -> &'static str {3616 "line-regexp"3617 }3618 fn doc_category(&self) -> Category {3619 Category::Search3620 }3621 fn doc_short(&self) -> &'static str {3622 r"Show matches surrounded by line boundaries."3623 }3624 fn doc_long(&self) -> &'static str {3625 r"3626When enabled, ripgrep will only show matches surrounded by line boundaries.3627This is equivalent to surrounding every pattern with \fB^\fP and \fB$\fP. In3628other words, this only prints lines where the entire line participates in a3629match.3630.sp3631This overrides the \flag{word-regexp} flag.3632"3633 }36343635 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3636 assert!(v.unwrap_switch(), "--line-regexp has no negation");3637 args.boundary = Some(BoundaryMode::Line);3638 Ok(())3639 }3640}36413642#[cfg(test)]3643#[test]3644fn test_line_regexp() {3645 let args = parse_low_raw(None::<&str>).unwrap();3646 assert_eq!(None, args.boundary);36473648 let args = parse_low_raw(["--line-regexp"]).unwrap();3649 assert_eq!(Some(BoundaryMode::Line), args.boundary);36503651 let args = parse_low_raw(["-x"]).unwrap();3652 assert_eq!(Some(BoundaryMode::Line), args.boundary);3653}36543655/// -M/--max-columns3656#[derive(Debug)]3657struct MaxColumns;36583659impl Flag for MaxColumns {3660 fn is_switch(&self) -> bool {3661 false3662 }3663 fn name_short(&self) -> Option<u8> {3664 Some(b'M')3665 }3666 fn name_long(&self) -> &'static str {3667 "max-columns"3668 }3669 fn doc_variable(&self) -> Option<&'static str> {3670 Some("NUM")3671 }3672 fn doc_category(&self) -> Category {3673 Category::Output3674 }3675 fn doc_short(&self) -> &'static str {3676 r"Omit lines longer than this limit."3677 }3678 fn doc_long(&self) -> &'static str {3679 r"3680When given, ripgrep will omit lines longer than this limit in bytes. Instead of3681printing long lines, only the number of matches in that line is printed.3682.sp3683When this flag is omitted or is set to \fB0\fP, then it has no effect.3684"3685 }36863687 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3688 let max = convert::u64(&v.unwrap_value())?;3689 args.max_columns = if max == 0 { None } else { Some(max) };3690 Ok(())3691 }3692}36933694#[cfg(test)]3695#[test]3696fn test_max_columns() {3697 let args = parse_low_raw(None::<&str>).unwrap();3698 assert_eq!(None, args.max_columns);36993700 let args = parse_low_raw(["--max-columns", "5"]).unwrap();3701 assert_eq!(Some(5), args.max_columns);37023703 let args = parse_low_raw(["-M", "5"]).unwrap();3704 assert_eq!(Some(5), args.max_columns);37053706 let args = parse_low_raw(["-M5"]).unwrap();3707 assert_eq!(Some(5), args.max_columns);37083709 let args = parse_low_raw(["--max-columns", "5", "-M0"]).unwrap();3710 assert_eq!(None, args.max_columns);3711}37123713/// --max-columns-preview3714#[derive(Debug)]3715struct MaxColumnsPreview;37163717impl Flag for MaxColumnsPreview {3718 fn is_switch(&self) -> bool {3719 true3720 }3721 fn name_long(&self) -> &'static str {3722 "max-columns-preview"3723 }3724 fn name_negated(&self) -> Option<&'static str> {3725 Some("no-max-columns-preview")3726 }3727 fn doc_category(&self) -> Category {3728 Category::Output3729 }3730 fn doc_short(&self) -> &'static str {3731 r"Show preview for lines exceeding the limit."3732 }3733 fn doc_long(&self) -> &'static str {3734 r"3735Prints a preview for lines exceeding the configured max column limit.3736.sp3737When the \flag{max-columns} flag is used, ripgrep will by default completely3738replace any line that is too long with a message indicating that a matching3739line was removed. When this flag is combined with \flag{max-columns}, a preview3740of the line (corresponding to the limit size) is shown instead, where the part3741of the line exceeding the limit is not shown.3742.sp3743If the \flag{max-columns} flag is not set, then this has no effect.3744"3745 }37463747 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3748 args.max_columns_preview = v.unwrap_switch();3749 Ok(())3750 }3751}37523753#[cfg(test)]3754#[test]3755fn test_max_columns_preview() {3756 let args = parse_low_raw(None::<&str>).unwrap();3757 assert_eq!(false, args.max_columns_preview);37583759 let args = parse_low_raw(["--max-columns-preview"]).unwrap();3760 assert_eq!(true, args.max_columns_preview);37613762 let args =3763 parse_low_raw(["--max-columns-preview", "--no-max-columns-preview"])3764 .unwrap();3765 assert_eq!(false, args.max_columns_preview);3766}37673768/// -m/--max-count3769#[derive(Debug)]3770struct MaxCount;37713772impl Flag for MaxCount {3773 fn is_switch(&self) -> bool {3774 false3775 }3776 fn name_short(&self) -> Option<u8> {3777 Some(b'm')3778 }3779 fn name_long(&self) -> &'static str {3780 "max-count"3781 }3782 fn doc_variable(&self) -> Option<&'static str> {3783 Some("NUM")3784 }3785 fn doc_category(&self) -> Category {3786 Category::Search3787 }3788 fn doc_short(&self) -> &'static str {3789 r"Limit the number of matching lines."3790 }3791 fn doc_long(&self) -> &'static str {3792 r"3793Limit the number of matching lines per file searched to \fINUM\fP.3794.sp3795Note that \fB0\fP is a legal value but not likely to be useful. When used,3796ripgrep won't search anything.3797"3798 }37993800 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3801 args.max_count = Some(convert::u64(&v.unwrap_value())?);3802 Ok(())3803 }3804}38053806#[cfg(test)]3807#[test]3808fn test_max_count() {3809 let args = parse_low_raw(None::<&str>).unwrap();3810 assert_eq!(None, args.max_count);38113812 let args = parse_low_raw(["--max-count", "5"]).unwrap();3813 assert_eq!(Some(5), args.max_count);38143815 let args = parse_low_raw(["-m", "5"]).unwrap();3816 assert_eq!(Some(5), args.max_count);38173818 let args = parse_low_raw(["-m", "5", "--max-count=10"]).unwrap();3819 assert_eq!(Some(10), args.max_count);3820 let args = parse_low_raw(["-m0"]).unwrap();3821 assert_eq!(Some(0), args.max_count);3822}38233824/// --max-depth3825#[derive(Debug)]3826struct MaxDepth;38273828impl Flag for MaxDepth {3829 fn is_switch(&self) -> bool {3830 false3831 }3832 fn name_long(&self) -> &'static str {3833 "max-depth"3834 }3835 fn aliases(&self) -> &'static [&'static str] {3836 &["maxdepth"]3837 }3838 fn doc_variable(&self) -> Option<&'static str> {3839 Some("NUM")3840 }3841 fn doc_category(&self) -> Category {3842 Category::Filter3843 }3844 fn doc_short(&self) -> &'static str {3845 r"Descend at most NUM directories."3846 }3847 fn doc_long(&self) -> &'static str {3848 r"3849This flag limits the depth of directory traversal to \fINUM\fP levels beyond3850the paths given. A value of \fB0\fP only searches the explicitly given paths3851themselves.3852.sp3853For example, \fBrg --max-depth 0 \fP\fIdir/\fP is a no-op because \fIdir/\fP3854will not be descended into. \fBrg --max-depth 1 \fP\fIdir/\fP will search only3855the direct children of \fIdir\fP.3856.sp3857An alternative spelling for this flag is \fB\-\-maxdepth\fP.3858"3859 }38603861 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3862 args.max_depth = Some(convert::usize(&v.unwrap_value())?);3863 Ok(())3864 }3865}38663867#[cfg(test)]3868#[test]3869fn test_max_depth() {3870 let args = parse_low_raw(None::<&str>).unwrap();3871 assert_eq!(None, args.max_depth);38723873 let args = parse_low_raw(["--max-depth", "5"]).unwrap();3874 assert_eq!(Some(5), args.max_depth);38753876 let args = parse_low_raw(["--max-depth", "5", "--max-depth=10"]).unwrap();3877 assert_eq!(Some(10), args.max_depth);38783879 let args = parse_low_raw(["--max-depth", "0"]).unwrap();3880 assert_eq!(Some(0), args.max_depth);38813882 let args = parse_low_raw(["--maxdepth", "5"]).unwrap();3883 assert_eq!(Some(5), args.max_depth);3884}38853886/// --max-filesize3887#[derive(Debug)]3888struct MaxFilesize;38893890impl Flag for MaxFilesize {3891 fn is_switch(&self) -> bool {3892 false3893 }3894 fn name_long(&self) -> &'static str {3895 "max-filesize"3896 }3897 fn doc_variable(&self) -> Option<&'static str> {3898 Some("NUM+SUFFIX?")3899 }3900 fn doc_category(&self) -> Category {3901 Category::Filter3902 }3903 fn doc_short(&self) -> &'static str {3904 r"Ignore files larger than NUM in size."3905 }3906 fn doc_long(&self) -> &'static str {3907 r"3908Ignore files larger than \fINUM\fP in size. This does not apply to directories.3909.sp3910The input format accepts suffixes of \fBK\fP, \fBM\fP or \fBG\fP which3911correspond to kilobytes, megabytes and gigabytes, respectively. If no suffix is3912provided the input is treated as bytes.3913.sp3914Examples: \fB\-\-max-filesize 50K\fP or \fB\-\-max\-filesize 80M\fP.3915"3916 }39173918 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3919 let v = v.unwrap_value();3920 args.max_filesize = Some(convert::human_readable_u64(&v)?);3921 Ok(())3922 }3923}39243925#[cfg(test)]3926#[test]3927fn test_max_filesize() {3928 let args = parse_low_raw(None::<&str>).unwrap();3929 assert_eq!(None, args.max_filesize);39303931 let args = parse_low_raw(["--max-filesize", "1024"]).unwrap();3932 assert_eq!(Some(1024), args.max_filesize);39333934 let args = parse_low_raw(["--max-filesize", "1K"]).unwrap();3935 assert_eq!(Some(1024), args.max_filesize);39363937 let args =3938 parse_low_raw(["--max-filesize", "1K", "--max-filesize=1M"]).unwrap();3939 assert_eq!(Some(1024 * 1024), args.max_filesize);3940}39413942/// --mmap3943#[derive(Debug)]3944struct Mmap;39453946impl Flag for Mmap {3947 fn is_switch(&self) -> bool {3948 true3949 }3950 fn name_long(&self) -> &'static str {3951 "mmap"3952 }3953 fn name_negated(&self) -> Option<&'static str> {3954 Some("no-mmap")3955 }3956 fn doc_category(&self) -> Category {3957 Category::Search3958 }3959 fn doc_short(&self) -> &'static str {3960 r"Search with memory maps when possible."3961 }3962 fn doc_long(&self) -> &'static str {3963 r"3964When enabled, ripgrep will search using memory maps when possible. This is3965enabled by default when ripgrep thinks it will be faster.3966.sp3967Memory map searching cannot be used in all circumstances. For example, when3968searching virtual files or streams likes \fBstdin\fP. In such cases, memory3969maps will not be used even when this flag is enabled.3970.sp3971Note that ripgrep may abort unexpectedly when memory maps are used if it3972searches a file that is simultaneously truncated. Users can opt out of this3973possibility by disabling memory maps.3974"3975 }39763977 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {3978 args.mmap = if v.unwrap_switch() {3979 MmapMode::AlwaysTryMmap3980 } else {3981 MmapMode::Never3982 };3983 Ok(())3984 }3985}39863987#[cfg(test)]3988#[test]3989fn test_mmap() {3990 let args = parse_low_raw(None::<&str>).unwrap();3991 assert_eq!(MmapMode::Auto, args.mmap);39923993 let args = parse_low_raw(["--mmap"]).unwrap();3994 assert_eq!(MmapMode::AlwaysTryMmap, args.mmap);39953996 let args = parse_low_raw(["--no-mmap"]).unwrap();3997 assert_eq!(MmapMode::Never, args.mmap);39983999 let args = parse_low_raw(["--mmap", "--no-mmap"]).unwrap();4000 assert_eq!(MmapMode::Never, args.mmap);40014002 let args = parse_low_raw(["--no-mmap", "--mmap"]).unwrap();4003 assert_eq!(MmapMode::AlwaysTryMmap, args.mmap);4004}40054006/// -U/--multiline4007#[derive(Debug)]4008struct Multiline;40094010impl Flag for Multiline {4011 fn is_switch(&self) -> bool {4012 true4013 }4014 fn name_short(&self) -> Option<u8> {4015 Some(b'U')4016 }4017 fn name_long(&self) -> &'static str {4018 "multiline"4019 }4020 fn name_negated(&self) -> Option<&'static str> {4021 Some("no-multiline")4022 }4023 fn doc_category(&self) -> Category {4024 Category::Search4025 }4026 fn doc_short(&self) -> &'static str {4027 r"Enable searching across multiple lines."4028 }4029 fn doc_long(&self) -> &'static str {4030 r#"4031This flag enable searching across multiple lines.4032.sp4033When multiline mode is enabled, ripgrep will lift the restriction that a4034match cannot include a line terminator. For example, when multiline mode4035is not enabled (the default), then the regex \fB\\p{any}\fP will match any4036Unicode codepoint other than \fB\\n\fP. Similarly, the regex \fB\\n\fP is4037explicitly forbidden, and if you try to use it, ripgrep will return an error.4038However, when multiline mode is enabled, \fB\\p{any}\fP will match any Unicode4039codepoint, including \fB\\n\fP, and regexes like \fB\\n\fP are permitted.4040.sp4041An important caveat is that multiline mode does not change the match semantics4042of \fB.\fP. Namely, in most regex matchers, a \fB.\fP will by default match any4043character other than \fB\\n\fP, and this is true in ripgrep as well. In order4044to make \fB.\fP match \fB\\n\fP, you must enable the "dot all" flag inside the4045regex. For example, both \fB(?s).\fP and \fB(?s:.)\fP have the same semantics,4046where \fB.\fP will match any character, including \fB\\n\fP. Alternatively, the4047\flag{multiline-dotall} flag may be passed to make the "dot all" behavior the4048default. This flag only applies when multiline search is enabled.4049.sp4050There is no limit on the number of the lines that a single match can span.4051.sp4052\fBWARNING\fP: Because of how the underlying regex engine works, multiline4053searches may be slower than normal line-oriented searches, and they may also4054use more memory. In particular, when multiline mode is enabled, ripgrep4055requires that each file it searches is laid out contiguously in memory (either4056by reading it onto the heap or by memory-mapping it). Things that cannot be4057memory-mapped (such as \fBstdin\fP) will be consumed until EOF before searching4058can begin. In general, ripgrep will only do these things when necessary.4059Specifically, if the \flag{multiline} flag is provided but the regex does4060not contain patterns that would match \fB\\n\fP characters, then ripgrep4061will automatically avoid reading each file into memory before searching it.4062Nevertheless, if you only care about matches spanning at most one line, then it4063is always better to disable multiline mode.4064.sp4065This overrides the \flag{stop-on-nonmatch} flag.4066"#4067 }40684069 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4070 args.multiline = v.unwrap_switch();4071 if args.multiline {4072 args.stop_on_nonmatch = false;4073 }4074 Ok(())4075 }4076}40774078#[cfg(test)]4079#[test]4080fn test_multiline() {4081 let args = parse_low_raw(None::<&str>).unwrap();4082 assert_eq!(false, args.multiline);40834084 let args = parse_low_raw(["--multiline"]).unwrap();4085 assert_eq!(true, args.multiline);40864087 let args = parse_low_raw(["-U"]).unwrap();4088 assert_eq!(true, args.multiline);40894090 let args = parse_low_raw(["-U", "--no-multiline"]).unwrap();4091 assert_eq!(false, args.multiline);4092}40934094/// --multiline-dotall4095#[derive(Debug)]4096struct MultilineDotall;40974098impl Flag for MultilineDotall {4099 fn is_switch(&self) -> bool {4100 true4101 }4102 fn name_long(&self) -> &'static str {4103 "multiline-dotall"4104 }4105 fn name_negated(&self) -> Option<&'static str> {4106 Some("no-multiline-dotall")4107 }4108 fn doc_category(&self) -> Category {4109 Category::Search4110 }4111 fn doc_short(&self) -> &'static str {4112 r"Make '.' match line terminators."4113 }4114 fn doc_long(&self) -> &'static str {4115 r#"4116This flag enables "dot all" mode in all regex patterns. This causes \fB.\fP to4117match line terminators when multiline searching is enabled. This flag has no4118effect if multiline searching isn't enabled with the \flag{multiline} flag.4119.sp4120Normally, a \fB.\fP will match any character except line terminators. While4121this behavior typically isn't relevant for line-oriented matching (since4122matches can span at most one line), this can be useful when searching with the4123\flag{multiline} flag. By default, multiline mode runs without "dot all" mode4124enabled.4125.sp4126This flag is generally intended to be used in an alias or your ripgrep config4127file if you prefer "dot all" semantics by default. Note that regardless of4128whether this flag is used, "dot all" semantics can still be controlled via4129inline flags in the regex pattern itself, e.g., \fB(?s:.)\fP always enables4130"dot all" whereas \fB(?-s:.)\fP always disables "dot all". Moreover, you4131can use character classes like \fB\\p{any}\fP to match any Unicode codepoint4132regardless of whether "dot all" mode is enabled or not.4133"#4134 }41354136 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4137 args.multiline_dotall = v.unwrap_switch();4138 Ok(())4139 }4140}41414142#[cfg(test)]4143#[test]4144fn test_multiline_dotall() {4145 let args = parse_low_raw(None::<&str>).unwrap();4146 assert_eq!(false, args.multiline_dotall);41474148 let args = parse_low_raw(["--multiline-dotall"]).unwrap();4149 assert_eq!(true, args.multiline_dotall);41504151 let args = parse_low_raw(["--multiline-dotall", "--no-multiline-dotall"])4152 .unwrap();4153 assert_eq!(false, args.multiline_dotall);4154}41554156/// --no-config4157#[derive(Debug)]4158struct NoConfig;41594160impl Flag for NoConfig {4161 fn is_switch(&self) -> bool {4162 true4163 }4164 fn name_long(&self) -> &'static str {4165 "no-config"4166 }4167 fn doc_category(&self) -> Category {4168 Category::OtherBehaviors4169 }4170 fn doc_short(&self) -> &'static str {4171 r"Never read configuration files."4172 }4173 fn doc_long(&self) -> &'static str {4174 r"4175When set, ripgrep will never read configuration files. When this flag is4176present, ripgrep will not respect the \fBRIPGREP_CONFIG_PATH\fP environment4177variable.4178.sp4179If ripgrep ever grows a feature to automatically read configuration files in4180pre-defined locations, then this flag will also disable that behavior as well.4181"4182 }41834184 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4185 assert!(v.unwrap_switch(), "--no-config has no negation");4186 args.no_config = true;4187 Ok(())4188 }4189}41904191#[cfg(test)]4192#[test]4193fn test_no_config() {4194 let args = parse_low_raw(None::<&str>).unwrap();4195 assert_eq!(false, args.no_config);41964197 let args = parse_low_raw(["--no-config"]).unwrap();4198 assert_eq!(true, args.no_config);4199}42004201/// --no-ignore4202#[derive(Debug)]4203struct NoIgnore;42044205impl Flag for NoIgnore {4206 fn is_switch(&self) -> bool {4207 true4208 }4209 fn name_long(&self) -> &'static str {4210 "no-ignore"4211 }4212 fn name_negated(&self) -> Option<&'static str> {4213 Some("ignore")4214 }4215 fn doc_category(&self) -> Category {4216 Category::Filter4217 }4218 fn doc_short(&self) -> &'static str {4219 r"Don't use ignore files."4220 }4221 fn doc_long(&self) -> &'static str {4222 r"4223When set, ignore files such as \fB.gitignore\fP, \fB.ignore\fP and4224\fB.rgignore\fP will not be respected. This implies \flag{no-ignore-dot},4225\flag{no-ignore-exclude}, \flag{no-ignore-global}, \flag{no-ignore-parent} and4226\flag{no-ignore-vcs}.4227.sp4228This does not imply \flag{no-ignore-files}, since \flag{ignore-file} is4229specified explicitly as a command line argument.4230.sp4231When given only once, the \flag{unrestricted} flag is identical in4232behavior to this flag and can be considered an alias. However, subsequent4233\flag{unrestricted} flags have additional effects.4234"4235 }42364237 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4238 let yes = v.unwrap_switch();4239 args.no_ignore_dot = yes;4240 args.no_ignore_exclude = yes;4241 args.no_ignore_global = yes;4242 args.no_ignore_parent = yes;4243 args.no_ignore_vcs = yes;4244 Ok(())4245 }4246}42474248#[cfg(test)]4249#[test]4250fn test_no_ignore() {4251 let args = parse_low_raw(None::<&str>).unwrap();4252 assert_eq!(false, args.no_ignore_dot);4253 assert_eq!(false, args.no_ignore_exclude);4254 assert_eq!(false, args.no_ignore_global);4255 assert_eq!(false, args.no_ignore_parent);4256 assert_eq!(false, args.no_ignore_vcs);42574258 let args = parse_low_raw(["--no-ignore"]).unwrap();4259 assert_eq!(true, args.no_ignore_dot);4260 assert_eq!(true, args.no_ignore_exclude);4261 assert_eq!(true, args.no_ignore_global);4262 assert_eq!(true, args.no_ignore_parent);4263 assert_eq!(true, args.no_ignore_vcs);42644265 let args = parse_low_raw(["--no-ignore", "--ignore"]).unwrap();4266 assert_eq!(false, args.no_ignore_dot);4267 assert_eq!(false, args.no_ignore_exclude);4268 assert_eq!(false, args.no_ignore_global);4269 assert_eq!(false, args.no_ignore_parent);4270 assert_eq!(false, args.no_ignore_vcs);4271}42724273/// --no-ignore-dot4274#[derive(Debug)]4275struct NoIgnoreDot;42764277impl Flag for NoIgnoreDot {4278 fn is_switch(&self) -> bool {4279 true4280 }4281 fn name_long(&self) -> &'static str {4282 "no-ignore-dot"4283 }4284 fn name_negated(&self) -> Option<&'static str> {4285 Some("ignore-dot")4286 }4287 fn doc_category(&self) -> Category {4288 Category::Filter4289 }4290 fn doc_short(&self) -> &'static str {4291 r"Don't use .ignore or .rgignore files."4292 }4293 fn doc_long(&self) -> &'static str {4294 r"4295Don't respect filter rules from \fB.ignore\fP or \fB.rgignore\fP files.4296.sp4297This does not impact whether ripgrep will ignore files and directories whose4298names begin with a dot. For that, see the \flag{hidden} flag. This flag also4299does not impact whether filter rules from \fB.gitignore\fP files are respected.4300"4301 }43024303 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4304 args.no_ignore_dot = v.unwrap_switch();4305 Ok(())4306 }4307}43084309#[cfg(test)]4310#[test]4311fn test_no_ignore_dot() {4312 let args = parse_low_raw(None::<&str>).unwrap();4313 assert_eq!(false, args.no_ignore_dot);43144315 let args = parse_low_raw(["--no-ignore-dot"]).unwrap();4316 assert_eq!(true, args.no_ignore_dot);43174318 let args = parse_low_raw(["--no-ignore-dot", "--ignore-dot"]).unwrap();4319 assert_eq!(false, args.no_ignore_dot);4320}43214322/// --no-ignore-exclude4323#[derive(Debug)]4324struct NoIgnoreExclude;43254326impl Flag for NoIgnoreExclude {4327 fn is_switch(&self) -> bool {4328 true4329 }4330 fn name_long(&self) -> &'static str {4331 "no-ignore-exclude"4332 }4333 fn name_negated(&self) -> Option<&'static str> {4334 Some("ignore-exclude")4335 }4336 fn doc_category(&self) -> Category {4337 Category::Filter4338 }4339 fn doc_short(&self) -> &'static str {4340 r"Don't use local exclusion files."4341 }4342 fn doc_long(&self) -> &'static str {4343 r"4344Don't respect filter rules from files that are manually configured for the repository.4345For example, this includes \fBgit\fP's \fB.git/info/exclude\fP.4346"4347 }43484349 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4350 args.no_ignore_exclude = v.unwrap_switch();4351 Ok(())4352 }4353}43544355#[cfg(test)]4356#[test]4357fn test_no_ignore_exclude() {4358 let args = parse_low_raw(None::<&str>).unwrap();4359 assert_eq!(false, args.no_ignore_exclude);43604361 let args = parse_low_raw(["--no-ignore-exclude"]).unwrap();4362 assert_eq!(true, args.no_ignore_exclude);43634364 let args =4365 parse_low_raw(["--no-ignore-exclude", "--ignore-exclude"]).unwrap();4366 assert_eq!(false, args.no_ignore_exclude);4367}43684369/// --no-ignore-files4370#[derive(Debug)]4371struct NoIgnoreFiles;43724373impl Flag for NoIgnoreFiles {4374 fn is_switch(&self) -> bool {4375 true4376 }4377 fn name_long(&self) -> &'static str {4378 "no-ignore-files"4379 }4380 fn name_negated(&self) -> Option<&'static str> {4381 Some("ignore-files")4382 }4383 fn doc_category(&self) -> Category {4384 Category::Filter4385 }4386 fn doc_short(&self) -> &'static str {4387 r"Don't use --ignore-file arguments."4388 }4389 fn doc_long(&self) -> &'static str {4390 r"4391When set, any \flag{ignore-file} flags, even ones that come after this flag,4392are ignored.4393"4394 }43954396 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4397 args.no_ignore_files = v.unwrap_switch();4398 Ok(())4399 }4400}44014402#[cfg(test)]4403#[test]4404fn test_no_ignore_files() {4405 let args = parse_low_raw(None::<&str>).unwrap();4406 assert_eq!(false, args.no_ignore_files);44074408 let args = parse_low_raw(["--no-ignore-files"]).unwrap();4409 assert_eq!(true, args.no_ignore_files);44104411 let args = parse_low_raw(["--no-ignore-files", "--ignore-files"]).unwrap();4412 assert_eq!(false, args.no_ignore_files);4413}44144415/// --no-ignore-global4416#[derive(Debug)]4417struct NoIgnoreGlobal;44184419impl Flag for NoIgnoreGlobal {4420 fn is_switch(&self) -> bool {4421 true4422 }4423 fn name_long(&self) -> &'static str {4424 "no-ignore-global"4425 }4426 fn name_negated(&self) -> Option<&'static str> {4427 Some("ignore-global")4428 }4429 fn doc_category(&self) -> Category {4430 Category::Filter4431 }4432 fn doc_short(&self) -> &'static str {4433 r"Don't use global ignore files."4434 }4435 fn doc_long(&self) -> &'static str {4436 r#"4437Don't respect filter rules from ignore files that come from "global" sources4438such as \fBgit\fP's \fBcore.excludesFile\fP configuration option (which4439defaults to \fB$HOME/.config/git/ignore\fP).4440"#4441 }44424443 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4444 args.no_ignore_global = v.unwrap_switch();4445 Ok(())4446 }4447}44484449#[cfg(test)]4450#[test]4451fn test_no_ignore_global() {4452 let args = parse_low_raw(None::<&str>).unwrap();4453 assert_eq!(false, args.no_ignore_global);44544455 let args = parse_low_raw(["--no-ignore-global"]).unwrap();4456 assert_eq!(true, args.no_ignore_global);44574458 let args =4459 parse_low_raw(["--no-ignore-global", "--ignore-global"]).unwrap();4460 assert_eq!(false, args.no_ignore_global);4461}44624463/// --no-ignore-messages4464#[derive(Debug)]4465struct NoIgnoreMessages;44664467impl Flag for NoIgnoreMessages {4468 fn is_switch(&self) -> bool {4469 true4470 }4471 fn name_long(&self) -> &'static str {4472 "no-ignore-messages"4473 }4474 fn name_negated(&self) -> Option<&'static str> {4475 Some("ignore-messages")4476 }4477 fn doc_category(&self) -> Category {4478 Category::Logging4479 }4480 fn doc_short(&self) -> &'static str {4481 r"Suppress gitignore parse error messages."4482 }4483 fn doc_long(&self) -> &'static str {4484 r"4485When this flag is enabled, all error messages related to parsing ignore files4486are suppressed. By default, error messages are printed to stderr. In cases4487where these errors are expected, this flag can be used to avoid seeing the4488noise produced by the messages.4489"4490 }44914492 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4493 args.no_ignore_messages = v.unwrap_switch();4494 Ok(())4495 }4496}44974498#[cfg(test)]4499#[test]4500fn test_no_ignore_messages() {4501 let args = parse_low_raw(None::<&str>).unwrap();4502 assert_eq!(false, args.no_ignore_messages);45034504 let args = parse_low_raw(["--no-ignore-messages"]).unwrap();4505 assert_eq!(true, args.no_ignore_messages);45064507 let args =4508 parse_low_raw(["--no-ignore-messages", "--ignore-messages"]).unwrap();4509 assert_eq!(false, args.no_ignore_messages);4510}45114512/// --no-ignore-parent4513#[derive(Debug)]4514struct NoIgnoreParent;45154516impl Flag for NoIgnoreParent {4517 fn is_switch(&self) -> bool {4518 true4519 }4520 fn name_long(&self) -> &'static str {4521 "no-ignore-parent"4522 }4523 fn name_negated(&self) -> Option<&'static str> {4524 Some("ignore-parent")4525 }4526 fn doc_category(&self) -> Category {4527 Category::Filter4528 }4529 fn doc_short(&self) -> &'static str {4530 r"Don't use ignore files in parent directories."4531 }4532 fn doc_long(&self) -> &'static str {4533 r"4534When this flag is set, filter rules from ignore files found in parent4535directories are not respected. By default, ripgrep will ascend the parent4536directories of the current working directory to look for any applicable ignore4537files that should be applied. In some cases this may not be desirable.4538"4539 }45404541 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4542 args.no_ignore_parent = v.unwrap_switch();4543 Ok(())4544 }4545}45464547#[cfg(test)]4548#[test]4549fn test_no_ignore_parent() {4550 let args = parse_low_raw(None::<&str>).unwrap();4551 assert_eq!(false, args.no_ignore_parent);45524553 let args = parse_low_raw(["--no-ignore-parent"]).unwrap();4554 assert_eq!(true, args.no_ignore_parent);45554556 let args =4557 parse_low_raw(["--no-ignore-parent", "--ignore-parent"]).unwrap();4558 assert_eq!(false, args.no_ignore_parent);4559}45604561/// --no-ignore-vcs4562#[derive(Debug)]4563struct NoIgnoreVcs;45644565impl Flag for NoIgnoreVcs {4566 fn is_switch(&self) -> bool {4567 true4568 }4569 fn name_long(&self) -> &'static str {4570 "no-ignore-vcs"4571 }4572 fn name_negated(&self) -> Option<&'static str> {4573 Some("ignore-vcs")4574 }4575 fn doc_category(&self) -> Category {4576 Category::Filter4577 }4578 fn doc_short(&self) -> &'static str {4579 r"Don't use ignore files from source control."4580 }4581 fn doc_long(&self) -> &'static str {4582 r"4583When given, filter rules from source control ignore files (e.g., \fB.gitignore\fP)4584are not respected. By default, ripgrep respects \fBgit\fP's ignore rules for4585automatic filtering. In some cases, it may not be desirable to respect the4586source control's ignore rules and instead only respect rules in \fB.ignore\fP4587or \fB.rgignore\fP.4588.sp4589This flag implies \flag{no-ignore-parent} for source control ignore files as4590well.4591"4592 }45934594 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4595 args.no_ignore_vcs = v.unwrap_switch();4596 Ok(())4597 }4598}45994600#[cfg(test)]4601#[test]4602fn test_no_ignore_vcs() {4603 let args = parse_low_raw(None::<&str>).unwrap();4604 assert_eq!(false, args.no_ignore_vcs);46054606 let args = parse_low_raw(["--no-ignore-vcs"]).unwrap();4607 assert_eq!(true, args.no_ignore_vcs);46084609 let args = parse_low_raw(["--no-ignore-vcs", "--ignore-vcs"]).unwrap();4610 assert_eq!(false, args.no_ignore_vcs);4611}46124613/// --no-messages4614#[derive(Debug)]4615struct NoMessages;46164617impl Flag for NoMessages {4618 fn is_switch(&self) -> bool {4619 true4620 }4621 fn name_long(&self) -> &'static str {4622 "no-messages"4623 }4624 fn name_negated(&self) -> Option<&'static str> {4625 Some("messages")4626 }4627 fn doc_category(&self) -> Category {4628 Category::Logging4629 }4630 fn doc_short(&self) -> &'static str {4631 r"Suppress some error messages."4632 }4633 fn doc_long(&self) -> &'static str {4634 r"4635This flag suppresses some error messages. Specifically, messages related to4636the failed opening and reading of files. Error messages related to the syntax4637of the pattern are still shown.4638"4639 }46404641 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4642 args.no_messages = v.unwrap_switch();4643 Ok(())4644 }4645}46464647#[cfg(test)]4648#[test]4649fn test_no_messages() {4650 let args = parse_low_raw(None::<&str>).unwrap();4651 assert_eq!(false, args.no_messages);46524653 let args = parse_low_raw(["--no-messages"]).unwrap();4654 assert_eq!(true, args.no_messages);46554656 let args = parse_low_raw(["--no-messages", "--messages"]).unwrap();4657 assert_eq!(false, args.no_messages);4658}46594660/// --no-pcre2-unicode4661#[derive(Debug)]4662struct NoPcre2Unicode;46634664impl Flag for NoPcre2Unicode {4665 fn is_switch(&self) -> bool {4666 true4667 }4668 fn name_long(&self) -> &'static str {4669 "no-pcre2-unicode"4670 }4671 fn name_negated(&self) -> Option<&'static str> {4672 Some("pcre2-unicode")4673 }4674 fn doc_category(&self) -> Category {4675 Category::Search4676 }4677 fn doc_short(&self) -> &'static str {4678 r"(DEPRECATED) Disable Unicode mode for PCRE2."4679 }4680 fn doc_long(&self) -> &'static str {4681 r"4682DEPRECATED. Use \flag{no-unicode} instead.4683.sp4684Note that Unicode mode is enabled by default.4685"4686 }46874688 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4689 args.no_unicode = v.unwrap_switch();4690 Ok(())4691 }4692}46934694#[cfg(test)]4695#[test]4696fn test_no_pcre2_unicode() {4697 let args = parse_low_raw(None::<&str>).unwrap();4698 assert_eq!(false, args.no_unicode);46994700 let args = parse_low_raw(["--no-pcre2-unicode"]).unwrap();4701 assert_eq!(true, args.no_unicode);47024703 let args =4704 parse_low_raw(["--no-pcre2-unicode", "--pcre2-unicode"]).unwrap();4705 assert_eq!(false, args.no_unicode);4706}47074708/// --no-require-git4709#[derive(Debug)]4710struct NoRequireGit;47114712impl Flag for NoRequireGit {4713 fn is_switch(&self) -> bool {4714 true4715 }4716 fn name_long(&self) -> &'static str {4717 "no-require-git"4718 }4719 fn name_negated(&self) -> Option<&'static str> {4720 Some("require-git")4721 }4722 fn doc_category(&self) -> Category {4723 Category::Filter4724 }4725 fn doc_short(&self) -> &'static str {4726 r"Use .gitignore outside of git repositories."4727 }4728 fn doc_long(&self) -> &'static str {4729 r"4730When this flag is given, source control ignore files such as \fB.gitignore\fP4731are respect even if no \fBgit\fP repository is present.4732.sp4733By default, ripgrep will only respect filter rules from source control ignore4734files when ripgrep detects that the search is executed inside a source control4735repository. For example, when a \fB.git\fP directory is observed.4736.sp4737This flag relaxes the default restriction. For example, it might be useful when4738the contents of a \fBgit\fP repository are stored or copied somewhere, but4739where the repository state is absent.4740"4741 }47424743 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4744 args.no_require_git = v.unwrap_switch();4745 Ok(())4746 }4747}47484749#[cfg(test)]4750#[test]4751fn test_no_require_git() {4752 let args = parse_low_raw(None::<&str>).unwrap();4753 assert_eq!(false, args.no_require_git);47544755 let args = parse_low_raw(["--no-require-git"]).unwrap();4756 assert_eq!(true, args.no_require_git);47574758 let args = parse_low_raw(["--no-require-git", "--require-git"]).unwrap();4759 assert_eq!(false, args.no_require_git);4760}47614762/// --no-unicode4763#[derive(Debug)]4764struct NoUnicode;47654766impl Flag for NoUnicode {4767 fn is_switch(&self) -> bool {4768 true4769 }4770 fn name_long(&self) -> &'static str {4771 "no-unicode"4772 }4773 fn name_negated(&self) -> Option<&'static str> {4774 Some("unicode")4775 }4776 fn doc_category(&self) -> Category {4777 Category::Search4778 }4779 fn doc_short(&self) -> &'static str {4780 r"Disable Unicode mode."4781 }4782 fn doc_long(&self) -> &'static str {4783 r#"4784This flag disables Unicode mode for all patterns given to ripgrep.4785.sp4786By default, ripgrep will enable "Unicode mode" in all of its regexes. This has4787a number of consequences:4788.sp4789.IP \(bu 3n4790\fB.\fP will only match valid UTF-8 encoded Unicode scalar values.4791.sp4792.IP \(bu 3n4793Classes like \fB\\w\fP, \fB\\s\fP, \fB\\d\fP are all Unicode aware and much4794bigger than their ASCII only versions.4795.sp4796.IP \(bu 3n4797Case insensitive matching will use Unicode case folding.4798.sp4799.IP \(bu 3n4800A large array of classes like \fB\\p{Emoji}\fP are available. (Although the4801specific set of classes available varies based on the regex engine. In general,4802the default regex engine has more classes available to it.)4803.sp4804.IP \(bu 3n4805Word boundaries (\fB\\b\fP and \fB\\B\fP) use the Unicode definition of a word4806character.4807.PP4808In some cases it can be desirable to turn these things off. This flag will do4809exactly that. For example, Unicode mode can sometimes have a negative impact4810on performance, especially when things like \fB\\w\fP are used frequently4811(including via bounded repetitions like \fB\\w{100}\fP) when only their ASCII4812interpretation is needed.4813"#4814 }48154816 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4817 args.no_unicode = v.unwrap_switch();4818 Ok(())4819 }4820}48214822#[cfg(test)]4823#[test]4824fn test_no_unicode() {4825 let args = parse_low_raw(None::<&str>).unwrap();4826 assert_eq!(false, args.no_unicode);48274828 let args = parse_low_raw(["--no-unicode"]).unwrap();4829 assert_eq!(true, args.no_unicode);48304831 let args = parse_low_raw(["--no-unicode", "--unicode"]).unwrap();4832 assert_eq!(false, args.no_unicode);48334834 let args = parse_low_raw(["--no-unicode", "--pcre2-unicode"]).unwrap();4835 assert_eq!(false, args.no_unicode);48364837 let args = parse_low_raw(["--no-pcre2-unicode", "--unicode"]).unwrap();4838 assert_eq!(false, args.no_unicode);4839}48404841/// -0/--null4842#[derive(Debug)]4843struct Null;48444845impl Flag for Null {4846 fn is_switch(&self) -> bool {4847 true4848 }4849 fn name_short(&self) -> Option<u8> {4850 Some(b'0')4851 }4852 fn name_long(&self) -> &'static str {4853 "null"4854 }4855 fn doc_category(&self) -> Category {4856 Category::Output4857 }4858 fn doc_short(&self) -> &'static str {4859 r"Print a NUL byte after file paths."4860 }4861 fn doc_long(&self) -> &'static str {4862 r"4863Whenever a file path is printed, follow it with a \fBNUL\fP byte. This includes4864printing file paths before matches, and when printing a list of matching files4865such as with \flag{count}, \flag{files-with-matches} and \flag{files}. This4866option is useful for use with \fBxargs\fP.4867"4868 }48694870 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4871 assert!(v.unwrap_switch(), "--null has no negation");4872 args.null = true;4873 Ok(())4874 }4875}48764877#[cfg(test)]4878#[test]4879fn test_null() {4880 let args = parse_low_raw(None::<&str>).unwrap();4881 assert_eq!(false, args.null);48824883 let args = parse_low_raw(["--null"]).unwrap();4884 assert_eq!(true, args.null);48854886 let args = parse_low_raw(["-0"]).unwrap();4887 assert_eq!(true, args.null);4888}48894890/// --null-data4891#[derive(Debug)]4892struct NullData;48934894impl Flag for NullData {4895 fn is_switch(&self) -> bool {4896 true4897 }4898 fn name_long(&self) -> &'static str {4899 "null-data"4900 }4901 fn doc_category(&self) -> Category {4902 Category::Search4903 }4904 fn doc_short(&self) -> &'static str {4905 r"Use NUL as a line terminator."4906 }4907 fn doc_long(&self) -> &'static str {4908 r"4909Enabling this flag causes ripgrep to use \fBNUL\fP as a line terminator instead4910of the default of \fP\\n\fP.4911.sp4912This is useful when searching large binary files that would otherwise have4913very long lines if \fB\\n\fP were used as the line terminator. In particular,4914ripgrep requires that, at a minimum, each line must fit into memory. Using4915\fBNUL\fP instead can be a useful stopgap to keep memory requirements low and4916avoid OOM (out of memory) conditions.4917.sp4918This is also useful for processing NUL delimited data, such as that emitted4919when using ripgrep's \flag{null} flag or \fBfind\fP's \fB\-\-print0\fP flag.4920.sp4921Using this flag implies \flag{text}. It also overrides \flag{crlf}.4922"4923 }49244925 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4926 assert!(v.unwrap_switch(), "--null-data has no negation");4927 args.crlf = false;4928 args.null_data = true;4929 Ok(())4930 }4931}49324933#[cfg(test)]4934#[test]4935fn test_null_data() {4936 let args = parse_low_raw(None::<&str>).unwrap();4937 assert_eq!(false, args.null_data);49384939 let args = parse_low_raw(["--null-data"]).unwrap();4940 assert_eq!(true, args.null_data);49414942 let args = parse_low_raw(["--null-data", "--crlf"]).unwrap();4943 assert_eq!(false, args.null_data);4944 assert_eq!(true, args.crlf);49454946 let args = parse_low_raw(["--crlf", "--null-data"]).unwrap();4947 assert_eq!(true, args.null_data);4948 assert_eq!(false, args.crlf);49494950 let args = parse_low_raw(["--null-data", "--no-crlf"]).unwrap();4951 assert_eq!(true, args.null_data);4952 assert_eq!(false, args.crlf);4953}49544955/// --one-file-system4956#[derive(Debug)]4957struct OneFileSystem;49584959impl Flag for OneFileSystem {4960 fn is_switch(&self) -> bool {4961 true4962 }4963 fn name_long(&self) -> &'static str {4964 "one-file-system"4965 }4966 fn name_negated(&self) -> Option<&'static str> {4967 Some("no-one-file-system")4968 }4969 fn doc_category(&self) -> Category {4970 Category::Filter4971 }4972 fn doc_short(&self) -> &'static str {4973 r"Skip directories on other file systems."4974 }4975 fn doc_long(&self) -> &'static str {4976 r"4977When enabled, ripgrep will not cross file system boundaries relative to where4978the search started from.4979.sp4980Note that this applies to each path argument given to ripgrep. For example, in4981the command4982.sp4983.EX4984 rg \-\-one\-file\-system /foo/bar /quux/baz4985.EE4986.sp4987ripgrep will search both \fI/foo/bar\fP and \fI/quux/baz\fP even if they are4988on different file systems, but will not cross a file system boundary when4989traversing each path's directory tree.4990.sp4991This is similar to \fBfind\fP's \fB\-xdev\fP or \fB\-mount\fP flag.4992"4993 }49944995 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {4996 args.one_file_system = v.unwrap_switch();4997 Ok(())4998 }4999}50005001#[cfg(test)]5002#[test]5003fn test_one_file_system() {5004 let args = parse_low_raw(None::<&str>).unwrap();5005 assert_eq!(false, args.one_file_system);50065007 let args = parse_low_raw(["--one-file-system"]).unwrap();5008 assert_eq!(true, args.one_file_system);50095010 let args =5011 parse_low_raw(["--one-file-system", "--no-one-file-system"]).unwrap();5012 assert_eq!(false, args.one_file_system);5013}50145015/// -o/--only-matching5016#[derive(Debug)]5017struct OnlyMatching;50185019impl Flag for OnlyMatching {5020 fn is_switch(&self) -> bool {5021 true5022 }5023 fn name_short(&self) -> Option<u8> {5024 Some(b'o')5025 }5026 fn name_long(&self) -> &'static str {5027 "only-matching"5028 }5029 fn doc_category(&self) -> Category {5030 Category::Output5031 }5032 fn doc_short(&self) -> &'static str {5033 r"Print only matched parts of a line."5034 }5035 fn doc_long(&self) -> &'static str {5036 r"5037Print only the matched (non-empty) parts of a matching line, with each such5038part on a separate output line.5039"5040 }50415042 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5043 assert!(v.unwrap_switch(), "--only-matching does not have a negation");5044 args.only_matching = true;5045 Ok(())5046 }5047}50485049#[cfg(test)]5050#[test]5051fn test_only_matching() {5052 let args = parse_low_raw(None::<&str>).unwrap();5053 assert_eq!(false, args.only_matching);50545055 let args = parse_low_raw(["--only-matching"]).unwrap();5056 assert_eq!(true, args.only_matching);50575058 let args = parse_low_raw(["-o"]).unwrap();5059 assert_eq!(true, args.only_matching);5060}50615062/// --path-separator5063#[derive(Debug)]5064struct PathSeparator;50655066impl Flag for PathSeparator {5067 fn is_switch(&self) -> bool {5068 false5069 }5070 fn name_long(&self) -> &'static str {5071 "path-separator"5072 }5073 fn doc_variable(&self) -> Option<&'static str> {5074 Some("SEPARATOR")5075 }5076 fn doc_category(&self) -> Category {5077 Category::Output5078 }5079 fn doc_short(&self) -> &'static str {5080 r"Set the path separator for printing paths."5081 }5082 fn doc_long(&self) -> &'static str {5083 r"5084Set the path separator to use when printing file paths. This defaults to your5085platform's path separator, which is \fB/\fP on Unix and \fB\\\fP on Windows.5086This flag is intended for overriding the default when the environment demands5087it (e.g., cygwin). A path separator is limited to a single byte.5088.sp5089Setting this flag to an empty string reverts it to its default behavior. That5090is, the path separator is automatically chosen based on the environment.5091"5092 }50935094 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5095 let s = convert::string(v.unwrap_value())?;5096 let raw = Vec::unescape_bytes(&s);5097 args.path_separator = if raw.is_empty() {5098 None5099 } else if raw.len() == 1 {5100 Some(raw[0])5101 } else {5102 anyhow::bail!(5103 "A path separator must be exactly one byte, but \5104 the given separator is {len} bytes: {sep}\n\5105 In some shells on Windows '/' is automatically \5106 expanded. Use '//' instead.",5107 len = raw.len(),5108 sep = s,5109 )5110 };5111 Ok(())5112 }5113}51145115#[cfg(test)]5116#[test]5117fn test_path_separator() {5118 let args = parse_low_raw(None::<&str>).unwrap();5119 assert_eq!(None, args.path_separator);51205121 let args = parse_low_raw(["--path-separator", "/"]).unwrap();5122 assert_eq!(Some(b'/'), args.path_separator);51235124 let args = parse_low_raw(["--path-separator", r"\"]).unwrap();5125 assert_eq!(Some(b'\\'), args.path_separator);51265127 let args = parse_low_raw(["--path-separator", r"\x00"]).unwrap();5128 assert_eq!(Some(0), args.path_separator);51295130 let args = parse_low_raw(["--path-separator", r"\0"]).unwrap();5131 assert_eq!(Some(0), args.path_separator);51325133 let args = parse_low_raw(["--path-separator", "\x00"]).unwrap();5134 assert_eq!(Some(0), args.path_separator);51355136 let args = parse_low_raw(["--path-separator", "\0"]).unwrap();5137 assert_eq!(Some(0), args.path_separator);51385139 let args =5140 parse_low_raw(["--path-separator", r"\x00", "--path-separator=/"])5141 .unwrap();5142 assert_eq!(Some(b'/'), args.path_separator);51435144 let result = parse_low_raw(["--path-separator", "foo"]);5145 assert!(result.is_err(), "{result:?}");51465147 let result = parse_low_raw(["--path-separator", r"\\x00"]);5148 assert!(result.is_err(), "{result:?}");5149}51505151/// --passthru5152#[derive(Debug)]5153struct Passthru;51545155impl Flag for Passthru {5156 fn is_switch(&self) -> bool {5157 true5158 }5159 fn name_long(&self) -> &'static str {5160 "passthru"5161 }5162 fn aliases(&self) -> &'static [&'static str] {5163 &["passthrough"]5164 }5165 fn doc_category(&self) -> Category {5166 Category::Output5167 }5168 fn doc_short(&self) -> &'static str {5169 r"Print both matching and non-matching lines."5170 }5171 fn doc_long(&self) -> &'static str {5172 r#"5173Print both matching and non-matching lines.5174.sp5175Another way to achieve a similar effect is by modifying your pattern to match5176the empty string. For example, if you are searching using \fBrg\fP \fIfoo\fP,5177then using \fBrg\fP \fB'^|\fP\fIfoo\fP\fB'\fP instead will emit every line in5178every file searched, but only occurrences of \fIfoo\fP will be highlighted.5179This flag enables the same behavior without needing to modify the pattern.5180.sp5181An alternative spelling for this flag is \fB\-\-passthrough\fP.5182.sp5183This overrides the \flag{context}, \flag{after-context} and5184\flag{before-context} flags.5185"#5186 }51875188 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5189 assert!(v.unwrap_switch(), "--passthru has no negation");5190 args.context = ContextMode::Passthru;5191 Ok(())5192 }5193}51945195#[cfg(test)]5196#[test]5197fn test_passthru() {5198 let args = parse_low_raw(None::<&str>).unwrap();5199 assert_eq!(ContextMode::default(), args.context);52005201 let args = parse_low_raw(["--passthru"]).unwrap();5202 assert_eq!(ContextMode::Passthru, args.context);52035204 let args = parse_low_raw(["--passthrough"]).unwrap();5205 assert_eq!(ContextMode::Passthru, args.context);5206}52075208/// -P/--pcre25209#[derive(Debug)]5210struct PCRE2;52115212impl Flag for PCRE2 {5213 fn is_switch(&self) -> bool {5214 true5215 }5216 fn name_short(&self) -> Option<u8> {5217 Some(b'P')5218 }5219 fn name_long(&self) -> &'static str {5220 "pcre2"5221 }5222 fn name_negated(&self) -> Option<&'static str> {5223 Some("no-pcre2")5224 }5225 fn doc_category(&self) -> Category {5226 Category::Search5227 }5228 fn doc_short(&self) -> &'static str {5229 r"Enable PCRE2 matching."5230 }5231 fn doc_long(&self) -> &'static str {5232 r"5233When this flag is present, ripgrep will use the PCRE2 regex engine instead of5234its default regex engine.5235.sp5236This is generally useful when you want to use features such as look-around5237or backreferences.5238.sp5239Using this flag is the same as passing \fB\-\-engine=pcre2\fP. Users may5240instead elect to use \fB\-\-engine=auto\fP to ask ripgrep to automatically5241select the right regex engine based on the patterns given. This flag and the5242\flag{engine} flag override one another.5243.sp5244Note that PCRE2 is an optional ripgrep feature. If PCRE2 wasn't included in5245your build of ripgrep, then using this flag will result in ripgrep printing5246an error message and exiting. PCRE2 may also have worse user experience in5247some cases, since it has fewer introspection APIs than ripgrep's default5248regex engine. For example, if you use a \fB\\n\fP in a PCRE2 regex without5249the \flag{multiline} flag, then ripgrep will silently fail to match anything5250instead of reporting an error immediately (like it does with the default regex5251engine).5252"5253 }52545255 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5256 args.engine = if v.unwrap_switch() {5257 EngineChoice::PCRE25258 } else {5259 EngineChoice::Default5260 };5261 Ok(())5262 }5263}52645265#[cfg(test)]5266#[test]5267fn test_pcre2() {5268 let args = parse_low_raw(None::<&str>).unwrap();5269 assert_eq!(EngineChoice::Default, args.engine);52705271 let args = parse_low_raw(["--pcre2"]).unwrap();5272 assert_eq!(EngineChoice::PCRE2, args.engine);52735274 let args = parse_low_raw(["-P"]).unwrap();5275 assert_eq!(EngineChoice::PCRE2, args.engine);52765277 let args = parse_low_raw(["-P", "--no-pcre2"]).unwrap();5278 assert_eq!(EngineChoice::Default, args.engine);52795280 let args = parse_low_raw(["--engine=auto", "-P", "--no-pcre2"]).unwrap();5281 assert_eq!(EngineChoice::Default, args.engine);52825283 let args = parse_low_raw(["-P", "--engine=auto"]).unwrap();5284 assert_eq!(EngineChoice::Auto, args.engine);5285}52865287/// --pcre2-version5288#[derive(Debug)]5289struct PCRE2Version;52905291impl Flag for PCRE2Version {5292 fn is_switch(&self) -> bool {5293 true5294 }5295 fn name_long(&self) -> &'static str {5296 "pcre2-version"5297 }5298 fn doc_category(&self) -> Category {5299 Category::OtherBehaviors5300 }5301 fn doc_short(&self) -> &'static str {5302 r"Print the version of PCRE2 that ripgrep uses."5303 }5304 fn doc_long(&self) -> &'static str {5305 r"5306When this flag is present, ripgrep will print the version of PCRE2 in use,5307along with other information, and then exit. If PCRE2 is not available, then5308ripgrep will print an error message and exit with an error code.5309"5310 }53115312 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5313 assert!(v.unwrap_switch(), "--pcre2-version has no negation");5314 args.special = Some(SpecialMode::VersionPCRE2);5315 Ok(())5316 }5317}53185319#[cfg(test)]5320#[test]5321fn test_pcre2_version() {5322 let args = parse_low_raw(None::<&str>).unwrap();5323 assert_eq!(None, args.special);53245325 let args = parse_low_raw(["--pcre2-version"]).unwrap();5326 assert_eq!(Some(SpecialMode::VersionPCRE2), args.special);5327}53285329/// --pre5330#[derive(Debug)]5331struct Pre;53325333impl Flag for Pre {5334 fn is_switch(&self) -> bool {5335 false5336 }5337 fn name_long(&self) -> &'static str {5338 "pre"5339 }5340 fn name_negated(&self) -> Option<&'static str> {5341 Some("no-pre")5342 }5343 fn doc_variable(&self) -> Option<&'static str> {5344 Some("COMMAND")5345 }5346 fn doc_category(&self) -> Category {5347 Category::Input5348 }5349 fn doc_short(&self) -> &'static str {5350 r"Search output of COMMAND for each PATH."5351 }5352 fn doc_long(&self) -> &'static str {5353 r#"5354For each input \fIPATH\fP, this flag causes ripgrep to search the standard5355output of \fICOMMAND\fP \fIPATH\fP instead of the contents of \fIPATH\fP. This5356option expects the \fICOMMAND\fP program to either be an absolute path or to5357be available in your \fBPATH\fP. Either an empty string \fICOMMAND\fP or the5358\fB\-\-no\-pre\fP flag will disable this behavior.5359.sp5360.TP 125361\fBWARNING\fP5362When this flag is set, ripgrep will unconditionally spawn a process for every5363file that is searched. Therefore, this can incur an unnecessarily large5364performance penalty if you don't otherwise need the flexibility offered by this5365flag. One possible mitigation to this is to use the \flag{pre-glob} flag to5366limit which files a preprocessor is run with.5367.PP5368A preprocessor is not run when ripgrep is searching stdin.5369.sp5370When searching over sets of files that may require one of several5371preprocessors, \fICOMMAND\fP should be a wrapper program which first classifies5372\fIPATH\fP based on magic numbers/content or based on the \fIPATH\fP name and5373then dispatches to an appropriate preprocessor. Each \fICOMMAND\fP also has its5374standard input connected to \fIPATH\fP for convenience.5375.sp5376For example, a shell script for \fICOMMAND\fP might look like:5377.sp5378.EX5379 case "$1" in5380 *.pdf)5381 exec pdftotext "$1" -5382 ;;5383 *)5384 case $(file "$1") in5385 *Zstandard*)5386 exec pzstd -cdq5387 ;;5388 *)5389 exec cat5390 ;;5391 esac5392 ;;5393 esac5394.EE5395.sp5396The above script uses \fBpdftotext\fP to convert a PDF file to plain text. For5397all other files, the script uses the \fBfile\fP utility to sniff the type of5398the file based on its contents. If it is a compressed file in the Zstandard5399format, then \fBpzstd\fP is used to decompress the contents to stdout.5400.sp5401This overrides the \flag{search-zip} flag.5402"#5403 }54045405 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5406 let path = match v {5407 FlagValue::Value(v) => PathBuf::from(v),5408 FlagValue::Switch(yes) => {5409 assert!(!yes, "there is no affirmative switch for --pre");5410 args.pre = None;5411 return Ok(());5412 }5413 };5414 args.pre = if path.as_os_str().is_empty() { None } else { Some(path) };5415 if args.pre.is_some() {5416 args.search_zip = false;5417 }5418 Ok(())5419 }5420}54215422#[cfg(test)]5423#[test]5424fn test_pre() {5425 let args = parse_low_raw(None::<&str>).unwrap();5426 assert_eq!(None, args.pre);54275428 let args = parse_low_raw(["--pre", "foo/bar"]).unwrap();5429 assert_eq!(Some(PathBuf::from("foo/bar")), args.pre);54305431 let args = parse_low_raw(["--pre", ""]).unwrap();5432 assert_eq!(None, args.pre);54335434 let args = parse_low_raw(["--pre", "foo/bar", "--pre", ""]).unwrap();5435 assert_eq!(None, args.pre);54365437 let args = parse_low_raw(["--pre", "foo/bar", "--pre="]).unwrap();5438 assert_eq!(None, args.pre);54395440 let args = parse_low_raw(["--pre", "foo/bar", "--no-pre"]).unwrap();5441 assert_eq!(None, args.pre);5442}54435444/// --pre-glob5445#[derive(Debug)]5446struct PreGlob;54475448impl Flag for PreGlob {5449 fn is_switch(&self) -> bool {5450 false5451 }5452 fn name_long(&self) -> &'static str {5453 "pre-glob"5454 }5455 fn doc_variable(&self) -> Option<&'static str> {5456 Some("GLOB")5457 }5458 fn doc_category(&self) -> Category {5459 Category::Input5460 }5461 fn doc_short(&self) -> &'static str {5462 r"Include or exclude files from a preprocessor."5463 }5464 fn doc_long(&self) -> &'static str {5465 r#"5466This flag works in conjunction with the \flag{pre} flag. Namely, when one or5467more \flag{pre-glob} flags are given, then only files that match the given set5468of globs will be handed to the command specified by the \flag{pre} flag. Any5469non-matching files will be searched without using the preprocessor command.5470.sp5471This flag is useful when searching many files with the \flag{pre} flag.5472Namely, it provides the ability to avoid process overhead for files that5473don't need preprocessing. For example, given the following shell script,5474\fIpre-pdftotext\fP:5475.sp5476.EX5477 #!/bin/sh5478 pdftotext "$1" -5479.EE5480.sp5481then it is possible to use \fB\-\-pre\fP \fIpre-pdftotext\fP \fB--pre-glob5482'\fP\fI*.pdf\fP\fB'\fP to make it so ripgrep only executes the5483\fIpre-pdftotext\fP command on files with a \fI.pdf\fP extension.5484.sp5485Multiple \flag{pre-glob} flags may be used. Globbing rules match5486\fBgitignore\fP globs. Precede a glob with a \fB!\fP to exclude it.5487.sp5488This flag has no effect if the \flag{pre} flag is not used.5489"#5490 }54915492 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5493 let glob = convert::string(v.unwrap_value())?;5494 args.pre_glob.push(glob);5495 Ok(())5496 }5497}54985499#[cfg(test)]5500#[test]5501fn test_pre_glob() {5502 let args = parse_low_raw(None::<&str>).unwrap();5503 assert_eq!(Vec::<String>::new(), args.pre_glob);55045505 let args = parse_low_raw(["--pre-glob", "*.pdf"]).unwrap();5506 assert_eq!(vec!["*.pdf".to_string()], args.pre_glob);55075508 let args =5509 parse_low_raw(["--pre-glob", "*.pdf", "--pre-glob=foo"]).unwrap();5510 assert_eq!(vec!["*.pdf".to_string(), "foo".to_string()], args.pre_glob);5511}55125513/// -p/--pretty5514#[derive(Debug)]5515struct Pretty;55165517impl Flag for Pretty {5518 fn is_switch(&self) -> bool {5519 true5520 }5521 fn name_short(&self) -> Option<u8> {5522 Some(b'p')5523 }5524 fn name_long(&self) -> &'static str {5525 "pretty"5526 }5527 fn doc_category(&self) -> Category {5528 Category::Output5529 }5530 fn doc_short(&self) -> &'static str {5531 r"Alias for colors, headings and line numbers."5532 }5533 fn doc_long(&self) -> &'static str {5534 r"5535This is a convenience alias for \fB\-\-color=always \-\-heading5536\-\-line\-number\fP. This flag is useful when you still want pretty output even5537if you're piping ripgrep to another program or file. For example: \fBrg -p5538\fP\fIfoo\fP \fB| less -R\fP.5539"5540 }55415542 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5543 assert!(v.unwrap_switch(), "--pretty has no negation");5544 args.color = ColorChoice::Always;5545 args.heading = Some(true);5546 args.line_number = Some(true);5547 Ok(())5548 }5549}55505551#[cfg(test)]5552#[test]5553fn test_pretty() {5554 let args = parse_low_raw(None::<&str>).unwrap();5555 assert_eq!(ColorChoice::Auto, args.color);5556 assert_eq!(None, args.heading);5557 assert_eq!(None, args.line_number);55585559 let args = parse_low_raw(["--pretty"]).unwrap();5560 assert_eq!(ColorChoice::Always, args.color);5561 assert_eq!(Some(true), args.heading);5562 assert_eq!(Some(true), args.line_number);55635564 let args = parse_low_raw(["-p"]).unwrap();5565 assert_eq!(ColorChoice::Always, args.color);5566 assert_eq!(Some(true), args.heading);5567 assert_eq!(Some(true), args.line_number);5568}55695570/// -q/--quiet5571#[derive(Debug)]5572struct Quiet;55735574impl Flag for Quiet {5575 fn is_switch(&self) -> bool {5576 true5577 }5578 fn name_short(&self) -> Option<u8> {5579 Some(b'q')5580 }5581 fn name_long(&self) -> &'static str {5582 "quiet"5583 }5584 fn doc_category(&self) -> Category {5585 Category::Output5586 }5587 fn doc_short(&self) -> &'static str {5588 r"Do not print anything to stdout."5589 }5590 fn doc_long(&self) -> &'static str {5591 r"5592Do not print anything to stdout. If a match is found in a file, then ripgrep5593will stop searching. This is useful when ripgrep is used only for its exit code5594(which will be an error code if no matches are found).5595.sp5596When \flag{files} is used, ripgrep will stop finding files after finding the5597first file that does not match any ignore rules.5598"5599 }56005601 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5602 assert!(v.unwrap_switch(), "--quiet has no negation");5603 args.quiet = true;5604 Ok(())5605 }5606}56075608#[cfg(test)]5609#[test]5610fn test_quiet() {5611 let args = parse_low_raw(None::<&str>).unwrap();5612 assert_eq!(false, args.quiet);56135614 let args = parse_low_raw(["--quiet"]).unwrap();5615 assert_eq!(true, args.quiet);56165617 let args = parse_low_raw(["-q"]).unwrap();5618 assert_eq!(true, args.quiet);56195620 // flags like -l and --json cannot override -q, regardless of order5621 let args = parse_low_raw(["-q", "--json"]).unwrap();5622 assert_eq!(true, args.quiet);56235624 let args = parse_low_raw(["-q", "--files-with-matches"]).unwrap();5625 assert_eq!(true, args.quiet);56265627 let args = parse_low_raw(["-q", "--files-without-match"]).unwrap();5628 assert_eq!(true, args.quiet);56295630 let args = parse_low_raw(["-q", "--count"]).unwrap();5631 assert_eq!(true, args.quiet);56325633 let args = parse_low_raw(["-q", "--count-matches"]).unwrap();5634 assert_eq!(true, args.quiet);5635}56365637/// --regex-size-limit5638#[derive(Debug)]5639struct RegexSizeLimit;56405641impl Flag for RegexSizeLimit {5642 fn is_switch(&self) -> bool {5643 false5644 }5645 fn name_long(&self) -> &'static str {5646 "regex-size-limit"5647 }5648 fn doc_variable(&self) -> Option<&'static str> {5649 Some("NUM+SUFFIX?")5650 }5651 fn doc_category(&self) -> Category {5652 Category::Search5653 }5654 fn doc_short(&self) -> &'static str {5655 r"The size limit of the compiled regex."5656 }5657 fn doc_long(&self) -> &'static str {5658 r"5659The size limit of the compiled regex, where the compiled regex generally5660corresponds to a single object in memory that can match all of the patterns5661provided to ripgrep. The default limit is generous enough that most reasonable5662patterns (or even a small number of them) should fit.5663.sp5664This useful to change when you explicitly want to let ripgrep spend potentially5665much more time and/or memory building a regex matcher.5666.sp5667The input format accepts suffixes of \fBK\fP, \fBM\fP or \fBG\fP which5668correspond to kilobytes, megabytes and gigabytes, respectively. If no suffix is5669provided the input is treated as bytes.5670"5671 }56725673 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5674 let v = v.unwrap_value();5675 args.regex_size_limit = Some(convert::human_readable_usize(&v)?);5676 Ok(())5677 }5678}56795680#[cfg(test)]5681#[test]5682fn test_regex_size_limit() {5683 let args = parse_low_raw(None::<&str>).unwrap();5684 assert_eq!(None, args.regex_size_limit);56855686 #[cfg(target_pointer_width = "64")]5687 {5688 let args = parse_low_raw(["--regex-size-limit", "9G"]).unwrap();5689 assert_eq!(Some(9 * (1 << 30)), args.regex_size_limit);56905691 let args = parse_low_raw(["--regex-size-limit=9G"]).unwrap();5692 assert_eq!(Some(9 * (1 << 30)), args.regex_size_limit);56935694 let args =5695 parse_low_raw(["--regex-size-limit=9G", "--regex-size-limit=0"])5696 .unwrap();5697 assert_eq!(Some(0), args.regex_size_limit);5698 }56995700 let args = parse_low_raw(["--regex-size-limit=0K"]).unwrap();5701 assert_eq!(Some(0), args.regex_size_limit);57025703 let args = parse_low_raw(["--regex-size-limit=0M"]).unwrap();5704 assert_eq!(Some(0), args.regex_size_limit);57055706 let args = parse_low_raw(["--regex-size-limit=0G"]).unwrap();5707 assert_eq!(Some(0), args.regex_size_limit);57085709 let result =5710 parse_low_raw(["--regex-size-limit", "9999999999999999999999"]);5711 assert!(result.is_err(), "{result:?}");57125713 let result = parse_low_raw(["--regex-size-limit", "9999999999999999G"]);5714 assert!(result.is_err(), "{result:?}");5715}57165717/// -e/--regexp5718#[derive(Debug)]5719struct Regexp;57205721impl Flag for Regexp {5722 fn is_switch(&self) -> bool {5723 false5724 }5725 fn name_short(&self) -> Option<u8> {5726 Some(b'e')5727 }5728 fn name_long(&self) -> &'static str {5729 "regexp"5730 }5731 fn doc_variable(&self) -> Option<&'static str> {5732 Some("PATTERN")5733 }5734 fn doc_category(&self) -> Category {5735 Category::Input5736 }5737 fn doc_short(&self) -> &'static str {5738 r"A pattern to search for."5739 }5740 fn doc_long(&self) -> &'static str {5741 r"5742A pattern to search for. This option can be provided multiple times, where5743all patterns given are searched, in addition to any patterns provided by5744\flag{file}. Lines matching at least one of the provided patterns are printed.5745This flag can also be used when searching for patterns that start with a dash.5746.sp5747For example, to search for the literal \fB\-foo\fP:5748.sp5749.EX5750 rg \-e \-foo5751.EE5752.sp5753You can also use the special \fB\-\-\fP delimiter to indicate that no more5754flags will be provided. Namely, the following is equivalent to the above:5755.sp5756.EX5757 rg \-\- \-foo5758.EE5759.sp5760When \flag{file} or \flag{regexp} is used, then ripgrep treats all positional5761arguments as files or directories to search.5762"5763 }57645765 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5766 let regexp = convert::string(v.unwrap_value())?;5767 args.patterns.push(PatternSource::Regexp(regexp));5768 Ok(())5769 }5770}57715772#[cfg(test)]5773#[test]5774fn test_regexp() {5775 let args = parse_low_raw(None::<&str>).unwrap();5776 assert_eq!(Vec::<PatternSource>::new(), args.patterns);57775778 let args = parse_low_raw(["--regexp", "foo"]).unwrap();5779 assert_eq!(vec![PatternSource::Regexp("foo".to_string())], args.patterns);57805781 let args = parse_low_raw(["--regexp=foo"]).unwrap();5782 assert_eq!(vec![PatternSource::Regexp("foo".to_string())], args.patterns);57835784 let args = parse_low_raw(["-e", "foo"]).unwrap();5785 assert_eq!(vec![PatternSource::Regexp("foo".to_string())], args.patterns);57865787 let args = parse_low_raw(["-efoo"]).unwrap();5788 assert_eq!(vec![PatternSource::Regexp("foo".to_string())], args.patterns);57895790 let args = parse_low_raw(["--regexp", "-foo"]).unwrap();5791 assert_eq!(vec![PatternSource::Regexp("-foo".to_string())], args.patterns);57925793 let args = parse_low_raw(["--regexp=-foo"]).unwrap();5794 assert_eq!(vec![PatternSource::Regexp("-foo".to_string())], args.patterns);57955796 let args = parse_low_raw(["-e", "-foo"]).unwrap();5797 assert_eq!(vec![PatternSource::Regexp("-foo".to_string())], args.patterns);57985799 let args = parse_low_raw(["-e-foo"]).unwrap();5800 assert_eq!(vec![PatternSource::Regexp("-foo".to_string())], args.patterns);58015802 let args = parse_low_raw(["--regexp=foo", "--regexp", "bar"]).unwrap();5803 assert_eq!(5804 vec![5805 PatternSource::Regexp("foo".to_string()),5806 PatternSource::Regexp("bar".to_string())5807 ],5808 args.patterns5809 );58105811 // While we support invalid UTF-8 arguments in general, patterns must be5812 // valid UTF-8.5813 #[cfg(unix)]5814 {5815 use std::{ffi::OsStr, os::unix::ffi::OsStrExt};58165817 let bytes = &[b'A', 0xFF, b'Z'][..];5818 let result = parse_low_raw([5819 OsStr::from_bytes(b"-e"),5820 OsStr::from_bytes(bytes),5821 ]);5822 assert!(result.is_err(), "{result:?}");5823 }58245825 // Check that combining -e/--regexp and -f/--file works as expected.5826 let args = parse_low_raw(["-efoo", "-fbar"]).unwrap();5827 assert_eq!(5828 vec![5829 PatternSource::Regexp("foo".to_string()),5830 PatternSource::File(PathBuf::from("bar"))5831 ],5832 args.patterns5833 );58345835 let args = parse_low_raw(["-efoo", "-fbar", "-equux"]).unwrap();5836 assert_eq!(5837 vec![5838 PatternSource::Regexp("foo".to_string()),5839 PatternSource::File(PathBuf::from("bar")),5840 PatternSource::Regexp("quux".to_string()),5841 ],5842 args.patterns5843 );5844}58455846/// -r/--replace5847#[derive(Debug)]5848struct Replace;58495850impl Flag for Replace {5851 fn is_switch(&self) -> bool {5852 false5853 }5854 fn name_short(&self) -> Option<u8> {5855 Some(b'r')5856 }5857 fn name_long(&self) -> &'static str {5858 "replace"5859 }5860 fn doc_variable(&self) -> Option<&'static str> {5861 Some("REPLACEMENT")5862 }5863 fn doc_category(&self) -> Category {5864 Category::Output5865 }5866 fn doc_short(&self) -> &'static str {5867 r"Replace matches with the given text."5868 }5869 fn doc_long(&self) -> &'static str {5870 r#"5871Replaces every match with the text given when printing results. Neither this5872flag nor any other ripgrep flag will modify your files.5873.sp5874Capture group indices (e.g., \fB$\fP\fI5\fP) and names (e.g., \fB$\fP\fIfoo\fP)5875are supported in the replacement string. Capture group indices are numbered5876based on the position of the opening parenthesis of the group, where the5877leftmost such group is \fB$\fP\fI1\fP. The special \fB$\fP\fI0\fP group5878corresponds to the entire match.5879.sp5880The name of a group is formed by taking the longest string of letters, numbers5881and underscores (i.e. \fB[_0-9A-Za-z]\fP) after the \fB$\fP. For example,5882\fB$\fP\fI1a\fP will be replaced with the group named \fI1a\fP, not the5883group at index \fI1\fP. If the group's name contains characters that aren't5884letters, numbers or underscores, or you want to immediately follow the group5885with another string, the name should be put inside braces. For example,5886\fB${\fP\fI1\fP\fB}\fP\fIa\fP will take the content of the group at index5887\fI1\fP and append \fIa\fP to the end of it.5888.sp5889If an index or name does not refer to a valid capture group, it will be5890replaced with an empty string.5891.sp5892In shells such as Bash and zsh, you should wrap the pattern in single quotes5893instead of double quotes. Otherwise, capture group indices will be replaced by5894expanded shell variables which will most likely be empty.5895.sp5896To write a literal \fB$\fP, use \fB$$\fP.5897.sp5898Note that the replacement by default replaces each match, and not the entire5899line. To replace the entire line, you should match the entire line.5900.sp5901This flag can be used with the \flag{only-matching} flag.5902"#5903 }59045905 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5906 args.replace = Some(convert::string(v.unwrap_value())?.into());5907 Ok(())5908 }5909}59105911#[cfg(test)]5912#[test]5913fn test_replace() {5914 use bstr::BString;59155916 let args = parse_low_raw(None::<&str>).unwrap();5917 assert_eq!(None, args.replace);59185919 let args = parse_low_raw(["--replace", "foo"]).unwrap();5920 assert_eq!(Some(BString::from("foo")), args.replace);59215922 let args = parse_low_raw(["--replace", "-foo"]).unwrap();5923 assert_eq!(Some(BString::from("-foo")), args.replace);59245925 let args = parse_low_raw(["-r", "foo"]).unwrap();5926 assert_eq!(Some(BString::from("foo")), args.replace);59275928 let args = parse_low_raw(["-r", "foo", "-rbar"]).unwrap();5929 assert_eq!(Some(BString::from("bar")), args.replace);59305931 let args = parse_low_raw(["-r", "foo", "-r", ""]).unwrap();5932 assert_eq!(Some(BString::from("")), args.replace);5933}59345935/// -z/--search-zip5936#[derive(Debug)]5937struct SearchZip;59385939impl Flag for SearchZip {5940 fn is_switch(&self) -> bool {5941 true5942 }5943 fn name_short(&self) -> Option<u8> {5944 Some(b'z')5945 }5946 fn name_long(&self) -> &'static str {5947 "search-zip"5948 }5949 fn name_negated(&self) -> Option<&'static str> {5950 Some("no-search-zip")5951 }5952 fn doc_category(&self) -> Category {5953 Category::Input5954 }5955 fn doc_short(&self) -> &'static str {5956 r"Search in compressed files."5957 }5958 fn doc_long(&self) -> &'static str {5959 r"5960This flag instructs ripgrep to search in compressed files. Currently gzip,5961bzip2, xz, LZ4, LZMA, Brotli and Zstd files are supported. This option expects5962the decompression binaries (such as \fBgzip\fP) to be available in your5963\fBPATH\fP.5964.sp5965Note that this flag does not make ripgrep search archive formats as directory5966trees. It only makes ripgrep detect compressed files and then decompress them5967before searching their contents as it would any other file.5968.sp5969This overrides the \flag{pre} flag.5970"5971 }59725973 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {5974 args.search_zip = if v.unwrap_switch() {5975 args.pre = None;5976 true5977 } else {5978 false5979 };5980 Ok(())5981 }5982}59835984#[cfg(test)]5985#[test]5986fn test_search_zip() {5987 let args = parse_low_raw(None::<&str>).unwrap();5988 assert_eq!(false, args.search_zip);59895990 let args = parse_low_raw(["--search-zip"]).unwrap();5991 assert_eq!(true, args.search_zip);59925993 let args = parse_low_raw(["-z"]).unwrap();5994 assert_eq!(true, args.search_zip);59955996 let args = parse_low_raw(["-z", "--no-search-zip"]).unwrap();5997 assert_eq!(false, args.search_zip);59985999 let args = parse_low_raw(["--pre=foo", "--no-search-zip"]).unwrap();6000 assert_eq!(Some(PathBuf::from("foo")), args.pre);6001 assert_eq!(false, args.search_zip);60026003 let args = parse_low_raw(["--pre=foo", "--search-zip"]).unwrap();6004 assert_eq!(None, args.pre);6005 assert_eq!(true, args.search_zip);60066007 let args = parse_low_raw(["--pre=foo", "-z", "--no-search-zip"]).unwrap();6008 assert_eq!(None, args.pre);6009 assert_eq!(false, args.search_zip);6010}60116012/// -S/--smart-case6013#[derive(Debug)]6014struct SmartCase;60156016impl Flag for SmartCase {6017 fn is_switch(&self) -> bool {6018 true6019 }6020 fn name_short(&self) -> Option<u8> {6021 Some(b'S')6022 }6023 fn name_long(&self) -> &'static str {6024 "smart-case"6025 }6026 fn doc_category(&self) -> Category {6027 Category::Search6028 }6029 fn doc_short(&self) -> &'static str {6030 r"Smart case search."6031 }6032 fn doc_long(&self) -> &'static str {6033 r"6034This flag instructs ripgrep to searches case insensitively if the pattern is6035all lowercase. Otherwise, ripgrep will search case sensitively.6036.sp6037A pattern is considered all lowercase if both of the following rules hold:6038.sp6039.IP \(bu 3n6040First, the pattern contains at least one literal character. For example,6041\fBa\\w\fP contains a literal (\fBa\fP) but just \fB\\w\fP does not.6042.sp6043.IP \(bu 3n6044Second, of the literals in the pattern, none of them are considered to be6045uppercase according to Unicode. For example, \fBfoo\\pL\fP has no uppercase6046literals but \fBFoo\\pL\fP does.6047.PP6048This overrides the \flag{case-sensitive} and \flag{ignore-case} flags.6049"6050 }60516052 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6053 assert!(v.unwrap_switch(), "--smart-case flag has no negation");6054 args.case = CaseMode::Smart;6055 Ok(())6056 }6057}60586059#[cfg(test)]6060#[test]6061fn test_smart_case() {6062 let args = parse_low_raw(None::<&str>).unwrap();6063 assert_eq!(CaseMode::Sensitive, args.case);60646065 let args = parse_low_raw(["--smart-case"]).unwrap();6066 assert_eq!(CaseMode::Smart, args.case);60676068 let args = parse_low_raw(["-S"]).unwrap();6069 assert_eq!(CaseMode::Smart, args.case);60706071 let args = parse_low_raw(["-S", "-s"]).unwrap();6072 assert_eq!(CaseMode::Sensitive, args.case);60736074 let args = parse_low_raw(["-S", "-i"]).unwrap();6075 assert_eq!(CaseMode::Insensitive, args.case);60766077 let args = parse_low_raw(["-s", "-S"]).unwrap();6078 assert_eq!(CaseMode::Smart, args.case);60796080 let args = parse_low_raw(["-i", "-S"]).unwrap();6081 assert_eq!(CaseMode::Smart, args.case);6082}60836084/// --sort-files6085#[derive(Debug)]6086struct SortFiles;60876088impl Flag for SortFiles {6089 fn is_switch(&self) -> bool {6090 true6091 }6092 fn name_long(&self) -> &'static str {6093 "sort-files"6094 }6095 fn name_negated(&self) -> Option<&'static str> {6096 Some("no-sort-files")6097 }6098 fn doc_category(&self) -> Category {6099 Category::Output6100 }6101 fn doc_short(&self) -> &'static str {6102 r"(DEPRECATED) Sort results by file path."6103 }6104 fn doc_long(&self) -> &'static str {6105 r"6106DEPRECATED. Use \fB\-\-sort=path\fP instead.6107.sp6108This flag instructs ripgrep to sort search results by file path6109lexicographically in ascending order. Note that this currently disables all6110parallelism and runs search in a single thread.6111.sp6112This flag overrides \flag{sort} and \flag{sortr}.6113"6114 }61156116 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6117 args.sort = if v.unwrap_switch() {6118 Some(SortMode { reverse: false, kind: SortModeKind::Path })6119 } else {6120 None6121 };6122 Ok(())6123 }6124}61256126#[cfg(test)]6127#[test]6128fn test_sort_files() {6129 let args = parse_low_raw(None::<&str>).unwrap();6130 assert_eq!(None, args.sort);61316132 let args = parse_low_raw(["--sort-files"]).unwrap();6133 assert_eq!(6134 Some(SortMode { reverse: false, kind: SortModeKind::Path }),6135 args.sort6136 );61376138 let args = parse_low_raw(["--sort-files", "--no-sort-files"]).unwrap();6139 assert_eq!(None, args.sort);61406141 let args = parse_low_raw(["--sort", "created", "--sort-files"]).unwrap();6142 assert_eq!(6143 Some(SortMode { reverse: false, kind: SortModeKind::Path }),6144 args.sort6145 );61466147 let args = parse_low_raw(["--sort-files", "--sort", "created"]).unwrap();6148 assert_eq!(6149 Some(SortMode { reverse: false, kind: SortModeKind::Created }),6150 args.sort6151 );61526153 let args = parse_low_raw(["--sortr", "created", "--sort-files"]).unwrap();6154 assert_eq!(6155 Some(SortMode { reverse: false, kind: SortModeKind::Path }),6156 args.sort6157 );61586159 let args = parse_low_raw(["--sort-files", "--sortr", "created"]).unwrap();6160 assert_eq!(6161 Some(SortMode { reverse: true, kind: SortModeKind::Created }),6162 args.sort6163 );61646165 let args = parse_low_raw(["--sort=path", "--no-sort-files"]).unwrap();6166 assert_eq!(None, args.sort);61676168 let args = parse_low_raw(["--sortr=path", "--no-sort-files"]).unwrap();6169 assert_eq!(None, args.sort);6170}61716172/// --sort6173#[derive(Debug)]6174struct Sort;61756176impl Flag for Sort {6177 fn is_switch(&self) -> bool {6178 false6179 }6180 fn name_long(&self) -> &'static str {6181 "sort"6182 }6183 fn doc_variable(&self) -> Option<&'static str> {6184 Some("SORTBY")6185 }6186 fn doc_category(&self) -> Category {6187 Category::Output6188 }6189 fn doc_short(&self) -> &'static str {6190 r"Sort results in ascending order."6191 }6192 fn doc_long(&self) -> &'static str {6193 r"6194This flag enables sorting of results in ascending order. The possible values6195for this flag are:6196.sp6197.TP 126198\fBnone\fP6199(Default) Do not sort results. Fastest. Can be multi-threaded.6200.TP 126201\fBpath\fP6202Sort by file path. Always single-threaded.6203.TP 126204\fBmodified\fP6205Sort by the last modified time on a file. Always single-threaded.6206.TP 126207\fBaccessed\fP6208Sort by the last accessed time on a file. Always single-threaded.6209.TP 126210\fBcreated\fP6211Sort by the creation time on a file. Always single-threaded.6212.PP6213If the chosen (manually or by-default) sorting criteria isn't available on your6214system (for example, creation time is not available on ext4 file systems), then6215ripgrep will attempt to detect this, print an error and exit without searching.6216.sp6217To sort results in reverse or descending order, use the \flag{sortr} flag. Also,6218this flag overrides \flag{sortr}.6219.sp6220Note that sorting results currently always forces ripgrep to abandon6221parallelism and run in a single thread.6222"6223 }6224 fn doc_choices(&self) -> &'static [&'static str] {6225 &["none", "path", "modified", "accessed", "created"]6226 }62276228 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6229 let kind = match convert::str(&v.unwrap_value())? {6230 "none" => {6231 args.sort = None;6232 return Ok(());6233 }6234 "path" => SortModeKind::Path,6235 "modified" => SortModeKind::LastModified,6236 "accessed" => SortModeKind::LastAccessed,6237 "created" => SortModeKind::Created,6238 unk => anyhow::bail!("choice '{unk}' is unrecognized"),6239 };6240 args.sort = Some(SortMode { reverse: false, kind });6241 Ok(())6242 }6243}62446245#[cfg(test)]6246#[test]6247fn test_sort() {6248 let args = parse_low_raw(None::<&str>).unwrap();6249 assert_eq!(None, args.sort);62506251 let args = parse_low_raw(["--sort", "path"]).unwrap();6252 assert_eq!(6253 Some(SortMode { reverse: false, kind: SortModeKind::Path }),6254 args.sort6255 );62566257 let args = parse_low_raw(["--sort", "path", "--sort=created"]).unwrap();6258 assert_eq!(6259 Some(SortMode { reverse: false, kind: SortModeKind::Created }),6260 args.sort6261 );62626263 let args = parse_low_raw(["--sort=none"]).unwrap();6264 assert_eq!(None, args.sort);62656266 let args = parse_low_raw(["--sort", "path", "--sort=none"]).unwrap();6267 assert_eq!(None, args.sort);6268}62696270/// --sortr6271#[derive(Debug)]6272struct Sortr;62736274impl Flag for Sortr {6275 fn is_switch(&self) -> bool {6276 false6277 }6278 fn name_long(&self) -> &'static str {6279 "sortr"6280 }6281 fn doc_variable(&self) -> Option<&'static str> {6282 Some("SORTBY")6283 }6284 fn doc_category(&self) -> Category {6285 Category::Output6286 }6287 fn doc_short(&self) -> &'static str {6288 r"Sort results in descending order."6289 }6290 fn doc_long(&self) -> &'static str {6291 r"6292This flag enables sorting of results in descending order. The possible values6293for this flag are:6294.sp6295.TP 126296\fBnone\fP6297(Default) Do not sort results. Fastest. Can be multi-threaded.6298.TP 126299\fBpath\fP6300Sort by file path. Always single-threaded.6301.TP 126302\fBmodified\fP6303Sort by the last modified time on a file. Always single-threaded.6304.TP 126305\fBaccessed\fP6306Sort by the last accessed time on a file. Always single-threaded.6307.TP 126308\fBcreated\fP6309Sort by the creation time on a file. Always single-threaded.6310.PP6311If the chosen (manually or by-default) sorting criteria isn't available on your6312system (for example, creation time is not available on ext4 file systems), then6313ripgrep will attempt to detect this, print an error and exit without searching.6314.sp6315To sort results in ascending order, use the \flag{sort} flag. Also, this flag6316overrides \flag{sort}.6317.sp6318Note that sorting results currently always forces ripgrep to abandon6319parallelism and run in a single thread.6320"6321 }6322 fn doc_choices(&self) -> &'static [&'static str] {6323 &["none", "path", "modified", "accessed", "created"]6324 }63256326 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6327 let kind = match convert::str(&v.unwrap_value())? {6328 "none" => {6329 args.sort = None;6330 return Ok(());6331 }6332 "path" => SortModeKind::Path,6333 "modified" => SortModeKind::LastModified,6334 "accessed" => SortModeKind::LastAccessed,6335 "created" => SortModeKind::Created,6336 unk => anyhow::bail!("choice '{unk}' is unrecognized"),6337 };6338 args.sort = Some(SortMode { reverse: true, kind });6339 Ok(())6340 }6341}63426343#[cfg(test)]6344#[test]6345fn test_sortr() {6346 let args = parse_low_raw(None::<&str>).unwrap();6347 assert_eq!(None, args.sort);63486349 let args = parse_low_raw(["--sortr", "path"]).unwrap();6350 assert_eq!(6351 Some(SortMode { reverse: true, kind: SortModeKind::Path }),6352 args.sort6353 );63546355 let args = parse_low_raw(["--sortr", "path", "--sortr=created"]).unwrap();6356 assert_eq!(6357 Some(SortMode { reverse: true, kind: SortModeKind::Created }),6358 args.sort6359 );63606361 let args = parse_low_raw(["--sortr=none"]).unwrap();6362 assert_eq!(None, args.sort);63636364 let args = parse_low_raw(["--sortr", "path", "--sortr=none"]).unwrap();6365 assert_eq!(None, args.sort);63666367 let args = parse_low_raw(["--sort=path", "--sortr=path"]).unwrap();6368 assert_eq!(6369 Some(SortMode { reverse: true, kind: SortModeKind::Path }),6370 args.sort6371 );63726373 let args = parse_low_raw(["--sortr=path", "--sort=path"]).unwrap();6374 assert_eq!(6375 Some(SortMode { reverse: false, kind: SortModeKind::Path }),6376 args.sort6377 );6378}63796380/// --stats6381#[derive(Debug)]6382struct Stats;63836384impl Flag for Stats {6385 fn is_switch(&self) -> bool {6386 true6387 }6388 fn name_long(&self) -> &'static str {6389 "stats"6390 }6391 fn name_negated(&self) -> Option<&'static str> {6392 Some("no-stats")6393 }6394 fn doc_category(&self) -> Category {6395 Category::Logging6396 }6397 fn doc_short(&self) -> &'static str {6398 r"Print statistics about the search."6399 }6400 fn doc_long(&self) -> &'static str {6401 r"6402When enabled, ripgrep will print aggregate statistics about the search. When6403this flag is present, ripgrep will print at least the following stats to6404stdout at the end of the search: number of matched lines, number of files with6405matches, number of files searched, and the time taken for the entire search to6406complete.6407.sp6408This set of aggregate statistics may expand over time.6409.sp6410Note that this flag has no effect if \flag{files}, \flag{files-with-matches} or6411\flag{files-without-match} is passed.6412"6413 }64146415 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6416 args.stats = v.unwrap_switch();6417 Ok(())6418 }6419}64206421#[cfg(test)]6422#[test]6423fn test_stats() {6424 let args = parse_low_raw(None::<&str>).unwrap();6425 assert_eq!(false, args.stats);64266427 let args = parse_low_raw(["--stats"]).unwrap();6428 assert_eq!(true, args.stats);64296430 let args = parse_low_raw(["--stats", "--no-stats"]).unwrap();6431 assert_eq!(false, args.stats);6432}64336434/// --stop-on-nonmatch6435#[derive(Debug)]6436struct StopOnNonmatch;64376438impl Flag for StopOnNonmatch {6439 fn is_switch(&self) -> bool {6440 true6441 }6442 fn name_long(&self) -> &'static str {6443 "stop-on-nonmatch"6444 }6445 fn doc_category(&self) -> Category {6446 Category::Search6447 }6448 fn doc_short(&self) -> &'static str {6449 r"Stop searching after a non-match."6450 }6451 fn doc_long(&self) -> &'static str {6452 r"6453Enabling this option will cause ripgrep to stop reading a file once it6454encounters a non-matching line after it has encountered a matching line.6455This is useful if it is expected that all matches in a given file will be on6456sequential lines, for example due to the lines being sorted.6457.sp6458This overrides the \flag{multiline} flag.6459"6460 }64616462 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6463 assert!(v.unwrap_switch(), "--stop-on-nonmatch has no negation");6464 args.stop_on_nonmatch = true;6465 args.multiline = false;6466 Ok(())6467 }6468}64696470#[cfg(test)]6471#[test]6472fn test_stop_on_nonmatch() {6473 let args = parse_low_raw(None::<&str>).unwrap();6474 assert_eq!(false, args.stop_on_nonmatch);64756476 let args = parse_low_raw(["--stop-on-nonmatch"]).unwrap();6477 assert_eq!(true, args.stop_on_nonmatch);64786479 let args = parse_low_raw(["--stop-on-nonmatch", "-U"]).unwrap();6480 assert_eq!(true, args.multiline);6481 assert_eq!(false, args.stop_on_nonmatch);64826483 let args = parse_low_raw(["-U", "--stop-on-nonmatch"]).unwrap();6484 assert_eq!(false, args.multiline);6485 assert_eq!(true, args.stop_on_nonmatch);64866487 let args =6488 parse_low_raw(["--stop-on-nonmatch", "--no-multiline"]).unwrap();6489 assert_eq!(false, args.multiline);6490 assert_eq!(true, args.stop_on_nonmatch);6491}64926493/// -a/--text6494#[derive(Debug)]6495struct Text;64966497impl Flag for Text {6498 fn is_switch(&self) -> bool {6499 true6500 }6501 fn name_short(&self) -> Option<u8> {6502 Some(b'a')6503 }6504 fn name_long(&self) -> &'static str {6505 "text"6506 }6507 fn name_negated(&self) -> Option<&'static str> {6508 Some("no-text")6509 }6510 fn doc_category(&self) -> Category {6511 Category::Search6512 }6513 fn doc_short(&self) -> &'static str {6514 r"Search binary files as if they were text."6515 }6516 fn doc_long(&self) -> &'static str {6517 r"6518This flag instructs ripgrep to search binary files as if they were text. When6519this flag is present, ripgrep's binary file detection is disabled. This means6520that when a binary file is searched, its contents may be printed if there is6521a match. This may cause escape codes to be printed that alter the behavior of6522your terminal.6523.sp6524When binary file detection is enabled, it is imperfect. In general, it uses6525a simple heuristic. If a \fBNUL\fP byte is seen during search, then the file6526is considered binary and searching stops (unless this flag is present).6527Alternatively, if the \flag{binary} flag is used, then ripgrep will only quit6528when it sees a \fBNUL\fP byte after it sees a match (or searches the entire6529file).6530.sp6531This flag overrides the \flag{binary} flag.6532"6533 }65346535 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6536 args.binary = if v.unwrap_switch() {6537 BinaryMode::AsText6538 } else {6539 BinaryMode::Auto6540 };6541 Ok(())6542 }6543}65446545#[cfg(test)]6546#[test]6547fn test_text() {6548 let args = parse_low_raw(None::<&str>).unwrap();6549 assert_eq!(BinaryMode::Auto, args.binary);65506551 let args = parse_low_raw(["--text"]).unwrap();6552 assert_eq!(BinaryMode::AsText, args.binary);65536554 let args = parse_low_raw(["-a"]).unwrap();6555 assert_eq!(BinaryMode::AsText, args.binary);65566557 let args = parse_low_raw(["-a", "--no-text"]).unwrap();6558 assert_eq!(BinaryMode::Auto, args.binary);65596560 let args = parse_low_raw(["-a", "--binary"]).unwrap();6561 assert_eq!(BinaryMode::SearchAndSuppress, args.binary);65626563 let args = parse_low_raw(["--binary", "-a"]).unwrap();6564 assert_eq!(BinaryMode::AsText, args.binary);65656566 let args = parse_low_raw(["-a", "--no-binary"]).unwrap();6567 assert_eq!(BinaryMode::Auto, args.binary);65686569 let args = parse_low_raw(["--binary", "--no-text"]).unwrap();6570 assert_eq!(BinaryMode::Auto, args.binary);6571}65726573/// -j/--threads6574#[derive(Debug)]6575struct Threads;65766577impl Flag for Threads {6578 fn is_switch(&self) -> bool {6579 false6580 }6581 fn name_short(&self) -> Option<u8> {6582 Some(b'j')6583 }6584 fn name_long(&self) -> &'static str {6585 "threads"6586 }6587 fn doc_variable(&self) -> Option<&'static str> {6588 Some("NUM")6589 }6590 fn doc_category(&self) -> Category {6591 Category::Search6592 }6593 fn doc_short(&self) -> &'static str {6594 r"Set the approximate number of threads to use."6595 }6596 fn doc_long(&self) -> &'static str {6597 r"6598This flag sets the approximate number of threads to use. A value of \fB0\fP6599(which is the default) causes ripgrep to choose the thread count using6600heuristics.6601"6602 }66036604 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6605 let threads = convert::usize(&v.unwrap_value())?;6606 args.threads = if threads == 0 { None } else { Some(threads) };6607 Ok(())6608 }6609}66106611#[cfg(test)]6612#[test]6613fn test_threads() {6614 let args = parse_low_raw(None::<&str>).unwrap();6615 assert_eq!(None, args.threads);66166617 let args = parse_low_raw(["--threads", "5"]).unwrap();6618 assert_eq!(Some(5), args.threads);66196620 let args = parse_low_raw(["-j", "5"]).unwrap();6621 assert_eq!(Some(5), args.threads);66226623 let args = parse_low_raw(["-j5"]).unwrap();6624 assert_eq!(Some(5), args.threads);66256626 let args = parse_low_raw(["-j5", "-j10"]).unwrap();6627 assert_eq!(Some(10), args.threads);66286629 let args = parse_low_raw(["-j5", "-j0"]).unwrap();6630 assert_eq!(None, args.threads);6631}66326633/// --trace6634#[derive(Debug)]6635struct Trace;66366637impl Flag for Trace {6638 fn is_switch(&self) -> bool {6639 true6640 }6641 fn name_long(&self) -> &'static str {6642 "trace"6643 }6644 fn doc_category(&self) -> Category {6645 Category::Logging6646 }6647 fn doc_short(&self) -> &'static str {6648 r"Show trace messages."6649 }6650 fn doc_long(&self) -> &'static str {6651 r"6652Show trace messages. This shows even more detail than the \flag{debug}6653flag. Generally, one should only use this if \flag{debug} doesn't emit the6654information you're looking for.6655"6656 }66576658 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6659 assert!(v.unwrap_switch(), "--trace can only be enabled");6660 args.logging = Some(LoggingMode::Trace);6661 Ok(())6662 }6663}66646665#[cfg(test)]6666#[test]6667fn test_trace() {6668 let args = parse_low_raw(None::<&str>).unwrap();6669 assert_eq!(None, args.logging);66706671 let args = parse_low_raw(["--trace"]).unwrap();6672 assert_eq!(Some(LoggingMode::Trace), args.logging);66736674 let args = parse_low_raw(["--debug", "--trace"]).unwrap();6675 assert_eq!(Some(LoggingMode::Trace), args.logging);6676}66776678/// --trim6679#[derive(Debug)]6680struct Trim;66816682impl Flag for Trim {6683 fn is_switch(&self) -> bool {6684 true6685 }6686 fn name_long(&self) -> &'static str {6687 "trim"6688 }6689 fn name_negated(&self) -> Option<&'static str> {6690 Some("no-trim")6691 }6692 fn doc_category(&self) -> Category {6693 Category::Output6694 }6695 fn doc_short(&self) -> &'static str {6696 r"Trim prefix whitespace from matches."6697 }6698 fn doc_long(&self) -> &'static str {6699 r"6700When set, all ASCII whitespace at the beginning of each line printed will be6701removed.6702"6703 }67046705 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6706 args.trim = v.unwrap_switch();6707 Ok(())6708 }6709}67106711#[cfg(test)]6712#[test]6713fn test_trim() {6714 let args = parse_low_raw(None::<&str>).unwrap();6715 assert_eq!(false, args.trim);67166717 let args = parse_low_raw(["--trim"]).unwrap();6718 assert_eq!(true, args.trim);67196720 let args = parse_low_raw(["--trim", "--no-trim"]).unwrap();6721 assert_eq!(false, args.trim);6722}67236724/// -t/--type6725#[derive(Debug)]6726struct Type;67276728impl Flag for Type {6729 fn is_switch(&self) -> bool {6730 false6731 }6732 fn name_short(&self) -> Option<u8> {6733 Some(b't')6734 }6735 fn name_long(&self) -> &'static str {6736 "type"6737 }6738 fn doc_variable(&self) -> Option<&'static str> {6739 Some("TYPE")6740 }6741 fn doc_category(&self) -> Category {6742 Category::Filter6743 }6744 fn doc_short(&self) -> &'static str {6745 r"Only search files matching TYPE."6746 }6747 fn doc_long(&self) -> &'static str {6748 r#"6749This flag limits ripgrep to searching files matching \fITYPE\fP. Multiple6750\flag{type} flags may be provided.6751.sp6752This flag supports the special value \fBall\fP, which will behave as if6753\flag{type} was provided for every file type supported by ripgrep (including6754any custom file types). The end result is that \fB\-\-type=all\fP causes6755ripgrep to search in "whitelist" mode, where it will only search files it6756recognizes via its type definitions.6757.sp6758To see the list of available file types, use the \flag{type-list} flag.6759"#6760 }67616762 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6763 args.type_changes.push(TypeChange::Select {6764 name: convert::string(v.unwrap_value())?,6765 });6766 Ok(())6767 }6768}67696770#[cfg(test)]6771#[test]6772fn test_type() {6773 let select = |name: &str| TypeChange::Select { name: name.to_string() };67746775 let args = parse_low_raw(None::<&str>).unwrap();6776 assert_eq!(Vec::<TypeChange>::new(), args.type_changes);67776778 let args = parse_low_raw(["--type", "rust"]).unwrap();6779 assert_eq!(vec![select("rust")], args.type_changes);67806781 let args = parse_low_raw(["-t", "rust"]).unwrap();6782 assert_eq!(vec![select("rust")], args.type_changes);67836784 let args = parse_low_raw(["-trust"]).unwrap();6785 assert_eq!(vec![select("rust")], args.type_changes);67866787 let args = parse_low_raw(["-trust", "-tpython"]).unwrap();6788 assert_eq!(vec![select("rust"), select("python")], args.type_changes);67896790 let args = parse_low_raw(["-tabcdefxyz"]).unwrap();6791 assert_eq!(vec![select("abcdefxyz")], args.type_changes);6792}67936794/// --type-add6795#[derive(Debug)]6796struct TypeAdd;67976798impl Flag for TypeAdd {6799 fn is_switch(&self) -> bool {6800 false6801 }6802 fn name_long(&self) -> &'static str {6803 "type-add"6804 }6805 fn doc_variable(&self) -> Option<&'static str> {6806 Some("TYPESPEC")6807 }6808 fn doc_category(&self) -> Category {6809 Category::Filter6810 }6811 fn doc_short(&self) -> &'static str {6812 r"Add a new glob for a file type."6813 }6814 fn doc_long(&self) -> &'static str {6815 r"6816This flag adds a new glob for a particular file type. Only one glob can be6817added at a time. Multiple \flag{type-add} flags can be provided. Unless6818\flag{type-clear} is used, globs are added to any existing globs defined inside6819of ripgrep.6820.sp6821Note that this must be passed to every invocation of ripgrep. Type settings are6822not persisted. See \fBCONFIGURATION FILES\fP for a workaround.6823.sp6824Example:6825.sp6826.EX6827 rg \-\-type\-add 'foo:*.foo' -tfoo \fIPATTERN\fP6828.EE6829.sp6830This flag can also be used to include rules from other types with the special6831include directive. The include directive permits specifying one or more other6832type names (separated by a comma) that have been defined and its rules will6833automatically be imported into the type specified. For example, to create a6834type called src that matches C++, Python and Markdown files, one can use:6835.sp6836.EX6837 \-\-type\-add 'src:include:cpp,py,md'6838.EE6839.sp6840Additional glob rules can still be added to the src type by using this flag6841again:6842.sp6843.EX6844 \-\-type\-add 'src:include:cpp,py,md' \-\-type\-add 'src:*.foo'6845.EE6846.sp6847Note that type names must consist only of Unicode letters or numbers.6848Punctuation characters are not allowed.6849"6850 }68516852 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6853 args.type_changes6854 .push(TypeChange::Add { def: convert::string(v.unwrap_value())? });6855 Ok(())6856 }6857}68586859#[cfg(test)]6860#[test]6861fn test_type_add() {6862 let args = parse_low_raw(None::<&str>).unwrap();6863 assert_eq!(Vec::<TypeChange>::new(), args.type_changes);68646865 let args = parse_low_raw(["--type-add", "foo"]).unwrap();6866 assert_eq!(6867 vec![TypeChange::Add { def: "foo".to_string() }],6868 args.type_changes6869 );68706871 let args = parse_low_raw(["--type-add", "foo", "--type-add=bar"]).unwrap();6872 assert_eq!(6873 vec![6874 TypeChange::Add { def: "foo".to_string() },6875 TypeChange::Add { def: "bar".to_string() }6876 ],6877 args.type_changes6878 );6879}68806881/// --type-clear6882#[derive(Debug)]6883struct TypeClear;68846885impl Flag for TypeClear {6886 fn is_switch(&self) -> bool {6887 false6888 }6889 fn name_long(&self) -> &'static str {6890 "type-clear"6891 }6892 fn doc_variable(&self) -> Option<&'static str> {6893 Some("TYPE")6894 }6895 fn doc_category(&self) -> Category {6896 Category::Filter6897 }6898 fn doc_short(&self) -> &'static str {6899 r"Clear globs for a file type."6900 }6901 fn doc_long(&self) -> &'static str {6902 r"6903Clear the file type globs previously defined for \fITYPE\fP. This clears any6904previously defined globs for the \fITYPE\fP, but globs can be added after this6905flag.6906.sp6907Note that this must be passed to every invocation of ripgrep. Type settings are6908not persisted. See \fBCONFIGURATION FILES\fP for a workaround.6909"6910 }69116912 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6913 args.type_changes.push(TypeChange::Clear {6914 name: convert::string(v.unwrap_value())?,6915 });6916 Ok(())6917 }6918}69196920#[cfg(test)]6921#[test]6922fn test_type_clear() {6923 let args = parse_low_raw(None::<&str>).unwrap();6924 assert_eq!(Vec::<TypeChange>::new(), args.type_changes);69256926 let args = parse_low_raw(["--type-clear", "foo"]).unwrap();6927 assert_eq!(6928 vec![TypeChange::Clear { name: "foo".to_string() }],6929 args.type_changes6930 );69316932 let args =6933 parse_low_raw(["--type-clear", "foo", "--type-clear=bar"]).unwrap();6934 assert_eq!(6935 vec![6936 TypeChange::Clear { name: "foo".to_string() },6937 TypeChange::Clear { name: "bar".to_string() }6938 ],6939 args.type_changes6940 );6941}69426943/// --type-not6944#[derive(Debug)]6945struct TypeNot;69466947impl Flag for TypeNot {6948 fn is_switch(&self) -> bool {6949 false6950 }6951 fn name_short(&self) -> Option<u8> {6952 Some(b'T')6953 }6954 fn name_long(&self) -> &'static str {6955 "type-not"6956 }6957 fn doc_variable(&self) -> Option<&'static str> {6958 Some("TYPE")6959 }6960 fn doc_category(&self) -> Category {6961 Category::Filter6962 }6963 fn doc_short(&self) -> &'static str {6964 r"Do not search files matching TYPE."6965 }6966 fn doc_long(&self) -> &'static str {6967 r#"6968Do not search files matching \fITYPE\fP. Multiple \flag{type-not} flags may be6969provided. Use the \flag{type-list} flag to list all available types.6970.sp6971This flag supports the special value \fBall\fP, which will behave6972as if \flag{type-not} was provided for every file type supported by6973ripgrep (including any custom file types). The end result is that6974\fB\-\-type\-not=all\fP causes ripgrep to search in "blacklist" mode, where it6975will only search files that are unrecognized by its type definitions.6976.sp6977To see the list of available file types, use the \flag{type-list} flag.6978"#6979 }69806981 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {6982 args.type_changes.push(TypeChange::Negate {6983 name: convert::string(v.unwrap_value())?,6984 });6985 Ok(())6986 }6987}69886989#[cfg(test)]6990#[test]6991fn test_type_not() {6992 let select = |name: &str| TypeChange::Select { name: name.to_string() };6993 let negate = |name: &str| TypeChange::Negate { name: name.to_string() };69946995 let args = parse_low_raw(None::<&str>).unwrap();6996 assert_eq!(Vec::<TypeChange>::new(), args.type_changes);69976998 let args = parse_low_raw(["--type-not", "rust"]).unwrap();6999 assert_eq!(vec![negate("rust")], args.type_changes);70007001 let args = parse_low_raw(["-T", "rust"]).unwrap();7002 assert_eq!(vec![negate("rust")], args.type_changes);70037004 let args = parse_low_raw(["-Trust"]).unwrap();7005 assert_eq!(vec![negate("rust")], args.type_changes);70067007 let args = parse_low_raw(["-Trust", "-Tpython"]).unwrap();7008 assert_eq!(vec![negate("rust"), negate("python")], args.type_changes);70097010 let args = parse_low_raw(["-Tabcdefxyz"]).unwrap();7011 assert_eq!(vec![negate("abcdefxyz")], args.type_changes);70127013 let args = parse_low_raw(["-Trust", "-ttoml", "-Tjson"]).unwrap();7014 assert_eq!(7015 vec![negate("rust"), select("toml"), negate("json")],7016 args.type_changes7017 );7018}70197020/// --type-list7021#[derive(Debug)]7022struct TypeList;70237024impl Flag for TypeList {7025 fn is_switch(&self) -> bool {7026 true7027 }7028 fn name_long(&self) -> &'static str {7029 "type-list"7030 }7031 fn doc_category(&self) -> Category {7032 Category::OtherBehaviors7033 }7034 fn doc_short(&self) -> &'static str {7035 r"Show all supported file types."7036 }7037 fn doc_long(&self) -> &'static str {7038 r"7039Show all supported file types and their corresponding globs. This takes any7040\flag{type-add} and \flag{type-clear} flags given into account. Each type is7041printed on its own line, followed by a \fB:\fP and then a comma-delimited list7042of globs for that type on the same line.7043"7044 }70457046 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7047 assert!(v.unwrap_switch(), "--type-list has no negation");7048 args.mode.update(Mode::Types);7049 Ok(())7050 }7051}70527053#[cfg(test)]7054#[test]7055fn test_type_list() {7056 let args = parse_low_raw(None::<&str>).unwrap();7057 assert_eq!(Mode::Search(SearchMode::Standard), args.mode);70587059 let args = parse_low_raw(["--type-list"]).unwrap();7060 assert_eq!(Mode::Types, args.mode);7061}70627063/// -u/--unrestricted7064#[derive(Debug)]7065struct Unrestricted;70667067impl Flag for Unrestricted {7068 fn is_switch(&self) -> bool {7069 true7070 }7071 fn name_short(&self) -> Option<u8> {7072 Some(b'u')7073 }7074 fn name_long(&self) -> &'static str {7075 "unrestricted"7076 }7077 fn doc_category(&self) -> Category {7078 Category::Filter7079 }7080 fn doc_short(&self) -> &'static str {7081 r#"Reduce the level of "smart" filtering."#7082 }7083 fn doc_long(&self) -> &'static str {7084 r#"7085This flag reduces the level of "smart" filtering. Repeated uses (up to 3) reduces7086the filtering even more. When repeated three times, ripgrep will search every7087file in a directory tree.7088.sp7089A single \flag{unrestricted} flag is equivalent to \flag{no-ignore}. Two7090\flag{unrestricted} flags is equivalent to \flag{no-ignore} \flag{hidden}.7091Three \flag{unrestricted} flags is equivalent to \flag{no-ignore} \flag{hidden}7092\flag{binary}.7093.sp7094The only filtering ripgrep still does when \fB-uuu\fP is given is to skip7095symbolic links and to avoid printing matches from binary files. Symbolic links7096can be followed via the \flag{follow} flag, and binary files can be treated as7097text files via the \flag{text} flag.7098"#7099 }71007101 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7102 assert!(v.unwrap_switch(), "--unrestricted has no negation");7103 args.unrestricted = args.unrestricted.saturating_add(1);7104 anyhow::ensure!(7105 args.unrestricted <= 3,7106 "flag can only be repeated up to 3 times"7107 );7108 if args.unrestricted == 1 {7109 NoIgnore.update(FlagValue::Switch(true), args)?;7110 } else if args.unrestricted == 2 {7111 Hidden.update(FlagValue::Switch(true), args)?;7112 } else {7113 assert_eq!(args.unrestricted, 3);7114 Binary.update(FlagValue::Switch(true), args)?;7115 }7116 Ok(())7117 }7118}71197120#[cfg(test)]7121#[test]7122fn test_unrestricted() {7123 let args = parse_low_raw(None::<&str>).unwrap();7124 assert_eq!(false, args.no_ignore_vcs);7125 assert_eq!(false, args.hidden);7126 assert_eq!(BinaryMode::Auto, args.binary);71277128 let args = parse_low_raw(["--unrestricted"]).unwrap();7129 assert_eq!(true, args.no_ignore_vcs);7130 assert_eq!(false, args.hidden);7131 assert_eq!(BinaryMode::Auto, args.binary);71327133 let args = parse_low_raw(["--unrestricted", "-u"]).unwrap();7134 assert_eq!(true, args.no_ignore_vcs);7135 assert_eq!(true, args.hidden);7136 assert_eq!(BinaryMode::Auto, args.binary);71377138 let args = parse_low_raw(["-uuu"]).unwrap();7139 assert_eq!(true, args.no_ignore_vcs);7140 assert_eq!(true, args.hidden);7141 assert_eq!(BinaryMode::SearchAndSuppress, args.binary);71427143 let result = parse_low_raw(["-uuuu"]);7144 assert!(result.is_err(), "{result:?}");7145}71467147/// --version7148#[derive(Debug)]7149struct Version;71507151impl Flag for Version {7152 fn is_switch(&self) -> bool {7153 true7154 }7155 fn name_short(&self) -> Option<u8> {7156 Some(b'V')7157 }7158 fn name_long(&self) -> &'static str {7159 "version"7160 }7161 fn doc_category(&self) -> Category {7162 Category::OtherBehaviors7163 }7164 fn doc_short(&self) -> &'static str {7165 r"Print ripgrep's version."7166 }7167 fn doc_long(&self) -> &'static str {7168 r"7169This flag prints ripgrep's version. This also may print other relevant7170information, such as the presence of target specific optimizations and the7171\fBgit\fP revision that this build of ripgrep was compiled from.7172"7173 }71747175 fn update(&self, v: FlagValue, _: &mut LowArgs) -> anyhow::Result<()> {7176 assert!(v.unwrap_switch(), "--version has no negation");7177 // Since this flag has different semantics for -V and --version and the7178 // Flag trait doesn't support encoding this sort of thing, we handle it7179 // as a special case in the parser.7180 Ok(())7181 }7182}71837184#[cfg(test)]7185#[test]7186fn test_version() {7187 let args = parse_low_raw(None::<&str>).unwrap();7188 assert_eq!(None, args.special);71897190 let args = parse_low_raw(["-V"]).unwrap();7191 assert_eq!(Some(SpecialMode::VersionShort), args.special);71927193 let args = parse_low_raw(["--version"]).unwrap();7194 assert_eq!(Some(SpecialMode::VersionLong), args.special);71957196 let args = parse_low_raw(["-V", "--version"]).unwrap();7197 assert_eq!(Some(SpecialMode::VersionLong), args.special);71987199 let args = parse_low_raw(["--version", "-V"]).unwrap();7200 assert_eq!(Some(SpecialMode::VersionShort), args.special);7201}72027203/// --vimgrep7204#[derive(Debug)]7205struct Vimgrep;72067207impl Flag for Vimgrep {7208 fn is_switch(&self) -> bool {7209 true7210 }7211 fn name_long(&self) -> &'static str {7212 "vimgrep"7213 }7214 fn doc_category(&self) -> Category {7215 Category::Output7216 }7217 fn doc_short(&self) -> &'static str {7218 r"Print results im a vim compatible format."7219 }7220 fn doc_long(&self) -> &'static str {7221 r"7222This flag instructs ripgrep to print results with every match on its own line,7223including line numbers and column numbers.7224.sp7225With this option, a line with more than one match will be printed in its7226entirety more than once. For that reason, the total amount of output as a7227result of this flag can be quadratic in the size of the input. For example,7228if the pattern matches every byte in an input file, then each line will be7229repeated for every byte matched. For this reason, users should only use this7230flag when there is no other choice. Editor integrations should prefer some7231other way of reading results from ripgrep, such as via the \flag{json} flag.7232"7233 }7234 fn doc_choices(&self) -> &'static [&'static str] {7235 &[]7236 }72377238 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7239 assert!(v.unwrap_switch(), "--vimgrep has no negation");7240 args.vimgrep = true;7241 Ok(())7242 }7243}72447245#[cfg(test)]7246#[test]7247fn test_vimgrep() {7248 let args = parse_low_raw(None::<&str>).unwrap();7249 assert_eq!(false, args.vimgrep);72507251 let args = parse_low_raw(["--vimgrep"]).unwrap();7252 assert_eq!(true, args.vimgrep);7253}72547255/// --with-filename7256#[derive(Debug)]7257struct WithFilename;72587259impl Flag for WithFilename {7260 fn is_switch(&self) -> bool {7261 true7262 }7263 fn name_short(&self) -> Option<u8> {7264 Some(b'H')7265 }7266 fn name_long(&self) -> &'static str {7267 "with-filename"7268 }7269 fn doc_category(&self) -> Category {7270 Category::Output7271 }7272 fn doc_short(&self) -> &'static str {7273 r"Print the file path with each matching line."7274 }7275 fn doc_long(&self) -> &'static str {7276 r"7277This flag instructs ripgrep to print the file path for each matching line.7278This is the default when more than one file is searched. If \flag{heading} is7279enabled (the default when printing to a terminal), the file path will be shown7280above clusters of matches from each file; otherwise, the file name will be7281shown as a prefix for each matched line.7282.sp7283This flag overrides \flag{no-filename}.7284"7285 }72867287 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7288 assert!(v.unwrap_switch(), "--with-filename has no defined negation");7289 args.with_filename = Some(true);7290 Ok(())7291 }7292}72937294#[cfg(test)]7295#[test]7296fn test_with_filename() {7297 let args = parse_low_raw(None::<&str>).unwrap();7298 assert_eq!(None, args.with_filename);72997300 let args = parse_low_raw(["--with-filename"]).unwrap();7301 assert_eq!(Some(true), args.with_filename);73027303 let args = parse_low_raw(["-H"]).unwrap();7304 assert_eq!(Some(true), args.with_filename);7305}73067307/// --no-filename7308#[derive(Debug)]7309struct WithFilenameNo;73107311impl Flag for WithFilenameNo {7312 fn is_switch(&self) -> bool {7313 true7314 }7315 fn name_short(&self) -> Option<u8> {7316 Some(b'I')7317 }7318 fn name_long(&self) -> &'static str {7319 "no-filename"7320 }7321 fn doc_category(&self) -> Category {7322 Category::Output7323 }7324 fn doc_short(&self) -> &'static str {7325 r"Never print the path with each matching line."7326 }7327 fn doc_long(&self) -> &'static str {7328 r"7329This flag instructs ripgrep to never print the file path with each matching7330line. This is the default when ripgrep is explicitly instructed to search one7331file or stdin.7332.sp7333This flag overrides \flag{with-filename}.7334"7335 }7336 fn doc_choices(&self) -> &'static [&'static str] {7337 &[]7338 }73397340 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7341 assert!(v.unwrap_switch(), "--no-filename has no defined negation");7342 args.with_filename = Some(false);7343 Ok(())7344 }7345}73467347#[cfg(test)]7348#[test]7349fn test_with_filename_no() {7350 let args = parse_low_raw(None::<&str>).unwrap();7351 assert_eq!(None, args.with_filename);73527353 let args = parse_low_raw(["--no-filename"]).unwrap();7354 assert_eq!(Some(false), args.with_filename);73557356 let args = parse_low_raw(["-I"]).unwrap();7357 assert_eq!(Some(false), args.with_filename);73587359 let args = parse_low_raw(["-I", "-H"]).unwrap();7360 assert_eq!(Some(true), args.with_filename);73617362 let args = parse_low_raw(["-H", "-I"]).unwrap();7363 assert_eq!(Some(false), args.with_filename);7364}73657366/// -w/--word-regexp7367#[derive(Debug)]7368struct WordRegexp;73697370impl Flag for WordRegexp {7371 fn is_switch(&self) -> bool {7372 true7373 }7374 fn name_short(&self) -> Option<u8> {7375 Some(b'w')7376 }7377 fn name_long(&self) -> &'static str {7378 "word-regexp"7379 }7380 fn doc_category(&self) -> Category {7381 Category::Search7382 }7383 fn doc_short(&self) -> &'static str {7384 r"Show matches surrounded by word boundaries."7385 }7386 fn doc_long(&self) -> &'static str {7387 r"7388When enabled, ripgrep will only show matches surrounded by word boundaries.7389This is equivalent to surrounding every pattern with \fB\\b{start-half}\fP7390and \fB\\b{end-half}\fP.7391.sp7392This overrides the \flag{line-regexp} flag.7393"7394 }73957396 fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {7397 assert!(v.unwrap_switch(), "--word-regexp has no negation");7398 args.boundary = Some(BoundaryMode::Word);7399 Ok(())7400 }7401}74027403#[cfg(test)]7404#[test]7405fn test_word_regexp() {7406 let args = parse_low_raw(None::<&str>).unwrap();7407 assert_eq!(None, args.boundary);74087409 let args = parse_low_raw(["--word-regexp"]).unwrap();7410 assert_eq!(Some(BoundaryMode::Word), args.boundary);74117412 let args = parse_low_raw(["-w"]).unwrap();7413 assert_eq!(Some(BoundaryMode::Word), args.boundary);74147415 let args = parse_low_raw(["-x", "-w"]).unwrap();7416 assert_eq!(Some(BoundaryMode::Word), args.boundary);74177418 let args = parse_low_raw(["-w", "-x"]).unwrap();7419 assert_eq!(Some(BoundaryMode::Line), args.boundary);7420}74217422mod convert {7423 use std::ffi::{OsStr, OsString};74247425 use anyhow::Context;74267427 pub(super) fn str(v: &OsStr) -> anyhow::Result<&str> {7428 let Some(s) = v.to_str() else {7429 anyhow::bail!("value is not valid UTF-8")7430 };7431 Ok(s)7432 }74337434 pub(super) fn string(v: OsString) -> anyhow::Result<String> {7435 let Ok(s) = v.into_string() else {7436 anyhow::bail!("value is not valid UTF-8")7437 };7438 Ok(s)7439 }74407441 pub(super) fn usize(v: &OsStr) -> anyhow::Result<usize> {7442 str(v)?.parse().context("value is not a valid number")7443 }74447445 pub(super) fn u64(v: &OsStr) -> anyhow::Result<u64> {7446 str(v)?.parse().context("value is not a valid number")7447 }74487449 pub(super) fn human_readable_u64(v: &OsStr) -> anyhow::Result<u64> {7450 grep::cli::parse_human_readable_size(str(v)?).context("invalid size")7451 }74527453 pub(super) fn human_readable_usize(v: &OsStr) -> anyhow::Result<usize> {7454 let size = human_readable_u64(v)?;7455 let Ok(size) = usize::try_from(size) else {7456 anyhow::bail!("size is too big")7457 };7458 Ok(size)7459 }7460}74617462#[cfg(test)]7463mod tests {7464 use super::*;74657466 #[test]7467 fn available_shorts() {7468 let mut total = vec![false; 128];7469 for byte in 0..=0x7F {7470 match byte {7471 b'.' | b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => {7472 total[usize::from(byte)] = true7473 }7474 _ => continue,7475 }7476 }74777478 let mut taken = vec![false; 128];7479 for flag in FLAGS.iter() {7480 let Some(short) = flag.name_short() else { continue };7481 taken[usize::from(short)] = true;7482 }74837484 for byte in 0..=0x7F {7485 if total[usize::from(byte)] && !taken[usize::from(byte)] {7486 eprintln!("{}", char::from(byte));7487 }7488 }7489 }74907491 #[test]7492 fn shorts_all_ascii_alphanumeric() {7493 for flag in FLAGS.iter() {7494 let Some(byte) = flag.name_short() else { continue };7495 let long = flag.name_long();7496 assert!(7497 byte.is_ascii_alphanumeric() || byte == b'.',7498 "\\x{byte:0X} is not a valid short flag for {long}",7499 )7500 }7501 }75027503 #[test]7504 fn longs_all_ascii_alphanumeric() {7505 for flag in FLAGS.iter() {7506 let long = flag.name_long();7507 let count = long.chars().count();7508 assert!(count >= 2, "flag '{long}' is less than 2 characters");7509 assert!(7510 long.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),7511 "flag '{long}' does not match ^[-0-9A-Za-z]+$",7512 );7513 for alias in flag.aliases() {7514 let count = alias.chars().count();7515 assert!(7516 count >= 2,7517 "flag '{long}' has alias '{alias}' that is \7518 less than 2 characters",7519 );7520 assert!(7521 alias7522 .chars()7523 .all(|c| c.is_ascii_alphanumeric() || c == '-'),7524 "flag '{long}' has alias '{alias}' that does not \7525 match ^[-0-9A-Za-z]+$",7526 );7527 }7528 let Some(negated) = flag.name_negated() else { continue };7529 let count = negated.chars().count();7530 assert!(7531 count >= 2,7532 "flag '{long}' has negation '{negated}' that is \7533 less than 2 characters",7534 );7535 assert!(7536 negated.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),7537 "flag '{long}' has negation '{negated}' that \7538 does not match ^[-0-9A-Za-z]+$",7539 );7540 }7541 }75427543 #[test]7544 fn shorts_no_duplicates() {7545 let mut taken = vec![false; 128];7546 for flag in FLAGS.iter() {7547 let Some(short) = flag.name_short() else { continue };7548 let long = flag.name_long();7549 assert!(7550 !taken[usize::from(short)],7551 "flag {long} has duplicate short flag {}",7552 char::from(short)7553 );7554 taken[usize::from(short)] = true;7555 }7556 }75577558 #[test]7559 fn longs_no_duplicates() {7560 use std::collections::BTreeSet;75617562 let mut taken = BTreeSet::new();7563 for flag in FLAGS.iter() {7564 let long = flag.name_long();7565 assert!(taken.insert(long), "flag {long} has a duplicate name");7566 for alias in flag.aliases() {7567 assert!(7568 taken.insert(alias),7569 "flag {long} has an alias {alias} that is duplicative"7570 );7571 }7572 let Some(negated) = flag.name_negated() else { continue };7573 assert!(7574 taken.insert(negated),7575 "negated flag {negated} has a duplicate name"7576 );7577 }7578 }75797580 #[test]7581 fn non_switches_have_variable_names() {7582 for flag in FLAGS.iter() {7583 if flag.is_switch() {7584 continue;7585 }7586 let long = flag.name_long();7587 assert!(7588 flag.doc_variable().is_some(),7589 "flag '{long}' should have a variable name"7590 );7591 }7592 }75937594 #[test]7595 fn switches_have_no_choices() {7596 for flag in FLAGS.iter() {7597 if !flag.is_switch() {7598 continue;7599 }7600 let long = flag.name_long();7601 let choices = flag.doc_choices();7602 assert!(7603 choices.is_empty(),7604 "switch flag '{long}' \7605 should not have any choices but has some: {choices:?}",7606 );7607 }7608 }76097610 #[test]7611 fn choices_ascii_alphanumeric() {7612 for flag in FLAGS.iter() {7613 let long = flag.name_long();7614 for choice in flag.doc_choices() {7615 assert!(7616 choice.chars().all(|c| c.is_ascii_alphanumeric()7617 || c == '-'7618 || c == ':'),7619 "choice '{choice}' for flag '{long}' does not match \7620 ^[-:0-9A-Za-z]+$",7621 )7622 }7623 }7624 }7625}
added:crates/core/flags/hiargs.rs+1409 added
1/*!2Provides the definition of high level arguments from CLI flags.3*/45use std::{6 collections::HashSet,7 path::{Path, PathBuf},8};910use {11 bstr::BString,12 grep::printer::{ColorSpecs, SummaryKind},13};1415use crate::{16 flags::lowargs::{17 BinaryMode, BoundaryMode, BufferMode, CaseMode, ColorChoice,18 ContextMode, ContextSeparator, EncodingMode, EngineChoice,19 FieldContextSeparator, FieldMatchSeparator, LowArgs, MmapMode, Mode,20 PatternSource, SearchMode, SortMode, SortModeKind, TypeChange,21 },22 haystack::{Haystack, HaystackBuilder},23 search::{PatternMatcher, Printer, SearchWorker, SearchWorkerBuilder},24};2526/// A high level representation of CLI arguments.27///28/// The distinction between low and high level arguments is somewhat arbitrary29/// and wishy washy. The main idea here is that high level arguments generally30/// require all of CLI parsing to be finished. For example, one cannot31/// construct a glob matcher until all of the glob patterns are known.32///33/// So while low level arguments are collected during parsing itself, high34/// level arguments aren't created until parsing has completely finished.35#[derive(Debug)]36pub(crate) struct HiArgs {37 binary: BinaryDetection,38 boundary: Option<BoundaryMode>,39 buffer: BufferMode,40 byte_offset: bool,41 case: CaseMode,42 color: ColorChoice,43 colors: grep::printer::ColorSpecs,44 column: bool,45 context: ContextMode,46 context_separator: ContextSeparator,47 crlf: bool,48 dfa_size_limit: Option<usize>,49 encoding: EncodingMode,50 engine: EngineChoice,51 field_context_separator: FieldContextSeparator,52 field_match_separator: FieldMatchSeparator,53 file_separator: Option<Vec<u8>>,54 fixed_strings: bool,55 follow: bool,56 globs: ignore::overrides::Override,57 heading: bool,58 hidden: bool,59 hyperlink_config: grep::printer::HyperlinkConfig,60 ignore_file_case_insensitive: bool,61 ignore_file: Vec<PathBuf>,62 include_zero: bool,63 invert_match: bool,64 is_terminal_stdout: bool,65 line_number: bool,66 max_columns: Option<u64>,67 max_columns_preview: bool,68 max_count: Option<u64>,69 max_depth: Option<usize>,70 max_filesize: Option<u64>,71 mmap_choice: grep::searcher::MmapChoice,72 mode: Mode,73 multiline: bool,74 multiline_dotall: bool,75 no_ignore_dot: bool,76 no_ignore_exclude: bool,77 no_ignore_files: bool,78 no_ignore_global: bool,79 no_ignore_parent: bool,80 no_ignore_vcs: bool,81 no_require_git: bool,82 no_unicode: bool,83 null_data: bool,84 one_file_system: bool,85 only_matching: bool,86 path_separator: Option<u8>,87 paths: Paths,88 path_terminator: Option<u8>,89 patterns: Patterns,90 pre: Option<PathBuf>,91 pre_globs: ignore::overrides::Override,92 quiet: bool,93 quit_after_match: bool,94 regex_size_limit: Option<usize>,95 replace: Option<BString>,96 search_zip: bool,97 sort: Option<SortMode>,98 stats: Option<grep::printer::Stats>,99 stop_on_nonmatch: bool,100 threads: usize,101 trim: bool,102 types: ignore::types::Types,103 vimgrep: bool,104 with_filename: bool,105}106107impl HiArgs {108 /// Convert low level arguments into high level arguments.109 ///110 /// This process can fail for a variety of reasons. For example, invalid111 /// globs or some kind of environment issue.112 pub(crate) fn from_low_args(mut low: LowArgs) -> anyhow::Result<HiArgs> {113 // Callers should not be trying to convert low-level arguments when114 // a short-circuiting special mode is present.115 assert_eq!(None, low.special, "special mode demands short-circuiting");116 // If the sorting mode isn't supported, then we bail loudly. I'm not117 // sure if this is the right thing to do. We could silently "not sort"118 // as well. If we wanted to go that route, then we could just set119 // `low.sort = None` if `supported()` returns an error.120 if let Some(ref sort) = low.sort {121 sort.supported()?;122 }123124 // We modify the mode in-place on `low` so that subsequent conversions125 // see the correct mode.126 match low.mode {127 Mode::Search(ref mut mode) => match *mode {128 // treat `-v --count-matches` as `-v --count`129 SearchMode::CountMatches if low.invert_match => {130 *mode = SearchMode::Count;131 }132 // treat `-o --count` as `--count-matches`133 SearchMode::Count if low.only_matching => {134 *mode = SearchMode::CountMatches;135 }136 _ => {}137 },138 _ => {}139 }140141 let mut state = State::new()?;142 let patterns = Patterns::from_low_args(&mut state, &mut low)?;143 let paths = Paths::from_low_args(&mut state, &patterns, &mut low)?;144145 let binary = BinaryDetection::from_low_args(&state, &low);146 let colors = take_color_specs(&mut state, &mut low);147 let hyperlink_config = take_hyperlink_config(&mut state, &mut low)?;148 let stats = stats(&low);149 let types = types(&low)?;150 let globs = globs(&state, &low)?;151 let pre_globs = preprocessor_globs(&state, &low)?;152153 let color = match low.color {154 ColorChoice::Auto if !state.is_terminal_stdout => {155 ColorChoice::Never156 }157 _ => low.color,158 };159 let column = low.column.unwrap_or(low.vimgrep);160 let heading = match low.heading {161 None => !low.vimgrep && state.is_terminal_stdout,162 Some(false) => false,163 Some(true) => !low.vimgrep,164 };165 let path_terminator = if low.null { Some(b'\x00') } else { None };166 let quit_after_match = stats.is_none() && low.quiet;167 let threads = if low.sort.is_some() || paths.is_one_file {168 1169 } else if let Some(threads) = low.threads {170 threads171 } else {172 std::thread::available_parallelism().map_or(1, |n| n.get()).min(12)173 };174 let with_filename = low175 .with_filename176 .unwrap_or_else(|| low.vimgrep || !paths.is_one_file);177178 let file_separator = match low.mode {179 Mode::Search(SearchMode::Standard) => {180 if heading {181 Some(b"".to_vec())182 } else if let ContextMode::Limited(ref limited) = low.context {183 let (before, after) = limited.get();184 if before > 0 || after > 0 {185 low.context_separator.clone().into_bytes()186 } else {187 None188 }189 } else {190 None191 }192 }193 _ => None,194 };195196 let line_number = low.line_number.unwrap_or_else(|| {197 if low.quiet {198 return false;199 }200 let Mode::Search(ref search_mode) = low.mode else { return false };201 match *search_mode {202 SearchMode::FilesWithMatches203 | SearchMode::FilesWithoutMatch204 | SearchMode::Count205 | SearchMode::CountMatches => return false,206 SearchMode::JSON => return true,207 SearchMode::Standard => {208 // A few things can imply counting line numbers. In209 // particular, we generally want to show line numbers by210 // default when printing to a tty for human consumption,211 // except for one interesting case: when we're only212 // searching stdin. This makes pipelines work as expected.213 (state.is_terminal_stdout && !paths.is_only_stdin())214 || column215 || low.vimgrep216 }217 }218 });219220 let mmap_choice = {221 // SAFETY: Memory maps are difficult to impossible to encapsulate222 // safely in a portable way that doesn't simultaneously negate some223 // of the benfits of using memory maps. For ripgrep's use, we never224 // mutate a memory map and generally never store the contents of225 // memory map in a data structure that depends on immutability.226 // Generally speaking, the worst thing that can happen is a SIGBUS227 // (if the underlying file is truncated while reading it), which228 // will cause ripgrep to abort. This reasoning should be treated as229 // suspect.230 let maybe = unsafe { grep::searcher::MmapChoice::auto() };231 let never = grep::searcher::MmapChoice::never();232 match low.mmap {233 MmapMode::Auto => {234 if paths.paths.len() <= 10235 && paths.paths.iter().all(|p| p.is_file())236 {237 // If we're only searching a few paths and all of them238 // are files, then memory maps are probably faster.239 maybe240 } else {241 never242 }243 }244 MmapMode::AlwaysTryMmap => maybe,245 MmapMode::Never => never,246 }247 };248249 Ok(HiArgs {250 mode: low.mode,251 patterns,252 paths,253 binary,254 boundary: low.boundary,255 buffer: low.buffer,256 byte_offset: low.byte_offset,257 case: low.case,258 color,259 colors,260 column,261 context: low.context,262 context_separator: low.context_separator,263 crlf: low.crlf,264 dfa_size_limit: low.dfa_size_limit,265 encoding: low.encoding,266 engine: low.engine,267 field_context_separator: low.field_context_separator,268 field_match_separator: low.field_match_separator,269 file_separator,270 fixed_strings: low.fixed_strings,271 follow: low.follow,272 heading,273 hidden: low.hidden,274 hyperlink_config,275 ignore_file: low.ignore_file,276 ignore_file_case_insensitive: low.ignore_file_case_insensitive,277 include_zero: low.include_zero,278 invert_match: low.invert_match,279 is_terminal_stdout: state.is_terminal_stdout,280 line_number,281 max_columns: low.max_columns,282 max_columns_preview: low.max_columns_preview,283 max_count: low.max_count,284 max_depth: low.max_depth,285 max_filesize: low.max_filesize,286 mmap_choice,287 multiline: low.multiline,288 multiline_dotall: low.multiline_dotall,289 no_ignore_dot: low.no_ignore_dot,290 no_ignore_exclude: low.no_ignore_exclude,291 no_ignore_files: low.no_ignore_files,292 no_ignore_global: low.no_ignore_global,293 no_ignore_parent: low.no_ignore_parent,294 no_ignore_vcs: low.no_ignore_vcs,295 no_require_git: low.no_require_git,296 no_unicode: low.no_unicode,297 null_data: low.null_data,298 one_file_system: low.one_file_system,299 only_matching: low.only_matching,300 globs,301 path_separator: low.path_separator,302 path_terminator,303 pre: low.pre,304 pre_globs,305 quiet: low.quiet,306 quit_after_match,307 regex_size_limit: low.regex_size_limit,308 replace: low.replace,309 search_zip: low.search_zip,310 sort: low.sort,311 stats,312 stop_on_nonmatch: low.stop_on_nonmatch,313 threads,314 trim: low.trim,315 types,316 vimgrep: low.vimgrep,317 with_filename,318 })319 }320321 /// Returns a writer for printing buffers to stdout.322 ///323 /// This is intended to be used from multiple threads. Namely, a buffer324 /// writer can create new buffers that are sent to threads. Threads can325 /// then independently write to the buffers. Once a unit of work is326 /// complete, a buffer can be given to the buffer writer to write to327 /// stdout.328 pub(crate) fn buffer_writer(&self) -> termcolor::BufferWriter {329 let mut wtr =330 termcolor::BufferWriter::stdout(self.color.to_termcolor());331 wtr.separator(self.file_separator.clone());332 wtr333 }334335 /// Returns true when ripgrep had to guess to search the current working336 /// directory. That is, it's true when ripgrep is called without any file337 /// paths or directories to search.338 ///339 /// Other than changing how file paths are printed (i.e., without the340 /// leading `./`), it's also useful to know for diagnostic reasons. For341 /// example, ripgrep will print an error message when nothing is searched342 /// since it's possible the ignore rules in play are too aggressive. But343 /// this warning is only emitted when ripgrep was called without any344 /// explicit file paths since otherwise the warning would likely be too345 /// aggressive.346 pub(crate) fn has_implicit_path(&self) -> bool {347 self.paths.has_implicit_path348 }349350 /// Return a properly configured builder for constructing haystacks.351 ///352 /// The builder can be used to turn a directory entry (from the `ignore`353 /// crate) into something that can be searched.354 pub(crate) fn haystack_builder(&self) -> HaystackBuilder {355 let mut builder = HaystackBuilder::new();356 builder.strip_dot_prefix(self.paths.has_implicit_path);357 builder358 }359360 /// Return the matcher that should be used for searching using the engine361 /// choice made by the user.362 ///363 /// If there was a problem building the matcher (e.g., a syntax error),364 /// then this returns an error.365 pub(crate) fn matcher(&self) -> anyhow::Result<PatternMatcher> {366 match self.engine {367 EngineChoice::Default => match self.matcher_rust() {368 Ok(m) => Ok(m),369 Err(err) => {370 anyhow::bail!(suggest_other_engine(err.to_string()));371 }372 },373 EngineChoice::PCRE2 => Ok(self.matcher_pcre2()?),374 EngineChoice::Auto => {375 let rust_err = match self.matcher_rust() {376 Ok(m) => return Ok(m),377 Err(err) => err,378 };379 log::debug!(380 "error building Rust regex in hybrid mode:\n{rust_err}",381 );382383 let pcre_err = match self.matcher_pcre2() {384 Ok(m) => return Ok(m),385 Err(err) => err,386 };387 let divider = "~".repeat(79);388 anyhow::bail!(389 "regex could not be compiled with either the default \390 regex engine or with PCRE2.\n\n\391 default regex engine error:\n\392 {divider}\n\393 {rust_err}\n\394 {divider}\n\n\395 PCRE2 regex engine error:\n{pcre_err}",396 );397 }398 }399 }400401 /// Build a matcher using PCRE2.402 ///403 /// If there was a problem building the matcher (such as a regex syntax404 /// error), then an error is returned.405 ///406 /// If the `pcre2` feature is not enabled then this always returns an407 /// error.408 fn matcher_pcre2(&self) -> anyhow::Result<PatternMatcher> {409 #[cfg(feature = "pcre2")]410 {411 let mut builder = grep::pcre2::RegexMatcherBuilder::new();412 builder.multi_line(true).fixed_strings(self.fixed_strings);413 match self.case {414 CaseMode::Sensitive => builder.caseless(false),415 CaseMode::Insensitive => builder.caseless(true),416 CaseMode::Smart => builder.case_smart(true),417 };418 if let Some(ref boundary) = self.boundary {419 match *boundary {420 BoundaryMode::Line => builder.whole_line(true),421 BoundaryMode::Word => builder.word(true),422 };423 }424 // For whatever reason, the JIT craps out during regex compilation with425 // a "no more memory" error on 32 bit systems. So don't use it there.426 if cfg!(target_pointer_width = "64") {427 builder428 .jit_if_available(true)429 // The PCRE2 docs say that 32KB is the default, and that 1MB430 // should be big enough for anything. But let's crank it to431 // 10MB.432 .max_jit_stack_size(Some(10 * (1 << 20)));433 }434 if !self.no_unicode {435 builder.utf(true).ucp(true);436 }437 if self.multiline {438 builder.dotall(self.multiline_dotall);439 }440 if self.crlf {441 builder.crlf(true);442 }443 let m = builder.build_many(&self.patterns.patterns)?;444 Ok(PatternMatcher::PCRE2(m))445 }446 #[cfg(not(feature = "pcre2"))]447 {448 Err(anyhow::anyhow!(449 "PCRE2 is not available in this build of ripgrep"450 ))451 }452 }453454 /// Build a matcher using Rust's regex engine.455 ///456 /// If there was a problem building the matcher (such as a regex syntax457 /// error), then an error is returned.458 fn matcher_rust(&self) -> anyhow::Result<PatternMatcher> {459 let mut builder = grep::regex::RegexMatcherBuilder::new();460 builder461 .multi_line(true)462 .unicode(!self.no_unicode)463 .octal(false)464 .fixed_strings(self.fixed_strings);465 match self.case {466 CaseMode::Sensitive => builder.case_insensitive(false),467 CaseMode::Insensitive => builder.case_insensitive(true),468 CaseMode::Smart => builder.case_smart(true),469 };470 if let Some(ref boundary) = self.boundary {471 match *boundary {472 BoundaryMode::Line => builder.whole_line(true),473 BoundaryMode::Word => builder.word(true),474 };475 }476 if self.multiline {477 builder.dot_matches_new_line(self.multiline_dotall);478 if self.crlf {479 builder.crlf(true).line_terminator(None);480 }481 } else {482 builder.line_terminator(Some(b'\n')).dot_matches_new_line(false);483 if self.crlf {484 builder.crlf(true);485 }486 // We don't need to set this in multiline mode since mulitline487 // matchers don't use optimizations related to line terminators.488 // Moreover, a mulitline regex used with --null-data should489 // be allowed to match NUL bytes explicitly, which this would490 // otherwise forbid.491 if self.null_data {492 builder.line_terminator(Some(b'\x00'));493 }494 }495 if let Some(limit) = self.regex_size_limit {496 builder.size_limit(limit);497 }498 if let Some(limit) = self.dfa_size_limit {499 builder.dfa_size_limit(limit);500 }501 let m = match builder.build_many(&self.patterns.patterns) {502 Ok(m) => m,503 Err(err) => anyhow::bail!(suggest_multiline(err.to_string())),504 };505 Ok(PatternMatcher::RustRegex(m))506 }507508 /// Returns true if some non-zero number of matches is believed to be509 /// possible.510 ///511 /// When this returns false, it is impossible for ripgrep to ever report512 /// a match.513 pub(crate) fn matches_possible(&self) -> bool {514 if self.patterns.patterns.is_empty() {515 return false;516 }517 if self.max_count == Some(0) {518 return false;519 }520 true521 }522523 /// Returns the "mode" that ripgrep should operate in.524 ///525 /// This is generally useful for determining what action ripgrep should526 /// take. The main mode is of course to "search," but there are other527 /// non-search modes such as `--type-list` and `--files`.528 pub(crate) fn mode(&self) -> Mode {529 self.mode530 }531532 /// Returns a builder for constructing a "path printer."533 ///534 /// This is useful for the `--files` mode in ripgrep, where the printer535 /// just needs to emit paths and not need to worry about the functionality536 /// of searching.537 pub(crate) fn path_printer_builder(538 &self,539 ) -> grep::printer::PathPrinterBuilder {540 let mut builder = grep::printer::PathPrinterBuilder::new();541 builder542 .color_specs(self.colors.clone())543 .hyperlink(self.hyperlink_config.clone())544 .separator(self.path_separator.clone())545 .terminator(self.path_terminator.unwrap_or(b'\n'));546 builder547 }548549 /// Returns a printer for the given search mode.550 ///551 /// This chooses which printer to build (JSON, summary or standard) based552 /// on the search mode given.553 pub(crate) fn printer<W: termcolor::WriteColor>(554 &self,555 search_mode: SearchMode,556 wtr: W,557 ) -> Printer<W> {558 let summary_kind = if self.quiet {559 SummaryKind::Quiet560 } else {561 match search_mode {562 SearchMode::FilesWithMatches => SummaryKind::PathWithMatch,563 SearchMode::FilesWithoutMatch => SummaryKind::PathWithoutMatch,564 SearchMode::Count => SummaryKind::Count,565 SearchMode::CountMatches => SummaryKind::CountMatches,566 SearchMode::JSON => {567 return Printer::JSON(self.printer_json(wtr))568 }569 SearchMode::Standard => {570 return Printer::Standard(self.printer_standard(wtr))571 }572 }573 };574 Printer::Summary(self.printer_summary(wtr, summary_kind))575 }576577 /// Builds a JSON printer.578 fn printer_json<W: std::io::Write>(579 &self,580 wtr: W,581 ) -> grep::printer::JSON<W> {582 grep::printer::JSONBuilder::new()583 .pretty(false)584 .max_matches(self.max_count)585 .always_begin_end(false)586 .build(wtr)587 }588589 /// Builds a "standard" grep printer where matches are printed as plain590 /// text lines.591 fn printer_standard<W: termcolor::WriteColor>(592 &self,593 wtr: W,594 ) -> grep::printer::Standard<W> {595 grep::printer::StandardBuilder::new()596 .byte_offset(self.byte_offset)597 .color_specs(self.colors.clone())598 .column(self.column)599 .heading(self.heading)600 .hyperlink(self.hyperlink_config.clone())601 .max_columns_preview(self.max_columns_preview)602 .max_columns(self.max_columns)603 .max_matches(self.max_count)604 .only_matching(self.only_matching)605 .path(self.with_filename)606 .path_terminator(self.path_terminator.clone())607 .per_match_one_line(true)608 .per_match(self.vimgrep)609 .replacement(self.replace.clone().map(|r| r.into()))610 .separator_context(self.context_separator.clone().into_bytes())611 .separator_field_context(612 self.field_context_separator.clone().into_bytes(),613 )614 .separator_field_match(615 self.field_match_separator.clone().into_bytes(),616 )617 .separator_path(self.path_separator.clone())618 .separator_search(self.file_separator.clone())619 .stats(self.stats.is_some())620 .trim_ascii(self.trim)621 .build(wtr)622 }623624 /// Builds a "summary" printer where search results are aggregated on a625 /// file-by-file basis.626 fn printer_summary<W: termcolor::WriteColor>(627 &self,628 wtr: W,629 kind: SummaryKind,630 ) -> grep::printer::Summary<W> {631 grep::printer::SummaryBuilder::new()632 .color_specs(self.colors.clone())633 .exclude_zero(!self.include_zero)634 .hyperlink(self.hyperlink_config.clone())635 .kind(kind)636 .max_matches(self.max_count)637 .path(self.with_filename)638 .path_terminator(self.path_terminator.clone())639 .separator_field(b":".to_vec())640 .separator_path(self.path_separator.clone())641 .stats(self.stats.is_some())642 .build(wtr)643 }644645 /// Returns true if ripgrep should operate in "quiet" mode.646 ///647 /// Generally speaking, quiet mode means that ripgrep should not print648 /// anything to stdout. There are some exceptions. For example, when the649 /// user has provided `--stats`, then ripgrep will print statistics to650 /// stdout.651 pub(crate) fn quiet(&self) -> bool {652 self.quiet653 }654655 /// Returns true when ripgrep should stop searching after a single match is656 /// found.657 ///658 /// This is useful for example when quiet mode is enabled. In that case,659 /// users generally can't tell the difference in behavior between a search660 /// that finds all matches and a search that only finds one of them. (An661 /// exception here is if `--stats` is given, then `quit_after_match` will662 /// always return false since the user expects ripgrep to find everything.)663 pub(crate) fn quit_after_match(&self) -> bool {664 self.quit_after_match665 }666667 /// Build a worker for executing searches.668 ///669 /// Search results are found using the given matcher and written to the670 /// given printer.671 pub(crate) fn search_worker<W: termcolor::WriteColor>(672 &self,673 matcher: PatternMatcher,674 searcher: grep::searcher::Searcher,675 printer: Printer<W>,676 ) -> anyhow::Result<SearchWorker<W>> {677 let mut builder = SearchWorkerBuilder::new();678 builder679 .preprocessor(self.pre.clone())?680 .preprocessor_globs(self.pre_globs.clone())681 .search_zip(self.search_zip)682 .binary_detection_explicit(self.binary.explicit.clone())683 .binary_detection_implicit(self.binary.implicit.clone());684 Ok(builder.build(matcher, searcher, printer))685 }686687 /// Build a searcher from the command line parameters.688 pub(crate) fn searcher(&self) -> anyhow::Result<grep::searcher::Searcher> {689 let line_term = if self.crlf {690 grep::matcher::LineTerminator::crlf()691 } else if self.null_data {692 grep::matcher::LineTerminator::byte(b'\x00')693 } else {694 grep::matcher::LineTerminator::byte(b'\n')695 };696 let mut builder = grep::searcher::SearcherBuilder::new();697 builder698 .line_terminator(line_term)699 .invert_match(self.invert_match)700 .line_number(self.line_number)701 .multi_line(self.multiline)702 .memory_map(self.mmap_choice.clone())703 .stop_on_nonmatch(self.stop_on_nonmatch);704 match self.context {705 ContextMode::Passthru => {706 builder.passthru(true);707 }708 ContextMode::Limited(ref limited) => {709 let (before, after) = limited.get();710 builder.before_context(before);711 builder.after_context(after);712 }713 }714 match self.encoding {715 EncodingMode::Auto => {} // default for the searcher716 EncodingMode::Some(ref enc) => {717 builder.encoding(Some(enc.clone()));718 }719 EncodingMode::Disabled => {720 builder.bom_sniffing(false);721 }722 }723 Ok(builder.build())724 }725726 /// Given an iterator of haystacks, sort them if necessary.727 ///728 /// When sorting is necessary, this will collect the entire iterator into729 /// memory, sort them and then return a new iterator. When sorting is not730 /// necessary, then the iterator given is returned as is without collecting731 /// it into memory.732 ///733 /// Once special case is when sorting by path in ascending order has been734 /// requested. In this case, the iterator given is returned as is without735 /// any additional sorting. This is done because `walk_builder()` will sort736 /// the iterator it yields during directory traversal, so no additional737 /// sorting is needed.738 pub(crate) fn sort<'a, I>(739 &self,740 haystacks: I,741 ) -> Box<dyn Iterator<Item = Haystack> + 'a>742 where743 I: Iterator<Item = Haystack> + 'a,744 {745 use std::{cmp::Ordering, fs::Metadata, io, time::SystemTime};746747 fn attach_timestamps(748 haystacks: impl Iterator<Item = Haystack>,749 get: impl Fn(&Metadata) -> io::Result<SystemTime>,750 ) -> impl Iterator<Item = (Haystack, Option<SystemTime>)> {751 haystacks.map(move |s| {752 let time = s.path().metadata().and_then(|m| get(&m)).ok();753 (s, time)754 })755 }756757 let Some(ref sort) = self.sort else { return Box::new(haystacks) };758 let mut with_timestamps: Vec<_> = match sort.kind {759 SortModeKind::Path if !sort.reverse => return Box::new(haystacks),760 SortModeKind::Path => todo!(),761 SortModeKind::LastModified => {762 attach_timestamps(haystacks, |md| md.modified()).collect()763 }764 SortModeKind::LastAccessed => {765 attach_timestamps(haystacks, |md| md.accessed()).collect()766 }767 SortModeKind::Created => {768 attach_timestamps(haystacks, |md| md.created()).collect()769 }770 };771 with_timestamps.sort_by(|(_, ref t1), (_, ref t2)| {772 let ordering = match (*t1, *t2) {773 // Both have metadata, do the obvious thing.774 (Some(t1), Some(t2)) => t1.cmp(&t2),775 // Things that error should appear later (when ascending).776 (Some(_), None) => Ordering::Less,777 // Things that error should appear later (when ascending).778 (None, Some(_)) => Ordering::Greater,779 // When both error, we can't distinguish, so treat as equal.780 (None, None) => Ordering::Equal,781 };782 if sort.reverse {783 ordering.reverse()784 } else {785 ordering786 }787 });788 Box::new(with_timestamps.into_iter().map(|(s, _)| s))789 }790791 /// Returns a stats object if the user requested that ripgrep keep track792 /// of various metrics during a search.793 ///794 /// When this returns `None`, then callers may assume that the user did795 /// not request statistics.796 pub(crate) fn stats(&self) -> Option<grep::printer::Stats> {797 self.stats.clone()798 }799800 /// Returns a color-enabled writer for stdout.801 ///802 /// The writer returned is also configured to do either line or block803 /// buffering, based on either explicit configuration from the user via CLI804 /// flags, or automatically based on whether stdout is connected to a tty.805 pub(crate) fn stdout(&self) -> grep::cli::StandardStream {806 let color = self.color.to_termcolor();807 match self.buffer {808 BufferMode::Auto => {809 if self.is_terminal_stdout {810 grep::cli::stdout_buffered_line(color)811 } else {812 grep::cli::stdout_buffered_block(color)813 }814 }815 BufferMode::Line => grep::cli::stdout_buffered_line(color),816 BufferMode::Block => grep::cli::stdout_buffered_block(color),817 }818 }819820 /// Returns the total number of threads ripgrep should use to execute a821 /// search.822 ///823 /// This number is the result of reasoning about both heuristics (like824 /// the available number of cores) and whether ripgrep's mode supports825 /// parallelism. It is intended that this number be used to directly826 /// determine how many threads to spawn.827 pub(crate) fn threads(&self) -> usize {828 self.threads829 }830831 /// Returns the file type matcher that was built.832 ///833 /// The matcher includes both the default rules and any rules added by the834 /// user for this specific invocation.835 pub(crate) fn types(&self) -> &ignore::types::Types {836 &self.types837 }838839 /// Create a new builder for recursive directory traversal.840 ///841 /// The builder returned can be used to start a single threaded or multi842 /// threaded directory traversal. For multi threaded traversal, the number843 /// of threads configured is equivalent to `HiArgs::threads`.844 ///845 /// If `HiArgs::threads` is equal to `1`, then callers should generally846 /// choose to explicitly use single threaded traversal since it won't have847 /// the unnecessary overhead of synchronization.848 pub(crate) fn walk_builder(&self) -> anyhow::Result<ignore::WalkBuilder> {849 let mut builder = ignore::WalkBuilder::new(&self.paths.paths[0]);850 for path in self.paths.paths.iter().skip(1) {851 builder.add(path);852 }853 if !self.no_ignore_files {854 for path in self.ignore_file.iter() {855 if let Some(err) = builder.add_ignore(path) {856 ignore_message!("{err}");857 }858 }859 }860 builder861 .max_depth(self.max_depth)862 .follow_links(self.follow)863 .max_filesize(self.max_filesize)864 .threads(self.threads)865 .same_file_system(self.one_file_system)866 .skip_stdout(matches!(self.mode, Mode::Search(_)))867 .overrides(self.globs.clone())868 .types(self.types.clone())869 .hidden(!self.hidden)870 .parents(!self.no_ignore_parent)871 .ignore(!self.no_ignore_dot)872 .git_global(!self.no_ignore_vcs && !self.no_ignore_global)873 .git_ignore(!self.no_ignore_vcs)874 .git_exclude(!self.no_ignore_vcs && !self.no_ignore_exclude)875 .require_git(!self.no_require_git)876 .ignore_case_insensitive(self.ignore_file_case_insensitive);877 if !self.no_ignore_dot {878 builder.add_custom_ignore_filename(".rgignore");879 }880 // When we want to sort paths lexicographically in ascending order,881 // then we can actually do this during directory traversal itself.882 // Otherwise, sorting is done by collecting all paths, sorting them and883 // then searching them.884 if let Some(ref sort) = self.sort {885 assert_eq!(1, self.threads, "sorting implies single threaded");886 if !sort.reverse && matches!(sort.kind, SortModeKind::Path) {887 builder.sort_by_file_name(|a, b| a.cmp(b));888 }889 }890 Ok(builder)891 }892}893894/// State that only needs to be computed once during argument parsing.895///896/// This state is meant to be somewhat generic and shared across multiple897/// low->high argument conversions. The state can even be mutated by various898/// conversions as a way to communicate changes to other conversions. For899/// example, reading patterns might consume from stdin. If we know stdin900/// has been consumed and no other file paths have been given, then we know901/// for sure that we should search the CWD. In this way, a state change902/// when reading the patterns can impact how the file paths are ultimately903/// generated.904#[derive(Debug)]905struct State {906 /// Whether it's believed that tty is connected to stdout. Note that on907 /// unix systems, this is always correct. On Windows, heuristics are used908 /// by Rust's standard library, particularly for cygwin/MSYS environments.909 is_terminal_stdout: bool,910 /// Whether stdin has already been consumed. This is useful to know and for911 /// providing good error messages when the user has tried to read from stdin912 /// in two different places. For example, `rg -f - -`.913 stdin_consumed: bool,914 /// The current working directory.915 cwd: PathBuf,916}917918impl State {919 /// Initialize state to some sensible defaults.920 ///921 /// Note that the state values may change throughout the lifetime of922 /// argument parsing.923 fn new() -> anyhow::Result<State> {924 use std::io::IsTerminal;925926 Ok(State {927 is_terminal_stdout: std::io::stdout().is_terminal(),928 stdin_consumed: false,929 cwd: current_dir()?,930 })931 }932}933934/// The disjunction of patterns to search for.935///936/// The number of patterns can be empty, e.g., via `-f /dev/null`.937#[derive(Debug)]938struct Patterns {939 /// The actual patterns to match.940 patterns: Vec<String>,941}942943impl Patterns {944 /// Pulls the patterns out of the low arguments.945 ///946 /// This includes collecting patterns from -e/--regexp and -f/--file.947 ///948 /// If the invocation implies that the first positional argument is a949 /// pattern (the common case), then the first positional argument is950 /// extracted as well.951 fn from_low_args(952 state: &mut State,953 low: &mut LowArgs,954 ) -> anyhow::Result<Patterns> {955 // The first positional is only a pattern when ripgrep is instructed to956 // search and neither -e/--regexp nor -f/--file is given. Basically,957 // the first positional is a pattern only when a pattern hasn't been958 // given in some other way.959960 // No search means no patterns. Even if -e/--regexp or -f/--file is961 // given, we know we won't use them so don't bother collecting them.962 if !matches!(low.mode, Mode::Search(_)) {963 return Ok(Patterns { patterns: vec![] });964 }965 // If we got nothing from -e/--regexp and -f/--file, then the first966 // positional is a pattern.967 if low.patterns.is_empty() {968 anyhow::ensure!(969 !low.positional.is_empty(),970 "ripgrep requires at least one pattern to execute a search"971 );972 let ospat = low.positional.remove(0);973 let Ok(pat) = ospat.into_string() else {974 anyhow::bail!("pattern given is not valid UTF-8")975 };976 return Ok(Patterns { patterns: vec![pat] });977 }978 // Otherwise, we need to slurp up our patterns from -e/--regexp and979 // -f/--file. We de-duplicate as we go. If we don't de-duplicate,980 // then it can actually lead to major slow downs for sloppy inputs.981 // This might be surprising, and the regex engine will eventually982 // de-duplicate duplicative branches in a single regex (maybe), but983 // not until after it has gone through parsing and some other layers.984 // If there are a lot of duplicates, then that can lead to a sizeable985 // extra cost. It is lamentable that we pay the extra cost here to986 // de-duplicate for a likely uncommon case, but I've seen this have a987 // big impact on real world data.988 let mut seen = HashSet::new();989 let mut patterns = Vec::with_capacity(low.patterns.len());990 let mut add = |pat: String| {991 if !seen.contains(&pat) {992 seen.insert(pat.clone());993 patterns.push(pat);994 }995 };996 for source in low.patterns.drain(..) {997 match source {998 PatternSource::Regexp(pat) => add(pat),999 PatternSource::File(path) => {1000 if path == Path::new("-") {1001 anyhow::ensure!(1002 !state.stdin_consumed,1003 "error reading -f/--file from stdin: stdin \1004 has already been consumed"1005 );1006 for pat in grep::cli::patterns_from_stdin()? {1007 add(pat);1008 }1009 state.stdin_consumed = true;1010 } else {1011 for pat in grep::cli::patterns_from_path(&path)? {1012 add(pat);1013 }1014 }1015 }1016 }1017 }1018 Ok(Patterns { patterns })1019 }1020}10211022/// The collection of paths we want to search for.1023///1024/// This guarantees that there is always at least one path.1025#[derive(Debug)]1026struct Paths {1027 /// The actual paths.1028 paths: Vec<PathBuf>,1029 /// This is true when ripgrep had to guess to search the current working1030 /// directory. e.g., When the user just runs `rg foo`. It is odd to need1031 /// this, but it subtly changes how the paths are printed. When no explicit1032 /// path is given, then ripgrep doesn't prefix each path with `./`. But1033 /// otherwise it does! This curious behavior matches what GNU grep does.1034 has_implicit_path: bool,1035 /// Set to true if it is known that only a single file descriptor will1036 /// be searched.1037 is_one_file: bool,1038}10391040impl Paths {1041 /// Drain the search paths out of the given low arguments.1042 fn from_low_args(1043 state: &mut State,1044 _: &Patterns,1045 low: &mut LowArgs,1046 ) -> anyhow::Result<Paths> {1047 // We require a `&Patterns` even though we don't use it to ensure that1048 // patterns have already been read from LowArgs. This let's us safely1049 // assume that all remaining positional arguments are intended to be1050 // file paths.10511052 let mut paths = Vec::with_capacity(low.positional.len());1053 for osarg in low.positional.drain(..) {1054 let path = PathBuf::from(osarg);1055 if state.stdin_consumed && path == Path::new("-") {1056 anyhow::bail!(1057 "error: attempted to read patterns from stdin \1058 while also searching stdin",1059 );1060 }1061 paths.push(path);1062 }1063 if !paths.is_empty() {1064 let is_one_file = paths.len() == 11065 && (paths[0] == Path::new("-") || paths[0].is_file());1066 return Ok(Paths { paths, has_implicit_path: false, is_one_file });1067 }1068 // N.B. is_readable_stdin is a heuristic! Part of the issue is that a1069 // lot of "exec process" APIs will open a stdin pipe even though stdin1070 // isn't really being used. ripgrep then thinks it should search stdin1071 // and one gets the appearance of it hanging. It's a terrible failure1072 // mode, but there really is no good way to mitigate it. It's just a1073 // consequence of letting the user type 'rg foo' and "guessing" that1074 // they meant to search the CWD.1075 let use_cwd = !grep::cli::is_readable_stdin()1076 || state.stdin_consumed1077 || !matches!(low.mode, Mode::Search(_));1078 let (path, is_one_file) = if use_cwd {1079 (PathBuf::from("./"), false)1080 } else {1081 (PathBuf::from("-"), true)1082 };1083 Ok(Paths { paths: vec![path], has_implicit_path: true, is_one_file })1084 }10851086 /// Returns true if ripgrep will only search stdin and nothing else.1087 fn is_only_stdin(&self) -> bool {1088 self.paths.len() == 1 && self.paths[0] == Path::new("-")1089 }1090}10911092/// The "binary detection" configuration that ripgrep should use.1093///1094/// ripgrep actually uses two different binary detection heuristics depending1095/// on whether a file is explicitly being searched (e.g., via a CLI argument)1096/// or implicitly searched (e.g., via directory traversal). In general, the1097/// former can never use a heuristic that lets it "quit" seaching before1098/// either getting EOF or finding a match. (Because doing otherwise would be1099/// considered a filter, and ripgrep follows the rule that an explicitly given1100/// file is always searched.)1101#[derive(Debug)]1102struct BinaryDetection {1103 explicit: grep::searcher::BinaryDetection,1104 implicit: grep::searcher::BinaryDetection,1105}11061107impl BinaryDetection {1108 /// Determines the correct binary detection mode from low-level arguments.1109 fn from_low_args(_: &State, low: &LowArgs) -> BinaryDetection {1110 let none = matches!(low.binary, BinaryMode::AsText) || low.null_data;1111 let convert = matches!(low.binary, BinaryMode::SearchAndSuppress);1112 let explicit = if none {1113 grep::searcher::BinaryDetection::none()1114 } else {1115 grep::searcher::BinaryDetection::convert(b'\x00')1116 };1117 let implicit = if none {1118 grep::searcher::BinaryDetection::none()1119 } else if convert {1120 grep::searcher::BinaryDetection::convert(b'\x00')1121 } else {1122 grep::searcher::BinaryDetection::quit(b'\x00')1123 };1124 BinaryDetection { explicit, implicit }1125 }1126}11271128/// Builds the file type matcher from low level arguments.1129fn types(low: &LowArgs) -> anyhow::Result<ignore::types::Types> {1130 let mut builder = ignore::types::TypesBuilder::new();1131 builder.add_defaults();1132 for tychange in low.type_changes.iter() {1133 match tychange {1134 TypeChange::Clear { ref name } => {1135 builder.clear(name);1136 }1137 TypeChange::Add { ref def } => {1138 builder.add_def(def)?;1139 }1140 TypeChange::Select { ref name } => {1141 builder.select(name);1142 }1143 TypeChange::Negate { ref name } => {1144 builder.negate(name);1145 }1146 }1147 }1148 Ok(builder.build()?)1149}11501151/// Builds the glob "override" matcher from the CLI `-g/--glob` and `--iglob`1152/// flags.1153fn globs(1154 state: &State,1155 low: &LowArgs,1156) -> anyhow::Result<ignore::overrides::Override> {1157 if low.globs.is_empty() && low.iglobs.is_empty() {1158 return Ok(ignore::overrides::Override::empty());1159 }1160 let mut builder = ignore::overrides::OverrideBuilder::new(&state.cwd);1161 // Make all globs case insensitive with --glob-case-insensitive.1162 if low.glob_case_insensitive {1163 builder.case_insensitive(true).unwrap();1164 }1165 for glob in low.globs.iter() {1166 builder.add(glob)?;1167 }1168 // This only enables case insensitivity for subsequent globs.1169 builder.case_insensitive(true).unwrap();1170 for glob in low.iglobs.iter() {1171 builder.add(&glob)?;1172 }1173 Ok(builder.build()?)1174}11751176/// Builds a glob matcher for all of the preprocessor globs (via `--pre-glob`).1177fn preprocessor_globs(1178 state: &State,1179 low: &LowArgs,1180) -> anyhow::Result<ignore::overrides::Override> {1181 if low.pre_glob.is_empty() {1182 return Ok(ignore::overrides::Override::empty());1183 }1184 let mut builder = ignore::overrides::OverrideBuilder::new(&state.cwd);1185 for glob in low.pre_glob.iter() {1186 builder.add(glob)?;1187 }1188 Ok(builder.build()?)1189}11901191/// Determines whether stats should be tracked for this search. If so, a stats1192/// object is returned.1193fn stats(low: &LowArgs) -> Option<grep::printer::Stats> {1194 if !matches!(low.mode, Mode::Search(_)) {1195 return None;1196 }1197 if low.stats || matches!(low.mode, Mode::Search(SearchMode::JSON)) {1198 return Some(grep::printer::Stats::new());1199 }1200 None1201}12021203/// Pulls out any color specs provided by the user and assembles them into one1204/// single configuration.1205fn take_color_specs(_: &mut State, low: &mut LowArgs) -> ColorSpecs {1206 let mut specs = grep::printer::default_color_specs();1207 for spec in low.colors.drain(..) {1208 specs.push(spec);1209 }1210 ColorSpecs::new(&specs)1211}12121213/// Pulls out the necessary info from the low arguments to build a full1214/// hyperlink configuration.1215fn take_hyperlink_config(1216 _: &mut State,1217 low: &mut LowArgs,1218) -> anyhow::Result<grep::printer::HyperlinkConfig> {1219 let mut env = grep::printer::HyperlinkEnvironment::new();1220 if let Some(hostname) = hostname(low.hostname_bin.as_deref()) {1221 log::debug!("found hostname for hyperlink configuration: {hostname}");1222 env.host(Some(hostname));1223 }1224 if let Some(wsl_prefix) = wsl_prefix() {1225 log::debug!(1226 "found wsl_prefix for hyperlink configuration: {wsl_prefix}"1227 );1228 env.wsl_prefix(Some(wsl_prefix));1229 }1230 let fmt = std::mem::take(&mut low.hyperlink_format);1231 log::debug!("hyperlink format: {:?}", fmt.to_string());1232 Ok(grep::printer::HyperlinkConfig::new(env, fmt))1233}12341235/// Attempts to discover the current working directory.1236///1237/// This mostly just defers to the standard library, however, such things will1238/// fail if ripgrep is in a directory that no longer exists. We attempt some1239/// fallback mechanisms, such as querying the PWD environment variable, but1240/// otherwise return an error.1241fn current_dir() -> anyhow::Result<PathBuf> {1242 let err = match std::env::current_dir() {1243 Err(err) => err,1244 Ok(cwd) => return Ok(cwd),1245 };1246 if let Some(cwd) = std::env::var_os("PWD") {1247 if !cwd.is_empty() {1248 return Ok(PathBuf::from(cwd));1249 }1250 }1251 anyhow::bail!(1252 "failed to get current working directory: {err}\n\1253 did your CWD get deleted?",1254 )1255}12561257/// Retrieves the hostname that should be used wherever a hostname is required.1258///1259/// Currently, this is only used in the hyperlink format.1260///1261/// This works by first running the given binary program (if present and with1262/// no arguments) to get the hostname after trimming leading and trailing1263/// whitespace. If that fails for any reason, then it falls back to getting1264/// the hostname via platform specific means (e.g., `gethostname` on Unix).1265///1266/// The purpose of `bin` is to make it possible for end users to override how1267/// ripgrep determines the hostname.1268fn hostname(bin: Option<&Path>) -> Option<String> {1269 let Some(bin) = bin else { return platform_hostname() };1270 let bin = match grep::cli::resolve_binary(bin) {1271 Ok(bin) => bin,1272 Err(err) => {1273 log::debug!(1274 "failed to run command '{bin:?}' to get hostname \1275 (falling back to platform hostname): {err}",1276 );1277 return platform_hostname();1278 }1279 };1280 let mut cmd = std::process::Command::new(&bin);1281 cmd.stdin(std::process::Stdio::null());1282 let rdr = match grep::cli::CommandReader::new(&mut cmd) {1283 Ok(rdr) => rdr,1284 Err(err) => {1285 log::debug!(1286 "failed to spawn command '{bin:?}' to get \1287 hostname (falling back to platform hostname): {err}",1288 );1289 return platform_hostname();1290 }1291 };1292 let out = match std::io::read_to_string(rdr) {1293 Ok(out) => out,1294 Err(err) => {1295 log::debug!(1296 "failed to read output from command '{bin:?}' to get \1297 hostname (falling back to platform hostname): {err}",1298 );1299 return platform_hostname();1300 }1301 };1302 let hostname = out.trim();1303 if hostname.is_empty() {1304 log::debug!(1305 "output from command '{bin:?}' is empty after trimming \1306 leading and trailing whitespace (falling back to \1307 platform hostname)",1308 );1309 return platform_hostname();1310 }1311 Some(hostname.to_string())1312}13131314/// Attempts to get the hostname by using platform specific routines.1315///1316/// For example, this will do `gethostname` on Unix and `GetComputerNameExW` on1317/// Windows.1318fn platform_hostname() -> Option<String> {1319 let hostname_os = match grep::cli::hostname() {1320 Ok(x) => x,1321 Err(err) => {1322 log::debug!("could not get hostname: {}", err);1323 return None;1324 }1325 };1326 let Some(hostname) = hostname_os.to_str() else {1327 log::debug!(1328 "got hostname {:?}, but it's not valid UTF-8",1329 hostname_os1330 );1331 return None;1332 };1333 Some(hostname.to_string())1334}13351336/// Returns the value for the `{wslprefix}` variable in a hyperlink format.1337///1338/// A WSL prefix is a share/network like thing that is meant to permit Windows1339/// applications to open files stored within a WSL drive.1340///1341/// If a WSL distro name is unavailable, not valid UTF-8 or this isn't running1342/// in a Unix environment, then this returns None.1343///1344/// See: <https://learn.microsoft.com/en-us/windows/wsl/filesystems>1345fn wsl_prefix() -> Option<String> {1346 if !cfg!(unix) {1347 return None;1348 }1349 let distro_os = std::env::var_os("WSL_DISTRO_NAME")?;1350 let Some(distro) = distro_os.to_str() else {1351 log::debug!(1352 "found WSL_DISTRO_NAME={:?}, but value is not UTF-8",1353 distro_os1354 );1355 return None;1356 };1357 Some(format!("wsl$/{distro}"))1358}13591360/// Possibly suggest another regex engine based on the error message given.1361///1362/// This inspects an error resulting from building a Rust regex matcher, and1363/// if it's believed to correspond to a syntax error that another engine could1364/// handle, then add a message to suggest the use of the engine flag.1365fn suggest_other_engine(msg: String) -> String {1366 if let Some(pcre_msg) = suggest_pcre2(&msg) {1367 return pcre_msg;1368 }1369 msg1370}13711372/// Possibly suggest PCRE2 based on the error message given.1373///1374/// Inspect an error resulting from building a Rust regex matcher, and if it's1375/// believed to correspond to a syntax error that PCRE2 could handle, then1376/// add a message to suggest the use of -P/--pcre2.1377fn suggest_pcre2(msg: &str) -> Option<String> {1378 if !cfg!(feature = "pcre2") {1379 return None;1380 }1381 if !msg.contains("backreferences") && !msg.contains("look-around") {1382 None1383 } else {1384 Some(format!(1385 "{msg}13861387Consider enabling PCRE2 with the --pcre2 flag, which can handle backreferences1388and look-around.",1389 ))1390 }1391}13921393/// Possibly suggest multiline mode based on the error message given.1394///1395/// Does a bit of a hacky inspection of the given error message, and if it1396/// looks like the user tried to type a literal line terminator then it will1397/// return a new error message suggesting the use of -U/--multiline.1398fn suggest_multiline(msg: String) -> String {1399 if msg.contains("the literal") && msg.contains("not allowed") {1400 format!(1401 "{msg}14021403Consider enabling multiline mode with the --multiline flag (or -U for short).1404When multiline mode is enabled, new line characters can be matched.",1405 )1406 } else {1407 msg1408 }1409}
added:crates/core/flags/lowargs.rs+758 added
1/*!2Provides the definition of low level arguments from CLI flags.3*/45use std::{6 ffi::{OsStr, OsString},7 path::PathBuf,8};910use {11 bstr::{BString, ByteVec},12 grep::printer::{HyperlinkFormat, UserColorSpec},13};1415/// A collection of "low level" arguments.16///17/// The "low level" here is meant to constrain this type to be as close to the18/// actual CLI flags and arguments as possible. Namely, other than some19/// convenience types to help validate flag values and deal with overrides20/// between flags, these low level arguments do not contain any higher level21/// abstractions.22///23/// Another self-imposed constraint is that populating low level arguments24/// should not require anything other than validating what the user has25/// provided. For example, low level arguments should not contain a26/// `HyperlinkConfig`, since in order to get a full configuration, one needs to27/// discover the hostname of the current system (which might require running a28/// binary or a syscall).29///30/// Low level arguments are populated by the parser directly via the `update`31/// method on the corresponding implementation of the `Flag` trait.32#[derive(Debug, Default)]33pub(crate) struct LowArgs {34 // Essential arguments.35 pub(crate) special: Option<SpecialMode>,36 pub(crate) mode: Mode,37 pub(crate) positional: Vec<OsString>,38 pub(crate) patterns: Vec<PatternSource>,39 // Everything else, sorted lexicographically.40 pub(crate) binary: BinaryMode,41 pub(crate) boundary: Option<BoundaryMode>,42 pub(crate) buffer: BufferMode,43 pub(crate) byte_offset: bool,44 pub(crate) case: CaseMode,45 pub(crate) color: ColorChoice,46 pub(crate) colors: Vec<UserColorSpec>,47 pub(crate) column: Option<bool>,48 pub(crate) context: ContextMode,49 pub(crate) context_separator: ContextSeparator,50 pub(crate) crlf: bool,51 pub(crate) dfa_size_limit: Option<usize>,52 pub(crate) encoding: EncodingMode,53 pub(crate) engine: EngineChoice,54 pub(crate) field_context_separator: FieldContextSeparator,55 pub(crate) field_match_separator: FieldMatchSeparator,56 pub(crate) fixed_strings: bool,57 pub(crate) follow: bool,58 pub(crate) glob_case_insensitive: bool,59 pub(crate) globs: Vec<String>,60 pub(crate) heading: Option<bool>,61 pub(crate) hidden: bool,62 pub(crate) hostname_bin: Option<PathBuf>,63 pub(crate) hyperlink_format: HyperlinkFormat,64 pub(crate) iglobs: Vec<String>,65 pub(crate) ignore_file: Vec<PathBuf>,66 pub(crate) ignore_file_case_insensitive: bool,67 pub(crate) include_zero: bool,68 pub(crate) invert_match: bool,69 pub(crate) line_number: Option<bool>,70 pub(crate) logging: Option<LoggingMode>,71 pub(crate) max_columns: Option<u64>,72 pub(crate) max_columns_preview: bool,73 pub(crate) max_count: Option<u64>,74 pub(crate) max_depth: Option<usize>,75 pub(crate) max_filesize: Option<u64>,76 pub(crate) mmap: MmapMode,77 pub(crate) multiline: bool,78 pub(crate) multiline_dotall: bool,79 pub(crate) no_config: bool,80 pub(crate) no_ignore_dot: bool,81 pub(crate) no_ignore_exclude: bool,82 pub(crate) no_ignore_files: bool,83 pub(crate) no_ignore_global: bool,84 pub(crate) no_ignore_messages: bool,85 pub(crate) no_ignore_parent: bool,86 pub(crate) no_ignore_vcs: bool,87 pub(crate) no_messages: bool,88 pub(crate) no_require_git: bool,89 pub(crate) no_unicode: bool,90 pub(crate) null: bool,91 pub(crate) null_data: bool,92 pub(crate) one_file_system: bool,93 pub(crate) only_matching: bool,94 pub(crate) path_separator: Option<u8>,95 pub(crate) pre: Option<PathBuf>,96 pub(crate) pre_glob: Vec<String>,97 pub(crate) quiet: bool,98 pub(crate) regex_size_limit: Option<usize>,99 pub(crate) replace: Option<BString>,100 pub(crate) search_zip: bool,101 pub(crate) sort: Option<SortMode>,102 pub(crate) stats: bool,103 pub(crate) stop_on_nonmatch: bool,104 pub(crate) threads: Option<usize>,105 pub(crate) trim: bool,106 pub(crate) type_changes: Vec<TypeChange>,107 pub(crate) unrestricted: usize,108 pub(crate) vimgrep: bool,109 pub(crate) with_filename: Option<bool>,110}111112/// A "special" mode that supercedes everything else.113///114/// When one of these modes is present, it overrides everything else and causes115/// ripgrep to short-circuit. In particular, we avoid converting low-level116/// argument types into higher level arguments types that can fail for various117/// reasons related to the environment. (Parsing the low-level arguments can118/// fail too, but usually not in a way that can't be worked around by removing119/// the corresponding arguments from the CLI command.) This is overall a hedge120/// to ensure that version and help information are basically always available.121#[derive(Clone, Copy, Debug, Eq, PartialEq)]122pub(crate) enum SpecialMode {123 /// Show a condensed version of "help" output. Generally speaking, this124 /// shows each flag and an extremely terse description of that flag on125 /// a single line. This corresponds to the `-h` flag.126 HelpShort,127 /// Shows a very verbose version of the "help" output. The docs for some128 /// flags will be paragraphs long. This corresponds to the `--help` flag.129 HelpLong,130 /// Show condensed version information. e.g., `ripgrep x.y.z`.131 VersionShort,132 /// Show verbose version information. Includes "short" information as well133 /// as features included in the build.134 VersionLong,135 /// Show PCRE2's version information, or an error if this version of136 /// ripgrep wasn't compiled with PCRE2 support.137 VersionPCRE2,138}139140/// The overall mode that ripgrep should operate in.141///142/// If ripgrep were designed without the legacy of grep, these would probably143/// be sub-commands? Perhaps not, since they aren't as frequently used.144///145/// The point of putting these in one enum is that they are all mutually146/// exclusive and override one another.147///148/// Note that -h/--help and -V/--version are not included in this because149/// they always overrides everything else, regardless of where it appears150/// in the command line. They are treated as "special" modes that short-circuit151/// ripgrep's usual flow.152#[derive(Clone, Copy, Debug, Eq, PartialEq)]153pub(crate) enum Mode {154 /// ripgrep will execute a search of some kind.155 Search(SearchMode),156 /// Show the files that *would* be searched, but don't actually search157 /// them.158 Files,159 /// List all file type definitions configured, including the default file160 /// types and any additional file types added to the command line.161 Types,162 /// Generate various things like the man page and completion files.163 Generate(GenerateMode),164}165166impl Default for Mode {167 fn default() -> Mode {168 Mode::Search(SearchMode::Standard)169 }170}171172impl Mode {173 /// Update this mode to the new mode while implementing various override174 /// semantics. For example, a search mode cannot override a non-search175 /// mode.176 pub(crate) fn update(&mut self, new: Mode) {177 match *self {178 // If we're in a search mode, then anything can override it.179 Mode::Search(_) => *self = new,180 _ => {181 // Once we're in a non-search mode, other non-search modes182 // can override it. But search modes cannot. So for example,183 // `--files -l` will still be Mode::Files.184 if !matches!(*self, Mode::Search(_)) {185 *self = new;186 }187 }188 }189 }190}191192/// The kind of search that ripgrep is going to perform.193#[derive(Clone, Copy, Debug, Eq, PartialEq)]194pub(crate) enum SearchMode {195 /// The default standard mode of operation. ripgrep looks for matches and196 /// prints them when found.197 ///198 /// There is no specific flag for this mode since it's the default. But199 /// some of the modes below, like JSON, have negation flags like --no-json200 /// that let you revert back to this default mode.201 Standard,202 /// Show files containing at least one match.203 FilesWithMatches,204 /// Show files that don't contain any matches.205 FilesWithoutMatch,206 /// Show files containing at least one match and the number of matching207 /// lines.208 Count,209 /// Show files containing at least one match and the total number of210 /// matches.211 CountMatches,212 /// Print matches in a JSON lines format.213 JSON,214}215216/// The thing to generate via the --generate flag.217#[derive(Clone, Copy, Debug, Eq, PartialEq)]218pub(crate) enum GenerateMode {219 /// Generate the raw roff used for the man page.220 Man,221 /// Completions for bash.222 CompleteBash,223 /// Completions for zsh.224 CompleteZsh,225 /// Completions for fish.226 CompleteFish,227 /// Completions for PowerShell.228 CompletePowerShell,229}230231/// Indicates how ripgrep should treat binary data.232#[derive(Debug, Eq, PartialEq)]233pub(crate) enum BinaryMode {234 /// Automatically determine the binary mode to use. Essentially, when235 /// a file is searched explicitly, then it will be searched using the236 /// `SearchAndSuppress` strategy. Otherwise, it will be searched in a way237 /// that attempts to skip binary files as much as possible. That is, once238 /// a file is classified as binary, searching will immediately stop.239 Auto,240 /// Search files even when they have binary data, but if a match is found,241 /// suppress it and emit a warning.242 ///243 /// In this mode, `NUL` bytes are replaced with line terminators. This is244 /// a heuristic meant to reduce heap memory usage, since true binary data245 /// isn't line oriented. If one attempts to treat such data as line246 /// oriented, then one may wind up with impractically large lines. For247 /// example, many binary files contain very long runs of NUL bytes.248 SearchAndSuppress,249 /// Treat all files as if they were plain text. There's no skipping and no250 /// replacement of `NUL` bytes with line terminators.251 AsText,252}253254impl Default for BinaryMode {255 fn default() -> BinaryMode {256 BinaryMode::Auto257 }258}259260/// Indicates what kind of boundary mode to use (line or word).261#[derive(Debug, Eq, PartialEq)]262pub(crate) enum BoundaryMode {263 /// Only allow matches when surrounded by line bounaries.264 Line,265 /// Only allow matches when surrounded by word bounaries.266 Word,267}268269/// Indicates the buffer mode that ripgrep should use when printing output.270///271/// The default is `Auto`.272#[derive(Debug, Eq, PartialEq)]273pub(crate) enum BufferMode {274 /// Select the buffer mode, 'line' or 'block', automatically based on275 /// whether stdout is connected to a tty.276 Auto,277 /// Flush the output buffer whenever a line terminator is seen.278 ///279 /// This is useful when wants to see search results more immediately,280 /// for example, with `tail -f`.281 Line,282 /// Flush the output buffer whenever it reaches some fixed size. The size283 /// is usually big enough to hold many lines.284 ///285 /// This is useful for maximum performance, particularly when printing286 /// lots of results.287 Block,288}289290impl Default for BufferMode {291 fn default() -> BufferMode {292 BufferMode::Auto293 }294}295296/// Indicates the case mode for how to interpret all patterns given to ripgrep.297///298/// The default is `Sensitive`.299#[derive(Debug, Eq, PartialEq)]300pub(crate) enum CaseMode {301 /// Patterns are matched case sensitively. i.e., `a` does not match `A`.302 Sensitive,303 /// Patterns are matched case insensitively. i.e., `a` does match `A`.304 Insensitive,305 /// Patterns are automatically matched case insensitively only when they306 /// consist of all lowercase literal characters. For example, the pattern307 /// `a` will match `A` but `A` will not match `a`.308 Smart,309}310311impl Default for CaseMode {312 fn default() -> CaseMode {313 CaseMode::Sensitive314 }315}316317/// Indicates whether ripgrep should include color/hyperlinks in its output.318///319/// The default is `Auto`.320#[derive(Debug, Eq, PartialEq)]321pub(crate) enum ColorChoice {322 /// Color and hyperlinks will never be used.323 Never,324 /// Color and hyperlinks will be used only when stdout is connected to a325 /// tty.326 Auto,327 /// Color will always be used.328 Always,329 /// Color will always be used and only ANSI escapes will be used.330 ///331 /// This only makes sense in the context of legacy Windows console APIs.332 /// At time of writing, ripgrep will try to use the legacy console APIs333 /// if ANSI coloring isn't believed to be possible. This option will force334 /// ripgrep to use ANSI coloring.335 Ansi,336}337338impl Default for ColorChoice {339 fn default() -> ColorChoice {340 ColorChoice::Auto341 }342}343344impl ColorChoice {345 /// Convert this color choice to the corresponding termcolor type.346 pub(crate) fn to_termcolor(&self) -> termcolor::ColorChoice {347 match *self {348 ColorChoice::Never => termcolor::ColorChoice::Never,349 ColorChoice::Auto => termcolor::ColorChoice::Auto,350 ColorChoice::Always => termcolor::ColorChoice::Always,351 ColorChoice::Ansi => termcolor::ColorChoice::AlwaysAnsi,352 }353 }354}355356/// Indicates the line context options ripgrep should use for output.357///358/// The default is no context at all.359#[derive(Debug, Eq, PartialEq)]360pub(crate) enum ContextMode {361 /// All lines will be printed. That is, the context is unbounded.362 Passthru,363 /// Only show a certain number of lines before and after each match.364 Limited(ContextModeLimited),365}366367impl Default for ContextMode {368 fn default() -> ContextMode {369 ContextMode::Limited(ContextModeLimited::default())370 }371}372373impl ContextMode {374 /// Set the "before" context.375 ///376 /// If this was set to "passthru" context, then it is overridden in favor377 /// of limited context with the given value for "before" and `0` for378 /// "after."379 pub(crate) fn set_before(&mut self, lines: usize) {380 match *self {381 ContextMode::Passthru => {382 *self = ContextMode::Limited(ContextModeLimited {383 before: Some(lines),384 after: None,385 both: None,386 })387 }388 ContextMode::Limited(ContextModeLimited {389 ref mut before,390 ..391 }) => *before = Some(lines),392 }393 }394395 /// Set the "after" context.396 ///397 /// If this was set to "passthru" context, then it is overridden in favor398 /// of limited context with the given value for "after" and `0` for399 /// "before."400 pub(crate) fn set_after(&mut self, lines: usize) {401 match *self {402 ContextMode::Passthru => {403 *self = ContextMode::Limited(ContextModeLimited {404 before: None,405 after: Some(lines),406 both: None,407 })408 }409 ContextMode::Limited(ContextModeLimited {410 ref mut after, ..411 }) => *after = Some(lines),412 }413 }414415 /// Set the "both" context.416 ///417 /// If this was set to "passthru" context, then it is overridden in favor418 /// of limited context with the given value for "both" and `None` for419 /// "before" and "after".420 pub(crate) fn set_both(&mut self, lines: usize) {421 match *self {422 ContextMode::Passthru => {423 *self = ContextMode::Limited(ContextModeLimited {424 before: None,425 after: None,426 both: Some(lines),427 })428 }429 ContextMode::Limited(ContextModeLimited {430 ref mut both, ..431 }) => *both = Some(lines),432 }433 }434435 /// A convenience function for use in tests that returns the limited436 /// context. If this mode isn't limited, then it panics.437 #[cfg(test)]438 pub(crate) fn get_limited(&self) -> (usize, usize) {439 match *self {440 ContextMode::Passthru => unreachable!("context mode is passthru"),441 ContextMode::Limited(ref limited) => limited.get(),442 }443 }444}445446/// A context mode for a finite number of lines.447///448/// Namely, this indicates that a specific number of lines (possibly zero)449/// should be shown before and/or after each matching line.450///451/// Note that there is a subtle difference between `Some(0)` and `None`. In the452/// former case, it happens when `0` is given explicitly, where as `None` is453/// the default value and occurs when no value is specified.454///455/// `both` is only set by the -C/--context flag. The reason why we don't just456/// set before = after = --context is because the before and after context457/// settings always take precedent over the -C/--context setting, regardless of458/// order. Thus, we need to keep track of them separately.459#[derive(Debug, Default, Eq, PartialEq)]460pub(crate) struct ContextModeLimited {461 before: Option<usize>,462 after: Option<usize>,463 both: Option<usize>,464}465466impl ContextModeLimited {467 /// Returns the specific number of contextual lines that should be shown468 /// around each match. This takes proper precedent into account, i.e.,469 /// that `before` and `after` both partially override `both` in all cases.470 ///471 /// By default, this returns `(0, 0)`.472 pub(crate) fn get(&self) -> (usize, usize) {473 let (mut before, mut after) =474 self.both.map(|lines| (lines, lines)).unwrap_or((0, 0));475 // --before and --after always override --context, regardless476 // of where they appear relative to each other.477 if let Some(lines) = self.before {478 before = lines;479 }480 if let Some(lines) = self.after {481 after = lines;482 }483 (before, after)484 }485}486487/// Represents the separator to use between non-contiguous sections of488/// contextual lines.489///490/// The default is `--`.491#[derive(Clone, Debug, Eq, PartialEq)]492pub(crate) struct ContextSeparator(Option<BString>);493494impl Default for ContextSeparator {495 fn default() -> ContextSeparator {496 ContextSeparator(Some(BString::from("--")))497 }498}499500impl ContextSeparator {501 /// Create a new context separator from the user provided argument. This502 /// handles unescaping.503 pub(crate) fn new(os: &OsStr) -> anyhow::Result<ContextSeparator> {504 let Some(string) = os.to_str() else {505 anyhow::bail!(506 "separator must be valid UTF-8 (use escape sequences \507 to provide a separator that is not valid UTF-8)"508 )509 };510 Ok(ContextSeparator(Some(Vec::unescape_bytes(string).into())))511 }512513 /// Creates a new separator that intructs the printer to disable contextual514 /// separators entirely.515 pub(crate) fn disabled() -> ContextSeparator {516 ContextSeparator(None)517 }518519 /// Return the raw bytes of this separator.520 ///521 /// If context separators were disabled, then this returns `None`.522 ///523 /// Note that this may return a `Some` variant with zero bytes.524 pub(crate) fn into_bytes(self) -> Option<Vec<u8>> {525 self.0.map(|sep| sep.into())526 }527}528529/// The encoding mode the searcher will use.530///531/// The default is `Auto`.532#[derive(Debug, Eq, PartialEq)]533pub(crate) enum EncodingMode {534 /// Use only BOM sniffing to auto-detect an encoding.535 Auto,536 /// Use an explicit encoding forcefully, but let BOM sniffing override it.537 Some(grep::searcher::Encoding),538 /// Use no explicit encoding and disable all BOM sniffing. This will539 /// always result in searching the raw bytes, regardless of their540 /// true encoding.541 Disabled,542}543544impl Default for EncodingMode {545 fn default() -> EncodingMode {546 EncodingMode::Auto547 }548}549550/// The regex engine to use.551///552/// The default is `Default`.553#[derive(Debug, Eq, PartialEq)]554pub(crate) enum EngineChoice {555 /// Uses the default regex engine: Rust's `regex` crate.556 ///557 /// (Well, technically it uses `regex-automata`, but `regex-automata` is558 /// the implementation of the `regex` crate.)559 Default,560 /// Dynamically select the right engine to use.561 ///562 /// This works by trying to use the default engine, and if the pattern does563 /// not compile, it switches over to the PCRE2 engine if it's available.564 Auto,565 /// Uses the PCRE2 regex engine if it's available.566 PCRE2,567}568569impl Default for EngineChoice {570 fn default() -> EngineChoice {571 EngineChoice::Default572 }573}574575/// The field context separator to use to between metadata for each contextual576/// line.577///578/// The default is `-`.579#[derive(Clone, Debug, Eq, PartialEq)]580pub(crate) struct FieldContextSeparator(BString);581582impl Default for FieldContextSeparator {583 fn default() -> FieldContextSeparator {584 FieldContextSeparator(BString::from("-"))585 }586}587588impl FieldContextSeparator {589 /// Create a new separator from the given argument value provided by the590 /// user. Unescaping it automatically handled.591 pub(crate) fn new(os: &OsStr) -> anyhow::Result<FieldContextSeparator> {592 let Some(string) = os.to_str() else {593 anyhow::bail!(594 "separator must be valid UTF-8 (use escape sequences \595 to provide a separator that is not valid UTF-8)"596 )597 };598 Ok(FieldContextSeparator(Vec::unescape_bytes(string).into()))599 }600601 /// Return the raw bytes of this separator.602 ///603 /// Note that this may return an empty `Vec`.604 pub(crate) fn into_bytes(self) -> Vec<u8> {605 self.0.into()606 }607}608609/// The field match separator to use to between metadata for each matching610/// line.611///612/// The default is `:`.613#[derive(Clone, Debug, Eq, PartialEq)]614pub(crate) struct FieldMatchSeparator(BString);615616impl Default for FieldMatchSeparator {617 fn default() -> FieldMatchSeparator {618 FieldMatchSeparator(BString::from(":"))619 }620}621622impl FieldMatchSeparator {623 /// Create a new separator from the given argument value provided by the624 /// user. Unescaping it automatically handled.625 pub(crate) fn new(os: &OsStr) -> anyhow::Result<FieldMatchSeparator> {626 let Some(string) = os.to_str() else {627 anyhow::bail!(628 "separator must be valid UTF-8 (use escape sequences \629 to provide a separator that is not valid UTF-8)"630 )631 };632 Ok(FieldMatchSeparator(Vec::unescape_bytes(string).into()))633 }634635 /// Return the raw bytes of this separator.636 ///637 /// Note that this may return an empty `Vec`.638 pub(crate) fn into_bytes(self) -> Vec<u8> {639 self.0.into()640 }641}642643/// The type of logging to do. `Debug` emits some details while `Trace` emits644/// much more.645#[derive(Debug, Eq, PartialEq)]646pub(crate) enum LoggingMode {647 Debug,648 Trace,649}650651/// Indicates when to use memory maps.652///653/// The default is `Auto`.654#[derive(Debug, Eq, PartialEq)]655pub(crate) enum MmapMode {656 /// This instructs ripgrep to use heuristics for selecting when to and not657 /// to use memory maps for searching.658 Auto,659 /// This instructs ripgrep to always try memory maps when possible. (Memory660 /// maps are not possible to use in all circumstances, for example, for661 /// virtual files.)662 AlwaysTryMmap,663 /// Never use memory maps under any circumstances. This includes even664 /// when multi-line search is enabled where ripgrep will read the entire665 /// contents of a file on to the heap before searching it.666 Never,667}668669impl Default for MmapMode {670 fn default() -> MmapMode {671 MmapMode::Auto672 }673}674675/// Represents a source of patterns that ripgrep should search for.676///677/// The reason to unify these is so that we can retain the order of `-f/--flag`678/// and `-e/--regexp` flags relative to one another.679#[derive(Debug, Eq, PartialEq)]680pub(crate) enum PatternSource {681 /// Comes from the `-e/--regexp` flag.682 Regexp(String),683 /// Comes from the `-f/--file` flag.684 File(PathBuf),685}686687/// The sort criteria, if present.688#[derive(Debug, Eq, PartialEq)]689pub(crate) struct SortMode {690 /// Whether to reverse the sort criteria (i.e., descending order).691 pub(crate) reverse: bool,692 /// The actual sorting criteria.693 pub(crate) kind: SortModeKind,694}695696/// The criteria to use for sorting.697#[derive(Debug, Eq, PartialEq)]698pub(crate) enum SortModeKind {699 /// Sort by path.700 Path,701 /// Sort by last modified time.702 LastModified,703 /// Sort by last accessed time.704 LastAccessed,705 /// Sort by creation time.706 Created,707}708709impl SortMode {710 /// Checks whether the selected sort mode is supported. If it isn't, an711 /// error (hopefully explaining why) is returned.712 pub(crate) fn supported(&self) -> anyhow::Result<()> {713 match self.kind {714 SortModeKind::Path => Ok(()),715 SortModeKind::LastModified => {716 let md = std::env::current_exe()717 .and_then(|p| p.metadata())718 .and_then(|md| md.modified());719 let Err(err) = md else { return Ok(()) };720 anyhow::bail!(721 "sorting by last modified isn't supported: {err}"722 );723 }724 SortModeKind::LastAccessed => {725 let md = std::env::current_exe()726 .and_then(|p| p.metadata())727 .and_then(|md| md.accessed());728 let Err(err) = md else { return Ok(()) };729 anyhow::bail!(730 "sorting by last accessed isn't supported: {err}"731 );732 }733 SortModeKind::Created => {734 let md = std::env::current_exe()735 .and_then(|p| p.metadata())736 .and_then(|md| md.created());737 let Err(err) = md else { return Ok(()) };738 anyhow::bail!(739 "sorting by creation time isn't supported: {err}"740 );741 }742 }743 }744}745746/// A single instance of either a change or a selection of one ripgrep's747/// file types.748#[derive(Debug, Eq, PartialEq)]749pub(crate) enum TypeChange {750 /// Clear the given type from ripgrep.751 Clear { name: String },752 /// Add the given type definition (name and glob) to ripgrep.753 Add { def: String },754 /// Select the given type for filtering.755 Select { name: String },756 /// Select the given type for filtering but negate it.757 Negate { name: String },758}
added:crates/core/flags/mod.rs+282 added
1/*!2Defines ripgrep's command line interface.34This modules deals with everything involving ripgrep's flags and positional5arguments. This includes generating shell completions, `--help` output and even6ripgrep's man page. It's also responsible for parsing and validating every7flag (including reading ripgrep's config file), and manages the contact points8between these flags and ripgrep's cast of supporting libraries. For example,9once [`HiArgs`] has been created, it knows how to create a multi threaded10recursive directory traverser.11*/12use std::{13 ffi::OsString,14 fmt::Debug,15 panic::{RefUnwindSafe, UnwindSafe},16};1718pub(crate) use crate::flags::{19 complete::{20 bash::generate as generate_complete_bash,21 fish::generate as generate_complete_fish,22 powershell::generate as generate_complete_powershell,23 zsh::generate as generate_complete_zsh,24 },25 doc::{26 help::{27 generate_long as generate_help_long,28 generate_short as generate_help_short,29 },30 man::generate as generate_man_page,31 version::{32 generate_long as generate_version_long,33 generate_short as generate_version_short,34 },35 },36 hiargs::HiArgs,37 lowargs::{GenerateMode, Mode, SearchMode, SpecialMode},38 parse::{parse, ParseResult},39};4041mod complete;42mod config;43mod defs;44mod doc;45mod hiargs;46mod lowargs;47mod parse;4849/// A trait that encapsulates the definition of an optional flag for ripgrep.50///51/// This trait is meant to be used via dynamic dispatch. Namely, the `defs`52/// module provides a single global slice of `&dyn Flag` values correspondings53/// to all of the flags in ripgrep.54///55/// ripgrep's required positional arguments are handled by the parser and by56/// the conversion from low-level arguments to high level arguments. Namely,57/// all of ripgrep's positional arguments are treated as file paths, except58/// in certain circumstances where the first argument is treated as a regex59/// pattern.60///61/// Note that each implementation of this trait requires a long flag name,62/// but can also optionally have a short version and even a negation flag.63/// For example, the `-E/--encoding` flag accepts a value, but it also has a64/// `--no-encoding` negation flag for reverting back to "automatic" encoding65/// detection. All three of `-E`, `--encoding` and `--no-encoding` are provided66/// by a single implementation of this trait.67///68/// ripgrep only supports flags that are switches or flags that accept a single69/// value. Flags that accept multiple values are an unsupported abberation.70trait Flag: Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static {71 /// Returns true if this flag is a switch. When a flag is a switch, the72 /// CLI parser will look for a value after the flag is seen.73 fn is_switch(&self) -> bool;7475 /// A short single byte name for this flag. This returns `None` by default,76 /// which signifies that the flag has no short name.77 ///78 /// The byte returned must be an ASCII codepoint that is a `.` or is79 /// alpha-numeric.80 fn name_short(&self) -> Option<u8> {81 None82 }8384 /// Returns the long name of this flag. All flags must have a "long" name.85 ///86 /// The long name must be at least 2 bytes, and all of its bytes must be87 /// ASCII codepoints that are either `-` or alpha-numeric.88 fn name_long(&self) -> &'static str;8990 /// Returns a list of aliases for this flag.91 ///92 /// The aliases must follow the same rules as `Flag::name_long`.93 ///94 /// By default, an empty slice is returned.95 fn aliases(&self) -> &'static [&'static str] {96 &[]97 }9899 /// Returns a negated name for this flag. The negation of a flag is100 /// intended to have the opposite meaning of a flag or to otherwise turn101 /// something "off" or revert it to its default behavior.102 ///103 /// Negated flags are not listed in their own section in the `-h/--help`104 /// output or man page. Instead, they are automatically mentioned at the105 /// end of the documentation section of the flag they negated.106 ///107 /// The aliases must follow the same rules as `Flag::name_long`.108 ///109 /// By default, a flag has no negation and this returns `None`.110 fn name_negated(&self) -> Option<&'static str> {111 None112 }113114 /// Returns the variable name describing the type of value this flag115 /// accepts. This should always be set for non-switch flags and never set116 /// for switch flags.117 ///118 /// For example, the `--max-count` flag has its variable name set to `NUM`.119 ///120 /// The convention is to capitalize variable names.121 ///122 /// By default this returns `None`.123 fn doc_variable(&self) -> Option<&'static str> {124 None125 }126127 /// Returns the category of this flag.128 ///129 /// Every flag must have a single category. Categories are used to organize130 /// flags in the generated documentation.131 fn doc_category(&self) -> Category;132133 /// A (very) short documentation string describing what this flag does.134 ///135 /// This may sacrifice "proper English" in order to be as terse as136 /// possible. Generally, we try to ensure that `rg -h` doesn't have any137 /// lines that exceed 79 columns.138 fn doc_short(&self) -> &'static str;139140 /// A (possibly very) longer documentation string describing in full141 /// detail what this flag does. This should be in mandoc/mdoc format.142 fn doc_long(&self) -> &'static str;143144 /// If this is a non-switch flag that accepts a small set of specific145 /// values, then this should list them.146 ///147 /// This returns an empty slice by default.148 fn doc_choices(&self) -> &'static [&'static str] {149 &[]150 }151152 /// Given the parsed value (which might just be a switch), this should153 /// update the state in `args` based on the value given for this flag.154 ///155 /// This may update state for other flags as appropriate.156 ///157 /// The `-V/--version` and `-h/--help` flags are treated specially in the158 /// parser and should do nothing here.159 ///160 /// By convention, implementations should generally not try to "do"161 /// anything other than validate the value given. For example, the162 /// implementation for `--hostname-bin` should not try to resolve the163 /// hostname to use by running the binary provided. That should be saved164 /// for a later step. This convention is used to ensure that getting the165 /// low-level arguments is as reliable and quick as possible. It also166 /// ensures that "doing something" occurs a minimal number of times. For167 /// example, by avoiding trying to find the hostname here, we can do it168 /// once later no matter how many times `--hostname-bin` is provided.169 ///170 /// Implementations should not include the flag name in the error message171 /// returned. The flag name is included automatically by the parser.172 fn update(173 &self,174 value: FlagValue,175 args: &mut crate::flags::lowargs::LowArgs,176 ) -> anyhow::Result<()>;177}178179/// The category that a flag belongs to.180///181/// Categories are used to organize flags into "logical" groups in the182/// generated documentation.183#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]184enum Category {185 /// Flags related to how ripgrep reads its input. Its "input" generally186 /// consists of the patterns it is trying to match and the haystacks it is187 /// trying to search.188 Input,189 /// Flags related to the operation of the search itself. For example,190 /// whether case insensitive matching is enabled.191 Search,192 /// Flags related to how ripgrep filters haystacks. For example, whether193 /// to respect gitignore files or not.194 Filter,195 /// Flags related to how ripgrep shows its search results. For example,196 /// whether to show line numbers or not.197 Output,198 /// Flags related to changing ripgrep's output at a more fundamental level.199 /// For example, flags like `--count` suppress printing of individual200 /// lines, and instead just print the total count of matches for each file201 /// searched.202 OutputModes,203 /// Flags related to logging behavior such as emitting non-fatal error204 /// messages or printing search statistics.205 Logging,206 /// Other behaviors not related to ripgrep's core functionality. For207 /// example, printing the file type globbing rules, or printing the list208 /// of files ripgrep would search without actually searching them.209 OtherBehaviors,210}211212impl Category {213 /// Returns a string representation of this category.214 ///215 /// This string is the name of the variable used in various templates for216 /// generated documentation. This name can be used for interpolation.217 fn as_str(&self) -> &'static str {218 match *self {219 Category::Input => "input",220 Category::Search => "search",221 Category::Filter => "filter",222 Category::Output => "output",223 Category::OutputModes => "output-modes",224 Category::Logging => "logging",225 Category::OtherBehaviors => "other-behaviors",226 }227 }228}229230/// Represents a value parsed from the command line.231///232/// This doesn't include the corresponding flag, but values come in one of233/// two forms: a switch (on or off) or an arbitrary value.234///235/// Note that the CLI doesn't directly support negated switches. For example,236/// you can'd do anything like `-n=false` or any of that nonsense. Instead,237/// the CLI parser knows about which flag names are negations and which aren't238/// (courtesy of the `Flag` trait). If a flag given is known as a negation,239/// then a `FlagValue::Switch(false)` value is passed into `Flag::update`.240#[derive(Debug)]241enum FlagValue {242 /// A flag that is either on or off.243 Switch(bool),244 /// A flag that comes with an arbitrary user value.245 Value(OsString),246}247248impl FlagValue {249 /// Return the yes or no value of this switch.250 ///251 /// If this flag value is not a switch, then this panics.252 ///253 /// This is useful when writing the implementation of `Flag::update`.254 /// namely, callers usually know whether a switch or a value is expected.255 /// If a flag is something different, then it indicates a bug, and thus a256 /// panic is acceptable.257 fn unwrap_switch(self) -> bool {258 match self {259 FlagValue::Switch(yes) => yes,260 FlagValue::Value(_) => {261 unreachable!("got flag value but expected switch")262 }263 }264 }265266 /// Return the user provided value of this flag.267 ///268 /// If this flag is a switch, then this panics.269 ///270 /// This is useful when writing the implementation of `Flag::update`.271 /// namely, callers usually know whether a switch or a value is expected.272 /// If a flag is something different, then it indicates a bug, and thus a273 /// panic is acceptable.274 fn unwrap_value(self) -> OsString {275 match self {276 FlagValue::Switch(_) => {277 unreachable!("got switch but expected flag value")278 }279 FlagValue::Value(v) => v,280 }281 }282}
added:crates/core/flags/parse.rs+392 added
1/*!2Parses command line arguments into a structured and typed representation.3*/45use std::ffi::OsString;67use anyhow::Context;89use crate::flags::{10 defs::FLAGS,11 hiargs::HiArgs,12 lowargs::{LoggingMode, LowArgs, SpecialMode},13 Flag, FlagValue,14};1516/// The result of parsing CLI arguments.17///18/// This is basically a `anyhow::Result<T>`, but with one extra variant that is19/// inhabited whenever ripgrep should execute a "special" mode. That is, when a20/// user provides the `-h/--help` or `-V/--version` flags.21///22/// This special variant exists to allow CLI parsing to short circuit as23/// quickly as is reasonable. For example, it lets CLI parsing avoid reading24/// ripgrep's configuration and converting low level arguments into a higher25/// level representation.26#[derive(Debug)]27pub(crate) enum ParseResult<T> {28 Special(SpecialMode),29 Ok(T),30 Err(anyhow::Error),31}3233impl<T> ParseResult<T> {34 /// If this result is `Ok`, then apply `then` to it. Otherwise, return this35 /// result unchanged.36 fn and_then<U>(37 self,38 mut then: impl FnMut(T) -> ParseResult<U>,39 ) -> ParseResult<U> {40 match self {41 ParseResult::Special(mode) => ParseResult::Special(mode),42 ParseResult::Ok(t) => then(t),43 ParseResult::Err(err) => ParseResult::Err(err),44 }45 }46}4748/// Parse CLI arguments and convert then to their high level representation.49pub(crate) fn parse() -> ParseResult<HiArgs> {50 parse_low().and_then(|low| match HiArgs::from_low_args(low) {51 Ok(hi) => ParseResult::Ok(hi),52 Err(err) => ParseResult::Err(err),53 })54}5556/// Parse CLI arguments only into their low level representation.57///58/// This takes configuration into account. That is, it will try to read59/// `RIPGREP_CONFIG_PATH` and prepend any arguments found there to the60/// arguments passed to this process.61///62/// This will also set one-time global state flags, such as the log level and63/// whether messages should be printed.64fn parse_low() -> ParseResult<LowArgs> {65 if let Err(err) = crate::logger::Logger::init() {66 let err = anyhow::anyhow!("failed to initialize logger: {err}");67 return ParseResult::Err(err);68 }6970 let parser = Parser::new();71 let mut low = LowArgs::default();72 if let Err(err) = parser.parse(std::env::args_os().skip(1), &mut low) {73 return ParseResult::Err(err);74 }75 // Even though we haven't parsed the config file yet (assuming it exists),76 // we can still use the arguments given on the CLI to setup ripgrep's77 // logging preferences. Even if the config file changes them in some way,78 // it's really the best we can do. This way, for example, folks can pass79 // `--trace` and see any messages logged during config file parsing.80 set_log_levels(&low);81 // Before we try to take configuration into account, we can bail early82 // if a special mode was enabled. This is basically only for version and83 // help output which shouldn't be impacted by extra configuration.84 if let Some(special) = low.special.take() {85 return ParseResult::Special(special);86 }87 // If the end user says no config, then respect it.88 if low.no_config {89 log::debug!("not reading config files because --no-config is present");90 return ParseResult::Ok(low);91 }92 // Look for arguments from a config file. If we got nothing (whether the93 // file is empty or RIPGREP_CONFIG_PATH wasn't set), then we don't need94 // to re-parse.95 let config_args = crate::flags::config::args();96 if config_args.is_empty() {97 log::debug!("no extra arguments found from configuration file");98 return ParseResult::Ok(low);99 }100 // The final arguments are just the arguments from the CLI appending to101 // the end of the config arguments.102 let mut final_args = config_args;103 final_args.extend(std::env::args_os().skip(1));104105 // Now do the CLI parsing dance again.106 let mut low = LowArgs::default();107 if let Err(err) = parser.parse(final_args.into_iter(), &mut low) {108 return ParseResult::Err(err);109 }110 // Reset the message and logging levels, since they could have changed.111 set_log_levels(&low);112 ParseResult::Ok(low)113}114115/// Sets global state flags that control logging based on low-level arguments.116fn set_log_levels(low: &LowArgs) {117 crate::messages::set_messages(!low.no_messages);118 crate::messages::set_ignore_messages(!low.no_ignore_messages);119 match low.logging {120 Some(LoggingMode::Trace) => {121 log::set_max_level(log::LevelFilter::Trace)122 }123 Some(LoggingMode::Debug) => {124 log::set_max_level(log::LevelFilter::Debug)125 }126 None => log::set_max_level(log::LevelFilter::Warn),127 }128}129130/// Parse the sequence of CLI arguments given a low level typed set of131/// arguments.132///133/// This is exposed for testing that the correct low-level arguments are parsed134/// from a CLI. It just runs the parser once over the CLI arguments. It doesn't135/// setup logging or read from a config file.136///137/// This assumes the iterator given does *not* begin with the binary name.138#[cfg(test)]139pub(crate) fn parse_low_raw(140 rawargs: impl IntoIterator<Item = impl Into<OsString>>,141) -> anyhow::Result<LowArgs> {142 let mut args = LowArgs::default();143 Parser::new().parse(rawargs, &mut args)?;144 Ok(args)145}146147/// Return the metadata for the flag of the given name.148pub(super) fn lookup(name: &str) -> Option<&'static dyn Flag> {149 // N.B. Creating a new parser might look expensive, but it only builds150 // the lookup trie exactly once. That is, we get a `&'static Parser` from151 // `Parser::new()`.152 match Parser::new().find_long(name) {153 FlagLookup::Match(&FlagInfo { flag, .. }) => Some(flag),154 _ => None,155 }156}157158/// A parser for turning a sequence of command line arguments into a more159/// strictly typed set of arguments.160#[derive(Debug)]161struct Parser {162 /// A single map that contains all possible flag names. This includes163 /// short and long names, aliases and negations. This maps those names to164 /// indices into `info`.165 map: FlagMap,166 /// A map from IDs returned by the `map` to the corresponding flag167 /// information.168 info: Vec<FlagInfo>,169}170171impl Parser {172 /// Create a new parser.173 ///174 /// This always creates the same parser and only does it once. Callers may175 /// call this repeatedly, and the parser will only be built once.176 fn new() -> &'static Parser {177 use std::sync::OnceLock;178179 // Since a parser's state is immutable and completely determined by180 // FLAGS, and since FLAGS is a constant, we can initialize it exactly181 // once.182 static P: OnceLock<Parser> = OnceLock::new();183 P.get_or_init(|| {184 let mut infos = vec![];185 for &flag in FLAGS.iter() {186 infos.push(FlagInfo {187 flag,188 name: Ok(flag.name_long()),189 kind: FlagInfoKind::Standard,190 });191 for alias in flag.aliases() {192 infos.push(FlagInfo {193 flag,194 name: Ok(alias),195 kind: FlagInfoKind::Alias,196 });197 }198 if let Some(byte) = flag.name_short() {199 infos.push(FlagInfo {200 flag,201 name: Err(byte),202 kind: FlagInfoKind::Standard,203 });204 }205 if let Some(name) = flag.name_negated() {206 infos.push(FlagInfo {207 flag,208 name: Ok(name),209 kind: FlagInfoKind::Negated,210 });211 }212 }213 let map = FlagMap::new(&infos);214 Parser { map, info: infos }215 })216 }217218 /// Parse the given CLI arguments into a low level representation.219 ///220 /// The iterator given should *not* start with the binary name.221 fn parse<I, O>(&self, rawargs: I, args: &mut LowArgs) -> anyhow::Result<()>222 where223 I: IntoIterator<Item = O>,224 O: Into<OsString>,225 {226 let mut p = lexopt::Parser::from_args(rawargs);227 while let Some(arg) = p.next().context("invalid CLI arguments")? {228 let lookup = match arg {229 lexopt::Arg::Value(value) => {230 args.positional.push(value);231 continue;232 }233 lexopt::Arg::Short(ch) if ch == 'h' => {234 // Special case -h/--help since behavior is different235 // based on whether short or long flag is given.236 args.special = Some(SpecialMode::HelpShort);237 continue;238 }239 lexopt::Arg::Short(ch) if ch == 'V' => {240 // Special case -V/--version since behavior is different241 // based on whether short or long flag is given.242 args.special = Some(SpecialMode::VersionShort);243 continue;244 }245 lexopt::Arg::Short(ch) => self.find_short(ch),246 lexopt::Arg::Long(name) if name == "help" => {247 // Special case -h/--help since behavior is different248 // based on whether short or long flag is given.249 args.special = Some(SpecialMode::HelpLong);250 continue;251 }252 lexopt::Arg::Long(name) if name == "version" => {253 // Special case -V/--version since behavior is different254 // based on whether short or long flag is given.255 args.special = Some(SpecialMode::VersionLong);256 continue;257 }258 lexopt::Arg::Long(name) => self.find_long(name),259 };260 let mat = match lookup {261 FlagLookup::Match(mat) => mat,262 FlagLookup::UnrecognizedShort(name) => {263 anyhow::bail!("unrecognized flag -{name}")264 }265 FlagLookup::UnrecognizedLong(name) => {266 anyhow::bail!("unrecognized flag --{name}")267 }268 };269 let value = if matches!(mat.kind, FlagInfoKind::Negated) {270 // Negated flags are always switches, even if the non-negated271 // flag is not. For example, --context-separator accepts a272 // value, but --no-context-separator does not.273 FlagValue::Switch(false)274 } else if mat.flag.is_switch() {275 FlagValue::Switch(true)276 } else {277 FlagValue::Value(p.value().with_context(|| {278 format!("missing value for flag {mat}")279 })?)280 };281 mat.flag282 .update(value, args)283 .with_context(|| format!("error parsing flag {mat}"))?;284 }285 Ok(())286 }287288 /// Look for a flag by its short name.289 fn find_short(&self, ch: char) -> FlagLookup<'_> {290 if !ch.is_ascii() {291 return FlagLookup::UnrecognizedShort(ch);292 }293 let byte = u8::try_from(ch).unwrap();294 let Some(index) = self.map.find(&[byte]) else {295 return FlagLookup::UnrecognizedShort(ch);296 };297 FlagLookup::Match(&self.info[index])298 }299300 /// Look for a flag by its long name.301 ///302 /// This also works for aliases and negated names.303 fn find_long(&self, name: &str) -> FlagLookup<'_> {304 let Some(index) = self.map.find(name.as_bytes()) else {305 return FlagLookup::UnrecognizedLong(name.to_string());306 };307 FlagLookup::Match(&self.info[index])308 }309}310311/// The result of looking up a flag name.312#[derive(Debug)]313enum FlagLookup<'a> {314 /// Lookup found a match and the metadata for the flag is attached.315 Match(&'a FlagInfo),316 /// The given short name is unrecognized.317 UnrecognizedShort(char),318 /// The given long name is unrecognized.319 UnrecognizedLong(String),320}321322/// The info about a flag associated with a flag's ID in the the flag map.323#[derive(Debug)]324struct FlagInfo {325 /// The flag object and its associated metadata.326 flag: &'static dyn Flag,327 /// The actual name that is stored in the Aho-Corasick automaton. When this328 /// is a byte, it corresponds to a short single character ASCII flag. The329 /// actual pattern that's in the Aho-Corasick automaton is just the single330 /// byte.331 name: Result<&'static str, u8>,332 /// The type of flag that is stored for the corresponding Aho-Corasick333 /// pattern.334 kind: FlagInfoKind,335}336337/// The kind of flag that is being matched.338#[derive(Debug)]339enum FlagInfoKind {340 /// A standard flag, e.g., --passthru.341 Standard,342 /// A negation of a standard flag, e.g., --no-multiline.343 Negated,344 /// An alias for a standard flag, e.g., --passthrough.345 Alias,346}347348impl std::fmt::Display for FlagInfo {349 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {350 match self.name {351 Ok(long) => write!(f, "--{long}"),352 Err(short) => write!(f, "-{short}", short = char::from(short)),353 }354 }355}356357/// A map from flag names (short, long, negated and aliases) to their ID.358///359/// Once an ID is known, it can be used to look up a flag's metadata in the360/// parser's internal state.361#[derive(Debug)]362struct FlagMap {363 map: std::collections::HashMap<Vec<u8>, usize>,364}365366impl FlagMap {367 /// Create a new map of flags for the given flag information.368 ///369 /// The index of each flag info corresponds to its ID.370 fn new(infos: &[FlagInfo]) -> FlagMap {371 let mut map = std::collections::HashMap::with_capacity(infos.len());372 for (i, info) in infos.iter().enumerate() {373 match info.name {374 Ok(name) => {375 assert_eq!(None, map.insert(name.as_bytes().to_vec(), i));376 }377 Err(byte) => {378 assert_eq!(None, map.insert(vec![byte], i));379 }380 }381 }382 FlagMap { map }383 }384385 /// Look for a match of `name` in the given Aho-Corasick automaton.386 ///387 /// This only returns a match if the one found has a length equivalent to388 /// the length of the name given.389 fn find(&self, name: &[u8]) -> Option<usize> {390 self.map.get(name).copied()391 }392}
deleted:crates/core/app.rs-3251 removed
1// This module defines the set of command line arguments that ripgrep supports,2// including some light validation.3//4// This module is purposely written in a bare-bones way, since it is included5// in ripgrep's build.rs file as a way to generate a man page and completion6// files for common shells.7//8// The only other place that ripgrep deals with clap is in src/args.rs, which9// is where we read clap's configuration from the end user's arguments and turn10// it into a ripgrep-specific configuration type that is not coupled with clap.1112use clap::{self, crate_authors, crate_version, App, AppSettings};1314const ABOUT: &str = "15ripgrep (rg) recursively searches the current directory for a regex pattern.16By default, ripgrep will respect gitignore rules and automatically skip hidden17files/directories and binary files.1819Use -h for short descriptions and --help for more details.2021Project home page: https://github.com/BurntSushi/ripgrep22";2324const USAGE: &str = "25 rg [OPTIONS] PATTERN [PATH ...]26 rg [OPTIONS] -e PATTERN ... [PATH ...]27 rg [OPTIONS] -f PATTERNFILE ... [PATH ...]28 rg [OPTIONS] --files [PATH ...]29 rg [OPTIONS] --type-list30 command | rg [OPTIONS] PATTERN31 rg [OPTIONS] --help32 rg [OPTIONS] --version";3334const TEMPLATE: &str = "\35{bin} {version}36{author}37{about}3839USAGE:{usage}4041ARGS:42{positionals}4344OPTIONS:45{unified}";4647/// Build a clap application parameterized by usage strings.48pub fn app() -> App<'static, 'static> {49 use std::sync::OnceLock;5051 // We need to specify our version in a static because we've painted clap52 // into a corner. We've told it that every string we give it will be53 // 'static, but we need to build the version string dynamically. We can54 // fake the 'static lifetime with lazy_static.55 static LONG_VERSION: OnceLock<String> = OnceLock::new();56 let long_version = LONG_VERSION.get_or_init(|| long_version(None, true));5758 let mut app = App::new("ripgrep")59 .author(crate_authors!())60 .version(crate_version!())61 .long_version(long_version.as_str())62 .about(ABOUT)63 .max_term_width(100)64 .setting(AppSettings::UnifiedHelpMessage)65 .setting(AppSettings::AllArgsOverrideSelf)66 .usage(USAGE)67 .template(TEMPLATE)68 .help_message("Prints help information. Use --help for more details.");69 for arg in all_args_and_flags() {70 app = app.arg(arg.claparg);71 }72 app73}7475/// Return the "long" format of ripgrep's version string.76///77/// If a revision hash is given, then it is used. If one isn't given, then78/// the RIPGREP_BUILD_GIT_HASH env var is inspected for it. If that isn't set,79/// then a revision hash is not included in the version string returned.80///81/// If `cpu` is true, then the version string will include the compiled and82/// runtime CPU features.83pub fn long_version(revision_hash: Option<&str>, cpu: bool) -> String {84 // Do we have a git hash?85 // (Yes, if ripgrep was built on a machine with `git` installed.)86 let hash = match revision_hash.or(option_env!("RIPGREP_BUILD_GIT_HASH")) {87 None => String::new(),88 Some(githash) => format!(" (rev {})", githash),89 };90 if !cpu {91 format!("{}{}", crate_version!(), hash,)92 } else {93 let runtime = runtime_cpu_features();94 if runtime.is_empty() {95 format!(96 "{}{}\n{} (compiled)",97 crate_version!(),98 hash,99 compile_cpu_features().join(" ")100 )101 } else {102 format!(103 "{}{}\n{} (compiled)\n{} (runtime)",104 crate_version!(),105 hash,106 compile_cpu_features().join(" "),107 runtime.join(" ")108 )109 }110 }111}112113/// Returns the relevant CPU features enabled at compile time.114fn compile_cpu_features() -> Vec<&'static str> {115 let mut features = vec![];116 if cfg!(feature = "simd-accel") {117 features.push("+SIMD");118 } else {119 features.push("-SIMD");120 }121 if cfg!(feature = "avx-accel") {122 features.push("+AVX");123 } else {124 features.push("-AVX");125 }126 features127}128129/// Returns the relevant CPU features enabled at runtime.130#[cfg(target_arch = "x86_64")]131fn runtime_cpu_features() -> Vec<&'static str> {132 // This is kind of a dirty violation of abstraction, since it assumes133 // knowledge about what specific SIMD features are being used.134135 let mut features = vec![];136 if is_x86_feature_detected!("ssse3") {137 features.push("+SIMD");138 } else {139 features.push("-SIMD");140 }141 if is_x86_feature_detected!("avx2") {142 features.push("+AVX");143 } else {144 features.push("-AVX");145 }146 features147}148149/// Returns the relevant CPU features enabled at runtime.150#[cfg(not(target_arch = "x86_64"))]151fn runtime_cpu_features() -> Vec<&'static str> {152 vec![]153}154155/// Arg is a light alias for a clap::Arg that is specialized to compile time156/// string literals.157type Arg = clap::Arg<'static, 'static>;158159/// RGArg is a light wrapper around a clap::Arg and also contains some metadata160/// about the underlying Arg so that it can be inspected for other purposes161/// (e.g., hopefully generating a man page).162///163/// Note that this type is purposely overly constrained to ripgrep's particular164/// use of clap.165#[allow(dead_code)]166#[derive(Clone)]167pub struct RGArg {168 /// The underlying clap argument.169 claparg: Arg,170 /// The name of this argument. This is always present and is the name171 /// used in the code to find the value of an argument at runtime.172 pub name: &'static str,173 /// A short documentation string describing this argument. This string174 /// should fit on a single line and be a complete sentence.175 ///176 /// This is shown in the `-h` output.177 pub doc_short: &'static str,178 /// A longer documentation string describing this argument. This usually179 /// starts with the contents of `doc_short`. This is also usually many180 /// lines, potentially paragraphs, and may contain examples and additional181 /// prose.182 ///183 /// This is shown in the `--help` output.184 pub doc_long: &'static str,185 /// Whether this flag is hidden or not.186 ///187 /// This is typically used for uncommon flags that only serve to override188 /// other flags. For example, --no-ignore is a prominent flag that disables189 /// ripgrep's gitignore functionality, but --ignore re-enables it. Since190 /// gitignore support is enabled by default, use of the --ignore flag is191 /// somewhat niche and relegated to special cases when users make use of192 /// configuration files to set defaults.193 ///194 /// Generally, these flags should be documented in the documentation for195 /// the flag they override.196 pub hidden: bool,197 /// The type of this argument.198 pub kind: RGArgKind,199}200201/// The kind of a ripgrep argument.202///203/// This can be one of three possibilities: a positional argument, a boolean204/// switch flag or a flag that accepts exactly one argument. Each variant205/// stores argument type specific data.206///207/// Note that clap supports more types of arguments than this, but we don't208/// (and probably shouldn't) use them in ripgrep.209///210/// Finally, note that we don't capture *all* state about an argument in this211/// type. Some state is only known to clap. There isn't any particular reason212/// why; the state we do capture is motivated by use cases (like generating213/// documentation).214#[derive(Clone)]215pub enum RGArgKind {216 /// A positional argument.217 Positional {218 /// The name of the value used in the `-h/--help` output. By219 /// convention, this is an all-uppercase string. e.g., `PATH` or220 /// `PATTERN`.221 value_name: &'static str,222 /// Whether an argument can be repeated multiple times or not.223 ///224 /// The only argument this applies to is PATH, where an end user can225 /// specify multiple paths for ripgrep to search.226 ///227 /// If this is disabled, then an argument can only be provided once.228 /// For example, PATTERN is one such argument. (Note that the229 /// -e/--regexp flag is distinct from the positional PATTERN argument,230 /// and it can be provided multiple times.)231 multiple: bool,232 },233 /// A boolean switch.234 Switch {235 /// The long name of a flag. This is always non-empty.236 long: &'static str,237 /// The short name of a flag. This is empty if a flag only has a long238 /// name.239 short: Option<&'static str>,240 /// Whether this switch can be provided multiple times where meaning241 /// is attached to the number of times this flag is given.242 ///243 /// Note that every switch can be provided multiple times. This244 /// particular state indicates whether all instances of a switch are245 /// relevant or not.246 ///247 /// For example, the -u/--unrestricted flag can be provided multiple248 /// times where each repeated use of it indicates more relaxing of249 /// ripgrep's filtering. Conversely, the -i/--ignore-case flag can250 /// also be provided multiple times, but it is simply considered either251 /// present or not. In these cases, -u/--unrestricted has `multiple`252 /// set to `true` while -i/--ignore-case has `multiple` set to `false`.253 multiple: bool,254 },255 /// A flag the accepts a single value.256 Flag {257 /// The long name of a flag. This is always non-empty.258 long: &'static str,259 /// The short name of a flag. This is empty if a flag only has a long260 /// name.261 short: Option<&'static str>,262 /// The name of the value used in the `-h/--help` output. By263 /// convention, this is an all-uppercase string. e.g., `PATH` or264 /// `PATTERN`.265 value_name: &'static str,266 /// Whether this flag can be provided multiple times with multiple267 /// distinct values.268 ///269 /// Note that every flag can be provided multiple times. This270 /// particular state indicates whether all instances of a flag are271 /// relevant or not.272 ///273 /// For example, the -g/--glob flag can be provided multiple times and274 /// all of its values should be interpreted by ripgrep. Conversely,275 /// while the -C/--context flag can also be provided multiple times,276 /// only its last instance is used while all previous instances are277 /// ignored. In these cases, -g/--glob has `multiple` set to `true`278 /// while -C/--context has `multiple` set to `false`.279 multiple: bool,280 /// A set of possible values for this flag. If an end user provides281 /// any value other than what's in this set, then clap will report an282 /// error.283 possible_values: Vec<&'static str>,284 },285}286287impl RGArg {288 /// Create a positional argument.289 ///290 /// The `long_name` parameter is the name of the argument, e.g., `pattern`.291 /// The `value_name` parameter is a name that describes the type of292 /// argument this flag accepts. It should be in uppercase, e.g., PATH or293 /// PATTERN.294 fn positional(name: &'static str, value_name: &'static str) -> RGArg {295 RGArg {296 claparg: Arg::with_name(name).value_name(value_name),297 name,298 doc_short: "",299 doc_long: "",300 hidden: false,301 kind: RGArgKind::Positional { value_name, multiple: false },302 }303 }304305 /// Create a boolean switch.306 ///307 /// The `long_name` parameter is the name of the flag, e.g., `--long-name`.308 ///309 /// All switches may be repeated an arbitrary number of times. If a switch310 /// is truly boolean, that consumers of clap's configuration should only311 /// check whether the flag is present or not. Otherwise, consumers may312 /// inspect the number of times the switch is used.313 fn switch(long_name: &'static str) -> RGArg {314 let claparg = Arg::with_name(long_name).long(long_name);315 RGArg {316 claparg,317 name: long_name,318 doc_short: "",319 doc_long: "",320 hidden: false,321 kind: RGArgKind::Switch {322 long: long_name,323 short: None,324 multiple: false,325 },326 }327 }328329 /// Create a flag. A flag always accepts exactly one argument.330 ///331 /// The `long_name` parameter is the name of the flag, e.g., `--long-name`.332 /// The `value_name` parameter is a name that describes the type of333 /// argument this flag accepts. It should be in uppercase, e.g., PATH or334 /// PATTERN.335 ///336 /// All flags may be repeated an arbitrary number of times. If a flag has337 /// only one logical value, that consumers of clap's configuration should338 /// only use the last value.339 fn flag(long_name: &'static str, value_name: &'static str) -> RGArg {340 let claparg = Arg::with_name(long_name)341 .long(long_name)342 .value_name(value_name)343 .takes_value(true)344 .number_of_values(1);345 RGArg {346 claparg,347 name: long_name,348 doc_short: "",349 doc_long: "",350 hidden: false,351 kind: RGArgKind::Flag {352 long: long_name,353 short: None,354 value_name,355 multiple: false,356 possible_values: vec![],357 },358 }359 }360361 /// Set the short flag name.362 ///363 /// This panics if this arg isn't a switch or a flag.364 fn short(mut self, name: &'static str) -> RGArg {365 match self.kind {366 RGArgKind::Positional { .. } => panic!("expected switch or flag"),367 RGArgKind::Switch { ref mut short, .. } => {368 *short = Some(name);369 }370 RGArgKind::Flag { ref mut short, .. } => {371 *short = Some(name);372 }373 }374 self.claparg = self.claparg.short(name);375 self376 }377378 /// Set the "short" help text.379 ///380 /// This should be a single line. It is shown in the `-h` output.381 fn help(mut self, text: &'static str) -> RGArg {382 self.doc_short = text;383 self.claparg = self.claparg.help(text);384 self385 }386387 /// Set the "long" help text.388 ///389 /// This should be at least a single line, usually longer. It is shown in390 /// the `--help` output.391 fn long_help(mut self, text: &'static str) -> RGArg {392 self.doc_long = text;393 self.claparg = self.claparg.long_help(text);394 self395 }396397 /// Enable this argument to accept multiple values.398 ///399 /// Note that while switches and flags can always be repeated an arbitrary400 /// number of times, this particular method enables the flag to be401 /// logically repeated where each occurrence of the flag may have402 /// significance. That is, when this is disabled, then a switch is either403 /// present or not and a flag has exactly one value (the last one given).404 /// When this is enabled, then a switch has a count corresponding to the405 /// number of times it is used and a flag's value is a list of all values406 /// given.407 ///408 /// For the most part, this distinction is resolved by consumers of clap's409 /// configuration.410 fn multiple(mut self) -> RGArg {411 // Why not put `multiple` on RGArg proper? Because it's useful to412 // document it distinct for each different kind. See RGArgKind docs.413 match self.kind {414 RGArgKind::Positional { ref mut multiple, .. } => {415 *multiple = true;416 }417 RGArgKind::Switch { ref mut multiple, .. } => {418 *multiple = true;419 }420 RGArgKind::Flag { ref mut multiple, .. } => {421 *multiple = true;422 }423 }424 self.claparg = self.claparg.multiple(true);425 self426 }427428 /// Hide this flag from all documentation.429 fn hidden(mut self) -> RGArg {430 self.hidden = true;431 self.claparg = self.claparg.hidden(true);432 self433 }434435 /// Set the possible values for this argument. If this argument is not436 /// a flag, then this panics.437 ///438 /// If the end user provides any value other than what is given here, then439 /// clap will report an error to the user.440 ///441 /// Note that this will suppress clap's automatic output of possible values442 /// when using -h/--help, so users of this method should provide443 /// appropriate documentation for the choices in the "long" help text.444 fn possible_values(mut self, values: &[&'static str]) -> RGArg {445 match self.kind {446 RGArgKind::Positional { .. } => panic!("expected flag"),447 RGArgKind::Switch { .. } => panic!("expected flag"),448 RGArgKind::Flag { ref mut possible_values, .. } => {449 *possible_values = values.to_vec();450 self.claparg = self451 .claparg452 .possible_values(values)453 .hide_possible_values(true);454 }455 }456 self457 }458459 /// Add an alias to this argument.460 ///461 /// Aliases are not show in the output of -h/--help.462 fn alias(mut self, name: &'static str) -> RGArg {463 self.claparg = self.claparg.alias(name);464 self465 }466467 /// Permit this flag to have values that begin with a hyphen.468 ///469 /// This panics if this arg is not a flag.470 fn allow_leading_hyphen(mut self) -> RGArg {471 match self.kind {472 RGArgKind::Positional { .. } => panic!("expected flag"),473 RGArgKind::Switch { .. } => panic!("expected flag"),474 RGArgKind::Flag { .. } => {475 self.claparg = self.claparg.allow_hyphen_values(true);476 }477 }478 self479 }480481 /// Sets this argument to a required argument, unless one of the given482 /// arguments is provided.483 fn required_unless(mut self, names: &[&'static str]) -> RGArg {484 self.claparg = self.claparg.required_unless_one(names);485 self486 }487488 /// Sets conflicting arguments. That is, if this argument is used whenever489 /// any of the other arguments given here are used, then clap will report490 /// an error.491 fn conflicts(mut self, names: &[&'static str]) -> RGArg {492 self.claparg = self.claparg.conflicts_with_all(names);493 self494 }495496 /// Sets an overriding argument. That is, if this argument and the given497 /// argument are both provided by an end user, then the "last" one will498 /// win. ripgrep will behave as if any previous instantiations did not499 /// happen.500 fn overrides(mut self, name: &'static str) -> RGArg {501 self.claparg = self.claparg.overrides_with(name);502 self503 }504505 /// Sets the default value of this argument when not specified at506 /// runtime.507 fn default_value(mut self, value: &'static str) -> RGArg {508 self.claparg = self.claparg.default_value(value);509 self510 }511512 /// Sets the default value of this argument if and only if the argument513 /// given is present.514 fn default_value_if(515 mut self,516 value: &'static str,517 arg_name: &'static str,518 ) -> RGArg {519 self.claparg = self.claparg.default_value_if(arg_name, None, value);520 self521 }522523 /// Indicate that any value given to this argument should be a number. If524 /// it's not a number, then clap will report an error to the end user.525 fn number(mut self) -> RGArg {526 self.claparg = self.claparg.validator(|val| {527 val.parse::<usize>().map(|_| ()).map_err(|err| err.to_string())528 });529 self530 }531}532533// We add an extra space to long descriptions so that a blank line is inserted534// between flag descriptions in --help output.535macro_rules! long {536 ($lit:expr) => {537 concat!($lit, " ")538 };539}540541/// Generate a sequence of all positional and flag arguments.542pub fn all_args_and_flags() -> Vec<RGArg> {543 let mut args = vec![];544 // The positional arguments must be defined first and in order.545 arg_pattern(&mut args);546 arg_path(&mut args);547 // Flags can be defined in any order, but we do it alphabetically. Note548 // that each function may define multiple flags. For example,549 // `flag_encoding` defines `--encoding` and `--no-encoding`. Most `--no`550 // flags are hidden and merely mentioned in the docs of the corresponding551 // "positive" flag.552 flag_after_context(&mut args);553 flag_auto_hybrid_regex(&mut args);554 flag_before_context(&mut args);555 flag_binary(&mut args);556 flag_block_buffered(&mut args);557 flag_byte_offset(&mut args);558 flag_case_sensitive(&mut args);559 flag_color(&mut args);560 flag_colors(&mut args);561 flag_column(&mut args);562 flag_context(&mut args);563 flag_context_separator(&mut args);564 flag_count(&mut args);565 flag_count_matches(&mut args);566 flag_crlf(&mut args);567 flag_debug(&mut args);568 flag_dfa_size_limit(&mut args);569 flag_encoding(&mut args);570 flag_engine(&mut args);571 flag_field_context_separator(&mut args);572 flag_field_match_separator(&mut args);573 flag_file(&mut args);574 flag_files(&mut args);575 flag_files_with_matches(&mut args);576 flag_files_without_match(&mut args);577 flag_fixed_strings(&mut args);578 flag_follow(&mut args);579 flag_glob(&mut args);580 flag_glob_case_insensitive(&mut args);581 flag_heading(&mut args);582 flag_hidden(&mut args);583 flag_hostname_bin(&mut args);584 flag_hyperlink_format(&mut args);585 flag_iglob(&mut args);586 flag_ignore_case(&mut args);587 flag_ignore_file(&mut args);588 flag_ignore_file_case_insensitive(&mut args);589 flag_include_zero(&mut args);590 flag_invert_match(&mut args);591 flag_json(&mut args);592 flag_line_buffered(&mut args);593 flag_line_number(&mut args);594 flag_line_regexp(&mut args);595 flag_max_columns(&mut args);596 flag_max_columns_preview(&mut args);597 flag_max_count(&mut args);598 flag_max_depth(&mut args);599 flag_max_filesize(&mut args);600 flag_mmap(&mut args);601 flag_multiline(&mut args);602 flag_multiline_dotall(&mut args);603 flag_no_config(&mut args);604 flag_no_ignore(&mut args);605 flag_no_ignore_dot(&mut args);606 flag_no_ignore_exclude(&mut args);607 flag_no_ignore_files(&mut args);608 flag_no_ignore_global(&mut args);609 flag_no_ignore_messages(&mut args);610 flag_no_ignore_parent(&mut args);611 flag_no_ignore_vcs(&mut args);612 flag_no_messages(&mut args);613 flag_no_pcre2_unicode(&mut args);614 flag_no_require_git(&mut args);615 flag_no_unicode(&mut args);616 flag_null(&mut args);617 flag_null_data(&mut args);618 flag_one_file_system(&mut args);619 flag_only_matching(&mut args);620 flag_path_separator(&mut args);621 flag_passthru(&mut args);622 flag_pcre2(&mut args);623 flag_pcre2_version(&mut args);624 flag_pre(&mut args);625 flag_pre_glob(&mut args);626 flag_pretty(&mut args);627 flag_quiet(&mut args);628 flag_regex_size_limit(&mut args);629 flag_regexp(&mut args);630 flag_replace(&mut args);631 flag_search_zip(&mut args);632 flag_smart_case(&mut args);633 flag_sort_files(&mut args);634 flag_sort(&mut args);635 flag_sortr(&mut args);636 flag_stats(&mut args);637 flag_stop_on_nonmatch(&mut args);638 flag_text(&mut args);639 flag_threads(&mut args);640 flag_trim(&mut args);641 flag_type(&mut args);642 flag_type_add(&mut args);643 flag_type_clear(&mut args);644 flag_type_list(&mut args);645 flag_type_not(&mut args);646 flag_unrestricted(&mut args);647 flag_vimgrep(&mut args);648 flag_with_filename(&mut args);649 flag_word_regexp(&mut args);650 args651}652653fn arg_pattern(args: &mut Vec<RGArg>) {654 const SHORT: &str = "A regular expression used for searching.";655 const LONG: &str = long!(656 "\657A regular expression used for searching. To match a pattern beginning with a658dash, use the -e/--regexp flag.659660For example, to search for the literal '-foo', you can use this flag:661662 rg -e -foo663664You can also use the special '--' delimiter to indicate that no more flags665will be provided. Namely, the following is equivalent to the above:666667 rg -- -foo668"669 );670 let arg = RGArg::positional("pattern", "PATTERN")671 .help(SHORT)672 .long_help(LONG)673 .required_unless(&[674 "file",675 "files",676 "regexp",677 "type-list",678 "pcre2-version",679 ]);680 args.push(arg);681}682683fn arg_path(args: &mut Vec<RGArg>) {684 const SHORT: &str = "A file or directory to search.";685 const LONG: &str = long!(686 "\687A file or directory to search. Directories are searched recursively. File \688paths specified on the command line override glob and ignore rules. \689"690 );691 let arg = RGArg::positional("path", "PATH")692 .help(SHORT)693 .long_help(LONG)694 .multiple();695 args.push(arg);696}697698fn flag_after_context(args: &mut Vec<RGArg>) {699 const SHORT: &str = "Show NUM lines after each match.";700 const LONG: &str = long!(701 "\702Show NUM lines after each match.703704This overrides the --passthru flag and partially overrides --context.705"706 );707 let arg = RGArg::flag("after-context", "NUM")708 .short("A")709 .help(SHORT)710 .long_help(LONG)711 .number()712 .overrides("passthru");713 args.push(arg);714}715716fn flag_auto_hybrid_regex(args: &mut Vec<RGArg>) {717 const SHORT: &str = "Dynamically use PCRE2 if necessary.";718 const LONG: &str = long!(719 "\720DEPRECATED. Use --engine instead.721722When this flag is used, ripgrep will dynamically choose between supported regex723engines depending on the features used in a pattern. When ripgrep chooses a724regex engine, it applies that choice for every regex provided to ripgrep (e.g.,725via multiple -e/--regexp or -f/--file flags).726727As an example of how this flag might behave, ripgrep will attempt to use728its default finite automata based regex engine whenever the pattern can be729successfully compiled with that regex engine. If PCRE2 is enabled and if the730pattern given could not be compiled with the default regex engine, then PCRE2731will be automatically used for searching. If PCRE2 isn't available, then this732flag has no effect because there is only one regex engine to choose from.733734In the future, ripgrep may adjust its heuristics for how it decides which735regex engine to use. In general, the heuristics will be limited to a static736analysis of the patterns, and not to any specific runtime behavior observed737while searching files.738739The primary downside of using this flag is that it may not always be obvious740which regex engine ripgrep uses, and thus, the match semantics or performance741profile of ripgrep may subtly and unexpectedly change. However, in many cases,742all regex engines will agree on what constitutes a match and it can be nice743to transparently support more advanced regex features like look-around and744backreferences without explicitly needing to enable them.745746This flag can be disabled with --no-auto-hybrid-regex.747"748 );749 let arg = RGArg::switch("auto-hybrid-regex")750 .help(SHORT)751 .long_help(LONG)752 .overrides("no-auto-hybrid-regex")753 .overrides("pcre2")754 .overrides("no-pcre2")755 .overrides("engine");756 args.push(arg);757758 let arg = RGArg::switch("no-auto-hybrid-regex")759 .hidden()760 .overrides("auto-hybrid-regex")761 .overrides("pcre2")762 .overrides("no-pcre2")763 .overrides("engine");764 args.push(arg);765}766767fn flag_before_context(args: &mut Vec<RGArg>) {768 const SHORT: &str = "Show NUM lines before each match.";769 const LONG: &str = long!(770 "\771Show NUM lines before each match.772773This overrides the --passthru flag and partially overrides --context.774"775 );776 let arg = RGArg::flag("before-context", "NUM")777 .short("B")778 .help(SHORT)779 .long_help(LONG)780 .number()781 .overrides("passthru");782 args.push(arg);783}784785fn flag_binary(args: &mut Vec<RGArg>) {786 const SHORT: &str = "Search binary files.";787 const LONG: &str = long!(788 "\789Enabling this flag will cause ripgrep to search binary files. By default,790ripgrep attempts to automatically skip binary files in order to improve the791relevance of results and make the search faster.792793Binary files are heuristically detected based on whether they contain a NUL794byte or not. By default (without this flag set), once a NUL byte is seen,795ripgrep will stop searching the file. Usually, NUL bytes occur in the beginning796of most binary files. If a NUL byte occurs after a match, then ripgrep will797still stop searching the rest of the file, but a warning will be printed.798799In contrast, when this flag is provided, ripgrep will continue searching a file800even if a NUL byte is found. In particular, if a NUL byte is found then ripgrep801will continue searching until either a match is found or the end of the file is802reached, whichever comes sooner. If a match is found, then ripgrep will stop803and print a warning saying that the search stopped prematurely.804805If you want ripgrep to search a file without any special NUL byte handling at806all (and potentially print binary data to stdout), then you should use the807'-a/--text' flag.808809The '--binary' flag is a flag for controlling ripgrep's automatic filtering810mechanism. As such, it does not need to be used when searching a file811explicitly or when searching stdin. That is, it is only applicable when812recursively searching a directory.813814Note that when the '-u/--unrestricted' flag is provided for a third time, then815this flag is automatically enabled.816817This flag can be disabled with '--no-binary'. It overrides the '-a/--text'818flag.819"820 );821 let arg = RGArg::switch("binary")822 .help(SHORT)823 .long_help(LONG)824 .overrides("no-binary")825 .overrides("text")826 .overrides("no-text");827 args.push(arg);828829 let arg = RGArg::switch("no-binary")830 .hidden()831 .overrides("binary")832 .overrides("text")833 .overrides("no-text");834 args.push(arg);835}836837fn flag_block_buffered(args: &mut Vec<RGArg>) {838 const SHORT: &str = "Force block buffering.";839 const LONG: &str = long!(840 "\841When enabled, ripgrep will use block buffering. That is, whenever a matching842line is found, it will be written to an in-memory buffer and will not be843written to stdout until the buffer reaches a certain size. This is the default844when ripgrep's stdout is redirected to a pipeline or a file. When ripgrep's845stdout is connected to a terminal, line buffering will be used. Forcing block846buffering can be useful when dumping a large amount of contents to a terminal.847848Forceful block buffering can be disabled with --no-block-buffered. Note that849using --no-block-buffered causes ripgrep to revert to its default behavior of850automatically detecting the buffering strategy. To force line buffering, use851the --line-buffered flag.852"853 );854 let arg = RGArg::switch("block-buffered")855 .help(SHORT)856 .long_help(LONG)857 .overrides("no-block-buffered")858 .overrides("line-buffered")859 .overrides("no-line-buffered");860 args.push(arg);861862 let arg = RGArg::switch("no-block-buffered")863 .hidden()864 .overrides("block-buffered")865 .overrides("line-buffered")866 .overrides("no-line-buffered");867 args.push(arg);868}869870fn flag_byte_offset(args: &mut Vec<RGArg>) {871 const SHORT: &str =872 "Print the 0-based byte offset for each matching line.";873 const LONG: &str = long!(874 "\875Print the 0-based byte offset within the input file before each line of output.876If -o (--only-matching) is specified, print the offset of the matching part877itself.878879If ripgrep does transcoding, then the byte offset is in terms of the result of880transcoding and not the original data. This applies similarly to another881transformation on the source, such as decompression or a --pre filter. Note882that when the PCRE2 regex engine is used, then UTF-8 transcoding is done by883default.884"885 );886 let arg =887 RGArg::switch("byte-offset").short("b").help(SHORT).long_help(LONG);888 args.push(arg);889}890891fn flag_case_sensitive(args: &mut Vec<RGArg>) {892 const SHORT: &str = "Search case sensitively (default).";893 const LONG: &str = long!(894 "\895Search case sensitively.896897This overrides the -i/--ignore-case and -S/--smart-case flags.898"899 );900 let arg = RGArg::switch("case-sensitive")901 .short("s")902 .help(SHORT)903 .long_help(LONG)904 .overrides("ignore-case")905 .overrides("smart-case");906 args.push(arg);907}908909fn flag_color(args: &mut Vec<RGArg>) {910 const SHORT: &str = "Controls when to use color.";911 const LONG: &str = long!(912 "\913This flag controls when to use colors. The default setting is 'auto', which914means ripgrep will try to guess when to use colors. For example, if ripgrep is915printing to a terminal, then it will use colors, but if it is redirected to a916file or a pipe, then it will suppress color output. ripgrep will suppress color917output in some other circumstances as well. For example, if the TERM918environment variable is not set or set to 'dumb', then ripgrep will not use919colors.920921The possible values for this flag are:922923 never Colors will never be used.924 auto The default. ripgrep tries to be smart.925 always Colors will always be used regardless of where output is sent.926 ansi Like 'always', but emits ANSI escapes (even in a Windows console).927928When the --vimgrep flag is given to ripgrep, then the default value for the929--color flag changes to 'never'.930"931 );932 let arg = RGArg::flag("color", "WHEN")933 .help(SHORT)934 .long_help(LONG)935 .possible_values(&["never", "auto", "always", "ansi"])936 .default_value_if("never", "vimgrep");937 args.push(arg);938}939940fn flag_colors(args: &mut Vec<RGArg>) {941 const SHORT: &str = "Configure color settings and styles.";942 const LONG: &str = long!(943 "\944This flag specifies color settings for use in the output. This flag may be945provided multiple times. Settings are applied iteratively. Colors are limited946to one of eight choices: red, blue, green, cyan, magenta, yellow, white and947black. Styles are limited to nobold, bold, nointense, intense, nounderline948or underline.949950The format of the flag is '{type}:{attribute}:{value}'. '{type}' should be951one of path, line, column or match. '{attribute}' can be fg, bg or style.952'{value}' is either a color (for fg and bg) or a text style. A special format,953'{type}:none', will clear all color settings for '{type}'.954955For example, the following command will change the match color to magenta and956the background color for line numbers to yellow:957958 rg --colors 'match:fg:magenta' --colors 'line:bg:yellow' foo.959960Extended colors can be used for '{value}' when the terminal supports ANSI color961sequences. These are specified as either 'x' (256-color) or 'x,x,x' (24-bit962truecolor) where x is a number between 0 and 255 inclusive. x may be given as963a normal decimal number or a hexadecimal number, which is prefixed by `0x`.964965For example, the following command will change the match background color to966that represented by the rgb value (0,128,255):967968 rg --colors 'match:bg:0,128,255'969970or, equivalently,971972 rg --colors 'match:bg:0x0,0x80,0xFF'973974Note that the intense and nointense style flags will have no effect when975used alongside these extended color codes.976"977 );978 let arg = RGArg::flag("colors", "COLOR_SPEC")979 .help(SHORT)980 .long_help(LONG)981 .multiple();982 args.push(arg);983}984985fn flag_column(args: &mut Vec<RGArg>) {986 const SHORT: &str = "Show column numbers.";987 const LONG: &str = long!(988 "\989Show column numbers (1-based). This only shows the column numbers for the first990match on each line. This does not try to account for Unicode. One byte is equal991to one column. This implies --line-number.992993This flag can be disabled with --no-column.994"995 );996 let arg = RGArg::switch("column")997 .help(SHORT)998 .long_help(LONG)999 .overrides("no-column");1000 args.push(arg);10011002 let arg = RGArg::switch("no-column").hidden().overrides("column");1003 args.push(arg);1004}10051006fn flag_context(args: &mut Vec<RGArg>) {1007 const SHORT: &str = "Show NUM lines before and after each match.";1008 const LONG: &str = long!(1009 "\1010Show NUM lines before and after each match. This is equivalent to providing1011both the -B/--before-context and -A/--after-context flags with the same value.10121013This overrides the --passthru flag.1014"1015 );1016 let arg = RGArg::flag("context", "NUM")1017 .short("C")1018 .help(SHORT)1019 .long_help(LONG)1020 .number()1021 .overrides("passthru");1022 args.push(arg);1023}10241025fn flag_context_separator(args: &mut Vec<RGArg>) {1026 const SHORT: &str = "Set the context separator string.";1027 const LONG: &str = long!(1028 "\1029The string used to separate non-contiguous context lines in the output. This1030is only used when one of the context flags is used (-A, -B or -C). Escape1031sequences like \\x7F or \\t may be used. The default value is --.10321033When the context separator is set to an empty string, then a line break1034is still inserted. To completely disable context separators, use the1035--no-context-separator flag.1036"1037 );10381039 let arg = RGArg::flag("context-separator", "SEPARATOR")1040 .help(SHORT)1041 .long_help(LONG)1042 .overrides("no-context-separator");1043 args.push(arg);10441045 let arg = RGArg::switch("no-context-separator")1046 .hidden()1047 .overrides("context-separator");1048 args.push(arg);1049}10501051fn flag_count(args: &mut Vec<RGArg>) {1052 const SHORT: &str = "Only show the count of matching lines for each file.";1053 const LONG: &str = long!(1054 "\1055This flag suppresses normal output and shows the number of lines that match1056the given patterns for each file searched. Each file containing a match has its1057path and count printed on each line. Note that this reports the number of lines1058that match and not the total number of matches, unless -U/--multiline is1059enabled. In multiline mode, --count is equivalent to --count-matches.10601061If only one file is given to ripgrep, then only the count is printed if there1062is a match. The --with-filename flag can be used to force printing the file1063path in this case. If you need a count to be printed regardless of whether1064there is a match, then use --include-zero.10651066This overrides the --count-matches flag. Note that when --count is combined1067with --only-matching, then ripgrep behaves as if --count-matches was given.1068"1069 );1070 let arg = RGArg::switch("count")1071 .short("c")1072 .help(SHORT)1073 .long_help(LONG)1074 .overrides("count-matches");1075 args.push(arg);1076}10771078fn flag_count_matches(args: &mut Vec<RGArg>) {1079 const SHORT: &str =1080 "Only show the count of individual matches for each file.";1081 const LONG: &str = long!(1082 "\1083This flag suppresses normal output and shows the number of individual1084matches of the given patterns for each file searched. Each file1085containing matches has its path and match count printed on each line.1086Note that this reports the total number of individual matches and not1087the number of lines that match.10881089If only one file is given to ripgrep, then only the count is printed if there1090is a match. The --with-filename flag can be used to force printing the file1091path in this case.10921093This overrides the --count flag. Note that when --count is combined with1094--only-matching, then ripgrep behaves as if --count-matches was given.1095"1096 );1097 let arg = RGArg::switch("count-matches")1098 .help(SHORT)1099 .long_help(LONG)1100 .overrides("count");1101 args.push(arg);1102}11031104fn flag_crlf(args: &mut Vec<RGArg>) {1105 const SHORT: &str = "Support CRLF line terminators (useful on Windows).";1106 const LONG: &str = long!(1107 "\1108When enabled, ripgrep will treat CRLF ('\\r\\n') as a line terminator instead1109of just '\\n'.11101111Principally, this permits '$' in regex patterns to match just before CRLF1112instead of just before LF. The underlying regex engine may not support this1113natively, so ripgrep will translate all instances of '$' to '(?:\\r??$)'. This1114may produce slightly different than desired match offsets. It is intended as a1115work-around until the regex engine supports this natively.11161117CRLF support can be disabled with --no-crlf.1118"1119 );1120 let arg = RGArg::switch("crlf")1121 .help(SHORT)1122 .long_help(LONG)1123 .overrides("no-crlf")1124 .overrides("null-data");1125 args.push(arg);11261127 let arg = RGArg::switch("no-crlf").hidden().overrides("crlf");1128 args.push(arg);1129}11301131fn flag_debug(args: &mut Vec<RGArg>) {1132 const SHORT: &str = "Show debug messages.";1133 const LONG: &str = long!(1134 "\1135Show debug messages. Please use this when filing a bug report.11361137The --debug flag is generally useful for figuring out why ripgrep skipped1138searching a particular file. The debug messages should mention all files1139skipped and why they were skipped.11401141To get even more debug output, use the --trace flag, which implies --debug1142along with additional trace data. With --trace, the output could be quite1143large and is generally more useful for development.1144"1145 );1146 let arg = RGArg::switch("debug").help(SHORT).long_help(LONG);1147 args.push(arg);11481149 let arg = RGArg::switch("trace").hidden().overrides("debug");1150 args.push(arg);1151}11521153fn flag_dfa_size_limit(args: &mut Vec<RGArg>) {1154 const SHORT: &str = "The upper size limit of the regex DFA.";1155 const LONG: &str = long!(1156 "\1157The upper size limit of the regex DFA. The default limit is 10M. This should1158only be changed on very large regex inputs where the (slower) fallback regex1159engine may otherwise be used if the limit is reached.11601161The argument accepts the same size suffixes as allowed in with the1162--max-filesize flag.1163"1164 );1165 let arg = RGArg::flag("dfa-size-limit", "NUM+SUFFIX?")1166 .help(SHORT)1167 .long_help(LONG);1168 args.push(arg);1169}11701171fn flag_encoding(args: &mut Vec<RGArg>) {1172 const SHORT: &str = "Specify the text encoding of files to search.";1173 const LONG: &str = long!(1174 "\1175Specify the text encoding that ripgrep will use on all files searched. The1176default value is 'auto', which will cause ripgrep to do a best effort automatic1177detection of encoding on a per-file basis. Automatic detection in this case1178only applies to files that begin with a UTF-8 or UTF-16 byte-order mark (BOM).1179No other automatic detection is performed. One can also specify 'none' which1180will then completely disable BOM sniffing and always result in searching the1181raw bytes, including a BOM if it's present, regardless of its encoding.11821183Other supported values can be found in the list of labels here:1184https://encoding.spec.whatwg.org/#concept-encoding-get11851186For more details on encoding and how ripgrep deals with it, see GUIDE.md.11871188This flag can be disabled with --no-encoding.1189"1190 );1191 let arg = RGArg::flag("encoding", "ENCODING")1192 .short("E")1193 .help(SHORT)1194 .long_help(LONG);1195 args.push(arg);11961197 let arg = RGArg::switch("no-encoding").hidden().overrides("encoding");1198 args.push(arg);1199}12001201fn flag_engine(args: &mut Vec<RGArg>) {1202 const SHORT: &str = "Specify which regexp engine to use.";1203 const LONG: &str = long!(1204 "\1205Specify which regular expression engine to use. When you choose a regex engine,1206it applies that choice for every regex provided to ripgrep (e.g., via multiple1207-e/--regexp or -f/--file flags).12081209Accepted values are 'default', 'pcre2', or 'auto'.12101211The default value is 'default', which is the fastest and should be good for1212most use cases. The 'pcre2' engine is generally useful when you want to use1213features such as look-around or backreferences. 'auto' will dynamically choose1214between supported regex engines depending on the features used in a pattern on1215a best effort basis.12161217Note that the 'pcre2' engine is an optional ripgrep feature. If PCRE2 wasn't1218included in your build of ripgrep, then using this flag will result in ripgrep1219printing an error message and exiting.12201221This overrides previous uses of --pcre2 and --auto-hybrid-regex flags.1222"1223 );1224 let arg = RGArg::flag("engine", "ENGINE")1225 .help(SHORT)1226 .long_help(LONG)1227 .possible_values(&["default", "pcre2", "auto"])1228 .default_value("default")1229 .overrides("pcre2")1230 .overrides("no-pcre2")1231 .overrides("auto-hybrid-regex")1232 .overrides("no-auto-hybrid-regex");1233 args.push(arg);1234}12351236fn flag_field_context_separator(args: &mut Vec<RGArg>) {1237 const SHORT: &str = "Set the field context separator.";1238 const LONG: &str = long!(1239 "\1240Set the field context separator, which is used to delimit file paths, line1241numbers, columns and the context itself, when printing contextual lines. The1242separator may be any number of bytes, including zero. Escape sequences like1243\\x7F or \\t may be used. The '-' character is the default value.1244"1245 );1246 let arg = RGArg::flag("field-context-separator", "SEPARATOR")1247 .help(SHORT)1248 .long_help(LONG);1249 args.push(arg);1250}12511252fn flag_field_match_separator(args: &mut Vec<RGArg>) {1253 const SHORT: &str = "Set the match separator.";1254 const LONG: &str = long!(1255 "\1256Set the field match separator, which is used to delimit file paths, line1257numbers, columns and the match itself. The separator may be any number of1258bytes, including zero. Escape sequences like \\x7F or \\t may be used. The ':'1259character is the default value.1260"1261 );1262 let arg = RGArg::flag("field-match-separator", "SEPARATOR")1263 .help(SHORT)1264 .long_help(LONG);1265 args.push(arg);1266}12671268fn flag_file(args: &mut Vec<RGArg>) {1269 const SHORT: &str = "Search for patterns from the given file.";1270 const LONG: &str = long!(1271 "\1272Search for patterns from the given file, with one pattern per line. When this1273flag is used multiple times or in combination with the -e/--regexp flag,1274then all patterns provided are searched. Empty pattern lines will match all1275input lines, and the newline is not counted as part of the pattern.12761277A line is printed if and only if it matches at least one of the patterns.1278"1279 );1280 let arg = RGArg::flag("file", "PATTERNFILE")1281 .short("f")1282 .help(SHORT)1283 .long_help(LONG)1284 .multiple()1285 .allow_leading_hyphen();1286 args.push(arg);1287}12881289fn flag_files(args: &mut Vec<RGArg>) {1290 const SHORT: &str = "Print each file that would be searched.";1291 const LONG: &str = long!(1292 "\1293Print each file that would be searched without actually performing the search.1294This is useful to determine whether a particular file is being searched or not.1295"1296 );1297 let arg = RGArg::switch("files")1298 .help(SHORT)1299 .long_help(LONG)1300 // This also technically conflicts with pattern, but the first file1301 // path will actually be in pattern.1302 .conflicts(&["file", "regexp", "type-list"]);1303 args.push(arg);1304}13051306fn flag_files_with_matches(args: &mut Vec<RGArg>) {1307 const SHORT: &str = "Print the paths with at least one match.";1308 const LONG: &str = long!(1309 "\1310Print the paths with at least one match and suppress match contents.13111312This overrides --files-without-match.1313"1314 );1315 let arg = RGArg::switch("files-with-matches")1316 .short("l")1317 .help(SHORT)1318 .long_help(LONG)1319 .overrides("files-without-match");1320 args.push(arg);1321}13221323fn flag_files_without_match(args: &mut Vec<RGArg>) {1324 const SHORT: &str = "Print the paths that contain zero matches.";1325 const LONG: &str = long!(1326 "\1327Print the paths that contain zero matches and suppress match contents. This1328inverts/negates the --files-with-matches flag.13291330This overrides --files-with-matches.1331"1332 );1333 let arg = RGArg::switch("files-without-match")1334 .help(SHORT)1335 .long_help(LONG)1336 .overrides("files-with-matches");1337 args.push(arg);1338}13391340fn flag_fixed_strings(args: &mut Vec<RGArg>) {1341 const SHORT: &str = "Treat the pattern as a literal string.";1342 const LONG: &str = long!(1343 "\1344Treat the pattern as a literal string instead of a regular expression. When1345this flag is used, special regular expression meta characters such as .(){}*+1346do not need to be escaped.13471348This flag can be disabled with --no-fixed-strings.1349"1350 );1351 let arg = RGArg::switch("fixed-strings")1352 .short("F")1353 .help(SHORT)1354 .long_help(LONG)1355 .overrides("no-fixed-strings");1356 args.push(arg);13571358 let arg =1359 RGArg::switch("no-fixed-strings").hidden().overrides("fixed-strings");1360 args.push(arg);1361}13621363fn flag_follow(args: &mut Vec<RGArg>) {1364 const SHORT: &str = "Follow symbolic links.";1365 const LONG: &str = long!(1366 "\1367When this flag is enabled, ripgrep will follow symbolic links while traversing1368directories. This is disabled by default. Note that ripgrep will check for1369symbolic link loops and report errors if it finds one.13701371This flag can be disabled with --no-follow.1372"1373 );1374 let arg = RGArg::switch("follow")1375 .short("L")1376 .help(SHORT)1377 .long_help(LONG)1378 .overrides("no-follow");1379 args.push(arg);13801381 let arg = RGArg::switch("no-follow").hidden().overrides("follow");1382 args.push(arg);1383}13841385fn flag_glob(args: &mut Vec<RGArg>) {1386 const SHORT: &str = "Include or exclude files.";1387 const LONG: &str = long!(1388 "\1389Include or exclude files and directories for searching that match the given1390glob. This always overrides any other ignore logic. Multiple glob flags may be1391used. Globbing rules match .gitignore globs. Precede a glob with a ! to exclude1392it. If multiple globs match a file or directory, the glob given later in the1393command line takes precedence.13941395As an extension, globs support specifying alternatives: *-g ab{c,d}* is1396equivalent to *-g abc -g abd*. Empty alternatives like *-g ab{,c}* are not1397currently supported. Note that this syntax extension is also currently enabled1398in gitignore files, even though this syntax isn't supported by git itself.1399ripgrep may disable this syntax extension in gitignore files, but it will1400always remain available via the -g/--glob flag.14011402When this flag is set, every file and directory is applied to it to test for1403a match. So for example, if you only want to search in a particular directory1404'foo', then *-g foo* is incorrect because 'foo/bar' does not match the glob1405'foo'. Instead, you should use *-g 'foo/**'*.1406"1407 );1408 let arg = RGArg::flag("glob", "GLOB")1409 .short("g")1410 .help(SHORT)1411 .long_help(LONG)1412 .multiple()1413 .allow_leading_hyphen();1414 args.push(arg);1415}14161417fn flag_glob_case_insensitive(args: &mut Vec<RGArg>) {1418 const SHORT: &str = "Process all glob patterns case insensitively.";1419 const LONG: &str = long!(1420 "\1421Process glob patterns given with the -g/--glob flag case insensitively. This1422effectively treats --glob as --iglob.14231424This flag can be disabled with the --no-glob-case-insensitive flag.1425"1426 );1427 let arg = RGArg::switch("glob-case-insensitive")1428 .help(SHORT)1429 .long_help(LONG)1430 .overrides("no-glob-case-insensitive");1431 args.push(arg);14321433 let arg = RGArg::switch("no-glob-case-insensitive")1434 .hidden()1435 .overrides("glob-case-insensitive");1436 args.push(arg);1437}14381439fn flag_heading(args: &mut Vec<RGArg>) {1440 const SHORT: &str = "Print matches grouped by each file.";1441 const LONG: &str = long!(1442 "\1443This flag prints the file path above clusters of matches from each file instead1444of printing the file path as a prefix for each matched line. This is the1445default mode when printing to a terminal.14461447This overrides the --no-heading flag.1448"1449 );1450 let arg = RGArg::switch("heading")1451 .help(SHORT)1452 .long_help(LONG)1453 .overrides("no-heading");1454 args.push(arg);14551456 const NO_SHORT: &str = "Don't group matches by each file.";1457 const NO_LONG: &str = long!(1458 "\1459Don't group matches by each file. If --no-heading is provided in addition to1460the -H/--with-filename flag, then file paths will be printed as a prefix for1461every matched line. This is the default mode when not printing to a terminal.14621463This overrides the --heading flag.1464"1465 );1466 let arg = RGArg::switch("no-heading")1467 .help(NO_SHORT)1468 .long_help(NO_LONG)1469 .overrides("heading");1470 args.push(arg);1471}14721473fn flag_hidden(args: &mut Vec<RGArg>) {1474 const SHORT: &str = "Search hidden files and directories.";1475 const LONG: &str = long!(1476 "\1477Search hidden files and directories. By default, hidden files and directories1478are skipped. Note that if a hidden file or a directory is whitelisted in an1479ignore file, then it will be searched even if this flag isn't provided.14801481A file or directory is considered hidden if its base name starts with a dot1482character ('.'). On operating systems which support a `hidden` file attribute,1483like Windows, files with this attribute are also considered hidden.14841485This flag can be disabled with --no-hidden.1486"1487 );1488 let arg = RGArg::switch("hidden")1489 .short(".")1490 .help(SHORT)1491 .long_help(LONG)1492 .overrides("no-hidden");1493 args.push(arg);14941495 let arg = RGArg::switch("no-hidden").hidden().overrides("hidden");1496 args.push(arg);1497}14981499fn flag_hostname_bin(args: &mut Vec<RGArg>) {1500 const SHORT: &str = "Run a program to get this system's hostname.";1501 const LONG: &str = long!(1502 "\1503This flag controls how ripgrep determines this system's hostname. The flag's1504value should correspond to an executable (either a path or something that can1505be found via your system's *PATH* environment variable). When set, ripgrep will1506run this executable, with no arguments, and treat its output (with leading and1507trailing whitespace stripped) as your system's hostname.15081509When not set (the default, or the empty string), ripgrep will try to1510automatically detect your system's hostname. On Unix, this corresponds1511to calling *gethostname*. On Windows, this corresponds to calling1512*GetComputerNameExW* to fetch the system's \"physical DNS hostname.\"15131514ripgrep uses your system's hostname for producing hyperlinks.1515"1516 );1517 let arg =1518 RGArg::flag("hostname-bin", "COMMAND").help(SHORT).long_help(LONG);1519 args.push(arg);1520}15211522fn flag_hyperlink_format(args: &mut Vec<RGArg>) {1523 const SHORT: &str = "Set the format of hyperlinks to match results.";1524 const LONG: &str = long!(1525 "\1526Set the format of hyperlinks to match results. Hyperlinks make certain elements1527of ripgrep's output, such as file paths, clickable. This generally only works1528in terminal emulators that support OSC-8 hyperlinks. For example, the format1529file://{host}{path} will emit an RFC 8089 hyperlink. To see the format that1530ripgrep is using, pass the --debug flag.15311532Alternatively, a format string may correspond to one of the following aliases:1533default, file, grep+, kitty, macvim, none, textmate, vscode, vscode-insiders,1534vscodium. The alias will be replaced with a format string that is intended to1535work for the corresponding application.15361537The following variables are available in the format string:15381539{path}: Required. This is replaced with a path to a matching file. The1540path is guaranteed to be absolute and percent encoded such that it is valid to1541put into a URI. Note that a path is guaranteed to start with a /.15421543{host}: Optional. This is replaced with your system's hostname. On Unix,1544this corresponds to calling 'gethostname'. On Windows, this corresponds to1545calling 'GetComputerNameExW' to fetch the system's \"physical DNS hostname.\"1546Alternatively, if --hostname-bin was provided, then the hostname returned from1547the output of that program will be returned. If no hostname could be found,1548then this variable is replaced with the empty string.15491550{line}: Optional. If appropriate, this is replaced with the line number of1551a match. If no line number is available (for example, if --no-line-number was1552given), then it is automatically replaced with the value 1.15531554{column}: Optional, but requires the presence of {line}. If appropriate, this1555is replaced with the column number of a match. If no column number is available1556(for example, if --no-column was given), then it is automatically replaced with1557the value 1.15581559{wslprefix}: Optional. This is a special value that is set to1560wsl$/WSL_DISTRO_NAME, where WSL_DISTRO_NAME corresponds to the value of1561the equivalent environment variable. If the system is not Unix or if the1562WSL_DISTRO_NAME environment variable is not set, then this is replaced with the1563empty string.15641565A format string may be empty. An empty format string is equivalent to the1566'none' alias. In this case, hyperlinks will be disabled.15671568At present, ripgrep does not enable hyperlinks by default. Users must opt into1569them. If you aren't sure what format to use, try 'default'.15701571When ripgrep detects a tty on stdout then hyperlinks are automatically1572disabled, regardless of the value of this flag. Users can pass '--color always'1573to forcefully emit hyperlinks.15741575Note that hyperlinks are only written when a path is also in the output1576and colors are enabled. To write hyperlinks without colors, you'll need to1577configure ripgrep to not colorize anything without actually disabling all ANSI1578escape codes completely:15791580 --colors 'path:none' --colors 'line:none' --colors 'column:none' --colors 'match:none'15811582ripgrep works this way because it treats the --color=(never|always|auto) flag1583as a proxy for whether ANSI escape codes should be used at all. This means1584that environment variables like NO_COLOR=1 and TERM=dumb not only disable1585colors, but hyperlinks as well. Similarly, colors and hyperlinks are disabled1586when ripgrep is not writing to a tty. (Unless one forces the issue by setting1587--color=always.)15881589If you're searching a file directly, for example:15901591 rg foo path/to/file15921593then hyperlinks will not be emitted since the path given does not appear1594in the output. To make the path appear, and thus also a hyperlink, use the1595-H/--with-filename flag.15961597For more information on hyperlinks in terminal emulators, see:1598https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda1599"1600 );1601 let arg =1602 RGArg::flag("hyperlink-format", "FORMAT").help(SHORT).long_help(LONG);1603 args.push(arg);1604}16051606fn flag_iglob(args: &mut Vec<RGArg>) {1607 const SHORT: &str = "Include or exclude files case insensitively.";1608 const LONG: &str = long!(1609 "\1610Include or exclude files and directories for searching that match the given1611glob. This always overrides any other ignore logic. Multiple glob flags may be1612used. Globbing rules match .gitignore globs. Precede a glob with a ! to exclude1613it. Globs are matched case insensitively.1614"1615 );1616 let arg = RGArg::flag("iglob", "GLOB")1617 .help(SHORT)1618 .long_help(LONG)1619 .multiple()1620 .allow_leading_hyphen();1621 args.push(arg);1622}16231624fn flag_ignore_case(args: &mut Vec<RGArg>) {1625 const SHORT: &str = "Case insensitive search.";1626 const LONG: &str = long!(1627 "\1628When this flag is provided, the given patterns will be searched case1629insensitively. The case insensitivity rules used by ripgrep conform to1630Unicode's \"simple\" case folding rules.16311632This flag overrides -s/--case-sensitive and -S/--smart-case.1633"1634 );1635 let arg = RGArg::switch("ignore-case")1636 .short("i")1637 .help(SHORT)1638 .long_help(LONG)1639 .overrides("case-sensitive")1640 .overrides("smart-case");1641 args.push(arg);1642}16431644fn flag_ignore_file(args: &mut Vec<RGArg>) {1645 const SHORT: &str = "Specify additional ignore files.";1646 const LONG: &str = long!(1647 "\1648Specifies a path to one or more .gitignore format rules files. These patterns1649are applied after the patterns found in .gitignore and .ignore are applied1650and are matched relative to the current working directory. Multiple additional1651ignore files can be specified by using the --ignore-file flag several times.1652When specifying multiple ignore files, earlier files have lower precedence1653than later files.16541655If you are looking for a way to include or exclude files and directories1656directly on the command line, then use -g instead.1657"1658 );1659 let arg = RGArg::flag("ignore-file", "PATH")1660 .help(SHORT)1661 .long_help(LONG)1662 .multiple()1663 .allow_leading_hyphen();1664 args.push(arg);1665}16661667fn flag_ignore_file_case_insensitive(args: &mut Vec<RGArg>) {1668 const SHORT: &str = "Process ignore files case insensitively.";1669 const LONG: &str = long!(1670 "\1671Process ignore files (.gitignore, .ignore, etc.) case insensitively. Note that1672this comes with a performance penalty and is most useful on case insensitive1673file systems (such as Windows).16741675This flag can be disabled with the --no-ignore-file-case-insensitive flag.1676"1677 );1678 let arg = RGArg::switch("ignore-file-case-insensitive")1679 .help(SHORT)1680 .long_help(LONG)1681 .overrides("no-ignore-file-case-insensitive");1682 args.push(arg);16831684 let arg = RGArg::switch("no-ignore-file-case-insensitive")1685 .hidden()1686 .overrides("ignore-file-case-insensitive");1687 args.push(arg);1688}16891690fn flag_include_zero(args: &mut Vec<RGArg>) {1691 const SHORT: &str = "Include files with zero matches in summary";1692 const LONG: &str = long!(1693 "\1694When used with --count or --count-matches, print the number of matches for1695each file even if there were zero matches. This is disabled by default but can1696be enabled to make ripgrep behave more like grep.1697"1698 );1699 let arg = RGArg::switch("include-zero").help(SHORT).long_help(LONG);1700 args.push(arg);1701}17021703fn flag_invert_match(args: &mut Vec<RGArg>) {1704 const SHORT: &str = "Invert matching.";1705 const LONG: &str = long!(1706 "\1707Invert matching. Show lines that do not match the given patterns.1708"1709 );1710 let arg =1711 RGArg::switch("invert-match").short("v").help(SHORT).long_help(LONG);1712 args.push(arg);1713}17141715fn flag_json(args: &mut Vec<RGArg>) {1716 const SHORT: &str = "Show search results in a JSON Lines format.";1717 const LONG: &str = long!(1718 "\1719Enable printing results in a JSON Lines format.17201721When this flag is provided, ripgrep will emit a sequence of messages, each1722encoded as a JSON object, where there are five different message types:17231724**begin** - A message that indicates a file is being searched and contains at1725least one match.17261727**end** - A message the indicates a file is done being searched. This message1728also include summary statistics about the search for a particular file.17291730**match** - A message that indicates a match was found. This includes the text1731and offsets of the match.17321733**context** - A message that indicates a contextual line was found. This1734includes the text of the line, along with any match information if the search1735was inverted.17361737**summary** - The final message emitted by ripgrep that contains summary1738statistics about the search across all files.17391740Since file paths or the contents of files are not guaranteed to be valid UTF-81741and JSON itself must be representable by a Unicode encoding, ripgrep will emit1742all data elements as objects with one of two keys: 'text' or 'bytes'. 'text' is1743a normal JSON string when the data is valid UTF-8 while 'bytes' is the base641744encoded contents of the data.17451746The JSON Lines format is only supported for showing search results. It cannot1747be used with other flags that emit other types of output, such as --files,1748--files-with-matches, --files-without-match, --count or --count-matches.1749ripgrep will report an error if any of the aforementioned flags are used in1750concert with --json.17511752Other flags that control aspects of the standard output such as1753--only-matching, --heading, --replace, --max-columns, etc., have no effect1754when --json is set.17551756A more complete description of the JSON format used can be found here:1757https://docs.rs/grep-printer/*/grep_printer/struct.JSON.html17581759The JSON Lines format can be disabled with --no-json.1760"1761 );1762 let arg = RGArg::switch("json")1763 .help(SHORT)1764 .long_help(LONG)1765 .overrides("no-json")1766 .conflicts(&[1767 "count",1768 "count-matches",1769 "files",1770 "files-with-matches",1771 "files-without-match",1772 ]);1773 args.push(arg);17741775 let arg = RGArg::switch("no-json").hidden().overrides("json");1776 args.push(arg);1777}17781779fn flag_line_buffered(args: &mut Vec<RGArg>) {1780 const SHORT: &str = "Force line buffering.";1781 const LONG: &str = long!(1782 "\1783When enabled, ripgrep will use line buffering. That is, whenever a matching1784line is found, it will be flushed to stdout immediately. This is the default1785when ripgrep's stdout is connected to a terminal, but otherwise, ripgrep will1786use block buffering, which is typically faster. This flag forces ripgrep to1787use line buffering even if it would otherwise use block buffering. This is1788typically useful in shell pipelines, e.g.,1789'tail -f something.log | rg foo --line-buffered | rg bar'.17901791Forceful line buffering can be disabled with --no-line-buffered. Note that1792using --no-line-buffered causes ripgrep to revert to its default behavior of1793automatically detecting the buffering strategy. To force block buffering, use1794the --block-buffered flag.1795"1796 );1797 let arg = RGArg::switch("line-buffered")1798 .help(SHORT)1799 .long_help(LONG)1800 .overrides("no-line-buffered")1801 .overrides("block-buffered")1802 .overrides("no-block-buffered");1803 args.push(arg);18041805 let arg = RGArg::switch("no-line-buffered")1806 .hidden()1807 .overrides("line-buffered")1808 .overrides("block-buffered")1809 .overrides("no-block-buffered");1810 args.push(arg);1811}18121813fn flag_line_number(args: &mut Vec<RGArg>) {1814 const SHORT: &str = "Show line numbers.";1815 const LONG: &str = long!(1816 "\1817Show line numbers (1-based). This is enabled by default when searching in a1818terminal.18191820This flag overrides --no-line-number.1821"1822 );1823 let arg = RGArg::switch("line-number")1824 .short("n")1825 .help(SHORT)1826 .long_help(LONG)1827 .overrides("no-line-number");1828 args.push(arg);18291830 const NO_SHORT: &str = "Suppress line numbers.";1831 const NO_LONG: &str = long!(1832 "\1833Suppress line numbers. This is enabled by default when not searching in a1834terminal.18351836This flag overrides --line-number.1837"1838 );1839 let arg = RGArg::switch("no-line-number")1840 .short("N")1841 .help(NO_SHORT)1842 .long_help(NO_LONG)1843 .overrides("line-number");1844 args.push(arg);1845}18461847fn flag_line_regexp(args: &mut Vec<RGArg>) {1848 const SHORT: &str = "Only show matches surrounded by line boundaries.";1849 const LONG: &str = long!(1850 "\1851Only show matches surrounded by line boundaries. This is equivalent to putting1852^...$ around all of the search patterns. In other words, this only prints lines1853where the entire line participates in a match.18541855This overrides the --word-regexp flag.1856"1857 );1858 let arg = RGArg::switch("line-regexp")1859 .short("x")1860 .help(SHORT)1861 .long_help(LONG)1862 .overrides("word-regexp");1863 args.push(arg);1864}18651866fn flag_max_columns(args: &mut Vec<RGArg>) {1867 const SHORT: &str = "Don't print lines longer than this limit.";1868 const LONG: &str = long!(1869 "\1870Don't print lines longer than this limit in bytes. Longer lines are omitted,1871and only the number of matches in that line is printed.18721873When this flag is omitted or is set to 0, then it has no effect.1874"1875 );1876 let arg = RGArg::flag("max-columns", "NUM")1877 .short("M")1878 .help(SHORT)1879 .long_help(LONG)1880 .number();1881 args.push(arg);1882}18831884fn flag_max_columns_preview(args: &mut Vec<RGArg>) {1885 const SHORT: &str = "Print a preview for lines exceeding the limit.";1886 const LONG: &str = long!(1887 "\1888When the '--max-columns' flag is used, ripgrep will by default completely1889replace any line that is too long with a message indicating that a matching1890line was removed. When this flag is combined with '--max-columns', a preview1891of the line (corresponding to the limit size) is shown instead, where the part1892of the line exceeding the limit is not shown.18931894If the '--max-columns' flag is not set, then this has no effect.18951896This flag can be disabled with '--no-max-columns-preview'.1897"1898 );1899 let arg = RGArg::switch("max-columns-preview")1900 .help(SHORT)1901 .long_help(LONG)1902 .overrides("no-max-columns-preview");1903 args.push(arg);19041905 let arg = RGArg::switch("no-max-columns-preview")1906 .hidden()1907 .overrides("max-columns-preview");1908 args.push(arg);1909}19101911fn flag_max_count(args: &mut Vec<RGArg>) {1912 const SHORT: &str = "Limit the number of matches.";1913 const LONG: &str = long!(1914 "\1915Limit the number of matching lines per file searched to NUM.1916"1917 );1918 let arg = RGArg::flag("max-count", "NUM")1919 .short("m")1920 .help(SHORT)1921 .long_help(LONG)1922 .number();1923 args.push(arg);1924}19251926fn flag_max_depth(args: &mut Vec<RGArg>) {1927 const SHORT: &str = "Descend at most NUM directories.";1928 const LONG: &str = long!(1929 "\1930Limit the depth of directory traversal to NUM levels beyond the paths given. A1931value of zero only searches the explicitly given paths themselves.19321933For example, 'rg --max-depth 0 dir/' is a no-op because dir/ will not be1934descended into. 'rg --max-depth 1 dir/' will search only the direct children of1935'dir'.1936"1937 );1938 let arg = RGArg::flag("max-depth", "NUM")1939 .help(SHORT)1940 .long_help(LONG)1941 .alias("maxdepth")1942 .number();1943 args.push(arg);1944}19451946fn flag_max_filesize(args: &mut Vec<RGArg>) {1947 const SHORT: &str = "Ignore files larger than NUM in size.";1948 const LONG: &str = long!(1949 "\1950Ignore files larger than NUM in size. This does not apply to directories.19511952The input format accepts suffixes of K, M or G which correspond to kilobytes,1953megabytes and gigabytes, respectively. If no suffix is provided the input is1954treated as bytes.19551956Examples: --max-filesize 50K or --max-filesize 80M1957"1958 );1959 let arg =1960 RGArg::flag("max-filesize", "NUM+SUFFIX?").help(SHORT).long_help(LONG);1961 args.push(arg);1962}19631964fn flag_mmap(args: &mut Vec<RGArg>) {1965 const SHORT: &str = "Search using memory maps when possible.";1966 const LONG: &str = long!(1967 "\1968Search using memory maps when possible. This is enabled by default when ripgrep1969thinks it will be faster.19701971Memory map searching doesn't currently support all options, so if an1972incompatible option (e.g., --context) is given with --mmap, then memory maps1973will not be used.19741975Note that ripgrep may abort unexpectedly when --mmap if it searches a file that1976is simultaneously truncated.19771978This flag overrides --no-mmap.1979"1980 );1981 let arg =1982 RGArg::switch("mmap").help(SHORT).long_help(LONG).overrides("no-mmap");1983 args.push(arg);19841985 const NO_SHORT: &str = "Never use memory maps.";1986 const NO_LONG: &str = long!(1987 "\1988Never use memory maps, even when they might be faster.19891990This flag overrides --mmap.1991"1992 );1993 let arg = RGArg::switch("no-mmap")1994 .help(NO_SHORT)1995 .long_help(NO_LONG)1996 .overrides("mmap");1997 args.push(arg);1998}19992000fn flag_multiline(args: &mut Vec<RGArg>) {2001 const SHORT: &str = "Enable matching across multiple lines.";2002 const LONG: &str = long!(2003 "\2004Enable matching across multiple lines.20052006When multiline mode is enabled, ripgrep will lift the restriction that a match2007cannot include a line terminator. For example, when multiline mode is not2008enabled (the default), then the regex '\\p{any}' will match any Unicode2009codepoint other than '\\n'. Similarly, the regex '\\n' is explicitly forbidden,2010and if you try to use it, ripgrep will return an error. However, when multiline2011mode is enabled, '\\p{any}' will match any Unicode codepoint, including '\\n',2012and regexes like '\\n' are permitted.20132014An important caveat is that multiline mode does not change the match semantics2015of '.'. Namely, in most regex matchers, a '.' will by default match any2016character other than '\\n', and this is true in ripgrep as well. In order to2017make '.' match '\\n', you must enable the \"dot all\" flag inside the regex.2018For example, both '(?s).' and '(?s:.)' have the same semantics, where '.' will2019match any character, including '\\n'. Alternatively, the '--multiline-dotall'2020flag may be passed to make the \"dot all\" behavior the default. This flag only2021applies when multiline search is enabled.20222023There is no limit on the number of the lines that a single match can span.20242025**WARNING**: Because of how the underlying regex engine works, multiline2026searches may be slower than normal line-oriented searches, and they may also2027use more memory. In particular, when multiline mode is enabled, ripgrep2028requires that each file it searches is laid out contiguously in memory2029(either by reading it onto the heap or by memory-mapping it). Things that2030cannot be memory-mapped (such as stdin) will be consumed until EOF before2031searching can begin. In general, ripgrep will only do these things when2032necessary. Specifically, if the --multiline flag is provided but the regex2033does not contain patterns that would match '\\n' characters, then ripgrep2034will automatically avoid reading each file into memory before searching it.2035Nevertheless, if you only care about matches spanning at most one line, then it2036is always better to disable multiline mode.20372038This flag can be disabled with --no-multiline.20392040This overrides the --stop-on-nonmatch flag.2041"2042 );2043 let arg = RGArg::switch("multiline")2044 .short("U")2045 .help(SHORT)2046 .long_help(LONG)2047 .overrides("no-multiline")2048 .overrides("stop-on-nonmatch");2049 args.push(arg);20502051 let arg = RGArg::switch("no-multiline").hidden().overrides("multiline");2052 args.push(arg);2053}20542055fn flag_multiline_dotall(args: &mut Vec<RGArg>) {2056 const SHORT: &str = "Make '.' match new lines when multiline is enabled.";2057 const LONG: &str = long!(2058 "\2059This flag enables \"dot all\" in your regex pattern, which causes '.' to match2060newlines when multiline searching is enabled. This flag has no effect if2061multiline searching isn't enabled with the --multiline flag.20622063Normally, a '.' will match any character except newlines. While this behavior2064typically isn't relevant for line-oriented matching (since matches can span at2065most one line), this can be useful when searching with the -U/--multiline flag.2066By default, the multiline mode runs without this flag.20672068This flag is generally intended to be used in an alias or your ripgrep config2069file if you prefer \"dot all\" semantics by default. Note that regardless of2070whether this flag is used, \"dot all\" semantics can still be controlled via2071inline flags in the regex pattern itself, e.g., '(?s:.)' always enables \"dot2072all\" whereas '(?-s:.)' always disables \"dot all\".20732074This flag can be disabled with --no-multiline-dotall.2075"2076 );2077 let arg = RGArg::switch("multiline-dotall")2078 .help(SHORT)2079 .long_help(LONG)2080 .overrides("no-multiline-dotall");2081 args.push(arg);20822083 let arg = RGArg::switch("no-multiline-dotall")2084 .hidden()2085 .overrides("multiline-dotall");2086 args.push(arg);2087}20882089fn flag_no_config(args: &mut Vec<RGArg>) {2090 const SHORT: &str = "Never read configuration files.";2091 const LONG: &str = long!(2092 "\2093Never read configuration files. When this flag is present, ripgrep will not2094respect the RIPGREP_CONFIG_PATH environment variable.20952096If ripgrep ever grows a feature to automatically read configuration files in2097pre-defined locations, then this flag will also disable that behavior as well.2098"2099 );2100 let arg = RGArg::switch("no-config").help(SHORT).long_help(LONG);2101 args.push(arg);2102}21032104fn flag_no_ignore(args: &mut Vec<RGArg>) {2105 const SHORT: &str = "Don't respect ignore files.";2106 const LONG: &str = long!(2107 "\2108Don't respect ignore files (.gitignore, .ignore, etc.). This implies2109--no-ignore-dot, --no-ignore-exclude, --no-ignore-global, no-ignore-parent and2110--no-ignore-vcs.21112112This does *not* imply --no-ignore-files, since --ignore-file is specified2113explicitly as a command line argument.21142115When given only once, the -u flag is identical in behavior to --no-ignore and2116can be considered an alias. However, subsequent -u flags have additional2117effects; see --unrestricted.21182119This flag can be disabled with the --ignore flag.2120"2121 );2122 let arg = RGArg::switch("no-ignore")2123 .help(SHORT)2124 .long_help(LONG)2125 .overrides("ignore");2126 args.push(arg);21272128 let arg = RGArg::switch("ignore").hidden().overrides("no-ignore");2129 args.push(arg);2130}21312132fn flag_no_ignore_dot(args: &mut Vec<RGArg>) {2133 const SHORT: &str = "Don't respect .ignore files.";2134 const LONG: &str = long!(2135 "\2136Don't respect .ignore files.21372138This does *not* affect whether ripgrep will ignore files and directories2139whose names begin with a dot. For that, see the -./--hidden flag.21402141This flag can be disabled with the --ignore-dot flag.2142"2143 );2144 let arg = RGArg::switch("no-ignore-dot")2145 .help(SHORT)2146 .long_help(LONG)2147 .overrides("ignore-dot");2148 args.push(arg);21492150 let arg = RGArg::switch("ignore-dot").hidden().overrides("no-ignore-dot");2151 args.push(arg);2152}21532154fn flag_no_ignore_exclude(args: &mut Vec<RGArg>) {2155 const SHORT: &str = "Don't respect local exclusion files.";2156 const LONG: &str = long!(2157 "\2158Don't respect ignore files that are manually configured for the repository2159such as git's '.git/info/exclude'.21602161This flag can be disabled with the --ignore-exclude flag.2162"2163 );2164 let arg = RGArg::switch("no-ignore-exclude")2165 .help(SHORT)2166 .long_help(LONG)2167 .overrides("ignore-exclude");2168 args.push(arg);21692170 let arg = RGArg::switch("ignore-exclude")2171 .hidden()2172 .overrides("no-ignore-exclude");2173 args.push(arg);2174}21752176fn flag_no_ignore_files(args: &mut Vec<RGArg>) {2177 const SHORT: &str = "Don't respect --ignore-file arguments.";2178 const LONG: &str = long!(2179 "\2180When set, any --ignore-file flags, even ones that come after this flag, are2181ignored.21822183This flag can be disabled with the --ignore-files flag.2184"2185 );2186 let arg = RGArg::switch("no-ignore-files")2187 .help(SHORT)2188 .long_help(LONG)2189 .overrides("ignore-files");2190 args.push(arg);21912192 let arg =2193 RGArg::switch("ignore-files").hidden().overrides("no-ignore-files");2194 args.push(arg);2195}21962197fn flag_no_ignore_global(args: &mut Vec<RGArg>) {2198 const SHORT: &str = "Don't respect global ignore files.";2199 const LONG: &str = long!(2200 "\2201Don't respect ignore files that come from \"global\" sources such as git's2202`core.excludesFile` configuration option (which defaults to2203`$HOME/.config/git/ignore`).22042205This flag can be disabled with the --ignore-global flag.2206"2207 );2208 let arg = RGArg::switch("no-ignore-global")2209 .help(SHORT)2210 .long_help(LONG)2211 .overrides("ignore-global");2212 args.push(arg);22132214 let arg =2215 RGArg::switch("ignore-global").hidden().overrides("no-ignore-global");2216 args.push(arg);2217}22182219fn flag_no_ignore_messages(args: &mut Vec<RGArg>) {2220 const SHORT: &str = "Suppress gitignore parse error messages.";2221 const LONG: &str = long!(2222 "\2223Suppresses all error messages related to parsing ignore files such as .ignore2224or .gitignore.22252226This flag can be disabled with the --ignore-messages flag.2227"2228 );2229 let arg = RGArg::switch("no-ignore-messages")2230 .help(SHORT)2231 .long_help(LONG)2232 .overrides("ignore-messages");2233 args.push(arg);22342235 let arg = RGArg::switch("ignore-messages")2236 .hidden()2237 .overrides("no-ignore-messages");2238 args.push(arg);2239}22402241fn flag_no_ignore_parent(args: &mut Vec<RGArg>) {2242 const SHORT: &str = "Don't respect ignore files in parent directories.";2243 const LONG: &str = long!(2244 "\2245Don't respect ignore files (.gitignore, .ignore, etc.) in parent directories.22462247This flag can be disabled with the --ignore-parent flag.2248"2249 );2250 let arg = RGArg::switch("no-ignore-parent")2251 .help(SHORT)2252 .long_help(LONG)2253 .overrides("ignore-parent");2254 args.push(arg);22552256 let arg =2257 RGArg::switch("ignore-parent").hidden().overrides("no-ignore-parent");2258 args.push(arg);2259}22602261fn flag_no_ignore_vcs(args: &mut Vec<RGArg>) {2262 const SHORT: &str = "Don't respect VCS ignore files.";2263 const LONG: &str = long!(2264 "\2265Don't respect version control ignore files (.gitignore, etc.). This implies2266--no-ignore-parent for VCS files. Note that .ignore files will continue to be2267respected.22682269This flag can be disabled with the --ignore-vcs flag.2270"2271 );2272 let arg = RGArg::switch("no-ignore-vcs")2273 .help(SHORT)2274 .long_help(LONG)2275 .overrides("ignore-vcs");2276 args.push(arg);22772278 let arg = RGArg::switch("ignore-vcs").hidden().overrides("no-ignore-vcs");2279 args.push(arg);2280}22812282fn flag_no_messages(args: &mut Vec<RGArg>) {2283 const SHORT: &str = "Suppress some error messages.";2284 const LONG: &str = long!(2285 "\2286Suppress all error messages related to opening and reading files. Error2287messages related to the syntax of the pattern given are still shown.22882289This flag can be disabled with the --messages flag.2290"2291 );2292 let arg = RGArg::switch("no-messages")2293 .help(SHORT)2294 .long_help(LONG)2295 .overrides("messages");2296 args.push(arg);22972298 let arg = RGArg::switch("messages").hidden().overrides("no-messages");2299 args.push(arg);2300}23012302fn flag_no_pcre2_unicode(args: &mut Vec<RGArg>) {2303 const SHORT: &str = "Disable Unicode mode for PCRE2 matching.";2304 const LONG: &str = long!(2305 "\2306DEPRECATED. Use --no-unicode instead.23072308This flag is now an alias for --no-unicode. And --pcre2-unicode is an alias2309for --unicode.2310"2311 );2312 let arg = RGArg::switch("no-pcre2-unicode")2313 .help(SHORT)2314 .long_help(LONG)2315 .overrides("pcre2-unicode")2316 .overrides("unicode");2317 args.push(arg);23182319 let arg = RGArg::switch("pcre2-unicode")2320 .hidden()2321 .overrides("no-pcre2-unicode")2322 .overrides("no-unicode");2323 args.push(arg);2324}23252326fn flag_no_require_git(args: &mut Vec<RGArg>) {2327 const SHORT: &str = "Do not require a git repository to use gitignores.";2328 const LONG: &str = long!(2329 "\2330By default, ripgrep will only respect global gitignore rules, .gitignore rules2331and local exclude rules if ripgrep detects that you are searching inside a2332git repository. This flag allows you to relax this restriction such that2333ripgrep will respect all git related ignore rules regardless of whether you're2334searching in a git repository or not.23352336This flag can be disabled with --require-git.2337"2338 );2339 let arg = RGArg::switch("no-require-git")2340 .help(SHORT)2341 .long_help(LONG)2342 .overrides("require-git");2343 args.push(arg);23442345 let arg =2346 RGArg::switch("require-git").hidden().overrides("no-require-git");2347 args.push(arg);2348}23492350fn flag_no_unicode(args: &mut Vec<RGArg>) {2351 const SHORT: &str = "Disable Unicode mode.";2352 const LONG: &str = long!(2353 "\2354By default, ripgrep will enable \"Unicode mode\" in all of its regexes. This2355has a number of consequences:23562357* '.' will only match valid UTF-8 encoded scalar values.2358* Classes like '\\w', '\\s', '\\d' are all Unicode aware and much bigger2359 than their ASCII only versions.2360* Case insensitive matching will use Unicode case folding.2361* A large array of classes like '\\p{Emoji}' are available.2362* Word boundaries ('\\b' and '\\B') use the Unicode definition of a word2363 character.23642365In some cases it can be desirable to turn these things off. The --no-unicode2366flag will do exactly that.23672368For PCRE2 specifically, Unicode mode represents a critical trade off in the2369user experience of ripgrep. In particular, unlike the default regex engine,2370PCRE2 does not support the ability to search possibly invalid UTF-8 with2371Unicode features enabled. Instead, PCRE2 *requires* that everything it searches2372when Unicode mode is enabled is valid UTF-8. (Or valid UTF-16/UTF-32, but for2373the purposes of ripgrep, we only discuss UTF-8.) This means that if you have2374PCRE2's Unicode mode enabled and you attempt to search invalid UTF-8, then2375the search for that file will halt and print an error. For this reason, when2376PCRE2's Unicode mode is enabled, ripgrep will automatically \"fix\" invalid2377UTF-8 sequences by replacing them with the Unicode replacement codepoint. This2378penalty does not occur when using the default regex engine.23792380If you would rather see the encoding errors surfaced by PCRE2 when Unicode mode2381is enabled, then pass the --no-encoding flag to disable all transcoding.23822383The --no-unicode flag can be disabled with --unicode. Note that2384--no-pcre2-unicode and --pcre2-unicode are aliases for --no-unicode and2385--unicode, respectively.2386"2387 );2388 let arg = RGArg::switch("no-unicode")2389 .help(SHORT)2390 .long_help(LONG)2391 .overrides("unicode")2392 .overrides("pcre2-unicode");2393 args.push(arg);23942395 let arg = RGArg::switch("unicode")2396 .hidden()2397 .overrides("no-unicode")2398 .overrides("no-pcre2-unicode");2399 args.push(arg);2400}24012402fn flag_null(args: &mut Vec<RGArg>) {2403 const SHORT: &str = "Print a NUL byte after file paths.";2404 const LONG: &str = long!(2405 "\2406Whenever a file path is printed, follow it with a NUL byte. This includes2407printing file paths before matches, and when printing a list of matching files2408such as with --count, --files-with-matches and --files. This option is useful2409for use with xargs.2410"2411 );2412 let arg = RGArg::switch("null").short("0").help(SHORT).long_help(LONG);2413 args.push(arg);2414}24152416fn flag_null_data(args: &mut Vec<RGArg>) {2417 const SHORT: &str = "Use NUL as a line terminator instead of \\n.";2418 const LONG: &str = long!(2419 "\2420Enabling this option causes ripgrep to use NUL as a line terminator instead of2421the default of '\\n'.24222423This is useful when searching large binary files that would otherwise have very2424long lines if '\\n' were used as the line terminator. In particular, ripgrep2425requires that, at a minimum, each line must fit into memory. Using NUL instead2426can be a useful stopgap to keep memory requirements low and avoid OOM (out of2427memory) conditions.24282429This is also useful for processing NUL delimited data, such as that emitted2430when using ripgrep's -0/--null flag or find's --print0 flag.24312432Using this flag implies -a/--text.2433"2434 );2435 let arg = RGArg::switch("null-data")2436 .help(SHORT)2437 .long_help(LONG)2438 .overrides("crlf");2439 args.push(arg);2440}24412442fn flag_one_file_system(args: &mut Vec<RGArg>) {2443 const SHORT: &str =2444 "Do not descend into directories on other file systems.";2445 const LONG: &str = long!(2446 "\2447When enabled, ripgrep will not cross file system boundaries relative to where2448the search started from.24492450Note that this applies to each path argument given to ripgrep. For example, in2451the command 'rg --one-file-system /foo/bar /quux/baz', ripgrep will search both2452'/foo/bar' and '/quux/baz' even if they are on different file systems, but will2453not cross a file system boundary when traversing each path's directory tree.24542455This is similar to find's '-xdev' or '-mount' flag.24562457This flag can be disabled with --no-one-file-system.2458"2459 );2460 let arg = RGArg::switch("one-file-system")2461 .help(SHORT)2462 .long_help(LONG)2463 .overrides("no-one-file-system");2464 args.push(arg);24652466 let arg = RGArg::switch("no-one-file-system")2467 .hidden()2468 .overrides("one-file-system");2469 args.push(arg);2470}24712472fn flag_only_matching(args: &mut Vec<RGArg>) {2473 const SHORT: &str = "Print only matched parts of a line.";2474 const LONG: &str = long!(2475 "\2476Print only the matched (non-empty) parts of a matching line, with each such2477part on a separate output line.2478"2479 );2480 let arg =2481 RGArg::switch("only-matching").short("o").help(SHORT).long_help(LONG);2482 args.push(arg);2483}24842485fn flag_path_separator(args: &mut Vec<RGArg>) {2486 const SHORT: &str = "Set the path separator.";2487 const LONG: &str = long!(2488 "\2489Set the path separator to use when printing file paths. This defaults to your2490platform's path separator, which is / on Unix and \\ on Windows. This flag is2491intended for overriding the default when the environment demands it (e.g.,2492cygwin). A path separator is limited to a single byte.2493"2494 );2495 let arg =2496 RGArg::flag("path-separator", "SEPARATOR").help(SHORT).long_help(LONG);2497 args.push(arg);2498}24992500fn flag_passthru(args: &mut Vec<RGArg>) {2501 const SHORT: &str = "Print both matching and non-matching lines.";2502 const LONG: &str = long!(2503 "\2504Print both matching and non-matching lines.25052506Another way to achieve a similar effect is by modifying your pattern to match2507the empty string. For example, if you are searching using 'rg foo' then using2508'rg \"^|foo\"' instead will emit every line in every file searched, but only2509occurrences of 'foo' will be highlighted. This flag enables the same behavior2510without needing to modify the pattern.25112512This overrides the --context, --after-context and --before-context flags.2513"2514 );2515 let arg = RGArg::switch("passthru")2516 .help(SHORT)2517 .long_help(LONG)2518 .alias("passthrough")2519 .overrides("after-context")2520 .overrides("before-context")2521 .overrides("context");2522 args.push(arg);2523}25242525fn flag_pcre2(args: &mut Vec<RGArg>) {2526 const SHORT: &str = "Enable PCRE2 matching.";2527 const LONG: &str = long!(2528 "\2529When this flag is present, ripgrep will use the PCRE2 regex engine instead of2530its default regex engine.25312532This is generally useful when you want to use features such as look-around2533or backreferences.25342535Note that PCRE2 is an optional ripgrep feature. If PCRE2 wasn't included in2536your build of ripgrep, then using this flag will result in ripgrep printing2537an error message and exiting. PCRE2 may also have worse user experience in2538some cases, since it has fewer introspection APIs than ripgrep's default regex2539engine. For example, if you use a '\\n' in a PCRE2 regex without the2540'-U/--multiline' flag, then ripgrep will silently fail to match anything2541instead of reporting an error immediately (like it does with the default2542regex engine).25432544Related flags: --no-pcre2-unicode25452546This flag can be disabled with --no-pcre2.2547"2548 );2549 let arg = RGArg::switch("pcre2")2550 .short("P")2551 .help(SHORT)2552 .long_help(LONG)2553 .overrides("no-pcre2")2554 .overrides("auto-hybrid-regex")2555 .overrides("no-auto-hybrid-regex")2556 .overrides("engine");2557 args.push(arg);25582559 let arg = RGArg::switch("no-pcre2")2560 .hidden()2561 .overrides("pcre2")2562 .overrides("auto-hybrid-regex")2563 .overrides("no-auto-hybrid-regex")2564 .overrides("engine");2565 args.push(arg);2566}25672568fn flag_pcre2_version(args: &mut Vec<RGArg>) {2569 const SHORT: &str = "Print the version of PCRE2 that ripgrep uses.";2570 const LONG: &str = long!(2571 "\2572When this flag is present, ripgrep will print the version of PCRE2 in use,2573along with other information, and then exit. If PCRE2 is not available, then2574ripgrep will print an error message and exit with an error code.2575"2576 );2577 let arg = RGArg::switch("pcre2-version").help(SHORT).long_help(LONG);2578 args.push(arg);2579}25802581fn flag_pre(args: &mut Vec<RGArg>) {2582 const SHORT: &str = "search outputs of COMMAND FILE for each FILE";2583 const LONG: &str = long!(2584 "\2585For each input FILE, search the standard output of COMMAND FILE rather than the2586contents of FILE. This option expects the COMMAND program to either be an2587absolute path or to be available in your PATH. Either an empty string COMMAND2588or the '--no-pre' flag will disable this behavior.25892590 WARNING: When this flag is set, ripgrep will unconditionally spawn a2591 process for every file that is searched. Therefore, this can incur an2592 unnecessarily large performance penalty if you don't otherwise need the2593 flexibility offered by this flag. One possible mitigation to this is to use2594 the '--pre-glob' flag to limit which files a preprocessor is run with.25952596A preprocessor is not run when ripgrep is searching stdin.25972598When searching over sets of files that may require one of several decoders2599as preprocessors, COMMAND should be a wrapper program or script which first2600classifies FILE based on magic numbers/content or based on the FILE name and2601then dispatches to an appropriate preprocessor. Each COMMAND also has its2602standard input connected to FILE for convenience.26032604For example, a shell script for COMMAND might look like:26052606 case \"$1\" in2607 *.pdf)2608 exec pdftotext \"$1\" -2609 ;;2610 *)2611 case $(file \"$1\") in2612 *Zstandard*)2613 exec pzstd -cdq2614 ;;2615 *)2616 exec cat2617 ;;2618 esac2619 ;;2620 esac26212622The above script uses `pdftotext` to convert a PDF file to plain text. For2623all other files, the script uses the `file` utility to sniff the type of the2624file based on its contents. If it is a compressed file in the Zstandard format,2625then `pzstd` is used to decompress the contents to stdout.26262627This overrides the -z/--search-zip flag.2628"2629 );2630 let arg = RGArg::flag("pre", "COMMAND")2631 .help(SHORT)2632 .long_help(LONG)2633 .overrides("no-pre")2634 .overrides("search-zip");2635 args.push(arg);26362637 let arg = RGArg::switch("no-pre").hidden().overrides("pre");2638 args.push(arg);2639}26402641fn flag_pre_glob(args: &mut Vec<RGArg>) {2642 const SHORT: &str =2643 "Include or exclude files from a preprocessing command.";2644 const LONG: &str = long!(2645 "\2646This flag works in conjunction with the --pre flag. Namely, when one or more2647--pre-glob flags are given, then only files that match the given set of globs2648will be handed to the command specified by the --pre flag. Any non-matching2649files will be searched without using the preprocessor command.26502651This flag is useful when searching many files with the --pre flag. Namely,2652it permits the ability to avoid process overhead for files that don't need2653preprocessing. For example, given the following shell script, 'pre-pdftotext':26542655 #!/bin/sh26562657 pdftotext \"$1\" -26582659then it is possible to use '--pre pre-pdftotext --pre-glob \'*.pdf\'' to make2660it so ripgrep only executes the 'pre-pdftotext' command on files with a '.pdf'2661extension.26622663Multiple --pre-glob flags may be used. Globbing rules match .gitignore globs.2664Precede a glob with a ! to exclude it.26652666This flag has no effect if the --pre flag is not used.2667"2668 );2669 let arg = RGArg::flag("pre-glob", "GLOB")2670 .help(SHORT)2671 .long_help(LONG)2672 .multiple()2673 .allow_leading_hyphen();2674 args.push(arg);2675}26762677fn flag_pretty(args: &mut Vec<RGArg>) {2678 const SHORT: &str = "Alias for --color always --heading --line-number.";2679 const LONG: &str = long!(2680 "\2681This is a convenience alias for '--color always --heading --line-number'. This2682flag is useful when you still want pretty output even if you're piping ripgrep2683to another program or file. For example: 'rg -p foo | less -R'.2684"2685 );2686 let arg = RGArg::switch("pretty").short("p").help(SHORT).long_help(LONG);2687 args.push(arg);2688}26892690fn flag_quiet(args: &mut Vec<RGArg>) {2691 const SHORT: &str = "Do not print anything to stdout.";2692 const LONG: &str = long!(2693 "\2694Do not print anything to stdout. If a match is found in a file, then ripgrep2695will stop searching. This is useful when ripgrep is used only for its exit2696code (which will be an error if no matches are found).26972698When --files is used, ripgrep will stop finding files after finding the2699first file that does not match any ignore rules.2700"2701 );2702 let arg = RGArg::switch("quiet").short("q").help(SHORT).long_help(LONG);2703 args.push(arg);2704}27052706fn flag_regex_size_limit(args: &mut Vec<RGArg>) {2707 const SHORT: &str = "The upper size limit of the compiled regex.";2708 const LONG: &str = long!(2709 "\2710The upper size limit of the compiled regex. The default limit is 10M.27112712The argument accepts the same size suffixes as allowed in the --max-filesize2713flag.2714"2715 );2716 let arg = RGArg::flag("regex-size-limit", "NUM+SUFFIX?")2717 .help(SHORT)2718 .long_help(LONG);2719 args.push(arg);2720}27212722fn flag_regexp(args: &mut Vec<RGArg>) {2723 const SHORT: &str = "A pattern to search for.";2724 const LONG: &str = long!(2725 "\2726A pattern to search for. This option can be provided multiple times, where2727all patterns given are searched. Lines matching at least one of the provided2728patterns are printed. This flag can also be used when searching for patterns2729that start with a dash.27302731For example, to search for the literal '-foo', you can use this flag:27322733 rg -e -foo27342735You can also use the special '--' delimiter to indicate that no more flags2736will be provided. Namely, the following is equivalent to the above:27372738 rg -- -foo2739"2740 );2741 let arg = RGArg::flag("regexp", "PATTERN")2742 .short("e")2743 .help(SHORT)2744 .long_help(LONG)2745 .multiple()2746 .allow_leading_hyphen();2747 args.push(arg);2748}27492750fn flag_replace(args: &mut Vec<RGArg>) {2751 const SHORT: &str = "Replace matches with the given text.";2752 const LONG: &str = long!(2753 "\2754Replace every match with the text given when printing results. Neither this2755flag nor any other ripgrep flag will modify your files.27562757Capture group indices (e.g., $5) and names (e.g., $foo) are supported in the2758replacement string. Capture group indices are numbered based on the position of2759the opening parenthesis of the group, where the leftmost such group is $1. The2760special $0 group corresponds to the entire match.27612762The name of a group is formed by taking the longest string of letters, numbers2763and underscores (i.e. [_0-9A-Za-z]) after the $. For example, $1a will be2764replaced with the group named '1a', not the group at index 1. If the group's2765name contains characters that aren't letters, numbers or underscores, or you2766want to immediately follow the group with another string, the name should be2767put inside braces. For example, ${1}a will take the content of the group at2768index 1 and append 'a' to the end of it.27692770If an index or name does not refer to a valid capture group, it will be2771replaced with an empty string.27722773In shells such as Bash and zsh, you should wrap the pattern in single quotes2774instead of double quotes. Otherwise, capture group indices will be replaced by2775expanded shell variables which will most likely be empty.27762777To write a literal '$', use '$$'.27782779Note that the replacement by default replaces each match, and NOT the entire2780line. To replace the entire line, you should match the entire line.27812782This flag can be used with the -o/--only-matching flag.2783"2784 );2785 let arg = RGArg::flag("replace", "REPLACEMENT_TEXT")2786 .short("r")2787 .help(SHORT)2788 .long_help(LONG)2789 .allow_leading_hyphen();2790 args.push(arg);2791}27922793fn flag_search_zip(args: &mut Vec<RGArg>) {2794 const SHORT: &str = "Search in compressed files.";2795 const LONG: &str = long!(2796 "\2797Search in compressed files. Currently gzip, bzip2, xz, LZ4, LZMA, Brotli and2798Zstd files are supported. This option expects the decompression binaries to be2799available in your PATH.28002801This flag can be disabled with --no-search-zip.2802"2803 );2804 let arg = RGArg::switch("search-zip")2805 .short("z")2806 .help(SHORT)2807 .long_help(LONG)2808 .overrides("no-search-zip")2809 .overrides("pre");2810 args.push(arg);28112812 let arg = RGArg::switch("no-search-zip").hidden().overrides("search-zip");2813 args.push(arg);2814}28152816fn flag_smart_case(args: &mut Vec<RGArg>) {2817 const SHORT: &str = "Smart case search.";2818 const LONG: &str = long!(2819 "\2820Searches case insensitively if the pattern is all lowercase. Search case2821sensitively otherwise.28222823A pattern is considered all lowercase if both of the following rules hold:28242825First, the pattern contains at least one literal character. For example, 'a\\w'2826contains a literal ('a') but just '\\w' does not.28272828Second, of the literals in the pattern, none of them are considered to be2829uppercase according to Unicode. For example, 'foo\\pL' has no uppercase2830literals but 'Foo\\pL' does.28312832This overrides the -s/--case-sensitive and -i/--ignore-case flags.2833"2834 );2835 let arg = RGArg::switch("smart-case")2836 .short("S")2837 .help(SHORT)2838 .long_help(LONG)2839 .overrides("case-sensitive")2840 .overrides("ignore-case");2841 args.push(arg);2842}28432844fn flag_sort_files(args: &mut Vec<RGArg>) {2845 const SHORT: &str = "DEPRECATED";2846 const LONG: &str = long!(2847 "\2848DEPRECATED: Use --sort or --sortr instead.28492850Sort results by file path. Note that this currently disables all parallelism2851and runs search in a single thread.28522853This flag can be disabled with --no-sort-files.2854"2855 );2856 let arg = RGArg::switch("sort-files")2857 .help(SHORT)2858 .long_help(LONG)2859 .hidden()2860 .overrides("no-sort-files")2861 .overrides("sort")2862 .overrides("sortr");2863 args.push(arg);28642865 let arg = RGArg::switch("no-sort-files")2866 .hidden()2867 .overrides("sort-files")2868 .overrides("sort")2869 .overrides("sortr");2870 args.push(arg);2871}28722873fn flag_sort(args: &mut Vec<RGArg>) {2874 const SHORT: &str =2875 "Sort results in ascending order. Implies --threads=1.";2876 const LONG: &str = long!(2877 "\2878This flag enables sorting of results in ascending order. The possible values2879for this flag are:28802881 none (Default) Do not sort results. Fastest. Can be multi-threaded.2882 path Sort by file path. Always single-threaded.2883 modified Sort by the last modified time on a file. Always single-threaded.2884 accessed Sort by the last accessed time on a file. Always single-threaded.2885 created Sort by the creation time on a file. Always single-threaded.28862887If the chosen (manually or by-default) sorting criteria isn't available on your2888system (for example, creation time is not available on ext4 file systems), then2889ripgrep will attempt to detect this, print an error and exit without searching.28902891To sort results in reverse or descending order, use the --sortr flag. Also,2892this flag overrides --sortr.28932894Note that sorting results currently always forces ripgrep to abandon2895parallelism and run in a single thread.2896"2897 );2898 let arg = RGArg::flag("sort", "SORTBY")2899 .help(SHORT)2900 .long_help(LONG)2901 .possible_values(&["path", "modified", "accessed", "created", "none"])2902 .overrides("sortr")2903 .overrides("sort-files")2904 .overrides("no-sort-files");2905 args.push(arg);2906}29072908fn flag_sortr(args: &mut Vec<RGArg>) {2909 const SHORT: &str =2910 "Sort results in descending order. Implies --threads=1.";2911 const LONG: &str = long!(2912 "\2913This flag enables sorting of results in descending order. The possible values2914for this flag are:29152916 none (Default) Do not sort results. Fastest. Can be multi-threaded.2917 path Sort by file path. Always single-threaded.2918 modified Sort by the last modified time on a file. Always single-threaded.2919 accessed Sort by the last accessed time on a file. Always single-threaded.2920 created Sort by the creation time on a file. Always single-threaded.29212922If the chosen (manually or by-default) sorting criteria isn't available on your2923system (for example, creation time is not available on ext4 file systems), then2924ripgrep will attempt to detect this, print an error and exit without searching.29252926To sort results in ascending order, use the --sort flag. Also, this flag2927overrides --sort.29282929Note that sorting results currently always forces ripgrep to abandon2930parallelism and run in a single thread.2931"2932 );2933 let arg = RGArg::flag("sortr", "SORTBY")2934 .help(SHORT)2935 .long_help(LONG)2936 .possible_values(&["path", "modified", "accessed", "created", "none"])2937 .overrides("sort")2938 .overrides("sort-files")2939 .overrides("no-sort-files");2940 args.push(arg);2941}29422943fn flag_stats(args: &mut Vec<RGArg>) {2944 const SHORT: &str = "Print statistics about this ripgrep search.";2945 const LONG: &str = long!(2946 "\2947Print aggregate statistics about this ripgrep search. When this flag is2948present, ripgrep will print the following stats to stdout at the end of the2949search: number of matched lines, number of files with matches, number of files2950searched, and the time taken for the entire search to complete.29512952This set of aggregate statistics may expand over time.29532954Note that this flag has no effect if --files, --files-with-matches or2955--files-without-match is passed.29562957This flag can be disabled with --no-stats.2958"2959 );2960 let arg = RGArg::switch("stats")2961 .help(SHORT)2962 .long_help(LONG)2963 .overrides("no-stats");2964 args.push(arg);29652966 let arg = RGArg::switch("no-stats").hidden().overrides("stats");2967 args.push(arg);2968}29692970fn flag_stop_on_nonmatch(args: &mut Vec<RGArg>) {2971 const SHORT: &str = "Stop searching after a non-match.";2972 const LONG: &str = long!(2973 "\2974Enabling this option will cause ripgrep to stop reading a file once it2975encounters a non-matching line after it has encountered a matching line.2976This is useful if it is expected that all matches in a given file will be on2977sequential lines, for example due to the lines being sorted.29782979This overrides the -U/--multiline flag.2980"2981 );2982 let arg = RGArg::switch("stop-on-nonmatch")2983 .help(SHORT)2984 .long_help(LONG)2985 .overrides("multiline");2986 args.push(arg);2987}29882989fn flag_text(args: &mut Vec<RGArg>) {2990 const SHORT: &str = "Search binary files as if they were text.";2991 const LONG: &str = long!(2992 "\2993Search binary files as if they were text. When this flag is present, ripgrep's2994binary file detection is disabled. This means that when a binary file is2995searched, its contents may be printed if there is a match. This may cause2996escape codes to be printed that alter the behavior of your terminal.29972998When binary file detection is enabled it is imperfect. In general, it uses2999a simple heuristic. If a NUL byte is seen during search, then the file is3000considered binary and search stops (unless this flag is present).3001Alternatively, if the '--binary' flag is used, then ripgrep will only quit3002when it sees a NUL byte after it sees a match (or searches the entire file).30033004This flag can be disabled with '--no-text'. It overrides the '--binary' flag.3005"3006 );3007 let arg = RGArg::switch("text")3008 .short("a")3009 .help(SHORT)3010 .long_help(LONG)3011 .overrides("no-text")3012 .overrides("binary")3013 .overrides("no-binary");3014 args.push(arg);30153016 let arg = RGArg::switch("no-text")3017 .hidden()3018 .overrides("text")3019 .overrides("binary")3020 .overrides("no-binary");3021 args.push(arg);3022}30233024fn flag_threads(args: &mut Vec<RGArg>) {3025 const SHORT: &str = "The approximate number of threads to use.";3026 const LONG: &str = long!(3027 "\3028The approximate number of threads to use. A value of 0 (which is the default)3029causes ripgrep to choose the thread count using heuristics.3030"3031 );3032 let arg =3033 RGArg::flag("threads", "NUM").short("j").help(SHORT).long_help(LONG);3034 args.push(arg);3035}30363037fn flag_trim(args: &mut Vec<RGArg>) {3038 const SHORT: &str = "Trim prefixed whitespace from matches.";3039 const LONG: &str = long!(3040 "\3041When set, all ASCII whitespace at the beginning of each line printed will be3042trimmed.30433044This flag can be disabled with --no-trim.3045"3046 );3047 let arg =3048 RGArg::switch("trim").help(SHORT).long_help(LONG).overrides("no-trim");3049 args.push(arg);30503051 let arg = RGArg::switch("no-trim").hidden().overrides("trim");3052 args.push(arg);3053}30543055fn flag_type(args: &mut Vec<RGArg>) {3056 const SHORT: &str = "Only search files matching TYPE.";3057 const LONG: &str = long!(3058 "\3059Only search files matching TYPE. Multiple type flags may be provided. Use the3060--type-list flag to list all available types.30613062This flag supports the special value 'all', which will behave as if --type3063was provided for every file type supported by ripgrep (including any custom3064file types). The end result is that '--type all' causes ripgrep to search in3065\"whitelist\" mode, where it will only search files it recognizes via its type3066definitions.3067"3068 );3069 let arg = RGArg::flag("type", "TYPE")3070 .short("t")3071 .help(SHORT)3072 .long_help(LONG)3073 .multiple();3074 args.push(arg);3075}30763077fn flag_type_add(args: &mut Vec<RGArg>) {3078 const SHORT: &str = "Add a new glob for a file type.";3079 const LONG: &str = long!(3080 "\3081Add a new glob for a particular file type. Only one glob can be added at a3082time. Multiple --type-add flags can be provided. Unless --type-clear is used,3083globs are added to any existing globs defined inside of ripgrep.30843085Note that this MUST be passed to every invocation of ripgrep. Type settings are3086NOT persisted. See CONFIGURATION FILES for a workaround.30873088Example:30893090 rg --type-add 'foo:*.foo' -tfoo PATTERN.30913092--type-add can also be used to include rules from other types with the special3093include directive. The include directive permits specifying one or more other3094type names (separated by a comma) that have been defined and its rules will3095automatically be imported into the type specified. For example, to create a3096type called src that matches C++, Python and Markdown files, one can use:30973098 --type-add 'src:include:cpp,py,md'30993100Additional glob rules can still be added to the src type by using the3101--type-add flag again:31023103 --type-add 'src:include:cpp,py,md' --type-add 'src:*.foo'31043105Note that type names must consist only of Unicode letters or numbers.3106Punctuation characters are not allowed.3107"3108 );3109 let arg = RGArg::flag("type-add", "TYPE_SPEC")3110 .help(SHORT)3111 .long_help(LONG)3112 .multiple();3113 args.push(arg);3114}31153116fn flag_type_clear(args: &mut Vec<RGArg>) {3117 const SHORT: &str = "Clear globs for a file type.";3118 const LONG: &str = long!(3119 "\3120Clear the file type globs previously defined for TYPE. This only clears the3121default type definitions that are found inside of ripgrep.31223123Note that this MUST be passed to every invocation of ripgrep. Type settings are3124NOT persisted. See CONFIGURATION FILES for a workaround.3125"3126 );3127 let arg = RGArg::flag("type-clear", "TYPE")3128 .help(SHORT)3129 .long_help(LONG)3130 .multiple();3131 args.push(arg);3132}31333134fn flag_type_not(args: &mut Vec<RGArg>) {3135 const SHORT: &str = "Do not search files matching TYPE.";3136 const LONG: &str = long!(3137 "\3138Do not search files matching TYPE. Multiple type-not flags may be provided. Use3139the --type-list flag to list all available types.3140"3141 );3142 let arg = RGArg::flag("type-not", "TYPE")3143 .short("T")3144 .help(SHORT)3145 .long_help(LONG)3146 .multiple();3147 args.push(arg);3148}31493150fn flag_type_list(args: &mut Vec<RGArg>) {3151 const SHORT: &str = "Show all supported file types.";3152 const LONG: &str = long!(3153 "\3154Show all supported file types and their corresponding globs.3155"3156 );3157 let arg = RGArg::switch("type-list")3158 .help(SHORT)3159 .long_help(LONG)3160 // This also technically conflicts with PATTERN, but the first file3161 // path will actually be in PATTERN.3162 .conflicts(&["file", "files", "pattern", "regexp"]);3163 args.push(arg);3164}31653166fn flag_unrestricted(args: &mut Vec<RGArg>) {3167 const SHORT: &str = "Reduce the level of \"smart\" searching.";3168 const LONG: &str = long!(3169 "\3170Reduce the level of \"smart\" searching. A single -u won't respect .gitignore3171(etc.) files (--no-ignore). Two -u flags will additionally search hidden files3172and directories (-./--hidden). Three -u flags will additionally search binary3173files (--binary).31743175'rg -uuu' is roughly equivalent to 'grep -r'.3176"3177 );3178 let arg = RGArg::switch("unrestricted")3179 .short("u")3180 .help(SHORT)3181 .long_help(LONG)3182 .multiple();3183 args.push(arg);3184}31853186fn flag_vimgrep(args: &mut Vec<RGArg>) {3187 const SHORT: &str = "Show results in vim compatible format.";3188 const LONG: &str = long!(3189 "\3190Show results with every match on its own line, including line numbers and3191column numbers. With this option, a line with more than one match will be3192printed more than once.3193"3194 );3195 let arg = RGArg::switch("vimgrep").help(SHORT).long_help(LONG);3196 args.push(arg);3197}31983199fn flag_with_filename(args: &mut Vec<RGArg>) {3200 const SHORT: &str = "Print the file path with the matched lines.";3201 const LONG: &str = long!(3202 "\3203Display the file path for matches. This is the default when more than one3204file is searched. If --heading is enabled (the default when printing to a3205terminal), the file path will be shown above clusters of matches from each3206file; otherwise, the file name will be shown as a prefix for each matched line.32073208This flag overrides --no-filename.3209"3210 );3211 let arg = RGArg::switch("with-filename")3212 .short("H")3213 .help(SHORT)3214 .long_help(LONG)3215 .overrides("no-filename");3216 args.push(arg);32173218 const NO_SHORT: &str = "Never print the file path with the matched lines.";3219 const NO_LONG: &str = long!(3220 "\3221Never print the file path with the matched lines. This is the default when3222ripgrep is explicitly instructed to search one file or stdin.32233224This flag overrides --with-filename.3225"3226 );3227 let arg = RGArg::switch("no-filename")3228 .short("I")3229 .help(NO_SHORT)3230 .long_help(NO_LONG)3231 .overrides("with-filename");3232 args.push(arg);3233}32343235fn flag_word_regexp(args: &mut Vec<RGArg>) {3236 const SHORT: &str = "Only show matches surrounded by word boundaries.";3237 const LONG: &str = long!(3238 "\3239Only show matches surrounded by word boundaries. This is roughly equivalent to3240putting \\b before and after all of the search patterns.32413242This overrides the --line-regexp flag.3243"3244 );3245 let arg = RGArg::switch("word-regexp")3246 .short("w")3247 .help(SHORT)3248 .long_help(LONG)3249 .overrides("line-regexp");3250 args.push(arg);3251}
deleted:crates/core/args.rs-1975 removed
1use std::{2 collections::HashSet,3 env,4 ffi::{OsStr, OsString},5 io::{self, IsTerminal, Write},6 path::{Path, PathBuf},7 sync::Arc,8};910use {11 clap,12 grep::{13 cli,14 matcher::LineTerminator,15 printer::{16 default_color_specs, ColorSpecs, HyperlinkConfig,17 HyperlinkEnvironment, HyperlinkFormat, JSONBuilder, PathPrinter,18 PathPrinterBuilder, Standard, StandardBuilder, Stats, Summary,19 SummaryBuilder, SummaryKind, JSON,20 },21 regex::{22 RegexMatcher as RustRegexMatcher,23 RegexMatcherBuilder as RustRegexMatcherBuilder,24 },25 searcher::{26 BinaryDetection, Encoding, MmapChoice, Searcher, SearcherBuilder,27 },28 },29 ignore::{30 overrides::{Override, OverrideBuilder},31 types::{FileTypeDef, Types, TypesBuilder},32 {Walk, WalkBuilder, WalkParallel},33 },34 termcolor::{BufferWriter, ColorChoice, WriteColor},35};3637#[cfg(feature = "pcre2")]38use grep::pcre2::{39 RegexMatcher as PCRE2RegexMatcher,40 RegexMatcherBuilder as PCRE2RegexMatcherBuilder,41};4243use crate::{44 app, config,45 logger::Logger,46 messages::{set_ignore_messages, set_messages},47 search::{PatternMatcher, Printer, SearchWorker, SearchWorkerBuilder},48 subject::{Subject, SubjectBuilder},49};5051/// The command that ripgrep should execute based on the command line52/// configuration.53#[derive(Clone, Copy, Debug, Eq, PartialEq)]54pub enum Command {55 /// Search using exactly one thread.56 Search,57 /// Search using possibly many threads.58 SearchParallel,59 /// The command line parameters suggest that a search should occur, but60 /// ripgrep knows that a match can never be found (e.g., no given patterns61 /// or --max-count=0).62 SearchNever,63 /// Show the files that would be searched, but don't actually search them,64 /// and use exactly one thread.65 Files,66 /// Show the files that would be searched, but don't actually search them,67 /// and perform directory traversal using possibly many threads.68 FilesParallel,69 /// List all file type definitions configured, including the default file70 /// types and any additional file types added to the command line.71 Types,72 /// Print the version of PCRE2 in use.73 PCRE2Version,74}7576impl Command {77 /// Returns true if and only if this command requires executing a search.78 fn is_search(&self) -> bool {79 use self::Command::*;8081 match *self {82 Search | SearchParallel => true,83 SearchNever | Files | FilesParallel | Types | PCRE2Version => {84 false85 }86 }87 }88}8990/// The primary configuration object used throughout ripgrep. It provides a91/// high-level convenient interface to the provided command line arguments.92///93/// An `Args` object is cheap to clone and can be used from multiple threads94/// simultaneously.95#[derive(Clone, Debug)]96pub struct Args(Arc<ArgsImp>);9798#[derive(Clone, Debug)]99struct ArgsImp {100 /// Mid-to-low level routines for extracting CLI arguments.101 matches: ArgMatches,102 /// The command we want to execute.103 command: Command,104 /// The number of threads to use. This is based in part on available105 /// threads, in part on the number of threads requested and in part on the106 /// command we're running.107 threads: usize,108 /// A matcher built from the patterns.109 ///110 /// It's important that this is only built once, since building this goes111 /// through regex compilation and various types of analyses. That is, if112 /// you need many of these (one per thread, for example), it is better to113 /// build it once and then clone it.114 matcher: PatternMatcher,115 /// The paths provided at the command line. This is guaranteed to be116 /// non-empty. (If no paths are provided, then a default path is created.)117 paths: Vec<PathBuf>,118 /// Returns true if and only if `paths` had to be populated with a single119 /// default path.120 using_default_path: bool,121}122123impl Args {124 /// Parse the command line arguments for this process.125 ///126 /// If a CLI usage error occurred, then exit the process and print a usage127 /// or error message. Similarly, if the user requested the version of128 /// ripgrep, then print the version and exit.129 ///130 /// Also, initialize a global logger.131 pub fn parse() -> anyhow::Result<Args> {132 // We parse the args given on CLI. This does not include args from133 // the config. We use the CLI args as an initial configuration while134 // trying to parse config files. If a config file exists and has135 // arguments, then we re-parse argv, otherwise we just use the matches136 // we have here.137 let early_matches = ArgMatches::new(clap_matches(env::args_os())?);138 set_messages(!early_matches.is_present("no-messages"));139 set_ignore_messages(!early_matches.is_present("no-ignore-messages"));140141 if let Err(err) = Logger::init() {142 anyhow::bail!("failed to initialize logger: {err}");143 }144 if early_matches.is_present("trace") {145 log::set_max_level(log::LevelFilter::Trace);146 } else if early_matches.is_present("debug") {147 log::set_max_level(log::LevelFilter::Debug);148 } else {149 log::set_max_level(log::LevelFilter::Warn);150 }151152 let matches = early_matches.reconfigure()?;153 // The logging level may have changed if we brought in additional154 // arguments from a configuration file, so recheck it and set the log155 // level as appropriate.156 if matches.is_present("trace") {157 log::set_max_level(log::LevelFilter::Trace);158 } else if matches.is_present("debug") {159 log::set_max_level(log::LevelFilter::Debug);160 } else {161 log::set_max_level(log::LevelFilter::Warn);162 }163 set_messages(!matches.is_present("no-messages"));164 set_ignore_messages(!matches.is_present("no-ignore-messages"));165 matches.to_args()166 }167168 /// Return direct access to command line arguments.169 fn matches(&self) -> &ArgMatches {170 &self.0.matches171 }172173 /// Return the matcher builder from the patterns.174 fn matcher(&self) -> &PatternMatcher {175 &self.0.matcher176 }177178 /// Return the paths found in the command line arguments. This is179 /// guaranteed to be non-empty. In the case where no explicit arguments are180 /// provided, a single default path is provided automatically.181 fn paths(&self) -> &[PathBuf] {182 &self.0.paths183 }184185 /// Returns true if and only if `paths` had to be populated with a default186 /// path, which occurs only when no paths were given as command line187 /// arguments.188 pub fn using_default_path(&self) -> bool {189 self.0.using_default_path190 }191192 /// Return the printer that should be used for formatting the output of193 /// search results.194 ///195 /// The returned printer will write results to the given writer.196 fn printer<W: WriteColor>(&self, wtr: W) -> anyhow::Result<Printer<W>> {197 match self.matches().output_kind() {198 OutputKind::Standard => {199 let separator_search = self.command() == Command::Search;200 self.matches()201 .printer_standard(self.paths(), wtr, separator_search)202 .map(Printer::Standard)203 }204 OutputKind::Summary => self205 .matches()206 .printer_summary(self.paths(), wtr)207 .map(Printer::Summary),208 OutputKind::JSON => {209 self.matches().printer_json(wtr).map(Printer::JSON)210 }211 }212 }213}214215/// High level public routines for building data structures used by ripgrep216/// from command line arguments.217impl Args {218 /// Create a new buffer writer for multi-threaded printing with color219 /// support.220 pub fn buffer_writer(&self) -> anyhow::Result<BufferWriter> {221 let mut wtr = BufferWriter::stdout(self.matches().color_choice());222 wtr.separator(self.matches().file_separator()?);223 Ok(wtr)224 }225226 /// Return the high-level command that ripgrep should run.227 pub fn command(&self) -> Command {228 self.0.command229 }230231 /// Builder a path printer that can be used for printing just file paths,232 /// with optional color support.233 ///234 /// The printer will print paths to the given writer.235 pub fn path_printer<W: WriteColor>(236 &self,237 wtr: W,238 ) -> anyhow::Result<PathPrinter<W>> {239 let mut builder = PathPrinterBuilder::new();240 builder241 .color_specs(self.matches().color_specs()?)242 .hyperlink(self.matches().hyperlink_config()?)243 .separator(self.matches().path_separator()?)244 .terminator(self.matches().path_terminator().unwrap_or(b'\n'));245 Ok(builder.build(wtr))246 }247248 /// Returns true if and only if ripgrep should be "quiet."249 pub fn quiet(&self) -> bool {250 self.matches().is_present("quiet")251 }252253 /// Returns true if and only if the search should quit after finding the254 /// first match.255 pub fn quit_after_match(&self) -> anyhow::Result<bool> {256 Ok(self.matches().is_present("quiet") && self.stats()?.is_none())257 }258259 /// Build a worker for executing searches.260 ///261 /// Search results are written to the given writer.262 pub fn search_worker<W: WriteColor>(263 &self,264 wtr: W,265 ) -> anyhow::Result<SearchWorker<W>> {266 let matches = self.matches();267 let matcher = self.matcher().clone();268 let printer = self.printer(wtr)?;269 let searcher = matches.searcher(self.paths())?;270 let mut builder = SearchWorkerBuilder::new();271 builder272 .json_stats(matches.is_present("json"))273 .preprocessor(matches.preprocessor())?274 .preprocessor_globs(matches.preprocessor_globs()?)275 .search_zip(matches.is_present("search-zip"))276 .binary_detection_implicit(matches.binary_detection_implicit())277 .binary_detection_explicit(matches.binary_detection_explicit());278 Ok(builder.build(matcher, searcher, printer))279 }280281 /// Returns a zero value for tracking statistics if and only if it has been282 /// requested.283 ///284 /// When this returns a `Stats` value, then it is guaranteed that the285 /// search worker will be configured to track statistics as well.286 pub fn stats(&self) -> anyhow::Result<Option<Stats>> {287 Ok(if self.command().is_search() && self.matches().stats() {288 Some(Stats::new())289 } else {290 None291 })292 }293294 /// Return a builder for constructing subjects. A subject represents a295 /// single unit of something to search. Typically, this corresponds to a296 /// file or a stream such as stdin.297 pub fn subject_builder(&self) -> SubjectBuilder {298 let mut builder = SubjectBuilder::new();299 builder.strip_dot_prefix(self.using_default_path());300 builder301 }302303 /// Execute the given function with a writer to stdout that enables color304 /// support based on the command line configuration.305 pub fn stdout(&self) -> cli::StandardStream {306 let color = self.matches().color_choice();307 if self.matches().is_present("line-buffered") {308 cli::stdout_buffered_line(color)309 } else if self.matches().is_present("block-buffered") {310 cli::stdout_buffered_block(color)311 } else {312 cli::stdout(color)313 }314 }315316 /// Return the type definitions compiled into ripgrep.317 ///318 /// If there was a problem reading and parsing the type definitions, then319 /// this returns an error.320 pub fn type_defs(&self) -> anyhow::Result<Vec<FileTypeDef>> {321 Ok(self.matches().types()?.definitions().to_vec())322 }323324 /// Return a walker that never uses additional threads.325 pub fn walker(&self) -> anyhow::Result<Walk> {326 Ok(self327 .matches()328 .walker_builder(self.paths(), self.0.threads)?329 .build())330 }331332 /// Returns true if and only if `stat`-related sorting is required333 pub fn needs_stat_sort(&self) -> bool {334 return self.matches().sort_by().map_or(335 false,336 |sort_by| match sort_by.kind {337 SortByKind::LastModified338 | SortByKind::Created339 | SortByKind::LastAccessed => sort_by.check().is_ok(),340 _ => false,341 },342 );343 }344345 /// Sort subjects if a sorter is specified, but only if the sort requires346 /// stat calls. Non-stat related sorts are handled during file traversal347 ///348 /// This function assumes that it is known that a stat-related sort is349 /// required, and does not check for it again.350 ///351 /// It is important that that precondition is fulfilled, since this function352 /// consumes the subjects iterator, and is therefore a blocking function.353 pub fn sort_by_stat<I>(&self, subjects: I) -> Vec<Subject>354 where355 I: Iterator<Item = Subject>,356 {357 let sorter = match self.matches().sort_by() {358 Ok(v) => v,359 Err(_) => return subjects.collect(),360 };361 use SortByKind::*;362 let mut keyed = match sorter.kind {363 LastModified => load_timestamps(subjects, |m| m.modified()),364 LastAccessed => load_timestamps(subjects, |m| m.accessed()),365 Created => load_timestamps(subjects, |m| m.created()),366 _ => return subjects.collect(),367 };368 keyed.sort_by(|a, b| sort_by_option(&a.0, &b.0, sorter.reverse));369 keyed.into_iter().map(|v| v.1).collect()370 }371372 /// Return a parallel walker that may use additional threads.373 pub fn walker_parallel(&self) -> anyhow::Result<WalkParallel> {374 Ok(self375 .matches()376 .walker_builder(self.paths(), self.0.threads)?377 .build_parallel())378 }379}380381/// `ArgMatches` wraps `clap::ArgMatches` and provides semantic meaning to382/// the parsed arguments.383#[derive(Clone, Debug)]384struct ArgMatches(clap::ArgMatches<'static>);385386/// The output format. Generally, this corresponds to the printer that ripgrep387/// uses to show search results.388#[derive(Clone, Copy, Debug, Eq, PartialEq)]389enum OutputKind {390 /// Classic grep-like or ack-like format.391 Standard,392 /// Show matching files and possibly the number of matches in each file.393 Summary,394 /// Emit match information in the JSON Lines format.395 JSON,396}397398/// The sort criteria, if present.399#[derive(Clone, Copy, Debug, Eq, PartialEq)]400struct SortBy {401 /// Whether to reverse the sort criteria (i.e., descending order).402 reverse: bool,403 /// The actual sorting criteria.404 kind: SortByKind,405}406407#[derive(Clone, Copy, Debug, Eq, PartialEq)]408enum SortByKind {409 /// No sorting at all.410 None,411 /// Sort by path.412 Path,413 /// Sort by last modified time.414 LastModified,415 /// Sort by last accessed time.416 LastAccessed,417 /// Sort by creation time.418 Created,419}420421impl SortBy {422 fn asc(kind: SortByKind) -> SortBy {423 SortBy { reverse: false, kind }424 }425426 fn desc(kind: SortByKind) -> SortBy {427 SortBy { reverse: true, kind }428 }429430 fn none() -> SortBy {431 SortBy::asc(SortByKind::None)432 }433434 /// Try to check that the sorting criteria selected is actually supported.435 /// If it isn't, then an error is returned.436 fn check(&self) -> anyhow::Result<()> {437 match self.kind {438 SortByKind::None | SortByKind::Path => {}439 SortByKind::LastModified => {440 env::current_exe()?.metadata()?.modified()?;441 }442 SortByKind::LastAccessed => {443 env::current_exe()?.metadata()?.accessed()?;444 }445 SortByKind::Created => {446 env::current_exe()?.metadata()?.created()?;447 }448 }449 Ok(())450 }451452 /// Load sorters only if they are applicable at the walk stage.453 ///454 /// In particular, sorts that involve `stat` calls are not loaded because455 /// the walk inherently assumes that parent directories are aware of all its456 /// decendent properties, but `stat` does not work that way.457 fn configure_builder_sort(self, builder: &mut WalkBuilder) {458 use SortByKind::*;459 match self.kind {460 Path if self.reverse => {461 builder.sort_by_file_name(|a, b| a.cmp(b).reverse());462 }463 Path => {464 builder.sort_by_file_name(|a, b| a.cmp(b));465 }466 // these use `stat` calls and will be sorted in Args::sort_by_stat()467 LastModified | LastAccessed | Created | None => {}468 };469 }470}471472impl SortByKind {473 fn new(kind: &str) -> SortByKind {474 match kind {475 "none" => SortByKind::None,476 "path" => SortByKind::Path,477 "modified" => SortByKind::LastModified,478 "accessed" => SortByKind::LastAccessed,479 "created" => SortByKind::Created,480 _ => SortByKind::None,481 }482 }483}484485/// Encoding mode the searcher will use.486#[derive(Clone, Debug)]487enum EncodingMode {488 /// Use an explicit encoding forcefully, but let BOM sniffing override it.489 Some(Encoding),490 /// Use only BOM sniffing to auto-detect an encoding.491 Auto,492 /// Use no explicit encoding and disable all BOM sniffing. This will493 /// always result in searching the raw bytes, regardless of their494 /// true encoding.495 Disabled,496}497498impl ArgMatches {499 /// Create an ArgMatches from clap's parse result.500 fn new(clap_matches: clap::ArgMatches<'static>) -> ArgMatches {501 ArgMatches(clap_matches)502 }503504 /// Run clap and return the matches using a config file if present. If clap505 /// determines a problem with the user provided arguments (or if --help or506 /// --version are given), then an error/usage/version will be printed and507 /// the process will exit.508 ///509 /// If there are no additional arguments from the environment (e.g., a510 /// config file), then the given matches are returned as is.511 fn reconfigure(self) -> anyhow::Result<ArgMatches> {512 // If the end user says no config, then respect it.513 if self.is_present("no-config") {514 log::debug!(515 "not reading config files because --no-config is present"516 );517 return Ok(self);518 }519 // If the user wants ripgrep to use a config file, then parse args520 // from that first.521 let mut args = config::args();522 if args.is_empty() {523 return Ok(self);524 }525 let mut cliargs = env::args_os();526 if let Some(bin) = cliargs.next() {527 args.insert(0, bin);528 }529 args.extend(cliargs);530 log::debug!("final argv: {:?}", args);531 Ok(ArgMatches(clap_matches(args)?))532 }533534 /// Convert the result of parsing CLI arguments into ripgrep's higher level535 /// configuration structure.536 fn to_args(self) -> anyhow::Result<Args> {537 // We compute these once since they could be large.538 let patterns = self.patterns()?;539 let matcher = self.matcher(&patterns)?;540 let mut paths = self.paths();541 let using_default_path = if paths.is_empty() {542 paths.push(self.path_default());543 true544 } else {545 false546 };547 // Now figure out the number of threads we'll use and which548 // command will run.549 let is_one_search = self.is_one_search(&paths);550 let threads = if is_one_search { 1 } else { self.threads()? };551 if threads == 1 {552 log::debug!("running in single threaded mode");553 } else {554 log::debug!("running with {threads} threads for parallelism");555 }556 let command = if self.is_present("pcre2-version") {557 Command::PCRE2Version558 } else if self.is_present("type-list") {559 Command::Types560 } else if self.is_present("files") {561 if threads == 1 {562 Command::Files563 } else {564 Command::FilesParallel565 }566 } else if self.can_never_match(&patterns) {567 Command::SearchNever568 } else if threads == 1 {569 Command::Search570 } else {571 Command::SearchParallel572 };573 Ok(Args(Arc::new(ArgsImp {574 matches: self,575 command,576 threads,577 matcher,578 paths,579 using_default_path,580 })))581 }582}583584/// High level routines for converting command line arguments into various585/// data structures used by ripgrep.586///587/// Methods are sorted alphabetically.588impl ArgMatches {589 /// Return the matcher that should be used for searching.590 ///591 /// If there was a problem building the matcher (e.g., a syntax error),592 /// then this returns an error.593 fn matcher(&self, patterns: &[String]) -> anyhow::Result<PatternMatcher> {594 if self.is_present("pcre2") {595 self.matcher_engine("pcre2", patterns)596 } else if self.is_present("auto-hybrid-regex") {597 self.matcher_engine("auto", patterns)598 } else {599 let engine = self.value_of_lossy("engine").unwrap();600 self.matcher_engine(&engine, patterns)601 }602 }603604 /// Return the matcher that should be used for searching using engine605 /// as the engine for the patterns.606 ///607 /// If there was a problem building the matcher (e.g., a syntax error),608 /// then this returns an error.609 fn matcher_engine(610 &self,611 engine: &str,612 patterns: &[String],613 ) -> anyhow::Result<PatternMatcher> {614 match engine {615 "default" => {616 let matcher = match self.matcher_rust(patterns) {617 Ok(matcher) => matcher,618 Err(err) => {619 anyhow::bail!(suggest(err.to_string()));620 }621 };622 Ok(PatternMatcher::RustRegex(matcher))623 }624 #[cfg(feature = "pcre2")]625 "pcre2" => {626 let matcher = self.matcher_pcre2(patterns)?;627 Ok(PatternMatcher::PCRE2(matcher))628 }629 #[cfg(not(feature = "pcre2"))]630 "pcre2" => anyhow::bail!(631 "PCRE2 is not available in this build of ripgrep",632 ),633 "auto" => {634 let rust_err = match self.matcher_rust(patterns) {635 Ok(matcher) => {636 return Ok(PatternMatcher::RustRegex(matcher));637 }638 Err(err) => err,639 };640 log::debug!(641 "error building Rust regex in hybrid mode:\n{}",642 rust_err,643 );644645 let pcre_err = match self.matcher_engine("pcre2", patterns) {646 Ok(matcher) => return Ok(matcher),647 Err(err) => err,648 };649 let divider = "~".repeat(79);650 anyhow::bail!(651 "regex could not be compiled with either the default \652 regex engine or with PCRE2.\n\n\653 default regex engine error:\n\654 {divider}\n\655 {rust_err}\n\656 {divider}\n\n\657 PCRE2 regex engine error:\n{pcre_err}",658 );659 }660 _ => anyhow::bail!("unrecognized regex engine '{engine}'"),661 }662 }663664 /// Build a matcher using Rust's regex engine.665 ///666 /// If there was a problem building the matcher (such as a regex syntax667 /// error), then an error is returned.668 fn matcher_rust(669 &self,670 patterns: &[String],671 ) -> anyhow::Result<RustRegexMatcher> {672 let mut builder = RustRegexMatcherBuilder::new();673 builder674 .case_smart(self.case_smart())675 .case_insensitive(self.case_insensitive())676 .multi_line(true)677 .unicode(self.unicode())678 .octal(false)679 .fixed_strings(self.is_present("fixed-strings"))680 .whole_line(self.is_present("line-regexp"))681 .word(self.is_present("word-regexp"));682 if self.is_present("multiline") {683 builder.dot_matches_new_line(self.is_present("multiline-dotall"));684 if self.is_present("crlf") {685 builder.crlf(true).line_terminator(None);686 }687 } else {688 builder.line_terminator(Some(b'\n')).dot_matches_new_line(false);689 if self.is_present("crlf") {690 builder.crlf(true);691 }692 // We don't need to set this in multiline mode since mulitline693 // matchers don't use optimizations related to line terminators.694 // Moreover, a mulitline regex used with --null-data should695 // be allowed to match NUL bytes explicitly, which this would696 // otherwise forbid.697 if self.is_present("null-data") {698 builder.line_terminator(Some(b'\x00'));699 }700 }701 if let Some(limit) = self.regex_size_limit()? {702 builder.size_limit(limit);703 }704 if let Some(limit) = self.dfa_size_limit()? {705 builder.dfa_size_limit(limit);706 }707 match builder.build_many(patterns) {708 Ok(m) => Ok(m),709 Err(err) => anyhow::bail!(suggest_multiline(err.to_string())),710 }711 }712713 /// Build a matcher using PCRE2.714 ///715 /// If there was a problem building the matcher (such as a regex syntax716 /// error), then an error is returned.717 #[cfg(feature = "pcre2")]718 fn matcher_pcre2(719 &self,720 patterns: &[String],721 ) -> anyhow::Result<PCRE2RegexMatcher> {722 let mut builder = PCRE2RegexMatcherBuilder::new();723 builder724 .case_smart(self.case_smart())725 .caseless(self.case_insensitive())726 .multi_line(true)727 .fixed_strings(self.is_present("fixed-strings"))728 .whole_line(self.is_present("line-regexp"))729 .word(self.is_present("word-regexp"));730 // For whatever reason, the JIT craps out during regex compilation with731 // a "no more memory" error on 32 bit systems. So don't use it there.732 if cfg!(target_pointer_width = "64") {733 builder734 .jit_if_available(true)735 // The PCRE2 docs say that 32KB is the default, and that 1MB736 // should be big enough for anything. But let's crank it to737 // 10MB.738 .max_jit_stack_size(Some(10 * (1 << 20)));739 }740 if self.unicode() {741 builder.utf(true).ucp(true);742 }743 if self.is_present("multiline") {744 builder.dotall(self.is_present("multiline-dotall"));745 }746 if self.is_present("crlf") {747 builder.crlf(true);748 }749 Ok(builder.build_many(patterns)?)750 }751752 /// Build a JSON printer that writes results to the given writer.753 fn printer_json<W: io::Write>(&self, wtr: W) -> anyhow::Result<JSON<W>> {754 let mut builder = JSONBuilder::new();755 builder756 .pretty(false)757 .max_matches(self.max_count()?)758 .always_begin_end(false);759 Ok(builder.build(wtr))760 }761762 /// Build a Standard printer that writes results to the given writer.763 ///764 /// The given paths are used to configure aspects of the printer.765 ///766 /// If `separator_search` is true, then the returned printer will assume767 /// the responsibility of printing a separator between each set of768 /// search results, when appropriate (e.g., when contexts are enabled).769 /// When it's set to false, the caller is responsible for handling770 /// separators.771 ///772 /// In practice, we want the printer to handle it in the single threaded773 /// case but not in the multi-threaded case.774 fn printer_standard<W: WriteColor>(775 &self,776 paths: &[PathBuf],777 wtr: W,778 separator_search: bool,779 ) -> anyhow::Result<Standard<W>> {780 let mut builder = StandardBuilder::new();781 builder782 .color_specs(self.color_specs()?)783 .hyperlink(self.hyperlink_config()?)784 .stats(self.stats())785 .heading(self.heading())786 .path(self.with_filename(paths))787 .only_matching(self.is_present("only-matching"))788 .per_match(self.is_present("vimgrep"))789 .per_match_one_line(true)790 .replacement(self.replacement())791 .max_columns(self.max_columns()?)792 .max_columns_preview(self.max_columns_preview())793 .max_matches(self.max_count()?)794 .column(self.column())795 .byte_offset(self.is_present("byte-offset"))796 .trim_ascii(self.is_present("trim"))797 .separator_search(None)798 .separator_context(self.context_separator())799 .separator_field_match(self.field_match_separator())800 .separator_field_context(self.field_context_separator())801 .separator_path(self.path_separator()?)802 .path_terminator(self.path_terminator());803 if separator_search {804 builder.separator_search(self.file_separator()?);805 }806 Ok(builder.build(wtr))807 }808809 /// Build a Summary printer that writes results to the given writer.810 ///811 /// The given paths are used to configure aspects of the printer.812 ///813 /// This panics if the output format is not `OutputKind::Summary`.814 fn printer_summary<W: WriteColor>(815 &self,816 paths: &[PathBuf],817 wtr: W,818 ) -> anyhow::Result<Summary<W>> {819 let mut builder = SummaryBuilder::new();820 builder821 .kind(self.summary_kind().expect("summary format"))822 .color_specs(self.color_specs()?)823 .hyperlink(self.hyperlink_config()?)824 .stats(self.stats())825 .path(self.with_filename(paths))826 .max_matches(self.max_count()?)827 .exclude_zero(!self.is_present("include-zero"))828 .separator_field(b":".to_vec())829 .separator_path(self.path_separator()?)830 .path_terminator(self.path_terminator());831 Ok(builder.build(wtr))832 }833834 /// Build a searcher from the command line parameters.835 fn searcher(&self, paths: &[PathBuf]) -> anyhow::Result<Searcher> {836 let (ctx_before, ctx_after) = self.contexts()?;837 let line_term = if self.is_present("crlf") {838 LineTerminator::crlf()839 } else if self.is_present("null-data") {840 LineTerminator::byte(b'\x00')841 } else {842 LineTerminator::byte(b'\n')843 };844 let mut builder = SearcherBuilder::new();845 builder846 .line_terminator(line_term)847 .invert_match(self.is_present("invert-match"))848 .line_number(self.line_number(paths))849 .multi_line(self.is_present("multiline"))850 .before_context(ctx_before)851 .after_context(ctx_after)852 .passthru(self.is_present("passthru"))853 .memory_map(self.mmap_choice(paths))854 .stop_on_nonmatch(self.is_present("stop-on-nonmatch"));855 match self.encoding()? {856 EncodingMode::Some(enc) => {857 builder.encoding(Some(enc));858 }859 EncodingMode::Auto => {} // default for the searcher860 EncodingMode::Disabled => {861 builder.bom_sniffing(false);862 }863 }864 Ok(builder.build())865 }866867 /// Return a builder for recursively traversing a directory while868 /// respecting ignore rules.869 ///870 /// If there was a problem parsing the CLI arguments necessary for871 /// constructing the builder, then this returns an error.872 fn walker_builder(873 &self,874 paths: &[PathBuf],875 threads: usize,876 ) -> anyhow::Result<WalkBuilder> {877 let mut builder = WalkBuilder::new(&paths[0]);878 for path in &paths[1..] {879 builder.add(path);880 }881 if !self.no_ignore_files() {882 for path in self.ignore_paths() {883 if let Some(err) = builder.add_ignore(path) {884 ignore_message!("{}", err);885 }886 }887 }888 builder889 .max_depth(self.usize_of("max-depth")?)890 .follow_links(self.is_present("follow"))891 .max_filesize(self.max_file_size()?)892 .threads(threads)893 .same_file_system(self.is_present("one-file-system"))894 .skip_stdout(!self.is_present("files"))895 .overrides(self.overrides()?)896 .types(self.types()?)897 .hidden(!self.hidden())898 .parents(!self.no_ignore_parent())899 .ignore(!self.no_ignore_dot())900 .git_global(!self.no_ignore_vcs() && !self.no_ignore_global())901 .git_ignore(!self.no_ignore_vcs())902 .git_exclude(!self.no_ignore_vcs() && !self.no_ignore_exclude())903 .require_git(!self.is_present("no-require-git"))904 .ignore_case_insensitive(self.ignore_file_case_insensitive());905 if !self.no_ignore() && !self.no_ignore_dot() {906 builder.add_custom_ignore_filename(".rgignore");907 }908 self.sort_by()?.configure_builder_sort(&mut builder);909 Ok(builder)910 }911}912913/// Mid level routines for converting command line arguments into various types914/// of data structures.915///916/// Methods are sorted alphabetically.917impl ArgMatches {918 /// Returns the form of binary detection to perform on files that are919 /// implicitly searched via recursive directory traversal.920 fn binary_detection_implicit(&self) -> BinaryDetection {921 let none = self.is_present("text") || self.is_present("null-data");922 let convert =923 self.is_present("binary") || self.unrestricted_count() >= 3;924 if none {925 BinaryDetection::none()926 } else if convert {927 BinaryDetection::convert(b'\x00')928 } else {929 BinaryDetection::quit(b'\x00')930 }931 }932933 /// Returns the form of binary detection to perform on files that are934 /// explicitly searched via the user invoking ripgrep on a particular935 /// file or files or stdin.936 ///937 /// In general, this should never be BinaryDetection::quit, since that acts938 /// as a filter (but quitting immediately once a NUL byte is seen), and we939 /// should never filter out files that the user wants to explicitly search.940 fn binary_detection_explicit(&self) -> BinaryDetection {941 let none = self.is_present("text") || self.is_present("null-data");942 if none {943 BinaryDetection::none()944 } else {945 BinaryDetection::convert(b'\x00')946 }947 }948949 /// Returns true if the command line configuration implies that a match950 /// can never be shown.951 fn can_never_match(&self, patterns: &[String]) -> bool {952 patterns.is_empty() || self.max_count().ok() == Some(Some(0))953 }954955 /// Returns true if and only if case should be ignore.956 ///957 /// If --case-sensitive is present, then case is never ignored, even if958 /// --ignore-case is present.959 fn case_insensitive(&self) -> bool {960 self.is_present("ignore-case") && !self.is_present("case-sensitive")961 }962963 /// Returns true if and only if smart case has been enabled.964 ///965 /// If either --ignore-case of --case-sensitive are present, then smart966 /// case is disabled.967 fn case_smart(&self) -> bool {968 self.is_present("smart-case")969 && !self.is_present("ignore-case")970 && !self.is_present("case-sensitive")971 }972973 /// Returns the user's color choice based on command line parameters and974 /// environment.975 fn color_choice(&self) -> ColorChoice {976 let preference = match self.value_of_lossy("color") {977 None => "auto".to_string(),978 Some(v) => v,979 };980 if preference == "always" {981 ColorChoice::Always982 } else if preference == "ansi" {983 ColorChoice::AlwaysAnsi984 } else if preference == "auto" {985 if std::io::stdout().is_terminal() || self.is_present("pretty") {986 ColorChoice::Auto987 } else {988 ColorChoice::Never989 }990 } else {991 ColorChoice::Never992 }993 }994995 /// Returns the color specifications given by the user on the CLI.996 ///997 /// If the was a problem parsing any of the provided specs, then an error998 /// is returned.999 fn color_specs(&self) -> anyhow::Result<ColorSpecs> {1000 // Start with a default set of color specs.1001 let mut specs = default_color_specs();1002 for spec_str in self.values_of_lossy_vec("colors") {1003 specs.push(spec_str.parse()?);1004 }1005 Ok(ColorSpecs::new(&specs))1006 }10071008 /// Returns true if and only if column numbers should be shown.1009 fn column(&self) -> bool {1010 if self.is_present("no-column") {1011 return false;1012 }1013 self.is_present("column") || self.is_present("vimgrep")1014 }10151016 /// Returns the before and after contexts from the command line.1017 ///1018 /// If a context setting was absent, then `0` is returned.1019 ///1020 /// If there was a problem parsing the values from the user as an integer,1021 /// then an error is returned.1022 fn contexts(&self) -> anyhow::Result<(usize, usize)> {1023 let both = self.usize_of("context")?.unwrap_or(0);1024 let after = self.usize_of("after-context")?.unwrap_or(both);1025 let before = self.usize_of("before-context")?.unwrap_or(both);1026 Ok((before, after))1027 }10281029 /// Returns the unescaped context separator in UTF-8 bytes.1030 ///1031 /// If one was not provided, the default `--` is returned.1032 /// If --no-context-separator is passed, None is returned.1033 fn context_separator(&self) -> Option<Vec<u8>> {1034 let nosep = self.is_present("no-context-separator");1035 let sep = self.value_of_os("context-separator");1036 match (nosep, sep) {1037 (true, _) => None,1038 (false, None) => Some(b"--".to_vec()),1039 (false, Some(sep)) => Some(cli::unescape_os(&sep)),1040 }1041 }10421043 /// Returns whether the -c/--count or the --count-matches flags were1044 /// passed from the command line.1045 ///1046 /// If --count-matches and --invert-match were passed in, behave1047 /// as if --count and --invert-match were passed in (i.e. rg will1048 /// count inverted matches as per existing behavior).1049 fn counts(&self) -> (bool, bool) {1050 let count = self.is_present("count");1051 let count_matches = self.is_present("count-matches");1052 let invert_matches = self.is_present("invert-match");1053 let only_matching = self.is_present("only-matching");1054 if count_matches && invert_matches {1055 // Treat `-v --count-matches` as `-v -c`.1056 (true, false)1057 } else if count && only_matching {1058 // Treat `-c --only-matching` as `--count-matches`.1059 (false, true)1060 } else {1061 (count, count_matches)1062 }1063 }10641065 /// Parse the dfa-size-limit argument option into a byte count.1066 fn dfa_size_limit(&self) -> anyhow::Result<Option<usize>> {1067 let r = self.parse_human_readable_size("dfa-size-limit")?;1068 u64_to_usize("dfa-size-limit", r)1069 }10701071 /// Returns the encoding mode to use.1072 ///1073 /// This only returns an encoding if one is explicitly specified. Otherwise1074 /// if set to automatic, the Searcher will do BOM sniffing for UTF-161075 /// and transcode seamlessly. If disabled, no BOM sniffing nor transcoding1076 /// will occur.1077 fn encoding(&self) -> anyhow::Result<EncodingMode> {1078 if self.is_present("no-encoding") {1079 return Ok(EncodingMode::Auto);1080 }10811082 let label = match self.value_of_lossy("encoding") {1083 None => return Ok(EncodingMode::Auto),1084 Some(label) => label,1085 };10861087 if label == "auto" {1088 return Ok(EncodingMode::Auto);1089 } else if label == "none" {1090 return Ok(EncodingMode::Disabled);1091 }10921093 Ok(EncodingMode::Some(Encoding::new(&label)?))1094 }10951096 /// Return the file separator to use based on the CLI configuration.1097 fn file_separator(&self) -> anyhow::Result<Option<Vec<u8>>> {1098 // File separators are only used for the standard grep-line format.1099 if self.output_kind() != OutputKind::Standard {1100 return Ok(None);1101 }11021103 let (ctx_before, ctx_after) = self.contexts()?;1104 Ok(if self.heading() {1105 Some(b"".to_vec())1106 } else if ctx_before > 0 || ctx_after > 0 {1107 self.context_separator()1108 } else {1109 None1110 })1111 }11121113 /// Returns true if and only if matches should be grouped with file name1114 /// headings.1115 fn heading(&self) -> bool {1116 if self.is_present("no-heading") || self.is_present("vimgrep") {1117 false1118 } else {1119 std::io::stdout().is_terminal()1120 || self.is_present("heading")1121 || self.is_present("pretty")1122 }1123 }11241125 /// Returns true if and only if hidden files/directories should be1126 /// searched.1127 fn hidden(&self) -> bool {1128 self.is_present("hidden") || self.unrestricted_count() >= 21129 }11301131 /// Returns the hyperlink pattern to use. A default pattern suitable1132 /// for the current system is used if the value is not set.1133 ///1134 /// If an invalid pattern is provided, then an error is returned.1135 fn hyperlink_config(&self) -> anyhow::Result<HyperlinkConfig> {1136 let mut env = HyperlinkEnvironment::new();1137 env.host(hostname(self.value_of_os("hostname-bin")))1138 .wsl_prefix(wsl_prefix());1139 let fmt: HyperlinkFormat =1140 match self.value_of_lossy("hyperlink-format") {1141 None => "none".parse().unwrap(),1142 Some(format) => match format.parse() {1143 Ok(format) => format,1144 Err(err) => {1145 anyhow::bail!("invalid hyperlink format: {err}");1146 }1147 },1148 };1149 log::debug!("hyperlink format: {:?}", fmt.to_string());1150 Ok(HyperlinkConfig::new(env, fmt))1151 }11521153 /// Returns true if ignore files should be processed case insensitively.1154 fn ignore_file_case_insensitive(&self) -> bool {1155 self.is_present("ignore-file-case-insensitive")1156 }11571158 /// Return all of the ignore file paths given on the command line.1159 fn ignore_paths(&self) -> Vec<PathBuf> {1160 let paths = match self.values_of_os("ignore-file") {1161 None => return vec![],1162 Some(paths) => paths,1163 };1164 paths.map(|p| Path::new(p).to_path_buf()).collect()1165 }11661167 /// Returns true if and only if ripgrep is invoked in a way where it knows1168 /// it search exactly one thing.1169 fn is_one_search(&self, paths: &[PathBuf]) -> bool {1170 if paths.len() != 1 {1171 return false;1172 }1173 self.is_only_stdin(paths) || paths[0].is_file()1174 }11751176 /// Returns true if and only if we're only searching a single thing and1177 /// that thing is stdin.1178 fn is_only_stdin(&self, paths: &[PathBuf]) -> bool {1179 paths == [Path::new("-")]1180 }11811182 /// Returns true if and only if we should show line numbers.1183 fn line_number(&self, paths: &[PathBuf]) -> bool {1184 if self.output_kind() == OutputKind::Summary {1185 return false;1186 }1187 if self.is_present("no-line-number") {1188 return false;1189 }1190 if self.output_kind() == OutputKind::JSON {1191 return true;1192 }11931194 // A few things can imply counting line numbers. In particular, we1195 // generally want to show line numbers by default when printing to a1196 // tty for human consumption, except for one interesting case: when1197 // we're only searching stdin. This makes pipelines work as expected.1198 (std::io::stdout().is_terminal() && !self.is_only_stdin(paths))1199 || self.is_present("line-number")1200 || self.is_present("column")1201 || self.is_present("pretty")1202 || self.is_present("vimgrep")1203 }12041205 /// The maximum number of columns allowed on each line.1206 ///1207 /// If `0` is provided, then this returns `None`.1208 fn max_columns(&self) -> anyhow::Result<Option<u64>> {1209 Ok(self.usize_of_nonzero("max-columns")?.map(|n| n as u64))1210 }12111212 /// Returns true if and only if a preview should be shown for lines that1213 /// exceed the maximum column limit.1214 fn max_columns_preview(&self) -> bool {1215 self.is_present("max-columns-preview")1216 }12171218 /// The maximum number of matches permitted.1219 fn max_count(&self) -> anyhow::Result<Option<u64>> {1220 Ok(self.usize_of("max-count")?.map(|n| n as u64))1221 }12221223 /// Parses the max-filesize argument option into a byte count.1224 fn max_file_size(&self) -> anyhow::Result<Option<u64>> {1225 self.parse_human_readable_size("max-filesize")1226 }12271228 /// Returns whether we should attempt to use memory maps or not.1229 fn mmap_choice(&self, paths: &[PathBuf]) -> MmapChoice {1230 // SAFETY: Memory maps are difficult to impossible to encapsulate1231 // safely in a portable way that doesn't simultaneously negate some of1232 // the benfits of using memory maps. For ripgrep's use, we never mutate1233 // a memory map and generally never store the contents of memory map1234 // in a data structure that depends on immutability. Generally1235 // speaking, the worst thing that can happen is a SIGBUS (if the1236 // underlying file is truncated while reading it), which will cause1237 // ripgrep to abort. This reasoning should be treated as suspect.1238 let maybe = unsafe { MmapChoice::auto() };1239 let never = MmapChoice::never();1240 if self.is_present("no-mmap") {1241 never1242 } else if self.is_present("mmap") {1243 maybe1244 } else if paths.len() <= 10 && paths.iter().all(|p| p.is_file()) {1245 // If we're only searching a few paths and all of them are1246 // files, then memory maps are probably faster.1247 maybe1248 } else {1249 never1250 }1251 }12521253 /// Returns true if ignore files should be ignored.1254 fn no_ignore(&self) -> bool {1255 self.is_present("no-ignore") || self.unrestricted_count() >= 11256 }12571258 /// Returns true if .ignore files should be ignored.1259 fn no_ignore_dot(&self) -> bool {1260 self.is_present("no-ignore-dot") || self.no_ignore()1261 }12621263 /// Returns true if local exclude (ignore) files should be ignored.1264 fn no_ignore_exclude(&self) -> bool {1265 self.is_present("no-ignore-exclude") || self.no_ignore()1266 }12671268 /// Returns true if explicitly given ignore files should be ignored.1269 fn no_ignore_files(&self) -> bool {1270 // We don't look at no-ignore here because --no-ignore is explicitly1271 // documented to not override --ignore-file. We could change this, but1272 // it would be a fairly severe breaking change.1273 self.is_present("no-ignore-files")1274 }12751276 /// Returns true if global ignore files should be ignored.1277 fn no_ignore_global(&self) -> bool {1278 self.is_present("no-ignore-global") || self.no_ignore()1279 }12801281 /// Returns true if parent ignore files should be ignored.1282 fn no_ignore_parent(&self) -> bool {1283 self.is_present("no-ignore-parent") || self.no_ignore()1284 }12851286 /// Returns true if VCS ignore files should be ignored.1287 fn no_ignore_vcs(&self) -> bool {1288 self.is_present("no-ignore-vcs") || self.no_ignore()1289 }12901291 /// Determine the type of output we should produce.1292 fn output_kind(&self) -> OutputKind {1293 if self.is_present("quiet") {1294 // While we don't technically print results (or aggregate results)1295 // in quiet mode, we still support the --stats flag, and those1296 // stats are computed by the Summary printer for now.1297 return OutputKind::Summary;1298 } else if self.is_present("json") {1299 return OutputKind::JSON;1300 }13011302 let (count, count_matches) = self.counts();1303 let summary = count1304 || count_matches1305 || self.is_present("files-with-matches")1306 || self.is_present("files-without-match");1307 if summary {1308 OutputKind::Summary1309 } else {1310 OutputKind::Standard1311 }1312 }13131314 /// Builds the set of glob overrides from the command line flags.1315 fn overrides(&self) -> anyhow::Result<Override> {1316 let globs = self.values_of_lossy_vec("glob");1317 let iglobs = self.values_of_lossy_vec("iglob");1318 if globs.is_empty() && iglobs.is_empty() {1319 return Ok(Override::empty());1320 }13211322 let mut builder = OverrideBuilder::new(current_dir()?);1323 // Make all globs case insensitive with --glob-case-insensitive.1324 if self.is_present("glob-case-insensitive") {1325 builder.case_insensitive(true).unwrap();1326 }1327 for glob in globs {1328 builder.add(&glob)?;1329 }1330 // This only enables case insensitivity for subsequent globs.1331 builder.case_insensitive(true).unwrap();1332 for glob in iglobs {1333 builder.add(&glob)?;1334 }1335 Ok(builder.build()?)1336 }13371338 /// Return all file paths that ripgrep should search.1339 ///1340 /// If no paths were given, then this returns an empty list.1341 fn paths(&self) -> Vec<PathBuf> {1342 let mut paths: Vec<PathBuf> = match self.values_of_os("path") {1343 None => vec![],1344 Some(paths) => paths.map(|p| Path::new(p).to_path_buf()).collect(),1345 };1346 // If --file, --files or --regexp is given, then the first path is1347 // always in `pattern`.1348 if self.is_present("file")1349 || self.is_present("files")1350 || self.is_present("regexp")1351 {1352 if let Some(path) = self.value_of_os("pattern") {1353 paths.insert(0, Path::new(path).to_path_buf());1354 }1355 }1356 paths1357 }13581359 /// Return the default path that ripgrep should search. This should only1360 /// be used when ripgrep is not otherwise given at least one file path1361 /// as a positional argument.1362 fn path_default(&self) -> PathBuf {1363 let file_is_stdin = self1364 .values_of_os("file")1365 .map_or(false, |mut files| files.any(|f| f == "-"));1366 let search_cwd = !cli::is_readable_stdin()1367 || (self.is_present("file") && file_is_stdin)1368 || self.is_present("files")1369 || self.is_present("type-list")1370 || self.is_present("pcre2-version");1371 if search_cwd {1372 Path::new("./").to_path_buf()1373 } else {1374 Path::new("-").to_path_buf()1375 }1376 }13771378 /// Returns the unescaped path separator as a single byte, if one exists.1379 ///1380 /// If the provided path separator is more than a single byte, then an1381 /// error is returned.1382 fn path_separator(&self) -> anyhow::Result<Option<u8>> {1383 let sep = match self.value_of_os("path-separator") {1384 None => return Ok(None),1385 Some(sep) => cli::unescape_os(&sep),1386 };1387 if sep.is_empty() {1388 Ok(None)1389 } else if sep.len() > 1 {1390 anyhow::bail!(1391 "A path separator must be exactly one byte, but \1392 the given separator is {} bytes: {}\n\1393 In some shells on Windows '/' is automatically \1394 expanded. Use '//' instead.",1395 sep.len(),1396 cli::escape(&sep),1397 )1398 } else {1399 Ok(Some(sep[0]))1400 }1401 }14021403 /// Returns the byte that should be used to terminate paths.1404 ///1405 /// Typically, this is only set to `\x00` when the --null flag is provided,1406 /// and `None` otherwise.1407 fn path_terminator(&self) -> Option<u8> {1408 if self.is_present("null") {1409 Some(b'\x00')1410 } else {1411 None1412 }1413 }14141415 /// Returns the unescaped field context separator. If one wasn't specified,1416 /// then '-' is used as the default.1417 fn field_context_separator(&self) -> Vec<u8> {1418 match self.value_of_os("field-context-separator") {1419 None => b"-".to_vec(),1420 Some(sep) => cli::unescape_os(&sep),1421 }1422 }14231424 /// Returns the unescaped field match separator. If one wasn't specified,1425 /// then ':' is used as the default.1426 fn field_match_separator(&self) -> Vec<u8> {1427 match self.value_of_os("field-match-separator") {1428 None => b":".to_vec(),1429 Some(sep) => cli::unescape_os(&sep),1430 }1431 }14321433 /// Get a sequence of all available patterns from the command line.1434 /// This includes reading the -e/--regexp and -f/--file flags.1435 ///1436 /// If any pattern is invalid UTF-8, then an error is returned.1437 fn patterns(&self) -> anyhow::Result<Vec<String>> {1438 if self.is_present("files") || self.is_present("type-list") {1439 return Ok(vec![]);1440 }1441 let mut seen = HashSet::new();1442 let mut pats = vec![];1443 let mut add = |pat: String| {1444 if !seen.contains(&pat) {1445 seen.insert(pat.clone());1446 pats.push(pat);1447 }1448 };1449 match self.values_of_os("regexp") {1450 None => {1451 if self.values_of_os("file").is_none() {1452 if let Some(os_pat) = self.value_of_os("pattern") {1453 add(self.pattern_from_os_str(os_pat)?);1454 }1455 }1456 }1457 Some(os_pats) => {1458 for os_pat in os_pats {1459 add(self.pattern_from_os_str(os_pat)?);1460 }1461 }1462 }1463 if let Some(paths) = self.values_of_os("file") {1464 for path in paths {1465 if path == "-" {1466 let it = cli::patterns_from_stdin()?1467 .into_iter()1468 .map(|p| self.pattern_from_string(p));1469 for pat in it {1470 add(pat);1471 }1472 } else {1473 let it = cli::patterns_from_path(path)?1474 .into_iter()1475 .map(|p| self.pattern_from_string(p));1476 for pat in it {1477 add(pat);1478 }1479 }1480 }1481 }1482 Ok(pats)1483 }14841485 /// Converts an OsStr pattern to a String pattern. The pattern is escaped1486 /// if -F/--fixed-strings is set.1487 ///1488 /// If the pattern is not valid UTF-8, then an error is returned.1489 fn pattern_from_os_str(&self, pat: &OsStr) -> anyhow::Result<String> {1490 let s = cli::pattern_from_os(pat)?;1491 Ok(self.pattern_from_str(s))1492 }14931494 /// Converts a &str pattern to a String pattern. The pattern is escaped1495 /// if -F/--fixed-strings is set.1496 fn pattern_from_str(&self, pat: &str) -> String {1497 self.pattern_from_string(pat.to_string())1498 }14991500 /// Applies additional processing on the given pattern if necessary1501 /// (such as escaping meta characters or turning it into a line regex).1502 fn pattern_from_string(&self, pat: String) -> String {1503 if pat.is_empty() {1504 // This would normally just be an empty string, which works on its1505 // own, but if the patterns are joined in a set of alternations,1506 // then you wind up with `foo|`, which is currently invalid in1507 // Rust's regex engine.1508 "(?:)".to_string()1509 } else {1510 pat1511 }1512 }15131514 /// Returns the preprocessor command if one was specified.1515 fn preprocessor(&self) -> Option<PathBuf> {1516 let path = match self.value_of_os("pre") {1517 None => return None,1518 Some(path) => path,1519 };1520 if path.is_empty() {1521 return None;1522 }1523 Some(Path::new(path).to_path_buf())1524 }15251526 /// Builds the set of globs for filtering files to apply to the --pre1527 /// flag. If no --pre-globs are available, then this always returns an1528 /// empty set of globs.1529 fn preprocessor_globs(&self) -> anyhow::Result<Override> {1530 let globs = self.values_of_lossy_vec("pre-glob");1531 if globs.is_empty() {1532 return Ok(Override::empty());1533 }1534 let mut builder = OverrideBuilder::new(current_dir()?);1535 for glob in globs {1536 builder.add(&glob)?;1537 }1538 Ok(builder.build()?)1539 }15401541 /// Parse the regex-size-limit argument option into a byte count.1542 fn regex_size_limit(&self) -> anyhow::Result<Option<usize>> {1543 let r = self.parse_human_readable_size("regex-size-limit")?;1544 u64_to_usize("regex-size-limit", r)1545 }15461547 /// Returns the replacement string as UTF-8 bytes if it exists.1548 fn replacement(&self) -> Option<Vec<u8>> {1549 self.value_of_lossy("replace").map(|s| s.into_bytes())1550 }15511552 /// Returns the sorting criteria based on command line parameters.1553 fn sort_by(&self) -> anyhow::Result<SortBy> {1554 // For backcompat, continue supporting deprecated --sort-files flag.1555 if self.is_present("sort-files") {1556 return Ok(SortBy::asc(SortByKind::Path));1557 }1558 let sortby = match self.value_of_lossy("sort") {1559 None => match self.value_of_lossy("sortr") {1560 None => return Ok(SortBy::none()),1561 Some(choice) => SortBy::desc(SortByKind::new(&choice)),1562 },1563 Some(choice) => SortBy::asc(SortByKind::new(&choice)),1564 };1565 Ok(sortby)1566 }15671568 /// Returns true if and only if aggregate statistics for a search should1569 /// be tracked.1570 ///1571 /// Generally, this is only enabled when explicitly requested by in the1572 /// command line arguments via the --stats flag, but this can also be1573 /// enabled implicitly via the output format, e.g., for JSON Lines.1574 fn stats(&self) -> bool {1575 self.output_kind() == OutputKind::JSON || self.is_present("stats")1576 }15771578 /// When the output format is `Summary`, this returns the type of summary1579 /// output to show.1580 ///1581 /// This returns `None` if the output format is not `Summary`.1582 fn summary_kind(&self) -> Option<SummaryKind> {1583 let (count, count_matches) = self.counts();1584 if self.is_present("quiet") {1585 Some(SummaryKind::Quiet)1586 } else if count_matches {1587 Some(SummaryKind::CountMatches)1588 } else if count {1589 Some(SummaryKind::Count)1590 } else if self.is_present("files-with-matches") {1591 Some(SummaryKind::PathWithMatch)1592 } else if self.is_present("files-without-match") {1593 Some(SummaryKind::PathWithoutMatch)1594 } else {1595 None1596 }1597 }15981599 /// Return the number of threads that should be used for parallelism.1600 fn threads(&self) -> anyhow::Result<usize> {1601 if self.sort_by()?.kind != SortByKind::None {1602 return Ok(1);1603 }1604 let threads = self.usize_of("threads")?.unwrap_or(0);1605 let available =1606 std::thread::available_parallelism().map_or(1, |n| n.get());1607 Ok(if threads == 0 { std::cmp::min(12, available) } else { threads })1608 }16091610 /// Builds a file type matcher from the command line flags.1611 fn types(&self) -> anyhow::Result<Types> {1612 let mut builder = TypesBuilder::new();1613 builder.add_defaults();1614 for ty in self.values_of_lossy_vec("type-clear") {1615 builder.clear(&ty);1616 }1617 for def in self.values_of_lossy_vec("type-add") {1618 builder.add_def(&def)?;1619 }1620 for ty in self.values_of_lossy_vec("type") {1621 builder.select(&ty);1622 }1623 for ty in self.values_of_lossy_vec("type-not") {1624 builder.negate(&ty);1625 }1626 builder.build().map_err(From::from)1627 }16281629 /// Returns the number of times the `unrestricted` flag is provided.1630 fn unrestricted_count(&self) -> u64 {1631 self.occurrences_of("unrestricted")1632 }16331634 /// Returns true if and only if Unicode mode should be enabled.1635 fn unicode(&self) -> bool {1636 // Unicode mode is enabled by default, so only disable it when1637 // --no-unicode is given explicitly.1638 !(self.is_present("no-unicode") || self.is_present("no-pcre2-unicode"))1639 }16401641 /// Returns true if and only if file names containing each match should1642 /// be emitted.1643 fn with_filename(&self, paths: &[PathBuf]) -> bool {1644 if self.is_present("no-filename") {1645 false1646 } else {1647 let path_stdin = Path::new("-");1648 self.is_present("with-filename")1649 || self.is_present("vimgrep")1650 || paths.len() > 11651 || paths1652 .get(0)1653 .map_or(false, |p| p != path_stdin && p.is_dir())1654 }1655 }1656}16571658/// Lower level generic helper methods for teasing values out of clap.1659impl ArgMatches {1660 /// Like values_of_lossy, but returns an empty vec if the flag is not1661 /// present.1662 fn values_of_lossy_vec(&self, name: &str) -> Vec<String> {1663 self.values_of_lossy(name).unwrap_or_else(Vec::new)1664 }16651666 /// Safely reads an arg value with the given name, and if it's present,1667 /// tries to parse it as a usize value.1668 ///1669 /// If the number is zero, then it is considered absent and `None` is1670 /// returned.1671 fn usize_of_nonzero(&self, name: &str) -> anyhow::Result<Option<usize>> {1672 let n = match self.usize_of(name)? {1673 None => return Ok(None),1674 Some(n) => n,1675 };1676 Ok(if n == 0 { None } else { Some(n) })1677 }16781679 /// Safely reads an arg value with the given name, and if it's present,1680 /// tries to parse it as a usize value.1681 fn usize_of(&self, name: &str) -> anyhow::Result<Option<usize>> {1682 match self.value_of_lossy(name) {1683 None => Ok(None),1684 Some(v) => v.parse().map(Some).map_err(From::from),1685 }1686 }16871688 /// Parses an argument of the form `[0-9]+(KMG)?`.1689 ///1690 /// If the aforementioned format is not recognized, then this returns an1691 /// error.1692 fn parse_human_readable_size(1693 &self,1694 arg_name: &str,1695 ) -> anyhow::Result<Option<u64>> {1696 let size = match self.value_of_lossy(arg_name) {1697 None => return Ok(None),1698 Some(size) => size,1699 };1700 Ok(Some(cli::parse_human_readable_size(&size)?))1701 }1702}17031704/// The following methods mostly dispatch to the underlying clap methods1705/// directly. Methods that would otherwise get a single value will fetch all1706/// values and return the last one. (Clap returns the first one.) We only1707/// define the ones we need.1708impl ArgMatches {1709 fn is_present(&self, name: &str) -> bool {1710 self.0.is_present(name)1711 }17121713 fn occurrences_of(&self, name: &str) -> u64 {1714 self.0.occurrences_of(name)1715 }17161717 fn value_of_lossy(&self, name: &str) -> Option<String> {1718 self.0.value_of_lossy(name).map(|s| s.into_owned())1719 }17201721 fn values_of_lossy(&self, name: &str) -> Option<Vec<String>> {1722 self.0.values_of_lossy(name)1723 }17241725 fn value_of_os(&self, name: &str) -> Option<&OsStr> {1726 self.0.value_of_os(name)1727 }17281729 fn values_of_os(&self, name: &str) -> Option<clap::OsValues<'_>> {1730 self.0.values_of_os(name)1731 }1732}17331734/// Inspect an error resulting from building a Rust regex matcher, and if it's1735/// believed to correspond to a syntax error that another engine could handle,1736/// then add a message to suggest the use of the engine flag.1737fn suggest(msg: String) -> String {1738 if let Some(pcre_msg) = suggest_pcre2(&msg) {1739 return pcre_msg;1740 }1741 msg1742}17431744/// Inspect an error resulting from building a Rust regex matcher, and if it's1745/// believed to correspond to a syntax error that PCRE2 could handle, then1746/// add a message to suggest the use of -P/--pcre2.1747fn suggest_pcre2(msg: &str) -> Option<String> {1748 #[cfg(feature = "pcre2")]1749 fn suggest(msg: &str) -> Option<String> {1750 if !msg.contains("backreferences") && !msg.contains("look-around") {1751 None1752 } else {1753 Some(format!(1754 "{}17551756Consider enabling PCRE2 with the --pcre2 flag, which can handle backreferences1757and look-around.",1758 msg1759 ))1760 }1761 }17621763 #[cfg(not(feature = "pcre2"))]1764 fn suggest(_: &str) -> Option<String> {1765 None1766 }17671768 suggest(msg)1769}17701771fn suggest_multiline(msg: String) -> String {1772 if msg.contains("the literal") && msg.contains("not allowed") {1773 format!(1774 "{msg}17751776Consider enabling multiline mode with the --multiline flag (or -U for short).1777When multiline mode is enabled, new line characters can be matched.",1778 )1779 } else {1780 msg1781 }1782}17831784/// Convert the result of parsing a human readable file size to a `usize`,1785/// failing if the type does not fit.1786fn u64_to_usize(1787 arg_name: &str,1788 value: Option<u64>,1789) -> anyhow::Result<Option<usize>> {1790 use std::usize;17911792 let Some(value) = value else { return Ok(None) };1793 usize::try_from(value)1794 .map_err(|_| anyhow::anyhow!("number too large for {arg_name}"))1795 .map(Some)1796}17971798/// Sorts by an optional parameter.1799//1800/// If parameter is found to be `None`, both entries compare equal.1801fn sort_by_option<T: Ord>(1802 p1: &Option<T>,1803 p2: &Option<T>,1804 reverse: bool,1805) -> std::cmp::Ordering {1806 match (p1, p2, reverse) {1807 (Some(p1), Some(p2), true) => p1.cmp(&p2).reverse(),1808 (Some(p1), Some(p2), false) => p1.cmp(&p2),1809 _ => std::cmp::Ordering::Equal,1810 }1811}18121813/// Returns a clap matches object if the given arguments parse successfully.1814///1815/// Otherwise, if an error occurred, then it is returned unless the error1816/// corresponds to a `--help` or `--version` request. In which case, the1817/// corresponding output is printed and the current process is exited1818/// successfully.1819fn clap_matches<I, T>(args: I) -> anyhow::Result<clap::ArgMatches<'static>>1820where1821 I: IntoIterator<Item = T>,1822 T: Into<OsString> + Clone,1823{1824 let err = match app::app().get_matches_from_safe(args) {1825 Ok(matches) => return Ok(matches),1826 Err(err) => err,1827 };1828 if err.use_stderr() {1829 return Err(err.into());1830 }1831 // Explicitly ignore any error returned by write!. The most likely error1832 // at this point is a broken pipe error, in which case, we want to ignore1833 // it and exit quietly.1834 //1835 // (This is the point of this helper function. clap's functionality for1836 // doing this will panic on a broken pipe error.)1837 let _ = write!(io::stdout(), "{}", err);1838 std::process::exit(0);1839}18401841/// Attempts to discover the current working directory. This mostly just defers1842/// to the standard library, however, such things will fail if ripgrep is in1843/// a directory that no longer exists. We attempt some fallback mechanisms,1844/// such as querying the PWD environment variable, but otherwise return an1845/// error.1846fn current_dir() -> anyhow::Result<PathBuf> {1847 let err = match env::current_dir() {1848 Err(err) => err,1849 Ok(cwd) => return Ok(cwd),1850 };1851 if let Some(cwd) = env::var_os("PWD") {1852 if !cwd.is_empty() {1853 return Ok(PathBuf::from(cwd));1854 }1855 }1856 anyhow::bail!(1857 "failed to get current working directory: {err} \1858 --- did your CWD get deleted?",1859 )1860}18611862/// Retrieves the hostname that ripgrep should use wherever a hostname is1863/// required. Currently, that's just in the hyperlink format.1864///1865/// This works by first running the given binary program (if present and with1866/// no arguments) to get the hostname after trimming leading and trailing1867/// whitespace. If that fails for any reason, then it falls back to getting1868/// the hostname via platform specific means (e.g., `gethostname` on Unix).1869///1870/// The purpose of `bin` is to make it possible for end users to override how1871/// ripgrep determines the hostname.1872fn hostname(bin: Option<&OsStr>) -> Option<String> {1873 let Some(bin) = bin else { return platform_hostname() };1874 let bin = match grep::cli::resolve_binary(bin) {1875 Ok(bin) => bin,1876 Err(err) => {1877 log::debug!(1878 "failed to run command '{bin:?}' to get hostname \1879 (falling back to platform hostname): {err}",1880 );1881 return platform_hostname();1882 }1883 };1884 let mut cmd = std::process::Command::new(&bin);1885 cmd.stdin(std::process::Stdio::null());1886 let rdr = match grep::cli::CommandReader::new(&mut cmd) {1887 Ok(rdr) => rdr,1888 Err(err) => {1889 log::debug!(1890 "failed to spawn command '{bin:?}' to get \1891 hostname (falling back to platform hostname): {err}",1892 );1893 return platform_hostname();1894 }1895 };1896 let out = match io::read_to_string(rdr) {1897 Ok(out) => out,1898 Err(err) => {1899 log::debug!(1900 "failed to read output from command '{bin:?}' to get \1901 hostname (falling back to platform hostname): {err}",1902 );1903 return platform_hostname();1904 }1905 };1906 let hostname = out.trim();1907 if hostname.is_empty() {1908 log::debug!(1909 "output from command '{bin:?}' is empty after trimming \1910 leading and trailing whitespace (falling back to \1911 platform hostname)",1912 );1913 return platform_hostname();1914 }1915 Some(hostname.to_string())1916}19171918/// Attempts to get the hostname by using platform specific routines. For1919/// example, this will do `gethostname` on Unix and `GetComputerNameExW` on1920/// Windows.1921fn platform_hostname() -> Option<String> {1922 let hostname_os = match grep::cli::hostname() {1923 Ok(x) => x,1924 Err(err) => {1925 log::debug!("could not get hostname: {}", err);1926 return None;1927 }1928 };1929 let Some(hostname) = hostname_os.to_str() else {1930 log::debug!(1931 "got hostname {:?}, but it's not valid UTF-8",1932 hostname_os1933 );1934 return None;1935 };1936 Some(hostname.to_string())1937}19381939/// Returns a value that is meant to fill in the `{wslprefix}` variable for1940/// a user given hyperlink format. A WSL prefix is a share/network like thing1941/// that is meant to permit Windows applications to open files stored within1942/// a WSL drive.1943///1944/// If a WSL distro name is unavailable, not valid UTF-8 or this isn't running1945/// in a Unix environment, then this returns None.1946///1947/// See: <https://learn.microsoft.com/en-us/windows/wsl/filesystems>1948fn wsl_prefix() -> Option<String> {1949 if !cfg!(unix) {1950 return None;1951 }1952 let distro_os = env::var_os("WSL_DISTRO_NAME")?;1953 let Some(distro) = distro_os.to_str() else {1954 log::debug!(1955 "found WSL_DISTRO_NAME={:?}, but value is not UTF-8",1956 distro_os1957 );1958 return None;1959 };1960 Some(format!("wsl$/{distro}"))1961}19621963/// Tries to assign a timestamp to every `Subject` in the vector to help with1964/// sorting Subjects by time.1965fn load_timestamps<G>(1966 subjects: impl Iterator<Item = Subject>,1967 get_time: G,1968) -> Vec<(Option<std::time::SystemTime>, Subject)>1969where1970 G: Fn(&std::fs::Metadata) -> io::Result<std::time::SystemTime>,1971{1972 subjects1973 .map(|s| (s.path().metadata().and_then(|m| get_time(&m)).ok(), s))1974 .collect()1975}
deleted:crates/core/config.rs-167 removed
1// This module provides routines for reading ripgrep config "rc" files. The2// primary output of these routines is a sequence of arguments, where each3// argument corresponds precisely to one shell argument.45use std::{6 ffi::OsString,7 path::{Path, PathBuf},8};910use bstr::{io::BufReadExt, ByteSlice};1112/// Return a sequence of arguments derived from ripgrep rc configuration files.13pub fn args() -> Vec<OsString> {14 let config_path = match std::env::var_os("RIPGREP_CONFIG_PATH") {15 None => return vec![],16 Some(config_path) => {17 if config_path.is_empty() {18 return vec![];19 }20 PathBuf::from(config_path)21 }22 };23 let (args, errs) = match parse(&config_path) {24 Ok((args, errs)) => (args, errs),25 Err(err) => {26 message!(27 "failed to read the file specified in RIPGREP_CONFIG_PATH: {}",28 err29 );30 return vec![];31 }32 };33 if !errs.is_empty() {34 for err in errs {35 message!("{}:{}", config_path.display(), err);36 }37 }38 log::debug!(39 "{}: arguments loaded from config file: {:?}",40 config_path.display(),41 args42 );43 args44}4546/// Parse a single ripgrep rc file from the given path.47///48/// On success, this returns a set of shell arguments, in order, that should49/// be pre-pended to the arguments given to ripgrep at the command line.50///51/// If the file could not be read, then an error is returned. If there was52/// a problem parsing one or more lines in the file, then errors are returned53/// for each line in addition to successfully parsed arguments.54fn parse<P: AsRef<Path>>(55 path: P,56) -> anyhow::Result<(Vec<OsString>, Vec<anyhow::Error>)> {57 let path = path.as_ref();58 match std::fs::File::open(&path) {59 Ok(file) => parse_reader(file),60 Err(err) => anyhow::bail!("{}: {}", path.display(), err),61 }62}6364/// Parse a single ripgrep rc file from the given reader.65///66/// Callers should not provided a buffered reader, as this routine will use its67/// own buffer internally.68///69/// On success, this returns a set of shell arguments, in order, that should70/// be pre-pended to the arguments given to ripgrep at the command line.71///72/// If the reader could not be read, then an error is returned. If there was a73/// problem parsing one or more lines, then errors are returned for each line74/// in addition to successfully parsed arguments.75fn parse_reader<R: std::io::Read>(76 rdr: R,77) -> anyhow::Result<(Vec<OsString>, Vec<anyhow::Error>)> {78 let mut bufrdr = std::io::BufReader::new(rdr);79 let (mut args, mut errs) = (vec![], vec![]);80 let mut line_number = 0;81 bufrdr.for_byte_line_with_terminator(|line| {82 line_number += 1;8384 let line = line.trim();85 if line.is_empty() || line[0] == b'#' {86 return Ok(true);87 }88 match line.to_os_str() {89 Ok(osstr) => {90 args.push(osstr.to_os_string());91 }92 Err(err) => {93 errs.push(anyhow::anyhow!("{line_number}: {err}"));94 }95 }96 Ok(true)97 })?;98 Ok((args, errs))99}100101#[cfg(test)]102mod tests {103 use super::parse_reader;104 use std::ffi::OsString;105106 #[test]107 fn basic() {108 let (args, errs) = parse_reader(109 &b"\110# Test111--context=0112 --smart-case113-u114115116 # --bar117--foo118"[..],119 )120 .unwrap();121 assert!(errs.is_empty());122 let args: Vec<String> =123 args.into_iter().map(|s| s.into_string().unwrap()).collect();124 assert_eq!(args, vec!["--context=0", "--smart-case", "-u", "--foo",]);125 }126127 // We test that we can handle invalid UTF-8 on Unix-like systems.128 #[test]129 #[cfg(unix)]130 fn error() {131 use std::os::unix::ffi::OsStringExt;132133 let (args, errs) = parse_reader(134 &b"\135quux136foo\xFFbar137baz138"[..],139 )140 .unwrap();141 assert!(errs.is_empty());142 assert_eq!(143 args,144 vec![145 OsString::from("quux"),146 OsString::from_vec(b"foo\xFFbar".to_vec()),147 OsString::from("baz"),148 ]149 );150 }151152 // ... but test that invalid UTF-8 fails on Windows.153 #[test]154 #[cfg(not(unix))]155 fn error() {156 let (args, errs) = parse_reader(157 &b"\158quux159foo\xFFbar160baz161"[..],162 )163 .unwrap();164 assert_eq!(errs.len(), 1);165 assert_eq!(args, vec![OsString::from("quux"), OsString::from("baz"),]);166 }167}
added:crates/core/haystack.rs+160 added
1/*!2Defines a builder for haystacks.34A "haystack" represents something we want to search. It encapsulates the logic5for whether a haystack ought to be searched or not, separate from the standard6ignore rules and other filtering logic.78Effectively, a haystack wraps a directory entry and adds some light application9level logic around it.10*/1112use std::path::Path;1314/// A builder for constructing things to search over.15#[derive(Clone, Debug)]16pub(crate) struct HaystackBuilder {17 strip_dot_prefix: bool,18}1920impl HaystackBuilder {21 /// Return a new haystack builder with a default configuration.22 pub(crate) fn new() -> HaystackBuilder {23 HaystackBuilder { strip_dot_prefix: false }24 }2526 /// Create a new haystack from a possibly missing directory entry.27 ///28 /// If the directory entry isn't present, then the corresponding error is29 /// logged if messages have been configured. Otherwise, if the directory30 /// entry is deemed searchable, then it is returned as a haystack.31 pub(crate) fn build_from_result(32 &self,33 result: Result<ignore::DirEntry, ignore::Error>,34 ) -> Option<Haystack> {35 match result {36 Ok(dent) => self.build(dent),37 Err(err) => {38 err_message!("{err}");39 None40 }41 }42 }4344 /// Create a new haystack using this builder's configuration.45 ///46 /// If a directory entry could not be created or should otherwise not be47 /// searched, then this returns `None` after emitting any relevant log48 /// messages.49 fn build(&self, dent: ignore::DirEntry) -> Option<Haystack> {50 let hay = Haystack { dent, strip_dot_prefix: self.strip_dot_prefix };51 if let Some(err) = hay.dent.error() {52 ignore_message!("{err}");53 }54 // If this entry was explicitly provided by an end user, then we always55 // want to search it.56 if hay.is_explicit() {57 return Some(hay);58 }59 // At this point, we only want to search something if it's explicitly a60 // file. This omits symlinks. (If ripgrep was configured to follow61 // symlinks, then they have already been followed by the directory62 // traversal.)63 if hay.is_file() {64 return Some(hay);65 }66 // We got nothing. Emit a debug message, but only if this isn't a67 // directory. Otherwise, emitting messages for directories is just68 // noisy.69 if !hay.is_dir() {70 log::debug!(71 "ignoring {}: failed to pass haystack filter: \72 file type: {:?}, metadata: {:?}",73 hay.dent.path().display(),74 hay.dent.file_type(),75 hay.dent.metadata()76 );77 }78 None79 }8081 /// When enabled, if the haystack's file path starts with `./` then it is82 /// stripped.83 ///84 /// This is useful when implicitly searching the current working directory.85 pub(crate) fn strip_dot_prefix(86 &mut self,87 yes: bool,88 ) -> &mut HaystackBuilder {89 self.strip_dot_prefix = yes;90 self91 }92}9394/// A haystack is a thing we want to search.95///96/// Generally, a haystack is either a file or stdin.97#[derive(Clone, Debug)]98pub(crate) struct Haystack {99 dent: ignore::DirEntry,100 strip_dot_prefix: bool,101}102103impl Haystack {104 /// Return the file path corresponding to this haystack.105 ///106 /// If this haystack corresponds to stdin, then a special `<stdin>` path107 /// is returned instead.108 pub(crate) fn path(&self) -> &Path {109 if self.strip_dot_prefix && self.dent.path().starts_with("./") {110 self.dent.path().strip_prefix("./").unwrap()111 } else {112 self.dent.path()113 }114 }115116 /// Returns true if and only if this entry corresponds to stdin.117 pub(crate) fn is_stdin(&self) -> bool {118 self.dent.is_stdin()119 }120121 /// Returns true if and only if this entry corresponds to a haystack to122 /// search that was explicitly supplied by an end user.123 ///124 /// Generally, this corresponds to either stdin or an explicit file path125 /// argument. e.g., in `rg foo some-file ./some-dir/`, `some-file` is126 /// an explicit haystack, but, e.g., `./some-dir/some-other-file` is not.127 ///128 /// However, note that ripgrep does not see through shell globbing. e.g.,129 /// in `rg foo ./some-dir/*`, `./some-dir/some-other-file` will be treated130 /// as an explicit haystack.131 pub(crate) fn is_explicit(&self) -> bool {132 // stdin is obvious. When an entry has a depth of 0, that means it133 // was explicitly provided to our directory iterator, which means it134 // was in turn explicitly provided by the end user. The !is_dir check135 // means that we want to search files even if their symlinks, again,136 // because they were explicitly provided. (And we never want to try137 // to search a directory.)138 self.is_stdin() || (self.dent.depth() == 0 && !self.is_dir())139 }140141 /// Returns true if and only if this haystack points to a directory after142 /// following symbolic links.143 fn is_dir(&self) -> bool {144 let ft = match self.dent.file_type() {145 None => return false,146 Some(ft) => ft,147 };148 if ft.is_dir() {149 return true;150 }151 // If this is a symlink, then we want to follow it to determine152 // whether it's a directory or not.153 self.dent.path_is_symlink() && self.dent.path().is_dir()154 }155156 /// Returns true if and only if this haystack points to a file.157 fn is_file(&self) -> bool {158 self.dent.file_type().map_or(false, |ft| ft.is_file())159 }160}
modified:crates/core/logger.rs+10 added-6 removed
1// This module defines a super simple logger that works with the `log` crate.2// We don't need anything fancy; just basic log levels and the ability to3// print to stderr. We therefore avoid bringing in extra dependencies just4// for this functionality.1/*!2Defines a super simple logger that works with the `log` crate.34We don't do anything fancy. We just need basic log levels and the ability to5print to stderr. We therefore avoid bringing in extra dependencies just for6this functionality.7*/89use log::{self, Log};1011/// The simplest possible logger that logs to stderr.12///13/// This logger does no filtering. Instead, it relies on the `log` crates14/// filtering via its global max_level setting.15#[derive(Debug)]13pub struct Logger(());16pub(crate) struct Logger(());1718/// A singleton used as the target for an implementation of the `Log` trait.19const LOGGER: &'static Logger = &Logger(());2021impl Logger {22 /// Create a new logger that logs to stderr and initialize it as the23 /// global logger. If there was a problem setting the logger, then an24 /// error is returned.21 pub fn init() -> Result<(), log::SetLoggerError> {25 pub(crate) fn init() -> Result<(), log::SetLoggerError> {26 log::set_logger(LOGGER)27 }28}29
43 unmodified lines
modified:crates/core/main.rs+332 added-207 removed
1use std::{2 io::{self, Write},3 time::Instant,4};1/*!2The main entry point into ripgrep.3*/45use std::{io::Write, process::ExitCode};67use ignore::WalkState;88use crate::{args::Args, subject::Subject};9use crate::flags::{HiArgs, SearchMode};1011#[macro_use]12mod messages;1313mod app;14mod args;15mod config;14mod flags;15mod haystack;16mod logger;17mod search;18mod subject;1819// Since Rust no longer uses jemalloc by default, ripgrep will, by default,20// use the system allocator. On Linux, this would normally be glibc's21// allocator, which is pretty good. In particular, ripgrep does not have a
16 unmodified lines
38#[cfg(all(target_env = "musl", target_pointer_width = "64"))]39#[global_allocator]40static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;4143fn main() {44 if let Err(err) = Args::parse().and_then(try_main) {45 eprintln_locked!("{:#}", err);46 std::process::exit(2);42/// Then, as it was, then again it will be.43fn main() -> ExitCode {44 match run(flags::parse()) {45 Ok(code) => code,46 Err(err) => {47 // Look for a broken pipe error. In this case, we generally want48 // to exit "gracefully" with a success exit code. This matches49 // existing Unix convention. We need to handle this explicitly50 // since the Rust runtime doesn't ask for PIPE signals, and thus51 // we get an I/O error instead. Traditional C Unix applications52 // quit by getting a PIPE signal that they don't handle, and thus53 // the unhandled signal causes the process to unceremoniously54 // terminate.55 for cause in err.chain() {56 if let Some(ioerr) = cause.downcast_ref::<std::io::Error>() {57 if ioerr.kind() == std::io::ErrorKind::BrokenPipe {58 return ExitCode::from(0);59 }60 }61 }62 eprintln_locked!("{:#}", err);63 ExitCode::from(2)64 }65 }66}6750fn try_main(args: Args) -> anyhow::Result<()> {51 use args::Command::*;68/// The main entry point for ripgrep.69///70/// The given parse result determines ripgrep's behavior. The parse71/// result should be the result of parsing CLI arguments in a low level72/// representation, and then followed by an attempt to convert them into a73/// higher level representation. The higher level representation has some nicer74/// abstractions, for example, instead of representing the `-g/--glob` flag75/// as a `Vec<String>` (as in the low level representation), the globs are76/// converted into a single matcher.77fn run(result: crate::flags::ParseResult<HiArgs>) -> anyhow::Result<ExitCode> {78 use crate::flags::{Mode, ParseResult};7953 let matched = match args.command() {54 Search => search(&args),55 SearchParallel => search_parallel(&args),56 SearchNever => Ok(false),57 Files => files(&args),58 FilesParallel => files_parallel(&args),59 Types => types(&args),60 PCRE2Version => pcre2_version(&args),61 }?;62 if matched && (args.quiet() || !messages::errored()) {63 std::process::exit(0)80 let args = match result {81 ParseResult::Err(err) => return Err(err),82 ParseResult::Special(mode) => return special(mode),83 ParseResult::Ok(args) => args,84 };85 let matched = match args.mode() {86 Mode::Search(_) if !args.matches_possible() => false,87 Mode::Search(mode) if args.threads() == 1 => search(&args, mode)?,88 Mode::Search(mode) => search_parallel(&args, mode)?,89 Mode::Files if args.threads() == 1 => files(&args)?,90 Mode::Files => files_parallel(&args)?,91 Mode::Types => return types(&args),92 Mode::Generate(mode) => return generate(mode),93 };94 Ok(if matched && (args.quiet() || !messages::errored()) {95 ExitCode::from(0)96 } else if messages::errored() {65 std::process::exit(2)97 ExitCode::from(2)98 } else {67 std::process::exit(1)68 }99 ExitCode::from(1)100 })101}10271/// The top-level entry point for single-threaded search. This recursively72/// steps through the file list (current directory by default) and searches73/// each file sequentially.74fn search(args: &Args) -> anyhow::Result<bool> {75 /// The meat of the routine is here. This lets us call the same iteration76 /// code over each file regardless of whether we stream over the files77 /// as they're produced by the underlying directory traversal or whether78 /// they've been collected and sorted (for example) first.79 fn iter(80 args: &Args,81 subjects: impl Iterator<Item = Subject>,82 started_at: std::time::Instant,83 ) -> anyhow::Result<bool> {84 let quit_after_match = args.quit_after_match()?;85 let mut stats = args.stats()?;86 let mut searcher = args.search_worker(args.stdout())?;87 let mut matched = false;88 let mut searched = false;103/// The top-level entry point for single-threaded search.104///105/// This recursively steps through the file list (current directory by default)106/// and searches each file sequentially.107fn search(args: &HiArgs, mode: SearchMode) -> anyhow::Result<bool> {108 let started_at = std::time::Instant::now();109 let haystack_builder = args.haystack_builder();110 let unsorted = args111 .walk_builder()?112 .build()113 .filter_map(|result| haystack_builder.build_from_result(result));114 let haystacks = args.sort(unsorted);11590 for subject in subjects {91 searched = true;92 let search_result = match searcher.search(&subject) {93 Ok(search_result) => search_result,94 // A broken pipe means graceful termination.95 Err(err) if err.kind() == io::ErrorKind::BrokenPipe => break,96 Err(err) => {97 err_message!("{}: {}", subject.path().display(), err);98 continue;99 }100 };101 matched |= search_result.has_match();102 if let Some(ref mut stats) = stats {103 *stats += search_result.stats().unwrap();116 let mut matched = false;117 let mut searched = false;118 let mut stats = args.stats();119 let mut searcher = args.search_worker(120 args.matcher()?,121 args.searcher()?,122 args.printer(mode, args.stdout()),123 )?;124 for haystack in haystacks {125 searched = true;126 let search_result = match searcher.search(&haystack) {127 Ok(search_result) => search_result,128 // A broken pipe means graceful termination.129 Err(err) if err.kind() == std::io::ErrorKind::BrokenPipe => break,130 Err(err) => {131 err_message!("{}: {}", haystack.path().display(), err);132 continue;133 }105 if matched && quit_after_match {106 break;107 }134 };135 matched = matched || search_result.has_match();136 if let Some(ref mut stats) = stats {137 *stats += search_result.stats().unwrap();138 }109 if args.using_default_path() && !searched {110 eprint_nothing_searched();139 if matched && args.quit_after_match() {140 break;141 }112 if let Some(ref stats) = stats {113 let elapsed = Instant::now().duration_since(started_at);114 // We don't care if we couldn't print this successfully.115 let _ = searcher.print_stats(elapsed, stats);116 }117 Ok(matched)142 }119120 let started_at = Instant::now();121 let subject_builder = args.subject_builder();122 let subjects = args123 .walker()?124 .filter_map(|result| subject_builder.build_from_result(result));125 if args.needs_stat_sort() {126 let subjects = args.sort_by_stat(subjects).into_iter();127 iter(args, subjects, started_at)128 } else {129 iter(args, subjects, started_at)143 if args.has_implicit_path() && !searched {144 eprint_nothing_searched();145 }146 if let Some(ref stats) = stats {147 let wtr = searcher.printer().get_mut();148 let _ = print_stats(mode, stats, started_at, wtr);149 }150 Ok(matched)151}152133/// The top-level entry point for multi-threaded search. The parallelism is134/// itself achieved by the recursive directory traversal. All we need to do is135/// feed it a worker for performing a search on each file.153/// The top-level entry point for multi-threaded search.154///155/// The parallelism is itself achieved by the recursive directory traversal.156/// All we need to do is feed it a worker for performing a search on each file.157///158/// Requesting a sorted output from ripgrep (such as with `--sort path`) will159/// automatically disable parallelism and hence sorting is not handled here.139fn search_parallel(args: &Args) -> anyhow::Result<bool> {140 use std::sync::atomic::{AtomicBool, Ordering::SeqCst};160fn search_parallel(args: &HiArgs, mode: SearchMode) -> anyhow::Result<bool> {161 use std::sync::atomic::{AtomicBool, Ordering};162142 let quit_after_match = args.quit_after_match()?;143 let started_at = Instant::now();144 let subject_builder = args.subject_builder();145 let bufwtr = args.buffer_writer()?;146 let stats = args.stats()?.map(std::sync::Mutex::new);163 let started_at = std::time::Instant::now();164 let haystack_builder = args.haystack_builder();165 let bufwtr = args.buffer_writer();166 let stats = args.stats().map(std::sync::Mutex::new);167 let matched = AtomicBool::new(false);168 let searched = AtomicBool::new(false);149 let mut searcher_err = None;150 args.walker_parallel()?.run(|| {169170 let mut searcher = args.search_worker(171 args.matcher()?,172 args.searcher()?,173 args.printer(mode, bufwtr.buffer()),174 )?;175 args.walk_builder()?.build_parallel().run(|| {176 let bufwtr = &bufwtr;177 let stats = &stats;178 let matched = &matched;179 let searched = &searched;155 let subject_builder = &subject_builder;156 let mut searcher = match args.search_worker(bufwtr.buffer()) {157 Ok(searcher) => searcher,158 Err(err) => {159 searcher_err = Some(err);160 return Box::new(move |_| WalkState::Quit);161 }162 };180 let haystack_builder = &haystack_builder;181 let mut searcher = searcher.clone();182183 Box::new(move |result| {165 let subject = match subject_builder.build_from_result(result) {166 Some(subject) => subject,184 let haystack = match haystack_builder.build_from_result(result) {185 Some(haystack) => haystack,186 None => return WalkState::Continue,187 };169 searched.store(true, SeqCst);188 searched.store(true, Ordering::SeqCst);189 searcher.printer().get_mut().clear();171 let search_result = match searcher.search(&subject) {190 let search_result = match searcher.search(&haystack) {191 Ok(search_result) => search_result,192 Err(err) => {174 err_message!("{}: {}", subject.path().display(), err);193 err_message!("{}: {}", haystack.path().display(), err);194 return WalkState::Continue;195 }196 };197 if search_result.has_match() {179 matched.store(true, SeqCst);198 matched.store(true, Ordering::SeqCst);199 }200 if let Some(ref locked_stats) = *stats {201 let mut stats = locked_stats.lock().unwrap();202 *stats += search_result.stats().unwrap();203 }204 if let Err(err) = bufwtr.print(searcher.printer().get_mut()) {205 // A broken pipe means graceful termination.187 if err.kind() == io::ErrorKind::BrokenPipe {206 if err.kind() == std::io::ErrorKind::BrokenPipe {207 return WalkState::Quit;208 }209 // Otherwise, we continue on our merry way.191 err_message!("{}: {}", subject.path().display(), err);210 err_message!("{}: {}", haystack.path().display(), err);211 }193 if matched.load(SeqCst) && quit_after_match {212 if matched.load(Ordering::SeqCst) && args.quit_after_match() {213 WalkState::Quit214 } else {215 WalkState::Continue216 }217 })218 });200 if let Some(err) = searcher_err.take() {201 return Err(err);202 }203 if args.using_default_path() && !searched.load(SeqCst) {219 if args.has_implicit_path() && !searched.load(Ordering::SeqCst) {220 eprint_nothing_searched();221 }222 if let Some(ref locked_stats) = stats {207 let elapsed = Instant::now().duration_since(started_at);223 let stats = locked_stats.lock().unwrap();209 let mut searcher = args.search_worker(args.stdout())?;210 // We don't care if we couldn't print this successfully.211 let _ = searcher.print_stats(elapsed, &stats);224 let mut wtr = searcher.printer().get_mut();225 let _ = print_stats(mode, &stats, started_at, &mut wtr);226 let _ = bufwtr.print(&mut wtr);227 }213 Ok(matched.load(SeqCst))228 Ok(matched.load(Ordering::SeqCst))229}230216fn eprint_nothing_searched() {217 err_message!(218 "No files were searched, which means ripgrep probably \219 applied a filter you didn't expect.\n\220 Running with --debug will show why files are being skipped."221 );222}231/// The top-level entry point for file listing without searching.232///233/// This recursively steps through the file list (current directory by default)234/// and prints each path sequentially using a single thread.235fn files(args: &HiArgs) -> anyhow::Result<bool> {236 let haystack_builder = args.haystack_builder();237 let unsorted = args238 .walk_builder()?239 .build()240 .filter_map(|result| haystack_builder.build_from_result(result));241 let haystacks = args.sort(unsorted);242224/// The top-level entry point for listing files without searching them. This225/// recursively steps through the file list (current directory by default) and226/// prints each path sequentially using a single thread.227fn files(args: &Args) -> anyhow::Result<bool> {228 /// The meat of the routine is here. This lets us call the same iteration229 /// code over each file regardless of whether we stream over the files230 /// as they're produced by the underlying directory traversal or whether231 /// they've been collected and sorted (for example) first.232 fn iter(233 args: &Args,234 subjects: impl Iterator<Item = Subject>,235 ) -> anyhow::Result<bool> {236 let quit_after_match = args.quit_after_match()?;237 let mut matched = false;238 let mut path_printer = args.path_printer(args.stdout())?;239240 for subject in subjects {241 matched = true;242 if quit_after_match {243 let mut matched = false;244 let mut path_printer = args.path_printer_builder().build(args.stdout());245 for haystack in haystacks {246 matched = true;247 if args.quit_after_match() {248 break;249 }250 if let Err(err) = path_printer.write(haystack.path()) {251 // A broken pipe means graceful termination.252 if err.kind() == std::io::ErrorKind::BrokenPipe {253 break;254 }245 if let Err(err) = path_printer.write(subject.path()) {246 // A broken pipe means graceful termination.247 if err.kind() == io::ErrorKind::BrokenPipe {248 break;249 }250 // Otherwise, we have some other error that's preventing us from251 // writing to stdout, so we should bubble it up.252 return Err(err.into());255 // Otherwise, we have some other error that's preventing us from256 // writing to stdout, so we should bubble it up.257 return Err(err.into());253 }258 }255 Ok(matched)259 }257258 let subject_builder = args.subject_builder();259 let subjects = args260 .walker()?261 .filter_map(|result| subject_builder.build_from_result(result));262 if args.needs_stat_sort() {263 let subjects = args.sort_by_stat(subjects).into_iter();264 iter(args, subjects)265 } else {266 iter(args, subjects)267 }260 Ok(matched)261}262270/// The top-level entry point for listing files without searching them. This271/// recursively steps through the file list (current directory by default) and272/// prints each path sequentially using multiple threads.263/// The top-level entry point for multi-threaded file listing without264/// searching.265///266/// This recursively steps through the file list (current directory by default)267/// and prints each path sequentially using multiple threads.268///269/// Requesting a sorted output from ripgrep (such as with `--sort path`) will270/// automatically disable parallelism and hence sorting is not handled here.276fn files_parallel(args: &Args) -> anyhow::Result<bool> {277 use std::sync::atomic::AtomicBool;278 use std::sync::atomic::Ordering::SeqCst;279 use std::sync::mpsc;280 use std::thread;271fn files_parallel(args: &HiArgs) -> anyhow::Result<bool> {272 use std::{273 sync::{274 atomic::{AtomicBool, Ordering},275 mpsc,276 },277 thread,278 };279282 let quit_after_match = args.quit_after_match()?;283 let subject_builder = args.subject_builder();284 let mut path_printer = args.path_printer(args.stdout())?;280 let haystack_builder = args.haystack_builder();281 let mut path_printer = args.path_printer_builder().build(args.stdout());282 let matched = AtomicBool::new(false);286 let (tx, rx) = mpsc::channel::<Subject>();283 let (tx, rx) = mpsc::channel::<crate::haystack::Haystack>();284285 // We spawn a single printing thread to make sure we don't tear writes.286 // We use a channel here under the presumption that it's probably faster287 // than using a mutex in the worker threads below, but this has never been288 // seriously litigated.288 let print_thread = thread::spawn(move || -> io::Result<()> {289 for subject in rx.iter() {290 path_printer.write(subject.path())?;289 let print_thread = thread::spawn(move || -> std::io::Result<()> {290 for haystack in rx.iter() {291 path_printer.write(haystack.path())?;292 }293 Ok(())294 });294 args.walker_parallel()?.run(|| {295 let subject_builder = &subject_builder;295 args.walk_builder()?.build_parallel().run(|| {296 let haystack_builder = &haystack_builder;297 let matched = &matched;298 let tx = tx.clone();299300 Box::new(move |result| {300 let subject = match subject_builder.build_from_result(result) {301 Some(subject) => subject,301 let haystack = match haystack_builder.build_from_result(result) {302 Some(haystack) => haystack,303 None => return WalkState::Continue,304 };304 matched.store(true, SeqCst);305 if quit_after_match {305 matched.store(true, Ordering::SeqCst);306 if args.quit_after_match() {307 WalkState::Quit308 } else {308 match tx.send(subject) {309 match tx.send(haystack) {310 Ok(_) => WalkState::Continue,311 Err(_) => WalkState::Quit,312 }313 }
3 unmodified lines
317 if let Err(err) = print_thread.join().unwrap() {318 // A broken pipe means graceful termination, so fall through.319 // Otherwise, something bad happened while writing to stdout, so bubble320 // it up.320 if err.kind() != io::ErrorKind::BrokenPipe {321 if err.kind() != std::io::ErrorKind::BrokenPipe {322 return Err(err.into());323 }324 }324 Ok(matched.load(SeqCst))325 Ok(matched.load(Ordering::SeqCst))326}327327/// The top-level entry point for --type-list.328fn types(args: &Args) -> anyhow::Result<bool> {328/// The top-level entry point for `--type-list`.329fn types(args: &HiArgs) -> anyhow::Result<ExitCode> {330 let mut count = 0;331 let mut stdout = args.stdout();331 for def in args.type_defs()? {332 for def in args.types().definitions() {333 count += 1;334 stdout.write_all(def.name().as_bytes())?;335 stdout.write_all(b": ")?;336
6 unmodified lines
343 first = false;344 }345 stdout.write_all(b"\n")?;346 }346 Ok(count > 0)347 Ok(ExitCode::from(if count == 0 { 1 } else { 0 }))348}349349/// The top-level entry point for --pcre2-version.350fn pcre2_version(args: &Args) -> anyhow::Result<bool> {350/// Implements ripgrep's "generate" modes.351///352/// These modes correspond to generating some kind of ancillary data related353/// to ripgrep. At present, this includes ripgrep's man page (in roff format)354/// and supported shell completions.355fn generate(mode: crate::flags::GenerateMode) -> anyhow::Result<ExitCode> {356 use crate::flags::GenerateMode;357358 let output = match mode {359 GenerateMode::Man => flags::generate_man_page(),360 GenerateMode::CompleteBash => flags::generate_complete_bash(),361 GenerateMode::CompleteZsh => flags::generate_complete_zsh(),362 GenerateMode::CompleteFish => flags::generate_complete_fish(),363 GenerateMode::CompletePowerShell => {364 flags::generate_complete_powershell()365 }366 };367 writeln!(std::io::stdout(), "{}", output.trim_end())?;368 Ok(ExitCode::from(0))369}370371/// Implements ripgrep's "special" modes.372///373/// A special mode is one that generally short-circuits most (not all) of374/// ripgrep's initialization logic and skips right to this routine. The375/// special modes essentially consist of printing help and version output. The376/// idea behind the short circuiting is to ensure there is as little as possible377/// (within reason) that would prevent ripgrep from emitting help output.378///379/// For example, part of the initialization logic that is skipped (among380/// other things) is accessing the current working directory. If that fails,381/// ripgrep emits an error. We don't want to emit an error if it fails and382/// the user requested version or help information.383fn special(mode: crate::flags::SpecialMode) -> anyhow::Result<ExitCode> {384 use crate::flags::SpecialMode;385386 let output = match mode {387 SpecialMode::HelpShort => flags::generate_help_short(),388 SpecialMode::HelpLong => flags::generate_help_long(),389 SpecialMode::VersionShort => flags::generate_version_short(),390 SpecialMode::VersionLong => flags::generate_version_long(),391 // --pcre2-version is a little special because it emits an error392 // exit code if this build of ripgrep doesn't support PCRE2.393 SpecialMode::VersionPCRE2 => return version_pcre2(),394 };395 writeln!(std::io::stdout(), "{}", output.trim_end())?;396 Ok(ExitCode::from(0))397}398399/// The top-level entry point for `--pcre2-version`.400fn version_pcre2() -> anyhow::Result<ExitCode> {401 let mut stdout = std::io::stdout().lock();402403 #[cfg(feature = "pcre2")]352 fn imp(args: &Args) -> anyhow::Result<bool> {404 {405 use grep::pcre2;406355 let mut stdout = args.stdout();356407 let (major, minor) = pcre2::version();408 writeln!(stdout, "PCRE2 {}.{} is available", major, minor)?;359409 if cfg!(target_pointer_width = "64") && pcre2::is_jit_available() {410 writeln!(stdout, "JIT is available")?;411 }363 Ok(true)412 Ok(ExitCode::from(0))413 }414415 #[cfg(not(feature = "pcre2"))]367 fn imp(args: &Args) -> anyhow::Result<bool> {368 let mut stdout = args.stdout();416 {417 writeln!(stdout, "PCRE2 is not available in this build of ripgrep.")?;370 Ok(false)418 Ok(ExitCode::from(1))419 }420}421373 imp(args)422/// Prints a heuristic error messages when nothing is searched.423///424/// This can happen if an applicable ignore file has one or more rules that425/// are too broad and cause ripgrep to ignore everything.426///427/// We only show this error message when the user does *not* provide an428/// explicit path to search. This is because the message can otherwise be429/// noisy, e.g., when it is intended that there is nothing to search.430fn eprint_nothing_searched() {431 err_message!(432 "No files were searched, which means ripgrep probably \433 applied a filter you didn't expect.\n\434 Running with --debug will show why files are being skipped."435 );436}437438/// Prints the statistics given to the writer given.439///440/// The search mode given determines whether the stats should be printed in441/// a plain text format or in a JSON format.442///443/// The `started` time should be the time at which ripgrep started working.444///445/// If an error occurs while writing, then writing stops and the error is446/// returned. Note that callers should probably ignore this errror, since447/// whether stats fail to print or not generally shouldn't cause ripgrep to448/// enter into an "error" state. And usually the only way for this to fail is449/// if writing to stdout itself fails.450fn print_stats<W: Write>(451 mode: SearchMode,452 stats: &grep::printer::Stats,453 started: std::time::Instant,454 mut wtr: W,455) -> std::io::Result<()> {456 let elapsed = std::time::Instant::now().duration_since(started);457 if matches!(mode, SearchMode::JSON) {458 // We specifically match the format laid out by the JSON printer in459 // the grep-printer crate. We simply "extend" it with the 'summary'460 // message type.461 serde_json::to_writer(462 &mut wtr,463 &serde_json::json!({464 "type": "summary",465 "data": {466 "stats": stats,467 "elapsed_total": {468 "secs": elapsed.as_secs(),469 "nanos": elapsed.subsec_nanos(),470 "human": format!("{:0.6}s", elapsed.as_secs_f64()),471 },472 }473 }),474 )?;475 write!(wtr, "\n")476 } else {477 write!(478 wtr,479 "480{matches} matches481{lines} matched lines482{searches_with_match} files contained matches483{searches} files searched484{bytes_printed} bytes printed485{bytes_searched} bytes searched486{search_time:0.6} seconds spent searching487{process_time:0.6} seconds488",489 matches = stats.matches(),490 lines = stats.matched_lines(),491 searches_with_match = stats.searches_with_match(),492 searches = stats.searches(),493 bytes_printed = stats.bytes_printed(),494 bytes_searched = stats.bytes_searched(),495 search_time = stats.elapsed().as_secs_f64(),496 process_time = elapsed.as_secs_f64(),497 )498 }499}
modified:crates/core/messages.rs+51 added-10 removed
1/*!2This module defines some macros and some light shared mutable state.34This state is responsible for keeping track of whether we should emit certain5kinds of messages to the user (such as errors) that are distinct from the6standard "debug" or "trace" log messages. This state is specifically set at7startup time when CLI arguments are parsed and then never changed.89The other state tracked here is whether ripgrep experienced an error10condition. Aside from errors associated with invalid CLI arguments, ripgrep11generally does not abort when an error occurs (e.g., if reading a file failed).12But when an error does occur, it will alter ripgrep's exit status. Thus, when13an error message is emitted via `err_message`, then a global flag is toggled14indicating that at least one error occurred. When ripgrep exits, this flag is15consulted to determine what the exit status ought to be.16*/1718use std::sync::atomic::{AtomicBool, Ordering};1920/// When false, "messages" will not be printed.21static MESSAGES: AtomicBool = AtomicBool::new(false);22/// When false, "messages" related to ignore rules will not be printed.23static IGNORE_MESSAGES: AtomicBool = AtomicBool::new(false);24/// Flipped to true when an error message is printed.25static ERRORED: AtomicBool = AtomicBool::new(false);267/// Like eprintln, but locks STDOUT to prevent interleaving lines.27/// Like eprintln, but locks stdout to prevent interleaving lines.28///29/// This locks stdout, not stderr, even though this prints to stderr. This30/// avoids the appearance of interleaving output when stdout and stderr both31/// correspond to a tty.)32#[macro_export]33macro_rules! eprintln_locked {34 ($($tt:tt)*) => {{35 {36 use std::io::Write;3738 // This is a bit of an abstraction violation because we explicitly13 // lock STDOUT before printing to STDERR. This avoids interleaving39 // lock stdout before printing to stderr. This avoids interleaving40 // lines within ripgrep because `search_parallel` uses `termcolor`,15 // which accesses the same STDOUT lock when writing lines.41 // which accesses the same stdout lock when writing lines.42 let stdout = std::io::stdout();43 let _handle = stdout.lock();18 eprintln!($($tt)*);44 // We specifically ignore any errors here. One plausible error we45 // can get in some cases is a broken pipe error. And when that46 // occurs, we should exit gracefully. Otherwise, just abort with47 // an error code because there isn't much else we can do.48 //49 // See: https://github.com/BurntSushi/ripgrep/issues/196650 if let Err(err) = writeln!(std::io::stderr(), $($tt)*) {51 if err.kind() == std::io::ErrorKind::BrokenPipe {52 std::process::exit(0);53 } else {54 std::process::exit(2);55 }56 }57 }58 }}59}60
28 unmodified lines
89 }90}9192/// Returns true if and only if messages should be shown.55pub fn messages() -> bool {93pub(crate) fn messages() -> bool {94 MESSAGES.load(Ordering::SeqCst)95}9697/// Set whether messages should be shown or not.98///99/// By default, they are not shown.62pub fn set_messages(yes: bool) {100pub(crate) fn set_messages(yes: bool) {101 MESSAGES.store(yes, Ordering::SeqCst)102}103104/// Returns true if and only if "ignore" related messages should be shown.67pub fn ignore_messages() -> bool {105pub(crate) fn ignore_messages() -> bool {106 IGNORE_MESSAGES.load(Ordering::SeqCst)107}108109/// Set whether "ignore" related messages should be shown or not.
2 unmodified lines
112///113/// Note that this is overridden if `messages` is disabled. Namely, if114/// `messages` is disabled, then "ignore" messages are never shown, regardless115/// of this setting.78pub fn set_ignore_messages(yes: bool) {116pub(crate) fn set_ignore_messages(yes: bool) {117 IGNORE_MESSAGES.store(yes, Ordering::SeqCst)118}119120/// Returns true if and only if ripgrep came across a non-fatal error.83pub fn errored() -> bool {121pub(crate) fn errored() -> bool {122 ERRORED.load(Ordering::SeqCst)123}124125/// Indicate that ripgrep has come across a non-fatal error.126///127/// Callers should not use this directly. Instead, it is called automatically128/// via the `err_message` macro.88pub fn set_errored() {129pub(crate) fn set_errored() {130 ERRORED.store(true, Ordering::SeqCst);131}
modified:crates/core/search.rs+79 added-185 removed
1use std::{2 io,3 path::{Path, PathBuf},4 time::Duration,5};1/*!2Defines a very high level "search worker" abstraction.37use {8 grep::{9 cli,10 matcher::Matcher,11 printer::{Standard, Stats, Summary, JSON},12 regex::RegexMatcher as RustRegexMatcher,13 searcher::{BinaryDetection, Searcher},14 },15 ignore::overrides::Override,16 serde_json::{self as json, json},17 termcolor::WriteColor,18};4A search worker manages the high level interaction points between the matcher5(i.e., which regex engine is used), the searcher (i.e., how data is actually6read and matched using the regex engine) and the printer. For example, the7search worker is where things like preprocessors or decompression happens.8*/920#[cfg(feature = "pcre2")]21use grep::pcre2::RegexMatcher as PCRE2RegexMatcher;10use std::{io, path::Path};1123use crate::subject::Subject;12use {grep::matcher::Matcher, termcolor::WriteColor};1325/// The configuration for the search worker. Among a few other things, the26/// configuration primarily controls the way we show search results to users27/// at a very high level.14/// The configuration for the search worker.15///16/// Among a few other things, the configuration primarily controls the way we17/// show search results to users at a very high level.18#[derive(Clone, Debug)]19struct Config {30 json_stats: bool,31 preprocessor: Option<PathBuf>,32 preprocessor_globs: Override,20 preprocessor: Option<std::path::PathBuf>,21 preprocessor_globs: ignore::overrides::Override,22 search_zip: bool,34 binary_implicit: BinaryDetection,35 binary_explicit: BinaryDetection,23 binary_implicit: grep::searcher::BinaryDetection,24 binary_explicit: grep::searcher::BinaryDetection,25}2627impl Default for Config {28 fn default() -> Config {29 Config {41 json_stats: false,30 preprocessor: None,43 preprocessor_globs: Override::empty(),31 preprocessor_globs: ignore::overrides::Override::empty(),32 search_zip: false,45 binary_implicit: BinaryDetection::none(),46 binary_explicit: BinaryDetection::none(),33 binary_implicit: grep::searcher::BinaryDetection::none(),34 binary_explicit: grep::searcher::BinaryDetection::none(),35 }36 }37}3839/// A builder for configuring and constructing a search worker.40#[derive(Clone, Debug)]53pub struct SearchWorkerBuilder {41pub(crate) struct SearchWorkerBuilder {42 config: Config,55 command_builder: cli::CommandReaderBuilder,56 decomp_builder: cli::DecompressionReaderBuilder,43 command_builder: grep::cli::CommandReaderBuilder,44 decomp_builder: grep::cli::DecompressionReaderBuilder,45}4647impl Default for SearchWorkerBuilder {48 fn default() -> SearchWorkerBuilder {
2 unmodified lines
51}5253impl SearchWorkerBuilder {54 /// Create a new builder for configuring and constructing a search worker.67 pub fn new() -> SearchWorkerBuilder {68 let mut cmd_builder = cli::CommandReaderBuilder::new();55 pub(crate) fn new() -> SearchWorkerBuilder {56 let mut cmd_builder = grep::cli::CommandReaderBuilder::new();57 cmd_builder.async_stderr(true);5871 let mut decomp_builder = cli::DecompressionReaderBuilder::new();59 let mut decomp_builder = grep::cli::DecompressionReaderBuilder::new();60 decomp_builder.async_stderr(true);6162 SearchWorkerBuilder {63 config: Config::default(),
3 unmodified lines
67 }6869 /// Create a new search worker using the given searcher, matcher and70 /// printer.83 pub fn build<W: WriteColor>(71 pub(crate) fn build<W: WriteColor>(72 &self,73 matcher: PatternMatcher,86 searcher: Searcher,74 searcher: grep::searcher::Searcher,75 printer: Printer<W>,76 ) -> SearchWorker<W> {77 let config = self.config.clone();78 let command_builder = self.command_builder.clone();
7 unmodified lines
86 printer,87 }88 }89102 /// Forcefully use JSON to emit statistics, even if the underlying printer103 /// is not the JSON printer.104 ///105 /// This is useful for implementing flag combinations like106 /// `--json --quiet`, which uses the summary printer for implementing107 /// `--quiet` but still wants to emit summary statistics, which should108 /// be JSON formatted because of the `--json` flag.109 pub fn json_stats(&mut self, yes: bool) -> &mut SearchWorkerBuilder {110 self.config.json_stats = yes;111 self112 }11390 /// Set the path to a preprocessor command.91 ///92 /// When this is set, instead of searching files directly, the given93 /// command will be run with the file path as the first argument, and the94 /// output of that command will be searched instead.119 pub fn preprocessor(95 pub(crate) fn preprocessor(96 &mut self,121 cmd: Option<PathBuf>,97 cmd: Option<std::path::PathBuf>,98 ) -> anyhow::Result<&mut SearchWorkerBuilder> {99 if let Some(ref prog) = cmd {124 let bin = cli::resolve_binary(prog)?;100 let bin = grep::cli::resolve_binary(prog)?;101 self.config.preprocessor = Some(bin);102 } else {103 self.config.preprocessor = None;104 }
2 unmodified lines
107108 /// Set the globs for determining which files should be run through the109 /// preprocessor. By default, with no globs and a preprocessor specified,110 /// every file is run through the preprocessor.135 pub fn preprocessor_globs(111 pub(crate) fn preprocessor_globs(112 &mut self,137 globs: Override,113 globs: ignore::overrides::Override,114 ) -> &mut SearchWorkerBuilder {115 self.config.preprocessor_globs = globs;116 self117 }
4 unmodified lines
122 /// file, then it is decompressed before searching.123 ///124 /// Note that if a preprocessor command is set, then it overrides this125 /// setting.150 pub fn search_zip(&mut self, yes: bool) -> &mut SearchWorkerBuilder {126 pub(crate) fn search_zip(127 &mut self,128 yes: bool,129 ) -> &mut SearchWorkerBuilder {130 self.config.search_zip = yes;131 self132 }133134 /// Set the binary detection that should be used when searching files135 /// found via a recursive directory search.136 ///158 /// Generally, this binary detection may be `BinaryDetection::quit` if159 /// we want to skip binary files completely.137 /// Generally, this binary detection may be138 /// `grep::searcher::BinaryDetection::quit` if we want to skip binary files139 /// completely.140 ///141 /// By default, no binary detection is performed.162 pub fn binary_detection_implicit(142 pub(crate) fn binary_detection_implicit(143 &mut self,164 detection: BinaryDetection,144 detection: grep::searcher::BinaryDetection,145 ) -> &mut SearchWorkerBuilder {146 self.config.binary_implicit = detection;147 self148 }149150 /// Set the binary detection that should be used when searching files151 /// explicitly supplied by an end user.152 ///173 /// Generally, this binary detection should NOT be `BinaryDetection::quit`,174 /// since we never want to automatically filter files supplied by the end175 /// user.153 /// Generally, this binary detection should NOT be154 /// `grep::searcher::BinaryDetection::quit`, since we never want to155 /// automatically filter files supplied by the end user.156 ///157 /// By default, no binary detection is performed.178 pub fn binary_detection_explicit(158 pub(crate) fn binary_detection_explicit(159 &mut self,180 detection: BinaryDetection,160 detection: grep::searcher::BinaryDetection,161 ) -> &mut SearchWorkerBuilder {162 self.config.binary_explicit = detection;163 self164 }
5 unmodified lines
170/// writes results to an underlying writer such as stdout or a file. However,171/// every search also has some aggregate statistics or meta data that may be172/// useful to higher level routines.173#[derive(Clone, Debug, Default)]194pub struct SearchResult {174pub(crate) struct SearchResult {175 has_match: bool,196 stats: Option<Stats>,176 stats: Option<grep::printer::Stats>,177}178179impl SearchResult {180 /// Whether the search found a match or not.201 pub fn has_match(&self) -> bool {181 pub(crate) fn has_match(&self) -> bool {182 self.has_match183 }184185 /// Return aggregate search statistics for a single search, if available.186 ///187 /// It can be expensive to compute statistics, so these are only present188 /// if explicitly enabled in the printer provided by the caller.209 pub fn stats(&self) -> Option<&Stats> {189 pub(crate) fn stats(&self) -> Option<&grep::printer::Stats> {190 self.stats.as_ref()191 }192}193194/// The pattern matcher used by a search worker.195#[derive(Clone, Debug)]216pub enum PatternMatcher {217 RustRegex(RustRegexMatcher),196pub(crate) enum PatternMatcher {197 RustRegex(grep::regex::RegexMatcher),198 #[cfg(feature = "pcre2")]219 PCRE2(PCRE2RegexMatcher),199 PCRE2(grep::pcre2::RegexMatcher),200}201202/// The printer used by a search worker.203///204/// The `W` type parameter refers to the type of the underlying writer.225#[derive(Debug)]226pub enum Printer<W> {205#[derive(Clone, Debug)]206pub(crate) enum Printer<W> {207 /// Use the standard printer, which supports the classic grep-like format.228 Standard(Standard<W>),208 Standard(grep::printer::Standard<W>),209 /// Use the summary printer, which supports aggregate displays of search210 /// results.231 Summary(Summary<W>),211 Summary(grep::printer::Summary<W>),212 /// A JSON printer, which emits results in the JSON Lines format.233 JSON(JSON<W>),213 JSON(grep::printer::JSON<W>),214}215216impl<W: WriteColor> Printer<W> {237 fn print_stats(238 &mut self,239 total_duration: Duration,240 stats: &Stats,241 ) -> io::Result<()> {242 match *self {243 Printer::JSON(_) => self.print_stats_json(total_duration, stats),244 Printer::Standard(_) | Printer::Summary(_) => {245 self.print_stats_human(total_duration, stats)246 }247 }248 }249250 fn print_stats_human(251 &mut self,252 total_duration: Duration,253 stats: &Stats,254 ) -> io::Result<()> {255 write!(256 self.get_mut(),257 "258{matches} matches259{lines} matched lines260{searches_with_match} files contained matches261{searches} files searched262{bytes_printed} bytes printed263{bytes_searched} bytes searched264{search_time:0.6} seconds spent searching265{process_time:0.6} seconds266",267 matches = stats.matches(),268 lines = stats.matched_lines(),269 searches_with_match = stats.searches_with_match(),270 searches = stats.searches(),271 bytes_printed = stats.bytes_printed(),272 bytes_searched = stats.bytes_searched(),273 search_time = fractional_seconds(stats.elapsed()),274 process_time = fractional_seconds(total_duration)275 )276 }277278 fn print_stats_json(279 &mut self,280 total_duration: Duration,281 stats: &Stats,282 ) -> io::Result<()> {283 // We specifically match the format laid out by the JSON printer in284 // the grep-printer crate. We simply "extend" it with the 'summary'285 // message type.286 let fractional = fractional_seconds(total_duration);287 json::to_writer(288 self.get_mut(),289 &json!({290 "type": "summary",291 "data": {292 "stats": stats,293 "elapsed_total": {294 "secs": total_duration.as_secs(),295 "nanos": total_duration.subsec_nanos(),296 "human": format!("{:0.6}s", fractional),297 },298 }299 }),300 )?;301 write!(self.get_mut(), "\n")302 }303217 /// Return a mutable reference to the underlying printer's writer.305 pub fn get_mut(&mut self) -> &mut W {218 pub(crate) fn get_mut(&mut self) -> &mut W {219 match *self {220 Printer::Standard(ref mut p) => p.get_mut(),221 Printer::Summary(ref mut p) => p.get_mut(),222 Printer::JSON(ref mut p) => p.get_mut(),
5 unmodified lines
228///229/// It is intended for a single worker to execute many searches, and is230/// generally intended to be used from a single thread. When searching using231/// multiple threads, it is better to create a new worker for each thread.319#[derive(Debug)]320pub struct SearchWorker<W> {232#[derive(Clone, Debug)]233pub(crate) struct SearchWorker<W> {234 config: Config,322 command_builder: cli::CommandReaderBuilder,323 decomp_builder: cli::DecompressionReaderBuilder,235 command_builder: grep::cli::CommandReaderBuilder,236 decomp_builder: grep::cli::DecompressionReaderBuilder,237 matcher: PatternMatcher,325 searcher: Searcher,238 searcher: grep::searcher::Searcher,239 printer: Printer<W>,240}241242impl<W: WriteColor> SearchWorker<W> {330 /// Execute a search over the given subject.331 pub fn search(&mut self, subject: &Subject) -> io::Result<SearchResult> {332 let bin = if subject.is_explicit() {243 /// Execute a search over the given haystack.244 pub(crate) fn search(245 &mut self,246 haystack: &crate::haystack::Haystack,247 ) -> io::Result<SearchResult> {248 let bin = if haystack.is_explicit() {249 self.config.binary_explicit.clone()250 } else {251 self.config.binary_implicit.clone()252 };337 let path = subject.path();253 let path = haystack.path();254 log::trace!("{}: binary detection: {:?}", path.display(), bin);255256 self.searcher.set_binary_detection(bin);341 if subject.is_stdin() {257 if haystack.is_stdin() {258 self.search_reader(path, &mut io::stdin().lock())259 } else if self.should_preprocess(path) {260 self.search_preprocessor(path)261 } else if self.should_decompress(path) {
3 unmodified lines
265 }266 }267268 /// Return a mutable reference to the underlying printer.353 pub fn printer(&mut self) -> &mut Printer<W> {269 pub(crate) fn printer(&mut self) -> &mut Printer<W> {270 &mut self.printer271 }272357 /// Print the given statistics to the underlying writer in a way that is358 /// consistent with this searcher's printer's format.359 ///360 /// While `Stats` contains a duration itself, this only corresponds to the361 /// time spent searching, where as `total_duration` should roughly362 /// approximate the lifespan of the ripgrep process itself.363 pub fn print_stats(364 &mut self,365 total_duration: Duration,366 stats: &Stats,367 ) -> io::Result<()> {368 if self.config.json_stats {369 self.printer().print_stats_json(total_duration, stats)370 } else {371 self.printer().print_stats(total_duration, stats)372 }373 }374273 /// Returns true if and only if the given file path should be274 /// decompressed before searching.275 fn should_decompress(&self, path: &Path) -> bool {276 if !self.config.search_zip {
19 unmodified lines
296 fn search_preprocessor(297 &mut self,298 path: &Path,299 ) -> io::Result<SearchResult> {300 use std::{fs::File, process::Stdio};301302 let bin = self.config.preprocessor.as_ref().unwrap();303 let mut cmd = std::process::Command::new(bin);404 cmd.arg(path)405 .stdin(std::process::Stdio::from(std::fs::File::open(path)?));304 cmd.arg(path).stdin(Stdio::from(File::open(path)?));305306 let mut rdr = self.command_builder.build(&mut cmd).map_err(|err| {307 io::Error::new(308 io::ErrorKind::Other,
67 unmodified lines
376/// Search the contents of the given file path using the given matcher,377/// searcher and printer.378fn search_path<M: Matcher, W: WriteColor>(379 matcher: M,481 searcher: &mut Searcher,380 searcher: &mut grep::searcher::Searcher,381 printer: &mut Printer<W>,382 path: &Path,383) -> io::Result<SearchResult> {384 match *printer {
27 unmodified lines
412/// Search the contents of the given reader using the given matcher, searcher413/// and printer.414fn search_reader<M: Matcher, R: io::Read, W: WriteColor>(415 matcher: M,517 searcher: &mut Searcher,416 searcher: &mut grep::searcher::Searcher,417 printer: &mut Printer<W>,418 path: &Path,419 mut rdr: R,420) -> io::Result<SearchResult> {
23 unmodified lines
444 })445 }446 }447}549550/// Return the given duration as fractional seconds.551fn fractional_seconds(duration: Duration) -> f64 {552 (duration.as_secs() as f64) + (duration.subsec_nanos() as f64 * 1e-9)553}
deleted:crates/core/subject.rs-157 removed
1use std::path::Path;23/// A configuration for describing how subjects should be built.4#[derive(Clone, Debug)]5struct Config {6 strip_dot_prefix: bool,7}89impl Default for Config {10 fn default() -> Config {11 Config { strip_dot_prefix: false }12 }13}1415/// A builder for constructing things to search over.16#[derive(Clone, Debug)]17pub struct SubjectBuilder {18 config: Config,19}2021impl SubjectBuilder {22 /// Return a new subject builder with a default configuration.23 pub fn new() -> SubjectBuilder {24 SubjectBuilder { config: Config::default() }25 }2627 /// Create a new subject from a possibly missing directory entry.28 ///29 /// If the directory entry isn't present, then the corresponding error is30 /// logged if messages have been configured. Otherwise, if the subject is31 /// deemed searchable, then it is returned.32 pub fn build_from_result(33 &self,34 result: Result<ignore::DirEntry, ignore::Error>,35 ) -> Option<Subject> {36 match result {37 Ok(dent) => self.build(dent),38 Err(err) => {39 err_message!("{}", err);40 None41 }42 }43 }4445 /// Create a new subject using this builder's configuration.46 ///47 /// If a subject could not be created or should otherwise not be searched,48 /// then this returns `None` after emitting any relevant log messages.49 pub fn build(&self, dent: ignore::DirEntry) -> Option<Subject> {50 let subj =51 Subject { dent, strip_dot_prefix: self.config.strip_dot_prefix };52 if let Some(ignore_err) = subj.dent.error() {53 ignore_message!("{}", ignore_err);54 }55 // If this entry was explicitly provided by an end user, then we always56 // want to search it.57 if subj.is_explicit() {58 return Some(subj);59 }60 // At this point, we only want to search something if it's explicitly a61 // file. This omits symlinks. (If ripgrep was configured to follow62 // symlinks, then they have already been followed by the directory63 // traversal.)64 if subj.is_file() {65 return Some(subj);66 }67 // We got nothing. Emit a debug message, but only if this isn't a68 // directory. Otherwise, emitting messages for directories is just69 // noisy.70 if !subj.is_dir() {71 log::debug!(72 "ignoring {}: failed to pass subject filter: \73 file type: {:?}, metadata: {:?}",74 subj.dent.path().display(),75 subj.dent.file_type(),76 subj.dent.metadata()77 );78 }79 None80 }8182 /// When enabled, if the subject's file path starts with `./` then it is83 /// stripped.84 ///85 /// This is useful when implicitly searching the current working directory.86 pub fn strip_dot_prefix(&mut self, yes: bool) -> &mut SubjectBuilder {87 self.config.strip_dot_prefix = yes;88 self89 }90}9192/// A subject is a thing we want to search. Generally, a subject is either a93/// file or stdin.94#[derive(Clone, Debug)]95pub struct Subject {96 dent: ignore::DirEntry,97 strip_dot_prefix: bool,98}99100impl Subject {101 /// Return the file path corresponding to this subject.102 ///103 /// If this subject corresponds to stdin, then a special `<stdin>` path104 /// is returned instead.105 pub fn path(&self) -> &Path {106 if self.strip_dot_prefix && self.dent.path().starts_with("./") {107 self.dent.path().strip_prefix("./").unwrap()108 } else {109 self.dent.path()110 }111 }112113 /// Returns true if and only if this entry corresponds to stdin.114 pub fn is_stdin(&self) -> bool {115 self.dent.is_stdin()116 }117118 /// Returns true if and only if this entry corresponds to a subject to119 /// search that was explicitly supplied by an end user.120 ///121 /// Generally, this corresponds to either stdin or an explicit file path122 /// argument. e.g., in `rg foo some-file ./some-dir/`, `some-file` is123 /// an explicit subject, but, e.g., `./some-dir/some-other-file` is not.124 ///125 /// However, note that ripgrep does not see through shell globbing. e.g.,126 /// in `rg foo ./some-dir/*`, `./some-dir/some-other-file` will be treated127 /// as an explicit subject.128 pub fn is_explicit(&self) -> bool {129 // stdin is obvious. When an entry has a depth of 0, that means it130 // was explicitly provided to our directory iterator, which means it131 // was in turn explicitly provided by the end user. The !is_dir check132 // means that we want to search files even if their symlinks, again,133 // because they were explicitly provided. (And we never want to try134 // to search a directory.)135 self.is_stdin() || (self.dent.depth() == 0 && !self.is_dir())136 }137138 /// Returns true if and only if this subject points to a directory after139 /// following symbolic links.140 fn is_dir(&self) -> bool {141 let ft = match self.dent.file_type() {142 None => return false,143 Some(ft) => ft,144 };145 if ft.is_dir() {146 return true;147 }148 // If this is a symlink, then we want to follow it to determine149 // whether it's a directory or not.150 self.dent.path_is_symlink() && self.dent.path().is_dir()151 }152153 /// Returns true if and only if this subject points to a file.154 fn is_file(&self) -> bool {155 self.dent.file_type().map_or(false, |ft| ft.is_file())156 }157}
modified:crates/printer/src/json.rs+1 added-1 removed
445 unmodified lines
446/// }447/// }448/// }449/// ```450#[derive(Debug)]450#[derive(Clone, Debug)]451pub struct JSON<W> {452 config: Config,453 wtr: CounterWriter<W>,454 matches: Vec<Match>,
556 unmodified lines
modified:crates/printer/src/standard.rs+1 added-1 removed
487 unmodified lines
488/// of the `termcolor::WriteColor` trait. If colors are not desired,489/// then the `new_no_color` constructor can be used, or, alternatively,490/// the `termcolor::NoColor` adapter can be used to wrap any `io::Write`491/// implementation without enabling any colors.492#[derive(Debug)]492#[derive(Clone, Debug)]493pub struct Standard<W> {494 config: Config,495 wtr: RefCell<CounterWriter<W>>,496 matches: Vec<Match>,
3336 unmodified lines
modified:crates/printer/src/summary.rs+1 added-1 removed
348 unmodified lines
349/// configured using [`SummaryBuilder`].350///351/// This type is generic over `W`, which represents any implementation of352/// the `termcolor::WriteColor` trait.353#[derive(Debug)]353#[derive(Clone, Debug)]354pub struct Summary<W> {355 config: Config,356 wtr: RefCell<CounterWriter<W>>,357}
792 unmodified lines
modified:crates/printer/src/util.rs+8 added-8 removed
44 unmodified lines
45 pub(crate) fn new() -> Replacer<M> {46 Replacer { space: None }47 }4849 /// Executes a replacement on the given subject string by replacing all49 /// Executes a replacement on the given haystack string by replacing all50 /// matches with the given replacement. To access the result of the51 /// replacement, use the `replacement` method.52 ///53 /// This can fail if the underlying matcher reports an error.54 pub(crate) fn replace_all<'a>(55 &'a mut self,56 searcher: &Searcher,57 matcher: &M,58 mut subject: &[u8],58 mut haystack: &[u8],59 range: std::ops::Range<usize>,60 replacement: &[u8],61 ) -> io::Result<()> {62 // See the giant comment in 'find_iter_at_in_context' below for why we63 // do this dance.64 let is_multi_line = searcher.multi_line_with_matcher(&matcher);65 if is_multi_line {66 if subject[range.end..].len() >= MAX_LOOK_AHEAD {67 subject = &subject[..range.end + MAX_LOOK_AHEAD];66 if haystack[range.end..].len() >= MAX_LOOK_AHEAD {67 haystack = &haystack[..range.end + MAX_LOOK_AHEAD];68 }69 } else {70 // When searching a single line, we should remove the line71 // terminator. Otherwise, it's possible for the regex (via72 // look-around) to observe the line terminator and not match73 // because of it.74 let mut m = Match::new(0, range.end);75 trim_line_terminator(searcher, subject, &mut m);76 subject = &subject[..m.end()];75 trim_line_terminator(searcher, haystack, &mut m);76 haystack = &haystack[..m.end()];77 }78 {79 let &mut Space { ref mut dst, ref mut caps, ref mut matches } =80 self.allocate(matcher)?;
1 unmodified line
82 matches.clear();8384 replace_with_captures_in_context(85 matcher,86 subject,86 haystack,87 range.clone(),88 caps,89 dst,90 |caps, dst| {91 let start = dst.len();92 caps.interpolate(93 |name| matcher.capture_index(name),94 subject,94 haystack,95 replacement,96 dst,97 );98 let end = dst.len();
491 unmodified lines
modified:crates/searcher/src/searcher/mod.rs+1 added-1 removed
122 unmodified lines
123/// An encoding can be used to configure a [`SearcherBuilder`] to transcode124/// source data from an encoding to UTF-8 before searching.125///126/// An `Encoding` will always be cheap to clone.127#[derive(Clone, Debug)]127#[derive(Clone, Debug, Eq, PartialEq)]128pub struct Encoding(&'static encoding_rs::Encoding);129130impl Encoding {131 /// Create a new encoding for the specified label.
923 unmodified lines
modified:tests/feature.rs+36 added-2 removed
409 unmodified lines
410 f411_single_threaded_search_stats,411 |dir: Dir, mut cmd: TestCommand| {412 dir.create("sherlock", SHERLOCK);413414 let lines = cmd.arg("--stats").arg("Sherlock").stdout();414 let lines = cmd.arg("-j1").arg("--stats").arg("Sherlock").stdout();415 assert!(lines.contains("Sherlock"));416 assert!(lines.contains("2 matched lines"));417 assert!(lines.contains("1 files contained matches"));418 assert!(lines.contains("1 files searched"));419 assert!(lines.contains("seconds"));
3 unmodified lines
423rgtest!(f411_parallel_search_stats, |dir: Dir, mut cmd: TestCommand| {424 dir.create("sherlock_1", SHERLOCK);425 dir.create("sherlock_2", SHERLOCK);426426 let lines = cmd.arg("--stats").arg("Sherlock").stdout();427 let lines = cmd.arg("-j2").arg("--stats").arg("Sherlock").stdout();428 dbg!(&lines);429 assert!(lines.contains("4 matched lines"));430 assert!(lines.contains("2 files contained matches"));431 assert!(lines.contains("2 files searched"));432 assert!(lines.contains("seconds"));433});434435rgtest!(436 f411_single_threaded_quiet_search_stats,437 |dir: Dir, mut cmd: TestCommand| {438 dir.create("sherlock", SHERLOCK);439440 let lines = cmd441 .arg("--quiet")442 .arg("-j1")443 .arg("--stats")444 .arg("Sherlock")445 .stdout();446 assert!(!lines.contains("Sherlock"));447 assert!(lines.contains("2 matched lines"));448 assert!(lines.contains("1 files contained matches"));449 assert!(lines.contains("1 files searched"));450 assert!(lines.contains("seconds"));451 }452);453454rgtest!(f411_parallel_quiet_search_stats, |dir: Dir, mut cmd: TestCommand| {455 dir.create("sherlock_1", SHERLOCK);456 dir.create("sherlock_2", SHERLOCK);457458 let lines =459 cmd.arg("-j2").arg("--quiet").arg("--stats").arg("Sherlock").stdout();460 assert!(!lines.contains("Sherlock"));461 assert!(lines.contains("4 matched lines"));462 assert!(lines.contains("2 files contained matches"));463 assert!(lines.contains("2 files searched"));464 assert!(lines.contains("seconds"));465});466467// See: https://github.com/BurntSushi/ripgrep/issues/416468rgtest!(f416_crlf, |dir: Dir, mut cmd: TestCommand| {469 dir.create("sherlock", SHERLOCK_CRLF);470 cmd.arg("--crlf").arg(r"Sherlock$").arg("sherlock");
590 unmodified lines
modified:tests/json.rs+13 added
187 unmodified lines
188 assert_eq!(msgs[4].unwrap_summary().stats.searches_with_match, 1);189 assert_eq!(msgs[4].unwrap_summary().stats.bytes_printed, 494);190});191192rgtest!(quiet_stats, |dir: Dir, mut cmd: TestCommand| {193 dir.create("sherlock", SHERLOCK);194 cmd.arg("--json")195 .arg("--quiet")196 .arg("--stats")197 .arg("Sherlock Holmes")198 .arg("sherlock");199200 let msgs = json_decode(&cmd.stdout());201 assert_eq!(msgs[0].unwrap_summary().stats.searches_with_match, 1);202 assert_eq!(msgs[0].unwrap_summary().stats.bytes_searched, 367);203});204205#[cfg(unix)]206rgtest!(notutf8, |dir: Dir, mut cmd: TestCommand| {207 use std::ffi::OsStr;208 use std::os::unix::ffi::OsStrExt;
165 unmodified lines
modified:tests/regression.rs+1 added
400 unmodified lines
401402 let output = cmd.cmd().output().unwrap();403 let stderr = String::from_utf8_lossy(&output.stderr);404 let expected = "\405error parsing flag --colors: \406unrecognized style attribute ''. Choose from: nobold, bold, nointense, \407intense, nounderline, underline.408";409 eqnice!(expected, stderr);
789 unmodified lines
modified:tests/util.rs+2 added-2 removed
76 unmodified lines
77 if dir.exists() {78 nice_err(&dir, fs::remove_dir_all(&dir));79 }80 nice_err(&dir, repeat(|| fs::create_dir_all(&dir)));81 Dir { root: root, dir: dir, pcre2: false }81 Dir { root, dir, pcre2: false }82 }8384 /// Use PCRE2 for this test.85 pub fn pcre2(&mut self, yes: bool) {
80 unmodified lines
166 cmd.arg("--path-separator").arg("/");167 if self.is_pcre2() {168 cmd.arg("--pcre2");169 }170 TestCommand { dir: self.clone(), cmd: cmd }170 TestCommand { dir: self.clone(), cmd }171 }172173 /// Returns the path to the ripgrep executable.174 pub fn bin(&self) -> process::Command {
328 unmodified lines
modified:build.rs+20 added-239 removed
1use std::{2 env,3 fs::{self, File},4 io::{self, Read, Write},5 path::Path,6 process,7};89use clap::Shell;1011use crate::app::{RGArg, RGArgKind};1213#[allow(dead_code)]14#[path = "crates/core/app.rs"]15mod app;161fn main() {18 // OUT_DIR is set by Cargo and it's where any additional build artifacts19 // are written.20 let Some(outdir) = env::var_os("OUT_DIR") else {21 eprintln!(22 "OUT_DIR environment variable not defined. \23 Please file a bug: \24 https://github.com/BurntSushi/ripgrep/issues/new"25 );26 process::exit(1);27 };28 fs::create_dir_all(&outdir).unwrap();2930 let stamp_path = Path::new(&outdir).join("ripgrep-stamp");31 if let Err(err) = File::create(&stamp_path) {32 panic!("failed to write {}: {}", stamp_path.display(), err);33 }34 if let Err(err) = generate_man_page(&outdir) {35 eprintln!("failed to generate man page: {}", err);36 }3738 // Use clap to build completion files.39 let mut app = app::app();40 app.gen_completions("rg", Shell::Bash, &outdir);41 app.gen_completions("rg", Shell::Fish, &outdir);42 app.gen_completions("rg", Shell::PowerShell, &outdir);43 // Note that we do not use clap's support for zsh. Instead, zsh completions44 // are manually maintained in `complete/_rg`.4546 // Make the current git hash available to the build.47 if let Some(rev) = git_revision_hash() {48 println!("cargo:rustc-env=RIPGREP_BUILD_GIT_HASH={}", rev);49 }50 // Embed a Windows manifest and set some linker options. The main reason51 // for this is to enable long path support on Windows. This still, I52 // believe, requires enabling long path support in the registry. But if53 // that's enabled, then this will let ripgrep use C:\... style paths that54 // are longer than 260 characters.2 set_git_revision_hash();3 set_windows_exe_options();4}56/// Embed a Windows manifest and set some linker options.7///8/// The main reason for this is to enable long path support on Windows. This9/// still, I believe, requires enabling long path support in the registry. But10/// if that's enabled, then this will let ripgrep use C:\... style paths that11/// are longer than 260 characters.12fn set_windows_exe_options() {13 static MANIFEST: &str = "pkg/windows/Manifest.xml";1461 let Ok(target_os) = env::var("CARGO_CFG_TARGET_OS") else { return };62 let Ok(target_env) = env::var("CARGO_CFG_TARGET_ENV") else { return };15 let Ok(target_os) = std::env::var("CARGO_CFG_TARGET_OS") else { return };16 let Ok(target_env) = std::env::var("CARGO_CFG_TARGET_ENV") else { return };17 if !(target_os == "windows" && target_env == "msvc") {18 return;19 }2067 let Ok(mut manifest) = env::current_dir() else { return };21 let Ok(mut manifest) = std::env::current_dir() else { return };22 manifest.push(MANIFEST);23 let Some(manifest) = manifest.to_str() else { return };2425 println!("cargo:rerun-if-changed={}", MANIFEST);
4 unmodified lines
30 // warnings get squashed (I believe).31 println!("cargo:rustc-link-arg-bin=rg=/WX");32}3380fn git_revision_hash() -> Option<String> {81 let output = process::Command::new("git")82 .args(&["rev-parse", "--short=10", "HEAD"])83 .output()84 .ok()?;85 let v = String::from_utf8_lossy(&output.stdout).trim().to_string();86 if v.is_empty() {87 None88 } else {89 Some(v)90 }91}34/// Make the current git hash available to the build as the environment35/// variable `RIPGREP_BUILD_GIT_HASH`.36fn set_git_revision_hash() {37 use std::process::Command;3893fn generate_man_page<P: AsRef<Path>>(outdir: P) -> io::Result<()> {94 // If asciidoctor isn't installed, fallback to asciidoc.95 if let Err(err) = process::Command::new("asciidoctor").output() {96 eprintln!(97 "Could not run 'asciidoctor' binary, falling back to 'a2x'."98 );99 eprintln!("Error from running 'asciidoctor': {}", err);100 return legacy_generate_man_page::<P>(outdir);39 let args = &["rev-parse", "--short=10", "HEAD"];40 let Ok(output) = Command::new("git").args(args).output() else { return };41 let rev = String::from_utf8_lossy(&output.stdout).trim().to_string();42 if rev.is_empty() {43 return;44 }102 // 1. Read asciidoctor template.103 // 2. Interpolate template with auto-generated docs.104 // 3. Save interpolation to disk.105 // 4. Use asciidoctor to convert to man page.106 let outdir = outdir.as_ref();107 let cwd = env::current_dir()?;108 let tpl_path = cwd.join("doc").join("rg.1.txt.tpl");109 let txt_path = outdir.join("rg.1.txt");110111 let mut tpl = String::new();112 File::open(&tpl_path)?.read_to_string(&mut tpl)?;113 let options =114 formatted_options()?.replace("&#123;", "{").replace("&#125;", "}");115 tpl = tpl.replace("{OPTIONS}", &options);116117 let githash = git_revision_hash();118 let githash = githash.as_ref().map(|x| &**x);119 tpl = tpl.replace("{VERSION}", &app::long_version(githash, false));120121 File::create(&txt_path)?.write_all(tpl.as_bytes())?;122 let result = process::Command::new("asciidoctor")123 .arg("--doctype")124 .arg("manpage")125 .arg("--backend")126 .arg("manpage")127 .arg(&txt_path)128 .spawn()?129 .wait()?;130 if !result.success() {131 let msg =132 format!("'asciidoctor' failed with exit code {:?}", result.code());133 return Err(ioerr(msg));134 }135 Ok(())45 println!("cargo:rustc-env=RIPGREP_BUILD_GIT_HASH={}", rev);46}137138fn legacy_generate_man_page<P: AsRef<Path>>(outdir: P) -> io::Result<()> {139 // If asciidoc isn't installed, then don't do anything.140 if let Err(err) = process::Command::new("a2x").output() {141 eprintln!("Could not run 'a2x' binary, skipping man page generation.");142 eprintln!("Error from running 'a2x': {}", err);143 return Ok(());144 }145 // 1. Read asciidoc template.146 // 2. Interpolate template with auto-generated docs.147 // 3. Save interpolation to disk.148 // 4. Use a2x (part of asciidoc) to convert to man page.149 let outdir = outdir.as_ref();150 let cwd = env::current_dir()?;151 let tpl_path = cwd.join("doc").join("rg.1.txt.tpl");152 let txt_path = outdir.join("rg.1.txt");153154 let mut tpl = String::new();155 File::open(&tpl_path)?.read_to_string(&mut tpl)?;156 tpl = tpl.replace("{OPTIONS}", &formatted_options()?);157158 let githash = git_revision_hash();159 let githash = githash.as_ref().map(|x| &**x);160 tpl = tpl.replace("{VERSION}", &app::long_version(githash, false));161162 File::create(&txt_path)?.write_all(tpl.as_bytes())?;163 let result = process::Command::new("a2x")164 .arg("--no-xmllint")165 .arg("--doctype")166 .arg("manpage")167 .arg("--format")168 .arg("manpage")169 .arg(&txt_path)170 .spawn()?171 .wait()?;172 if !result.success() {173 let msg = format!("'a2x' failed with exit code {:?}", result.code());174 return Err(ioerr(msg));175 }176 Ok(())177}178179fn formatted_options() -> io::Result<String> {180 let mut args = app::all_args_and_flags();181 args.sort_by(|x1, x2| x1.name.cmp(&x2.name));182183 let mut formatted = vec![];184 for arg in args {185 if arg.hidden {186 continue;187 }188 // ripgrep only has two positional arguments, and probably will only189 // ever have two positional arguments, so we just hardcode them into190 // the template.191 if let app::RGArgKind::Positional { .. } = arg.kind {192 continue;193 }194 formatted.push(formatted_arg(&arg)?);195 }196 Ok(formatted.join("\n\n"))197}198199fn formatted_arg(arg: &RGArg) -> io::Result<String> {200 match arg.kind {201 RGArgKind::Positional { .. } => {202 panic!("unexpected positional argument")203 }204 RGArgKind::Switch { long, short, multiple } => {205 let mut out = vec![];206207 let mut header = format!("--{}", long);208 if let Some(short) = short {209 header = format!("-{}, {}", short, header);210 }211 if multiple {212 header = format!("*{}* ...::", header);213 } else {214 header = format!("*{}*::", header);215 }216 writeln!(out, "{}", header)?;217 writeln!(out, "{}", formatted_doc_txt(arg)?)?;218219 Ok(String::from_utf8(out).unwrap())220 }221 RGArgKind::Flag { long, short, value_name, multiple, .. } => {222 let mut out = vec![];223224 let mut header = format!("--{}", long);225 if let Some(short) = short {226 header = format!("-{}, {}", short, header);227 }228 if multiple {229 header = format!("*{}* _{}_ ...::", header, value_name);230 } else {231 header = format!("*{}* _{}_::", header, value_name);232 }233 writeln!(out, "{}", header)?;234 writeln!(out, "{}", formatted_doc_txt(arg)?)?;235236 Ok(String::from_utf8(out).unwrap())237 }238 }239}240241fn formatted_doc_txt(arg: &RGArg) -> io::Result<String> {242 let paragraphs: Vec<String> = arg243 .doc_long244 .replace("{", "&#123;")245 .replace("}", r"&#125;")246 // Hack to render ** literally in man page correctly. We can't put247 // these crazy +++ in the help text directly, since that shows248 // literally in --help output.249 .replace("*-g 'foo/**'*", "*-g +++'foo/**'+++*")250 .split("\n\n")251 .map(|s| s.to_string())252 .collect();253 if paragraphs.is_empty() {254 return Err(ioerr(format!("missing docs for --{}", arg.name)));255 }256 let first = format!(" {}", paragraphs[0].replace("\n", "\n "));257 if paragraphs.len() == 1 {258 return Ok(first);259 }260 Ok(format!("{}\n+\n{}", first, paragraphs[1..].join("\n+\n")))261}262263fn ioerr(msg: String) -> io::Error {264 io::Error::new(io::ErrorKind::Other, msg)265}
modified:Cargo.lock+12 added-38 removed
28 unmodified lines
29source = "registry+https://github.com/rust-lang/crates.io-index"30checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2"3132[[package]]33name = "bitflags"34version = "1.3.2"35source = "registry+https://github.com/rust-lang/crates.io-index"36checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"3738[[package]]33name = "bstr"34version = "1.7.0"35source = "registry+https://github.com/rust-lang/crates.io-index"36checksum = "c79ad7fb2dd38f3dabd76b09c6a5a20c038fc0213ef1e9afd30eb777f120f019"
19 unmodified lines
56source = "registry+https://github.com/rust-lang/crates.io-index"57checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"5859[[package]]66name = "clap"67version = "2.34.0"68source = "registry+https://github.com/rust-lang/crates.io-index"69checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"70dependencies = [71 "bitflags",72 "strsim",73 "textwrap",74 "unicode-width",75]7677[[package]]60name = "crossbeam-channel"61version = "0.5.8"62source = "registry+https://github.com/rust-lang/crates.io-index"63checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200"
209 unmodified lines
273 "libc",274]275276[[package]]277name = "lexopt"278version = "0.3.0"279source = "registry+https://github.com/rust-lang/crates.io-index"280checksum = "baff4b617f7df3d896f97fe922b64817f6cd9a756bb81d40f8883f2f66dcb401"281282[[package]]283name = "libc"284version = "0.2.149"285source = "registry+https://github.com/rust-lang/crates.io-index"286checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b"
134 unmodified lines
421version = "13.0.0"422dependencies = [423 "anyhow",424 "bstr",437 "clap",425 "grep",426 "ignore",427 "jemallocator",428 "lexopt",429 "log",430 "serde",431 "serde_derive",432 "serde_json",433 "termcolor",434 "textwrap",435 "walkdir",436]437438[[package]]
48 unmodified lines
487 "serde",488]489490[[package]]502name = "strsim"503version = "0.8.0"504source = "registry+https://github.com/rust-lang/crates.io-index"505checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"506507[[package]]491name = "syn"492version = "2.0.38"493source = "registry+https://github.com/rust-lang/crates.io-index"494checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b"
4 unmodified lines
499]500501[[package]]502name = "termcolor"520version = "1.3.0"503version = "1.4.0"504source = "registry+https://github.com/rust-lang/crates.io-index"522checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64"505checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449"506dependencies = [507 "winapi-util",508]509510[[package]]511name = "textwrap"529version = "0.11.0"512version = "0.16.0"513source = "registry+https://github.com/rust-lang/crates.io-index"531checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"532dependencies = [533 "unicode-width",534]514checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"515516[[package]]517name = "unicode-ident"518version = "1.0.12"519source = "registry+https://github.com/rust-lang/crates.io-index"520checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"521522[[package]]543name = "unicode-width"544version = "0.1.11"545source = "registry+https://github.com/rust-lang/crates.io-index"546checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"547548[[package]]523name = "walkdir"524version = "2.4.0"525source = "registry+https://github.com/rust-lang/crates.io-index"526checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee"
35 unmodified lines
modified:Cargo.toml+3 added-11 removed
48 unmodified lines
49]5051[dependencies]52anyhow = "1.0.75"53bstr = "1.6.0"53bstr = "1.7.0"54grep = { version = "0.2.12", path = "crates/grep" }55ignore = { version = "0.4.19", path = "crates/ignore" }56lexopt = "0.3.0"57log = "0.4.5"58serde_json = "1.0.23"59termcolor = "1.1.0"60textwrap = { version = "0.16.0", default-features = false }6160[dependencies.clap]61version = "2.33.0"62default-features = false63features = ["suggestions"]6462[target.'cfg(all(target_env = "musl", target_pointer_width = "64"))'.dependencies.jemallocator]63version = "0.5.0"6468[build-dependencies.clap]69version = "2.33.0"70default-features = false71features = ["suggestions"]7265[dev-dependencies]66serde = "1.0.77"67serde_derive = "1.0.77"68walkdir = "2"
34 unmodified lines
modified:CHANGELOG.md+10 added
19 unmodified lines
20* Added or improved file type filtering for Ada, DITA, Elixir, Fuchsia, Gentoo,21 Gradle, GraphQL, Markdown, Prolog, Raku, TypeScript, USD, V22* [FEATURE #1790](https://github.com/BurntSushi/ripgrep/issues/1790):23 Add new `--stop-on-nonmatch` flag.24* [FEATURE #1814](https://github.com/BurntSushi/ripgrep/issues/1814):25 Flags are now categorized in `-h/--help` output and ripgrep's man page.26* [FEATURE #2195](https://github.com/BurntSushi/ripgrep/issues/2195):27 When `extra-verbose` mode is enabled in zsh, show extra file type info.28* [FEATURE #2409](https://github.com/BurntSushi/ripgrep/pull/2409):29 Added installation instructions for `winget`.3031Bug fixes:3233* [BUG #884](https://github.com/BurntSushi/ripgrep/issues/884):34 Don't error when `-v/--invert-match` is used multiple times.35* [BUG #1275](https://github.com/BurntSushi/ripgrep/issues/1275):36 Fix bug with `\b` assertion in the regex engine.37* [BUG #1648](https://github.com/BurntSushi/ripgrep/issues/1648):38 Fix bug where sometimes short flags with values, e.g., `-M 900`, would fail.39* [BUG #1701](https://github.com/BurntSushi/ripgrep/issues/1701):40 Fix bug where some flags could not be repeated.41* [BUG #1757](https://github.com/BurntSushi/ripgrep/issues/1757):42 Fix bug when searching a sub-directory didn't have ignores applied correctly.43* [BUG #1891](https://github.com/BurntSushi/ripgrep/issues/1891):44 Fix bug when using `-w` with a regex that can match the empty string.45* [BUG #1911](https://github.com/BurntSushi/ripgrep/issues/1911):46 Disable mmap searching in all non-64-bit environments.47* [BUG #1966](https://github.com/BurntSushi/ripgrep/issues/1966):48 Fix bug where ripgrep can panic when printing to stderr.49* [BUG #2108](https://github.com/BurntSushi/ripgrep/issues/2108):50 Improve docs for `-r/--replace` syntax.51* [BUG #2198](https://github.com/BurntSushi/ripgrep/issues/2198):52 Fix bug where `--no-ignore-dot` would not ignore `.rgignore`.
1495 unmodified lines
modified:RELEASE-CHECKLIST.md+10 added-6 removed
1Release Checklist2-----------------1# Release Checklist23* Ensure local `master` is up to date with respect to `origin/master`.4* Run `cargo update` and review dependency updates. Commit updated5 `Cargo.lock`.6* Run `cargo outdated` and review semver incompatible updates. Unless there is7 a strong motivation otherwise, review and update every dependency. Also8 run `--aggressive`, but don't update to crates that are still in beta.9* Update date in `crates/core/flags/doc/template.rg.1`.10* Review changes for every crate in `crates` since the last ripgrep release.11 If the set of changes is non-empty, issue a new release for that crate. Check12 crates in the following order. After updating a crate, ensure minimal13 versions are updated as appropriate in dependents. If an update is required,
25 unmodified lines
39 > In case you haven't heard of it before, ripgrep is a line-oriented search40 > tool that recursively searches the current directory for a regex pattern.41 > By default, ripgrep will respect gitignore rules and automatically skip42 > hidden files/directories and binary files.42* Run `ci/build-deb` locally and manually upload the deb package to the43 release.43* Run `git checkout $version && ci/build-and-publish-deb $version` on a Linux44 system that has `cargo deb` installed.45* Run `git checkout $version && ci/build-and-publish-m2 $version` on a macOS46 system with Apple silicon.47* Run `cargo publish`.48* Run `ci/sha256-releases {VERSION} >> pkg/brew/ripgrep-bin.rb`. Then edit49 `pkg/brew/ripgrep-bin.rb` to update the version number and sha256 hashes.50 Remove extraneous stuff added by `ci/sha256-releases`. Commit changes.
3 unmodified lines
54 ===55 Unreleased changes. Release notes have not yet been written.56 ```5755Note that56[`cargo-up` can be found in BurntSushi's dotfiles](https://github.com/BurntSushi/dotfiles/blob/master/bin/cargo-up).58Note that [`cargo-up` can be found in BurntSushi's dotfiles][dotfiles].5960[dotfiles]: https://github.com/BurntSushi/dotfiles/blob/master/bin/cargo-up