Debian Codegraph @

cli/src/commands/evolog.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 clap_complete::ArgValueCandidates;
16 use clap_complete::ArgValueCompleter;
17 use futures::Stream;
18 use futures::StreamExt as _;
19 use futures::TryStreamExt as _;
20 use futures::stream;
21 use futures::stream::LocalBoxStream;
22 use itertools::Itertools as _;
23 use jj_lib::commit::Commit;
24 use jj_lib::evolution::CommitEvolutionEntry;
25 use jj_lib::evolution::walk_predecessors;
26 use jj_lib::graph::GraphEdge;
27 use jj_lib::graph::TopoGroupedGraph;
28 use jj_lib::graph::reverse_graph;
29 use jj_lib::matchers::EverythingMatcher;
30 use tracing::instrument;
31
32 use crate::cli_util::CommandHelper;
33 use crate::cli_util::LogContentFormat;
34 use crate::cli_util::RevisionArg;
35 use crate::cli_util::format_template;
36 use crate::command_error::CommandError;
37 use crate::complete;
38 use crate::diff_util::DiffFormatArgs;
39 use crate::graphlog::GraphStyle;
40 use crate::graphlog::get_graphlog;
41 use crate::templater::TemplateRenderer;
42 use crate::ui::Ui;
43
44 /// Show how a change has evolved over time
45 ///
46 /// Lists the previous commits which a change has pointed to. The current commit
47 /// of a change evolves when the change is updated, rebased, etc.
48 #[derive(clap::Args, Clone, Debug)]
49 pub(crate) struct EvologArgs {
50 /// Follow changes from these revisions
51 #[arg(
52 long,
53 short,
54 default_value = "@",
55 value_name = "REVSETS",
56 alias = "revision"
57 )]
58 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
59 revisions: Vec<RevisionArg>,
60
61 /// Limit number of revisions to show
62 ///
63 /// Applied after revisions are reordered topologically, but before being
64 /// reversed.
65 #[arg(long, short = 'n')]
66 limit: Option<usize>,
67
68 /// Show revisions in the opposite order (older revisions first)
69 #[arg(long)]
70 reversed: bool,
71
72 /// Show a flat list of revisions instead of a graph
73 #[arg(long, short = 'G')]
74 no_graph: bool,
75
76 /// Render each revision using the given template
77 ///
78 /// All 0-argument methods of the [`CommitEvolutionEntry` type] are
79 /// available as keywords in the template expression. See [`jj help -k
80 /// templates`] for more information.
81 ///
82 /// If not specified, this defaults to the `templates.evolog` setting.
83 ///
84 /// [`CommitEvolutionEntry` type]:
85 /// https://docs.jj-vcs.dev/latest/templates/#commitevolutionentry-type
86 ///
87 /// [`jj help -k templates`]:
88 /// https://docs.jj-vcs.dev/latest/templates/
89 #[arg(long, short = 'T')]
90 #[arg(add = ArgValueCandidates::new(complete::template_aliases))]
91 template: Option<String>,
92
93 /// Show patch compared to the previous version of this change
94 ///
95 /// If the previous version has different parents, it will be temporarily
96 /// rebased to the parents of the new version, so the diff is not
97 /// contaminated by unrelated changes.
98 #[arg(long, short = 'p')]
99 patch: bool,
100
101 #[command(flatten)]
102 diff_format: DiffFormatArgs,
103 }
104
105 #[instrument(skip_all)]
106 pub(crate) async fn cmd_evolog(
107 ui: &mut Ui,
108 command: &CommandHelper,
109 args: &EvologArgs,
110 ) -> Result<(), CommandError> {
111 let workspace_command = command.workspace_helper(ui).await?;
112
113 let start_commit_ids: Vec<_> = workspace_command
114 .parse_union_revsets(ui, &args.revisions)?
115 .evaluate_to_commit_ids()?
116 .try_collect()
117 .await?;
118
119 let diff_renderer = workspace_command.diff_renderer_for_log(&args.diff_format, args.patch)?;
120 let graph_style = GraphStyle::from_settings(workspace_command.settings())?;
121 let with_content_format = LogContentFormat::new(ui, workspace_command.settings())?;
122
123 let template: TemplateRenderer<CommitEvolutionEntry>;
124 let node_template: TemplateRenderer<Option<Commit>>;
125 {
126 let language = workspace_command.commit_template_language();
127 let template_string = match &args.template {
128 Some(value) => value.clone(),
129 None => workspace_command.settings().get("templates.evolog")?,
130 };
131 template = workspace_command
132 .parse_template(ui, &language, &template_string)?
133 .labeled(["evolog"]); // TODO: add label for the context type?
134 node_template = workspace_command
135 .parse_template(
136 ui,
137 &language,
138 // TODO: should we add templates.evolog_node?
139 &workspace_command
140 .settings()
141 .get_string("templates.log_node")?,
142 )?
143 .labeled(["evolog", "commit", "node"]);
144 }
145
146 ui.request_pager();
147 let mut formatter = ui.stdout_formatter();
148 let formatter = formatter.as_mut();
149
150 let repo = workspace_command.repo();
151 let evolution_entries = walk_predecessors(repo, &start_commit_ids).boxed_local();
152 if !args.no_graph {
153 let mut raw_output = formatter.raw()?;
154 let mut graph = get_graphlog(graph_style, raw_output.as_mut());
155
156 let evolution_nodes = evolution_entries.map_ok(|entry| {
157 let ids = entry.predecessor_ids();
158 let edges = ids.iter().cloned().map(GraphEdge::direct).collect_vec();
159 (entry, edges)
160 });
161 // TopoGroupedGraph also helps emit squashed commits in reverse
162 // chronological order. Predecessors don't need to follow any defined
163 // order. However in practice, if there are multiple predecessors, then
164 // usually the first predecessor is the previous version of the same
165 // change, and the other predecessors are commits that were squashed
166 // into it. If multiple commits are squashed at once, then they are
167 // usually recorded in chronological order. We want to show squashed
168 // commits in reverse chronological order, and we also want to show
169 // squashed commits before the squash destination (since the
170 // destination's subgraph may contain earlier squashed commits as well.
171 let evolution_nodes =
172 TopoGroupedGraph::new(evolution_nodes, |node| node.commit.id()).stream();
173
174 let evolution_nodes = evolution_nodes.take(args.limit.unwrap_or(usize::MAX));
175 let mut evolution_nodes: LocalBoxStream<_> = if args.reversed {
176 let nodes: Vec<_> = evolution_nodes.collect().await;
177 let nodes = reverse_graph(nodes.into_iter(), |entry| entry.commit.id())?;
178 stream::iter(nodes.into_iter().map(Ok)).boxed_local()
179 } else {
180 evolution_nodes.boxed_local()
181 };
182
183 while let Some((entry, edges)) = evolution_nodes.try_next().await? {
184 let mut buffer = vec![];
185 let within_graph =
186 with_content_format.sub_width(graph.width(entry.commit.id(), &edges));
187 within_graph
188 .write(ui.new_formatter(&mut buffer).as_mut(), async |formatter| {
189 template.format(&entry, formatter)
190 })
191 .await?;
192 if let Some(renderer) = &diff_renderer {
193 let predecessors = entry.predecessors().await?;
194 let mut formatter = ui.new_formatter(&mut buffer);
195 renderer
196 .show_inter_diff(
197 ui,
198 formatter.as_mut(),
199 &predecessors,
200 &entry.commit,
201 &EverythingMatcher,
202 within_graph.width(),
203 )
204 .await?;
205 }
206 let node_symbol = format_template(ui, &Some(entry.commit.clone()), &node_template);
207 graph.add_node(
208 entry.commit.id(),
209 &edges,
210 &node_symbol,
211 &String::from_utf8_lossy(&buffer),
212 )?;
213 }
214 } else {
215 let evolution_entries = evolution_entries.take(args.limit.unwrap_or(usize::MAX));
216 let mut evolution_entries: Box<dyn Stream<Item = _> + Unpin> = if args.reversed {
217 let entries: Vec<_> = evolution_entries.try_collect().await?;
218 Box::new(stream::iter(entries.into_iter().rev().map(Ok)))
219 } else {
220 Box::new(evolution_entries)
221 };
222
223 while let Some(entry) = evolution_entries.try_next().await? {
224 with_content_format
225 .write(formatter, async |formatter| {
226 template.format(&entry, formatter)
227 })
228 .await?;
229 if let Some(renderer) = &diff_renderer {
230 let predecessors = entry.predecessors().await?;
231 let width = ui.term_width();
232 renderer
233 .show_inter_diff(
234 ui,
235 formatter,
236 &predecessors,
237 &entry.commit,
238 &EverythingMatcher,
239 width,
240 )
241 .await?;
242 }
243 }
244 }
245
246 Ok(())
247 }