Debian Codegraph @

cli/src/commands/log.rs

raw
1 // Copyright 2020 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::cmp::min;
16
17 use clap_complete::ArgValueCandidates;
18 use clap_complete::ArgValueCompleter;
19 use futures::StreamExt as _;
20 use futures::TryStreamExt as _;
21 use futures::stream;
22 use futures::stream::LocalBoxStream;
23 use itertools::Itertools as _;
24 use jj_lib::backend::CommitId;
25 use jj_lib::commit::Commit;
26 use jj_lib::graph::GraphEdge;
27 use jj_lib::graph::GraphEdgeType;
28 use jj_lib::graph::TopoGroupedGraph;
29 use jj_lib::graph::reverse_graph;
30 use jj_lib::repo::Repo as _;
31 use jj_lib::revset::RevsetEvaluationError;
32 use jj_lib::revset::RevsetExpression;
33 use jj_lib::revset::RevsetFilterPredicate;
34 use jj_lib::revset::RevsetStreamExt as _;
35 use tracing::instrument;
36
37 use crate::cli_util::CommandHelper;
38 use crate::cli_util::LogContentFormat;
39 use crate::cli_util::RevisionArg;
40 use crate::cli_util::format_template;
41 use crate::command_error::CommandError;
42 use crate::complete;
43 use crate::diff_util::DiffFormatArgs;
44 use crate::formatter::FormatterExt as _;
45 use crate::graphlog::GraphStyle;
46 use crate::graphlog::get_graphlog;
47 use crate::templater::TemplateRenderer;
48 use crate::ui::Ui;
49
50 /// Show revision history
51 ///
52 /// Renders a graphical view of the project's history, ordered with children
53 /// before parents. By default, the output only includes mutable revisions,
54 /// along with some additional revisions for context. Use `jj log -r ::` to see
55 /// all revisions. See [`jj help -k revsets`] for information about the syntax.
56 ///
57 /// [`jj help -k revsets`]:
58 /// https://docs.jj-vcs.dev/latest/revsets/
59 ///
60 /// Spans of revisions that are not included in the graph per `--revisions` are
61 /// rendered as a synthetic node labeled "(elided revisions)".
62 ///
63 /// The working-copy commit is indicated by a `@` symbol in the graph.
64 /// [Immutable revisions] have a `◆` symbol. Other commits have a `○` symbol.
65 /// All of these symbols can be [customized].
66 ///
67 /// [Immutable revisions]:
68 /// https://docs.jj-vcs.dev/latest/config/#set-of-immutable-commits
69 ///
70 /// [customized]:
71 /// https://docs.jj-vcs.dev/latest/config/#node-style
72 #[derive(clap::Args, Clone, Debug)]
73 pub(crate) struct LogArgs {
74 /// Which revisions to show
75 ///
76 /// If no paths nor revisions are specified, this defaults to the
77 /// `revsets.log` setting.
78 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
79 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
80 revisions: Vec<RevisionArg>,
81
82 /// Show revisions modifying the given paths
83 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
84 #[arg(add = ArgValueCompleter::new(complete::log_files))]
85 paths: Vec<String>,
86
87 /// Limit number of revisions to show
88 ///
89 /// Applied after revisions are filtered and reordered topologically, but
90 /// before being reversed.
91 #[arg(long, short = 'n')]
92 limit: Option<usize>,
93
94 /// Show revisions in the opposite order (older revisions first)
95 #[arg(long)]
96 reversed: bool,
97
98 /// Show a flat list of revisions instead of a graph
99 #[arg(long, short = 'G')]
100 no_graph: bool,
101
102 /// Render each revision using the given template
103 ///
104 /// Run `jj log -T` to list the built-in templates.
105 ///
106 /// You can also specify arbitrary template expressions using the
107 /// [built-in keywords]. See [`jj help -k templates`] for more
108 /// information.
109 ///
110 /// If not specified, this defaults to the `templates.log` setting.
111 ///
112 /// [built-in keywords]:
113 /// https://docs.jj-vcs.dev/latest/templates/#commit-keywords
114 ///
115 /// [`jj help -k templates`]:
116 /// https://docs.jj-vcs.dev/latest/templates/
117 #[arg(long, short = 'T')]
118 #[arg(add = ArgValueCandidates::new(complete::template_aliases))]
119 template: Option<String>,
120
121 /// Show patch
122 #[arg(long, short = 'p')]
123 patch: bool,
124
125 /// Print the number of commits instead of showing them
126 #[arg(long, conflicts_with_all = ["DiffFormatArgs", "no_graph", "patch", "reversed", "template"])]
127 count: bool,
128
129 #[command(flatten)]
130 diff_format: DiffFormatArgs,
131 }
132
133 #[instrument(skip_all)]
134 pub(crate) async fn cmd_log(
135 ui: &mut Ui,
136 command: &CommandHelper,
137 args: &LogArgs,
138 ) -> Result<(), CommandError> {
139 let workspace_command = command.workspace_helper(ui).await?;
140 let settings = workspace_command.settings();
141
142 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
143 let revset_expression = {
144 // only use default revset if neither revset nor path are specified
145 let mut expression = if args.revisions.is_empty() && args.paths.is_empty() {
146 let revset_string = settings.get_string("revsets.log")?;
147 workspace_command.parse_revset(ui, &RevisionArg::from(revset_string))?
148 } else if !args.revisions.is_empty() {
149 workspace_command.parse_union_revsets(ui, &args.revisions)?
150 } else {
151 // a path was specified so we use all() and add path filter later
152 workspace_command.attach_revset_evaluator(RevsetExpression::all())
153 };
154 if !args.paths.is_empty() {
155 // Beware that args.paths = ["root:."] is not identical to []. The
156 // former will filter out empty commits.
157 let predicate = RevsetFilterPredicate::File(fileset_expression.clone());
158 expression.intersect_with(&RevsetExpression::filter(predicate));
159 }
160 expression
161 };
162
163 let revset = revset_expression.evaluate()?;
164
165 if args.count {
166 let (lower, upper) = revset.count_estimate()?;
167 let limit = args.limit.unwrap_or(usize::MAX);
168 let count = if limit <= lower {
169 limit
170 } else if upper == Some(lower) {
171 min(lower, limit)
172 } else {
173 revset
174 .stream()
175 .take(limit)
176 .try_fold(0, |count, _| async move { Ok(count + 1) })
177 .await?
178 };
179 let mut formatter = ui.stdout_formatter();
180 writeln!(formatter, "{count}")?;
181 return Ok(());
182 }
183
184 let repo = workspace_command.repo();
185 let matcher = fileset_expression.to_matcher();
186
187 let prio_revset = {
188 let text = settings.get_string("revsets.log-graph-prioritize")?;
189 let mut prio_revset = workspace_command.parse_revset(ui, &RevisionArg::from(text))?;
190 // Resolve the query within a separate scope so its visibility and
191 // referenced commits aren't affected by the prioritize expression:
192 // `<prio> & at_operation(@, <query>)`
193 let query_expr = revset_expression
194 .expression()
195 .within_visibility(repo.as_ref());
196 prio_revset.intersect_with(&query_expr);
197 prio_revset
198 };
199
200 let store = repo.store();
201 let diff_renderer = workspace_command.diff_renderer_for_log(&args.diff_format, args.patch)?;
202 let graph_style = GraphStyle::from_settings(settings)?;
203
204 let use_elided_nodes = settings.get_bool("ui.log-synthetic-elided-nodes")?;
205 let with_content_format = LogContentFormat::new(ui, settings)?;
206
207 let template: TemplateRenderer<Commit>;
208 let node_template: TemplateRenderer<Option<Commit>>;
209 {
210 let language = workspace_command.commit_template_language();
211 let template_string = match &args.template {
212 Some(value) => value.clone(),
213 None => settings.get_string("templates.log")?,
214 };
215 template = workspace_command
216 .parse_template(ui, &language, &template_string)?
217 .labeled(["log", "commit"]);
218 node_template = workspace_command
219 .parse_template(ui, &language, &settings.get_string("templates.log_node")?)?
220 .labeled(["log", "commit", "node"]);
221 }
222
223 let mut unmatched_explicit_paths = fileset_expression.explicit_paths().collect_vec();
224 let mut update_unmatched_explicit_paths = async |commit: &Commit| -> Result<(), CommandError> {
225 if unmatched_explicit_paths.is_empty() {
226 return Ok(());
227 }
228 let tree = &commit.tree();
229 unmatched_explicit_paths = stream::iter(unmatched_explicit_paths.iter().copied())
230 .filter_map(|path| async move {
231 tree.path_value(path)
232 .await
233 .map(|value| value.is_absent().then_some(path))
234 .transpose()
235 })
236 .try_collect()
237 .await?;
238 Ok(())
239 };
240
241 {
242 ui.request_pager();
243 let mut formatter = ui.stdout_formatter();
244 let formatter = formatter.as_mut();
245
246 if !args.no_graph {
247 let mut raw_output = formatter.raw()?;
248 let mut graph = get_graphlog(graph_style, raw_output.as_mut());
249 let mut stream: LocalBoxStream<_> = {
250 let mut topo_order = TopoGroupedGraph::new(revset.stream_graph(), |id| id);
251
252 let mut prio_stream = prio_revset.evaluate_to_commit_ids()?;
253 while let Some(prio) = prio_stream.try_next().await? {
254 topo_order.prioritize_branch(prio);
255 }
256 let forward_stream = topo_order.stream();
257
258 // The input to TopoGroupedGraph shouldn't be truncated because the prioritized
259 // commit must exist in the input set.
260 let forward_stream = forward_stream.take(args.limit.unwrap_or(usize::MAX));
261 if args.reversed {
262 let nodes: Vec<_> = forward_stream.collect().await;
263 let nodes = reverse_graph(nodes.into_iter(), |id: &CommitId| id)?;
264 stream::iter(nodes.into_iter().map(Ok)).boxed_local()
265 } else {
266 forward_stream.boxed_local()
267 }
268 };
269 while let Some((commit_id, edges)) = stream.try_next().await? {
270 // The graph is keyed by (CommitId, is_synthetic)
271 let mut graphlog_edges = vec![];
272 // TODO: Should we update revset.stream_graph() to yield a `has_missing` flag
273 // instead of all the missing edges since we don't care about
274 // where they point here anyway?
275 let mut missing_edge_id = None;
276 let mut elided_targets = vec![];
277 for edge in edges {
278 match edge.edge_type {
279 GraphEdgeType::Missing => {
280 missing_edge_id = Some(edge.target);
281 }
282 GraphEdgeType::Direct => {
283 graphlog_edges.push(GraphEdge::direct((edge.target, false)));
284 }
285 GraphEdgeType::Indirect => {
286 if use_elided_nodes {
287 elided_targets.push(edge.target.clone());
288 graphlog_edges.push(GraphEdge::direct((edge.target, true)));
289 } else {
290 graphlog_edges.push(GraphEdge::indirect((edge.target, false)));
291 }
292 }
293 }
294 }
295 if let Some(missing_edge_id) = missing_edge_id {
296 graphlog_edges.push(GraphEdge::missing((missing_edge_id, false)));
297 }
298 let mut buffer = vec![];
299 let key = (commit_id, false);
300 let commit = store.get_commit_async(&key.0).await?;
301 update_unmatched_explicit_paths(&commit).await?;
302 let within_graph =
303 with_content_format.sub_width(graph.width(&key, &graphlog_edges));
304 within_graph
305 .write(ui.new_formatter(&mut buffer).as_mut(), async |formatter| {
306 template.format(&commit, formatter)
307 })
308 .await?;
309 if let Some(renderer) = &diff_renderer {
310 let mut formatter = ui.new_formatter(&mut buffer);
311 renderer
312 .show_patch(
313 ui,
314 formatter.as_mut(),
315 &commit,
316 matcher.as_ref(),
317 within_graph.width(),
318 )
319 .await?;
320 }
321
322 let commit = Some(commit);
323 let node_symbol = format_template(ui, &commit, &node_template);
324 graph.add_node(
325 &key,
326 &graphlog_edges,
327 &node_symbol,
328 &String::from_utf8_lossy(&buffer),
329 )?;
330
331 for elided_target in elided_targets {
332 let elided_key = (elided_target, true);
333 let real_key = (elided_key.0.clone(), false);
334 let edges = [GraphEdge::direct(real_key)];
335 let mut buffer = vec![];
336 let within_graph =
337 with_content_format.sub_width(graph.width(&elided_key, &edges));
338 within_graph
339 .write(ui.new_formatter(&mut buffer).as_mut(), async |formatter| {
340 writeln!(formatter.labeled("elided"), "(elided revisions)")
341 })
342 .await?;
343 let node_symbol = format_template(ui, &None, &node_template);
344 graph.add_node(
345 &elided_key,
346 &edges,
347 &node_symbol,
348 &String::from_utf8_lossy(&buffer),
349 )?;
350 }
351 }
352 } else {
353 let id_stream: LocalBoxStream<Result<CommitId, RevsetEvaluationError>> = {
354 let forward_stream = revset.stream().take(args.limit.unwrap_or(usize::MAX));
355 if args.reversed {
356 let entries: Vec<_> = forward_stream.try_collect().await?;
357 stream::iter(entries.into_iter().rev().map(Ok)).boxed_local()
358 } else {
359 forward_stream.boxed_local()
360 }
361 };
362 let mut commit_stream = id_stream.commits(store);
363 while let Some(commit) = commit_stream.try_next().await? {
364 update_unmatched_explicit_paths(&commit).await?;
365 with_content_format
366 .write(formatter, async |formatter| {
367 template.format(&commit, formatter)
368 })
369 .await?;
370 if let Some(renderer) = &diff_renderer {
371 let width = ui.term_width();
372 renderer
373 .show_patch(ui, formatter, &commit, matcher.as_ref(), width)
374 .await?;
375 }
376 }
377 }
378
379 if !unmatched_explicit_paths.is_empty() {
380 let ui_paths = unmatched_explicit_paths
381 .iter()
382 .map(|&path| workspace_command.format_file_path(path))
383 .join(", ");
384 writeln!(
385 ui.warning_default(),
386 "No matching entries for paths: {ui_paths}"
387 )?;
388 }
389 }
390
391 // Check to see if the user might have specified a path when they intended
392 // to specify a revset.
393 if let ([], [only_path]) = (args.revisions.as_slice(), args.paths.as_slice()) {
394 if only_path == "." && workspace_command.parse_file_path(only_path)?.is_root() {
395 // For users of e.g. Mercurial, where `.` indicates the current commit.
396 writeln!(
397 ui.warning_default(),
398 "The argument {only_path:?} is being interpreted as a fileset expression, but \
399 this is often not useful because all non-empty commits touch '.'. If you meant \
400 to show the working copy commit, pass -r '@' instead."
401 )?;
402 } else if revset.is_empty()?
403 && workspace_command
404 .parse_revset(ui, &RevisionArg::from(only_path.to_owned()))
405 .is_ok()
406 {
407 writeln!(
408 ui.warning_default(),
409 "The argument {only_path:?} is being interpreted as a fileset expression. To \
410 specify a revset, pass -r {only_path:?} instead."
411 )?;
412 }
413 }
414
415 Ok(())
416 }