Debian Codegraph @

cli/src/commands/status.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::collections::BTreeMap;
16
17 use futures::TryStreamExt as _;
18 use itertools::Itertools as _;
19 use jj_lib::commit::Commit;
20 use jj_lib::copies::CopyRecords;
21 use jj_lib::matchers::Matcher;
22 use jj_lib::merge::Diff;
23 use jj_lib::merged_tree::MergedTree;
24 use jj_lib::repo::Repo;
25 use jj_lib::repo_path::RepoPath;
26 use jj_lib::repo_path::RepoPathBuf;
27 use jj_lib::revset::RevsetExpression;
28 use jj_lib::revset::RevsetFilterPredicate;
29 use jj_lib::tree::TreeMergeExt as _;
30 use jj_lib::working_copy::SnapshotStats;
31 use jj_lib::working_copy::UntrackedReason;
32 use tracing::instrument;
33
34 use crate::cli_util::CommandHelper;
35 use crate::cli_util::print_conflicted_paths;
36 use crate::cli_util::print_snapshot_stats;
37 use crate::cli_util::print_unmatched_explicit_paths;
38 use crate::command_error::CommandError;
39 use crate::diff_util::DiffFormat;
40 use crate::diff_util::get_copy_records;
41 use crate::formatter::FormatterExt as _;
42 use crate::ui::Ui;
43
44 /// Show high-level repo status [default alias: st]
45 ///
46 /// This includes:
47 ///
48 /// * The working copy commit and its parents, and a summary of the changes in
49 /// the working copy (compared to the merged parents)
50 ///
51 /// * Conflicts in the working copy
52 ///
53 /// * [Conflicted bookmarks]
54 ///
55 /// Note: You can use `jj diff --summary -r <rev>` to see the changed files for
56 /// a specific revision.
57 ///
58 /// [Conflicted bookmarks]:
59 /// https://docs.jj-vcs.dev/latest/bookmarks/#conflicts
60 #[derive(clap::Args, Clone, Debug)]
61 pub(crate) struct StatusArgs {
62 /// Restrict the status display to these paths
63 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
64 paths: Vec<String>,
65 }
66
67 #[instrument(skip_all)]
68 pub(crate) async fn cmd_status(
69 ui: &mut Ui,
70 command: &CommandHelper,
71 args: &StatusArgs,
72 ) -> Result<(), CommandError> {
73 let (workspace_command, snapshot_stats, _) = command.workspace_helper_with_stats(ui).await?;
74 print_snapshot_stats(
75 ui,
76 &snapshot_stats,
77 workspace_command.env().path_converter(),
78 )?;
79 let repo = workspace_command.repo();
80 let maybe_wc_commit = workspace_command
81 .get_wc_commit_id()
82 .map(|id| repo.store().get_commit(id))
83 .transpose()?;
84 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
85 let matcher = fileset_expression.to_matcher();
86 ui.request_pager();
87 let mut formatter = ui.stdout_formatter();
88 let formatter = formatter.as_mut();
89
90 if let Some(wc_commit) = &maybe_wc_commit {
91 let status = collect_working_copy_status(repo.as_ref(), wc_commit, snapshot_stats).await?;
92 print_unmatched_explicit_paths(ui, &workspace_command, &fileset_expression, [&status.tree])
93 .await?;
94
95 if !status.has_any_tracked_changes() && !status.has_any_untracked_paths() {
96 writeln!(formatter, "The working copy has no changes.")?;
97 } else {
98 if status.has_any_tracked_changes() {
99 let mut copy_records = CopyRecords::default();
100 for parent in &status.parents {
101 let records =
102 get_copy_records(repo.store(), parent.id(), status.commit.id(), &matcher)
103 .await?;
104 copy_records.add_records(records);
105 }
106 let diff_renderer = workspace_command.diff_renderer(vec![DiffFormat::Summary]);
107 let width = ui.term_width();
108 let mut diff_output = vec![];
109 diff_renderer
110 .show_diff(
111 ui,
112 ui.new_formatter(&mut diff_output).as_mut(),
113 Diff::new(&status.parent_tree, &status.tree),
114 &matcher,
115 &copy_records,
116 width,
117 )
118 .await?;
119 if !diff_output.is_empty() {
120 writeln!(formatter, "Working copy changes:")?;
121 formatter.raw()?.write_all(&diff_output)?;
122 }
123 }
124
125 let mut matching_untracked_paths = status.untracked_paths_matching(&matcher).peekable();
126 if matching_untracked_paths.peek().is_some() {
127 writeln!(formatter, "Untracked paths:")?;
128 visit_collapsed_untracked_files(
129 matching_untracked_paths,
130 status.tree.clone(),
131 |path, is_dir| {
132 let ui_path = workspace_command.path_converter().format_file_path(path);
133 writeln!(
134 formatter.labeled("diff").labeled("untracked"),
135 "? {ui_path}{}",
136 if is_dir {
137 std::path::MAIN_SEPARATOR_STR
138 } else {
139 ""
140 }
141 )?;
142 Ok(())
143 },
144 )
145 .await?;
146 }
147 }
148
149 let template = workspace_command.commit_summary_template();
150 write!(formatter, "Working copy (@) : ")?;
151 template.format(&status.commit, formatter)?;
152 writeln!(formatter)?;
153 for parent in &status.parents {
154 // "Working copy (@) : "
155 write!(formatter, "Parent commit (@-): ")?;
156 template.format(parent, formatter)?;
157 writeln!(formatter)?;
158 }
159
160 if status.commit.has_conflict() {
161 let conflicts = status.tree.conflicts_matching(&matcher).collect_vec();
162 writeln!(
163 formatter.labeled("warning").with_heading("Warning: "),
164 "There are unresolved conflicts at these paths:"
165 )?;
166 print_conflicted_paths(conflicts, formatter, &workspace_command)?;
167
168 let wc_revset = RevsetExpression::commit(status.commit.id().clone());
169
170 // Ancestors with conflicts, excluding the current working copy commit.
171 let ancestors_conflicts: Vec<_> = workspace_command
172 .attach_revset_evaluator(
173 wc_revset
174 .parents()
175 .ancestors()
176 .filtered(RevsetFilterPredicate::HasConflict)
177 .minus(&workspace_command.env().immutable_expression()),
178 )
179 .evaluate_to_commit_ids()?
180 .try_collect()
181 .await?;
182
183 workspace_command
184 .report_repo_conflicts(formatter, repo, ancestors_conflicts)
185 .await?;
186 } else {
187 for parent in &status.parents {
188 if parent.has_conflict() {
189 writeln!(
190 formatter.labeled("hint").with_heading("Hint: "),
191 "Conflict in parent commit has been resolved in working copy."
192 )?;
193 break;
194 }
195 }
196 }
197 } else {
198 writeln!(formatter, "No working copy.")?;
199 }
200
201 let conflicted_local_bookmarks = repo
202 .view()
203 .local_bookmarks()
204 .filter(|(_, target)| target.has_conflict())
205 .map(|(bookmark_name, _)| bookmark_name)
206 .collect_vec();
207 let conflicted_remote_bookmarks = repo
208 .view()
209 .all_remote_bookmarks()
210 .filter(|(_, remote_ref)| remote_ref.target.has_conflict())
211 .map(|(symbol, _)| symbol)
212 .collect_vec();
213 if !conflicted_local_bookmarks.is_empty() {
214 writeln!(
215 formatter.labeled("warning").with_heading("Warning: "),
216 "These bookmarks have conflicts:"
217 )?;
218 for name in conflicted_local_bookmarks {
219 write!(formatter, " ")?;
220 write!(formatter.labeled("bookmark"), "{}", name.as_symbol())?;
221 writeln!(formatter)?;
222 }
223 writeln!(
224 formatter.labeled("hint").with_heading("Hint: "),
225 "Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to \
226 resolve."
227 )?;
228 }
229 if !conflicted_remote_bookmarks.is_empty() {
230 writeln!(
231 formatter.labeled("warning").with_heading("Warning: "),
232 "These remote bookmarks have conflicts:"
233 )?;
234 for symbol in conflicted_remote_bookmarks {
235 write!(formatter, " ")?;
236 write!(formatter.labeled("bookmark"), "{symbol}")?;
237 writeln!(formatter)?;
238 }
239 writeln!(
240 formatter.labeled("hint").with_heading("Hint: "),
241 "Use `jj bookmark list` to see details. Resolve by fetching an updated bookmark from \
242 the remote."
243 )?;
244 }
245
246 Ok(())
247 }
248
249 struct WorkingCopyStatus {
250 commit: Commit,
251 parents: Vec<Commit>,
252 parent_tree: MergedTree,
253 tree: MergedTree,
254 untracked_paths: BTreeMap<RepoPathBuf, UntrackedReason>,
255 }
256
257 impl WorkingCopyStatus {
258 fn has_any_tracked_changes(&self) -> bool {
259 self.tree.tree_ids() != self.parent_tree.tree_ids()
260 }
261
262 fn has_any_untracked_paths(&self) -> bool {
263 !self.untracked_paths.is_empty()
264 }
265
266 fn untracked_paths_matching(&self, matcher: &dyn Matcher) -> impl Iterator<Item = &RepoPath> {
267 self.untracked_paths
268 .keys()
269 .filter(|path| matcher.matches(path))
270 .map(|path| path.as_ref())
271 }
272 }
273
274 async fn collect_working_copy_status(
275 repo: &dyn Repo,
276 commit: &Commit,
277 snapshot_stats: SnapshotStats,
278 ) -> Result<WorkingCopyStatus, CommandError> {
279 let commit = commit.clone();
280 let parents = commit.parents().await?;
281 let parent_tree = commit.parent_tree(repo).await?;
282 let tree = commit.tree();
283 let untracked_paths = snapshot_stats.untracked_paths;
284
285 Ok(WorkingCopyStatus {
286 commit,
287 parents,
288 parent_tree,
289 tree,
290 untracked_paths,
291 })
292 }
293
294 async fn visit_collapsed_untracked_files(
295 untracked_paths: impl IntoIterator<Item = impl AsRef<RepoPath>>,
296 tree: MergedTree,
297 mut on_path: impl FnMut(&RepoPath, bool) -> Result<(), CommandError>,
298 ) -> Result<(), CommandError> {
299 let trees = tree.trees().await?;
300 let mut stack = vec![trees];
301
302 // TODO: This loop can be improved with BTreeMap cursors once that's stable,
303 // would remove the need for the whole `skip_prefixed_by` thing and turn it
304 // into a B-tree lookup.
305 let mut skip_prefixed_by_dir: Option<RepoPathBuf> = None;
306 'untracked: for path in untracked_paths {
307 let path = path.as_ref();
308 if skip_prefixed_by_dir
309 .as_ref()
310 .is_some_and(|p| path.starts_with(p))
311 {
312 continue;
313 } else {
314 skip_prefixed_by_dir = None;
315 }
316
317 let mut it = path.components().dropping_back(1);
318 let first_mismatch = it.by_ref().enumerate().find(|(i, component)| {
319 stack.get(i + 1).is_none_or(|tree| {
320 tree.dir()
321 .components()
322 .next_back()
323 .expect("should always have at least one element (the root)")
324 != *component
325 })
326 });
327
328 if let Some((i, component)) = first_mismatch {
329 stack.truncate(i + 1);
330 for component in std::iter::once(component).chain(it) {
331 let parent = stack
332 .last()
333 .expect("should always have at least one element (the root)");
334
335 if let Some(subtree) = parent.sub_tree(component).await? {
336 stack.push(subtree);
337 } else {
338 let dir = parent.dir().join(component);
339
340 on_path(&dir, true)?;
341 skip_prefixed_by_dir = Some(dir);
342
343 continue 'untracked;
344 }
345 }
346 }
347
348 on_path(path, false)?;
349 }
350
351 Ok(())
352 }
353
354 #[cfg(test)]
355 mod test {
356 use pollster::FutureExt as _;
357 use testutils::TestRepo;
358 use testutils::TestTreeBuilder;
359 use testutils::repo_path;
360
361 use super::*;
362
363 fn collect_collapsed_untracked_files_string(
364 untracked_paths: &[&RepoPath],
365 tree: MergedTree,
366 ) -> String {
367 let mut result = String::new();
368 visit_collapsed_untracked_files(untracked_paths, tree, |path, is_dir| {
369 result.push_str("? ");
370 if is_dir {
371 result.push_str(&path.to_internal_dir_string());
372 } else {
373 result.push_str(path.as_internal_file_string());
374 }
375 result.push('\n');
376 Ok(())
377 })
378 .block_on()
379 .unwrap();
380 result
381 }
382
383 #[test]
384 fn test_collapsed_untracked_files() {
385 let repo = TestRepo::init();
386
387 let tracked = {
388 let mut builder = TestTreeBuilder::new(repo.repo.store().clone());
389
390 builder.file(repo_path("top_level_file"), "");
391 // ? "untracked_top_level_file"
392 // ? "dir"
393 // ? "dir2/c"
394 builder.file(repo_path("dir2/d"), "");
395 // ? "dir3/partially_tracked/e"
396 builder.file(repo_path("dir3/partially_tracked/f"), "");
397 // ? "dir3/fully_untracked/"
398 builder.file(repo_path("dir3/j"), "");
399 // ? "dir3/k"
400
401 builder.write_merged_tree()
402 };
403 let untracked = &[
404 repo_path("untracked_top_level_file"),
405 repo_path("dir/a"),
406 repo_path("dir/b"),
407 repo_path("dir2/c"),
408 repo_path("dir3/partially_tracked/e"),
409 repo_path("dir3/fully_untracked/g"),
410 repo_path("dir3/fully_untracked/h"),
411 repo_path("dir3/k"),
412 ];
413
414 insta::assert_snapshot!(
415 collect_collapsed_untracked_files_string(untracked, tracked),
416 @"
417 ? untracked_top_level_file
418 ? dir/
419 ? dir2/c
420 ? dir3/partially_tracked/e
421 ? dir3/fully_untracked/
422 ? dir3/k
423 "
424 );
425 }
426 }