Debian Codegraph @

cli/src/commands/file/search.rs

raw
1 // Copyright 2025 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::io;
16 use std::io::Write as _;
17
18 use clap_complete::ArgValueCompleter;
19 use jj_lib::conflicts::MaterializedTreeValue;
20 use jj_lib::conflicts::materialize_tree_value;
21 use jj_lib::repo::Repo as _;
22 use jj_lib::str_util::StringMatcher;
23 use jj_lib::str_util::StringPattern;
24 use tracing::instrument;
25
26 use crate::cli_util::CommandHelper;
27 use crate::cli_util::RevisionArg;
28 use crate::cli_util::print_unmatched_explicit_paths;
29 use crate::command_error::CommandError;
30 use crate::command_error::cli_error;
31 use crate::complete;
32 use crate::formatter::Formatter;
33 use crate::ui::Ui;
34
35 /// Search for content in files
36 ///
37 /// Prints each line that matches the specified pattern, prefixed by the file
38 /// path. Use `--name-only` to print only the file paths.
39 ///
40 /// This is an early version of the command. It does not search files
41 /// concurrently.
42 #[derive(clap::Args, Clone, Debug)]
43 pub(crate) struct FileSearchArgs {
44 /// The revision to search files in
45 #[arg(long, short, default_value = "@", value_name = "REVSET")]
46 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
47 revision: RevisionArg,
48
49 /// The pattern to search for in a single line
50 ///
51 /// It is a [string pattern syntax] like `kind:pattern`. The kind
52 /// defaults to regex when omitted.
53 ///
54 /// If it is a glob pattern, the whole line must match the pattern,
55 /// so you may want to pass something like `--pattern 'glob:*foo*'`.
56 ///
57 /// [string pattern syntax]:
58 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
59 #[arg(long, short, value_name = "PATTERN")]
60 pattern: String,
61
62 /// Print only the paths of files that contain a match, not the matched
63 /// lines
64 #[arg(long, conflicts_with = "line_number")]
65 name_only: bool,
66
67 /// Prefix each matched line with its 1-based line number within the file
68 #[arg(long, short = 'n')]
69 line_number: bool,
70
71 /// Only search files matching these prefixes (instead of all files)
72 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
73 #[arg(add = ArgValueCompleter::new(complete::all_revision_files))]
74 paths: Vec<String>,
75 }
76
77 #[instrument(skip_all)]
78 pub(crate) async fn cmd_file_search(
79 ui: &mut Ui,
80 command: &CommandHelper,
81 args: &FileSearchArgs,
82 ) -> Result<(), CommandError> {
83 let workspace_command = command.workspace_helper(ui).await?;
84 let commit = workspace_command
85 .resolve_single_rev(ui, &args.revision)
86 .await?;
87 let tree = commit.tree();
88 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
89 let file_matcher = fileset_expression.to_matcher();
90
91 ui.request_pager();
92 let mut formatter = ui.stdout_formatter();
93 let store = workspace_command.repo().store().clone();
94
95 let pattern = if let Some((kind, pattern)) = args.pattern.split_once(':') {
96 StringPattern::from_str_kind(pattern, kind)
97 } else {
98 StringPattern::from_str_kind(args.pattern.as_str(), "regex")
99 }
100 .map_err(cli_error)?;
101 let pattern_matcher = pattern.to_matcher();
102 // TODO: Read files concurrently (depending on backend)
103 for (path, value) in tree.entries_matching(file_matcher.as_ref()) {
104 let value = value?;
105 let materialized =
106 materialize_tree_value(store.as_ref(), &path, value, tree.labels()).await?;
107 match materialized {
108 MaterializedTreeValue::Absent => panic!("Entry for absent path in file listing"),
109 MaterializedTreeValue::AccessDenied(error) => {
110 let ui_path = workspace_command.format_file_path(&path);
111 writeln!(
112 ui.warning_default(),
113 "Skipping '{ui_path}' due to permission error: {error}"
114 )?;
115 }
116 MaterializedTreeValue::File(mut materialized_file_value) => {
117 let content = materialized_file_value.read_all(&path).await?;
118 // TODO: Make output templated
119 let ui_path = workspace_command.format_file_path(&path);
120 if args.name_only {
121 if pattern_matcher.match_lines(&content).next().is_some() {
122 writeln!(formatter, "{ui_path}")?;
123 }
124 } else {
125 write_matches(
126 formatter.as_mut(),
127 &ui_path,
128 &content,
129 &pattern_matcher,
130 args.line_number,
131 )?;
132 }
133 }
134 MaterializedTreeValue::Symlink { .. } => {}
135 MaterializedTreeValue::FileConflict(materialized_file_value) => {
136 let ui_path = workspace_command.format_file_path(&path);
137 // TODO: Optionally also print the conflict side
138 let mut adds = materialized_file_value.contents.adds();
139 if args.name_only {
140 // Multiple blobs per file; print the path if any blob
141 // matches.
142 if adds.any(|c| pattern_matcher.match_lines(c).next().is_some()) {
143 writeln!(formatter, "{ui_path}")?;
144 }
145 } else {
146 // -n numbers lines within each side independently; there
147 // is no meaningful unified line numbering across sides.
148 for content in adds {
149 write_matches(
150 formatter.as_mut(),
151 &ui_path,
152 content,
153 &pattern_matcher,
154 args.line_number,
155 )?;
156 }
157 }
158 }
159 MaterializedTreeValue::OtherConflict { .. } => {}
160 MaterializedTreeValue::GitSubmodule(_) => {}
161 MaterializedTreeValue::Tree(_) => panic!("Entry for tree in file listing"),
162 }
163 }
164 print_unmatched_explicit_paths(ui, &workspace_command, &fileset_expression, [&tree]).await?;
165 Ok(())
166 }
167
168 fn write_matches(
169 formatter: &mut dyn Formatter,
170 ui_path: &str,
171 content: &[u8],
172 matcher: &StringMatcher,
173 line_number: bool,
174 ) -> io::Result<()> {
175 let matches = content
176 .split_inclusive(|b| *b == b'\n')
177 .enumerate()
178 .filter_map(|(i, line)| {
179 let stripped = line.strip_suffix(b"\n").unwrap_or(line);
180 matcher.is_match_bytes(stripped).then_some((i + 1, line))
181 });
182 for (line_no, line) in matches {
183 if line_number {
184 write!(formatter, "{ui_path}:{line_no}:")?;
185 } else {
186 write!(formatter, "{ui_path}:")?;
187 }
188 formatter.write_all(line)?;
189 if !line.ends_with(b"\n") {
190 writeln!(formatter)?;
191 }
192 }
193 Ok(())
194 }