Debian Codegraph @

cli/src/commands/bookmark/track.rs

raw
1 // Copyright 2020-2023 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::HashMap;
16 use std::rc::Rc;
17
18 use clap_complete::ArgValueCandidates;
19 use itertools::Itertools as _;
20 use jj_lib::repo::Repo as _;
21 use jj_lib::str_util::StringExpression;
22
23 use super::resolve_trackable_remote_bookmarks;
24 use super::trackable_remote_bookmarks_matching;
25 use super::warn_unmatched_local_or_remote_bookmarks;
26 use super::warn_unmatched_remotes;
27 use crate::cli_util::CommandHelper;
28 use crate::cli_util::default_ignored_remote_name;
29 use crate::command_error::CommandError;
30 use crate::command_error::cli_error;
31 use crate::commit_templater::CommitRef;
32 use crate::complete;
33 use crate::revset_util::parse_name_patterns_or_remote_symbols;
34 use crate::revset_util::parse_union_name_patterns;
35 use crate::templater::TemplateRenderer;
36 use crate::ui::Ui;
37
38 /// Start tracking given remote bookmarks
39 ///
40 /// A tracked remote bookmark will be imported as a local bookmark of the same
41 /// name. Changes to it will propagate to the existing local bookmark on future
42 /// pulls.
43 #[derive(clap::Args, Clone, Debug)]
44 pub struct BookmarkTrackArgs {
45 /// Bookmark name patterns or remote bookmark symbols to track
46 ///
47 /// `BOOKMARK` matches bookmark names using glob syntax by default. You can
48 /// also use other [string pattern syntax].
49 ///
50 /// `BOOKMARK@REMOTE` resolves to a remote bookmark exactly.
51 ///
52 /// [string pattern syntax]:
53 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
54 #[arg(required = true, value_name = "BOOKMARK[@REMOTE]")]
55 #[arg(add = ArgValueCandidates::new(complete::untracked_bookmarks))]
56 names: Vec<String>,
57
58 /// Remote names to track
59 ///
60 /// By default, the specified pattern matches remote names with glob syntax.
61 /// You can also use other [string pattern syntax].
62 ///
63 /// If no remote names are given, all remote bookmarks matching the bookmark
64 /// names will be tracked.
65 ///
66 /// [string pattern syntax]:
67 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
68 #[arg(long = "remote", value_name = "REMOTE")]
69 // TODO: Make this skip the remotes already tracked
70 #[arg(add = ArgValueCandidates::new(complete::git_remotes))]
71 remotes: Option<Vec<String>>,
72 }
73
74 pub async fn cmd_bookmark_track(
75 ui: &mut Ui,
76 command: &CommandHelper,
77 args: &BookmarkTrackArgs,
78 ) -> Result<(), CommandError> {
79 let mut workspace_command = command.workspace_helper(ui).await?;
80 let repo = workspace_command.repo().clone();
81 let view = repo.view();
82
83 let (bookmark_exprs, remote_symbols) = parse_name_patterns_or_remote_symbols(ui, &args.names)?;
84 // Reject mixed syntax. It is confusing if the default @<remote> or
85 // user-specified --remote flag applies only to <bookmark> patterns.
86 if !bookmark_exprs.is_empty() && !remote_symbols.is_empty() {
87 return Err(cli_error(
88 "Cannot specify both <bookmark> patterns and <bookmark>@<remote> symbols",
89 ));
90 } else if args.remotes.is_some() && !remote_symbols.is_empty() {
91 return Err(cli_error(
92 "--remote cannot be used with <bookmark>@<remote> symbols",
93 ));
94 }
95 let matched_refs = if !remote_symbols.is_empty() {
96 resolve_trackable_remote_bookmarks(ui, view, &remote_symbols)?
97 } else {
98 let ignored_remote = default_ignored_remote_name(repo.store())
99 // suppress unmatched remotes warning for default-ignored remote
100 .filter(|name| view.get_remote_view(name).is_some());
101 let bookmark_expr = StringExpression::union_all(bookmark_exprs);
102 let remote_expr = match (&args.remotes, ignored_remote) {
103 (Some(text), _) => parse_union_name_patterns(ui, text)?,
104 (None, Some(ignored)) => StringExpression::exact(ignored).negated(),
105 (None, None) => StringExpression::all(),
106 };
107 let bookmark_matcher = bookmark_expr.to_matcher();
108 let remote_matcher = remote_expr.to_matcher();
109 let matched_refs =
110 trackable_remote_bookmarks_matching(view, &bookmark_matcher, &remote_matcher).collect();
111 warn_unmatched_local_or_remote_bookmarks(ui, view, &bookmark_expr)?;
112 warn_unmatched_remotes(ui, view, &remote_expr)?;
113 matched_refs
114 };
115
116 let mut symbols = Vec::new();
117 for (symbol, remote_ref) in matched_refs {
118 if remote_ref.is_tracked() {
119 writeln!(
120 ui.warning_default(),
121 "Remote bookmark already tracked: {symbol}"
122 )?;
123 } else {
124 symbols.push(symbol);
125 }
126 }
127 let mut tx = workspace_command.start_transaction();
128 for &symbol in &symbols {
129 tx.repo_mut().track_remote_bookmark(symbol).await?;
130 }
131 if !symbols.is_empty() {
132 writeln!(
133 ui.status(),
134 "Started tracking {} remote bookmarks.",
135 symbols.len()
136 )?;
137 }
138 tx.finish(
139 ui,
140 format!("track remote bookmark {}", symbols.iter().join(", ")),
141 )
142 .await?;
143
144 //show conflicted bookmarks if there are some
145
146 if let Some(mut formatter) = ui.status_formatter() {
147 let template: TemplateRenderer<Rc<CommitRef>> = {
148 let language = workspace_command.commit_template_language();
149 let text = workspace_command
150 .settings()
151 .get::<String>("templates.bookmark_list")?;
152 workspace_command
153 .parse_template(ui, &language, &text)?
154 .labeled(["bookmark_list"])
155 };
156
157 let mut remote_per_bookmark: HashMap<_, Vec<_>> = HashMap::new();
158 for symbol in &symbols {
159 remote_per_bookmark
160 .entry(symbol.name)
161 .or_default()
162 .push(symbol.remote);
163 }
164 let bookmarks_to_list =
165 workspace_command
166 .repo()
167 .view()
168 .bookmarks()
169 .filter(|(name, target)| {
170 remote_per_bookmark.contains_key(name) && target.local_target.has_conflict()
171 });
172
173 for (name, bookmark_target) in bookmarks_to_list {
174 let local_target = bookmark_target.local_target;
175 let commit_ref = CommitRef::local(
176 name,
177 local_target.clone(),
178 bookmark_target.remote_refs.iter().map(|x| x.1),
179 );
180 template.format(&commit_ref, formatter.as_mut())?;
181
182 for (remote_name, remote_ref) in bookmark_target.remote_refs {
183 if remote_per_bookmark[name].contains(&remote_name) {
184 let commit_ref =
185 CommitRef::remote(name, remote_name, remote_ref.clone(), local_target);
186 template.format(&commit_ref, formatter.as_mut())?;
187 }
188 }
189 }
190 }
191 Ok(())
192 }