Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ cargo build --release

After the version bump is merged and CI passes, open **Actions > Release >
Run workflow**, select **main**, and enter the tag matching the workspace
version in `Cargo.toml`, for example `v1.2.8`. The equivalent CLI command is:
version in `Cargo.toml`, for example `v1.2.9`. The equivalent CLI command is:

```bash
gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.8
gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.9
```

The workflow validates the version, creates a missing tag at the exact commit
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ exclude = ["vendor/ignore"]
resolver = "2"

[workspace.package]
version = "1.2.8"
version = "1.2.9"
edition = "2024"
rust-version = "1.88"
license = "MIT"
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ These tables describe search flags. Use `tgrep index --help` and
| `-w, --word-regexp` | Require non-word characters or text boundaries on both sides of the match; overrides earlier `-x` |
| `-v, --invert-match` | Show lines that do NOT match |
| `-o, --only-matching` | Print only the matched parts |
| `--match-context <N>` | Like `-o`, with up to N Unicode characters on each side of each match on its line. Nearby excerpts may overlap. Columns and byte offsets still identify the match. JSON keeps its full-line events. |
| `-e, --regexp <PAT>` | Additional pattern (repeatable for OR) |
| `-f, --file <FILE>` | Read patterns verbatim, one per line; blank lines are empty patterns (repeatable) |
| `-U, --multiline` | Enable multiline matching (`.` still excludes `\n`) |
Expand Down
2 changes: 1 addition & 1 deletion fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion tgrep-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ struct Cli {
#[arg(short = 'o', long = "only-matching", global = true)]
only_matching: bool,

/// Print each match with up to N characters on either side on the same line. Implies -o.
#[arg(long, value_name = "N", global = true)]
match_context: Option<usize>,

/// Limit matches per file.
#[arg(short = 'm', long = "max-count", global = true)]
max_count: Option<usize>,
Expand Down Expand Up @@ -1163,7 +1167,8 @@ impl Cli {
glob_case_insensitive: self.glob_case_insensitive,
type_ops: self.type_ops.clone(),
invert_match: self.invert_match,
only_matching: self.only_matching,
only_matching: self.only_matching || self.match_context.is_some(),
match_context: self.match_context.unwrap_or(0),
after_context: self.after_context,
before_context: self.before_context,
context: self.context,
Expand Down
113 changes: 72 additions & 41 deletions tgrep-cli/src/matching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,7 @@ pub struct MatchOptions {
pub invert_match: bool,
pub multiline: bool,
pub only_matching: bool,
pub match_context: usize,
pub before_context: usize,
pub after_context: usize,
pub max_count: Option<usize>,
Expand Down Expand Up @@ -997,6 +998,27 @@ pub struct MatchOptions {
pub report_replacements: bool,
}

/// Return a same-line excerpt and the byte range to highlight inside it.
fn match_excerpt(line: &str, start: usize, end: usize, radius: usize) -> (&str, (usize, usize)) {
let mut left = start;
let mut right = end;
// A replacement can introduce a line break into an otherwise single-line buffer.
for ch in line[..start].chars().rev().take(radius) {
if ch == '\n' {
break;
}
left -= ch.len_utf8();
}
let right_context = &line[end..];
for (i, ch) in right_context.char_indices().take(radius) {
if ch == '\n' || (ch == '\r' && right_context[i + 1..].starts_with('\n')) {
break;
}
right += ch.len_utf8();
}
(&line[left..right], (start - left, end - left))
}

/// One unit of output produced by searching a single file.
pub enum Emit<'a> {
Match {
Expand Down Expand Up @@ -1202,51 +1224,52 @@ impl<'a> FileMatches<'a> {
}

if opts.only_matching && !hit.spans.is_empty() {
// With `-r`, `-o` prints the replacement of each match rather
// than the matched text itself.
if let Some(rep) = &opts.replace {
// ripgrep rewrites the line and reports offsets into the
// result, so each match moves by the length delta of the
// ones before it. Columns stay in source terms here and are
// corrected by `column_shifts` after the caller has mapped
// them back through any lossy-decoding repairs.
let mut shift: isize = 0;
for (start, end, text) in matcher.expansions(line, rep).map_err(E::from)? {
let len = text.len();
on_emit(Emit::Match {
line_number: hit.idx + 1,
content: Cow::Owned(text),
columns: vec![start + 1],
spans: vec![(0, len)],
absolute_offset: offset + start,
line_offset: offset,
column_shifts: vec![shift],
offset_shift: shift,
terminator_len: 0,
block: None,
hidden: false,
replacements: None,
})?;
shift += len as isize - (end - start) as isize;
}
return Ok(());
}
for &(s, e) in &hit.spans {
let text = &line[s..e];
let mut emit = |content, span, start, shift| {
on_emit(Emit::Match {
line_number: hit.idx + 1,
content: Cow::Borrowed(text),
columns: vec![s + 1],
spans: vec![(0, text.len())],
absolute_offset: offset + s,
content,
columns: vec![start + 1],
spans: vec![span],
absolute_offset: offset + start,
line_offset: offset,
column_shifts: Vec::new(),
offset_shift: 0,
column_shifts: if shift == 0 { Vec::new() } else { vec![shift] },
offset_shift: shift,
terminator_len: 0,
block: None,
hidden: false,
replacements: None,
})?;
})
};
match &opts.replace {
None => {
for &(start, end) in &hit.spans {
let (text, span) = match_excerpt(line, start, end, opts.match_context);
emit(Cow::Borrowed(text), span, start, 0)?;
}
}
Some(rep) if opts.match_context == 0 => {
// Plain -o only needs the expansions, even on very long lines.
let mut shift = 0;
for (start, end, text) in matcher.expansions(line, rep)? {
let len = text.len();
emit(Cow::Owned(text), (0, len), start, shift)?;
shift += len as isize - (end - start) as isize;
}
}
Some(rep) => {
// Nearby replacements can also fall inside the excerpt.
let (rewritten, spans) = matcher.replace_all(line, rep)?;
for (&(source, _), (start, end)) in hit.spans.iter().zip(spans) {
let (text, span) =
match_excerpt(&rewritten, start, end, opts.match_context);
emit(
Cow::Owned(text.to_owned()),
span,
source,
start as isize - source as isize,
)?;
}
}
}
return Ok(());
}
Expand Down Expand Up @@ -1426,6 +1449,12 @@ fn emit_block<'a, E>(
let (a, b) = (rep.dst.0.max(ls), rep.dst.1.min(te));
(a < b).then_some((a, b))
};
// With match context, an empty replacement still anchors an excerpt on the
// one rewritten line that contains its position.
let anchor = |rep: &Placed, ls: usize, te: usize| {
let at = rep.dst.0;
(opts.match_context > 0 && rep.dst.1 == at && (ls..=te).contains(&at)).then_some((at, at))
};
let mut rows = 0usize;

if opts.only_matching {
Expand All @@ -1441,14 +1470,16 @@ fn emit_block<'a, E>(
.collect();
for (k, &(ls, te, _)) in lines.iter().enumerate() {
for (rep, &shift) in block.reps.iter().zip(&shifts) {
let Some((a, b)) = piece(rep, ls, te) else {
let Some((a, b)) = piece(rep, ls, te).or_else(|| anchor(rep, ls, te)) else {
continue;
};
let (text, span) =
match_excerpt(&block.text[ls..te], a - ls, b - ls, opts.match_context);
on_emit(Emit::Match {
line_number: block.first + 1 + k,
content: Cow::Owned(block.text[a..b].to_owned()),
content: Cow::Owned(text.to_owned()),
columns: vec![rep.src.0 - block.start + 1],
spans: vec![(0, b - a)],
spans: vec![span],
absolute_offset: rep.src.0,
line_offset: block.start,
column_shifts: vec![shift],
Expand Down
38 changes: 20 additions & 18 deletions tgrep-cli/src/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub struct SearchOptions {
pub type_ops: Vec<filetypes::TypeOp>,
pub invert_match: bool,
pub only_matching: bool,
pub match_context: usize,
pub after_context: Option<usize>,
pub before_context: Option<usize>,
pub context: Option<usize>,
Expand Down Expand Up @@ -446,6 +447,7 @@ impl SearchOptions {
invert_match: self.invert_match,
multiline: self.multiline,
only_matching: self.effective_only_matching(),
match_context: self.match_context,
before_context: self.before_ctx(),
after_context: self.after_ctx(),
// `-q` and `--files-without-match` only need to know whether the
Expand Down Expand Up @@ -1013,7 +1015,7 @@ pub fn run(
})?;
require_server_coverage(&result)?;
require_ordered_filters(&result, &request)?;
require_replace_support(&result, &request)?;
require_render_support(&result, &request)?;
Ok((view.root, scope, request, result))
})();
match response {
Expand Down Expand Up @@ -1463,8 +1465,10 @@ fn server_search_request(
if opts.needs_ordered_filters()? {
request["params"]["ordered_filters"] = serde_json::json!(true);
}
// A server that predates a `--replace` rendering cannot honour it, and
// its reply is then refused. Ask only when the output depends on it.
// Ask for rendering extensions only when the output depends on them.
if opts.match_context > 0 && opts.prints_text_lines() {
request["params"]["match_context"] = serde_json::json!(opts.match_context);
}
if opts.needs_replace_blocks(ci) {
request["params"]["multiline_replace"] = serde_json::json!(true);
}
Expand All @@ -1479,13 +1483,12 @@ fn server_search_request(
Ok(request)
}

/// Fail when the result comes from a server that predates the `--replace`
/// rendering `request` asked for. Such a server ignores the request and
/// rewrites `-U` matches line by line, or leaves `--json` submatches without
/// their `replacement`. Reading the request rather than the options keeps
/// this check in step with what `server_search_request` decided to ask for.
fn require_replace_support(result: &serde_json::Value, request: &serde_json::Value) -> Result<()> {
/// Older servers ignore unknown rendering options. Check the reply before printing any rows.
fn require_render_support(result: &serde_json::Value, request: &serde_json::Value) -> Result<()> {
let params = &request["params"];
if params.get("match_context").is_some() && !flag_set(result, "match_context") {
anyhow::bail!("server does not support character context");
}
if flag_set(params, "multiline_replace") && !flag_set(result, "multiline_replace") {
anyhow::bail!("server does not support multiline replacement blocks");
}
Expand Down Expand Up @@ -1579,7 +1582,7 @@ fn render_server_result(
// rows, so an old/partial server can never silently answer --hidden.
require_server_coverage(result)?;
require_ordered_filters(result, request)?;
require_replace_support(result, request)?;
require_render_support(result, request)?;

let empty_vec = Vec::new();
let matches = result
Expand Down Expand Up @@ -4007,7 +4010,7 @@ mod tests {
let params = &request["params"];
assert!(params.get("multiline_replace").is_none(), "{params}");
assert!(params.get("report_replacements").is_none(), "{params}");
assert!(require_replace_support(&serde_json::json!({}), &request).is_ok());
assert!(require_render_support(&serde_json::json!({}), &request).is_ok());
}

for opts in [
Expand Down Expand Up @@ -4099,20 +4102,19 @@ mod tests {
serde_json::json!({}),
serde_json::json!({"multiline_replace": false, "report_replacements": false}),
] {
assert!(require_replace_support(&result, &blocks).is_err());
assert!(require_replace_support(&result, &json).is_err());
assert!(require_render_support(&result, &blocks).is_err());
assert!(require_render_support(&result, &json).is_err());
}
assert!(
require_replace_support(&serde_json::json!({"multiline_replace": true}), &json)
.is_err()
require_render_support(&serde_json::json!({"multiline_replace": true}), &json).is_err()
);
assert!(
require_replace_support(&serde_json::json!({"report_replacements": true}), &blocks)
require_render_support(&serde_json::json!({"report_replacements": true}), &blocks)
.is_err()
);
let acked = serde_json::json!({"multiline_replace": true, "report_replacements": true});
assert!(require_replace_support(&acked, &blocks).is_ok());
assert!(require_replace_support(&acked, &json).is_ok());
assert!(require_render_support(&acked, &blocks).is_ok());
assert!(require_render_support(&acked, &json).is_ok());
}

#[test]
Expand Down
Loading
Loading