Debian Codegraph @

cli/src/commands/git/fetch.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::io;
16
17 use clap_complete::ArgValueCandidates;
18 use itertools::Itertools as _;
19 use jj_lib::config::ConfigGetResultExt as _;
20 use jj_lib::git;
21 use jj_lib::git::GitFetch;
22 use jj_lib::git::GitFetchRefExpression;
23 use jj_lib::git::GitSettings;
24 use jj_lib::git::IgnoredRefspec;
25 use jj_lib::git::IgnoredRefspecs;
26 use jj_lib::git::expand_fetch_refspecs;
27 use jj_lib::git::get_git_backend;
28 use jj_lib::git::load_default_fetch_bookmarks;
29 use jj_lib::ref_name::RefName;
30 use jj_lib::ref_name::RemoteName;
31 use jj_lib::repo::Repo as _;
32 use jj_lib::str_util::StringExpression;
33
34 use crate::cli_util::CommandHelper;
35 use crate::cli_util::WorkspaceCommandHelper;
36 use crate::cli_util::WorkspaceCommandTransaction;
37 use crate::command_error::CommandError;
38 use crate::command_error::cli_error;
39 use crate::command_error::user_error;
40 use crate::commands::git::get_single_remote;
41 use crate::complete;
42 use crate::git_util::GitSubprocessUi;
43 use crate::git_util::load_git_import_options;
44 use crate::git_util::print_git_import_stats;
45 use crate::revset_util::parse_remote_fetch_bookmarks;
46 use crate::revset_util::parse_remote_fetch_tags;
47 use crate::revset_util::parse_union_name_patterns;
48 use crate::ui::Ui;
49
50 /// Fetch from a Git remote
51 ///
52 /// If no remotes are specified, fetches the remotes specified by the
53 /// `git.fetch` setting. If that is not configured and there are multiple
54 /// remotes, the remote named "origin" will be used.
55 ///
56 /// If no branches nor tags are specified, fetches bookmarks and tags specified
57 /// by the `remotes.<name>.fetch-bookmarks`/`fetch-tags` settings. If
58 /// `remotes.<name>.fetch-bookmarks` is not configured, the default fetch
59 /// refspecs for the selected remotes are read from the Git configuration.
60 ///
61 /// Commits that are no longer reachable from any branch on the remote will be
62 /// considered abandoned by the remote, and will be abandoned in the local repo
63 /// to match the remote. Set `git.abandon-unreachable-commits` to `false` to
64 /// disable this behavior.
65 ///
66 /// If a working-copy commit gets abandoned, it will be given a new, empty
67 /// commit. This is true in general; it is not specific to this command.
68 #[derive(clap::Args, Clone, Debug)]
69 #[command(group(clap::ArgGroup::new("specific").multiple(true)))]
70 pub struct GitFetchArgs {
71 /// Name of the branch to fetch (can be repeated)
72 ///
73 /// By default, the specified pattern matches branch names with glob syntax,
74 /// but only `*` is expanded. Other wildcard characters such as `?` are
75 /// *not* supported. Patterns can be repeated or combined with [logical
76 /// operators] to specify multiple branches, but only union and negative
77 /// intersection are supported.
78 ///
79 /// Examples: `push-*`, `(push-* | foo/*) ~ foo/unwanted`
80 ///
81 /// [logical operators]:
82 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
83 #[arg(
84 long = "branch",
85 short,
86 alias = "bookmark",
87 group = "specific",
88 value_name = "BRANCH"
89 )]
90 #[arg(add = ArgValueCandidates::new(complete::bookmarks))]
91 branches: Option<Vec<String>>,
92
93 /// Fetch only some of the tags (can be repeated)
94 ///
95 /// By default, the specified pattern matches tag names with glob syntax,
96 /// but only `*` is expanded. Other wildcard characters such as `?` are
97 /// *not* supported. Patterns can be repeated or combined with [logical
98 /// operators] to specify multiple tags, but only union and negative
99 /// intersection are supported.
100 ///
101 /// [logical operators]:
102 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
103 #[arg(long = "tag", short, group = "specific", value_name = "TAG")]
104 tags: Option<Vec<String>>,
105
106 /// Fetch only tracked bookmarks and tags
107 ///
108 /// This fetches only bookmarks and tags that are already tracked from the
109 /// specified remote(s).
110 #[arg(long, conflicts_with = "specific")]
111 tracked: bool,
112
113 /// The remote to fetch from (only named remotes are supported, can be
114 /// repeated)
115 ///
116 /// By default, the specified pattern matches remote names with glob syntax,
117 /// e.g. `--remote '*'`. You can also use other [string pattern syntax].
118 ///
119 /// [string pattern syntax]:
120 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
121 #[arg(long = "remote", value_name = "REMOTE")]
122 #[arg(add = ArgValueCandidates::new(complete::git_remotes))]
123 remotes: Option<Vec<String>>,
124
125 /// Fetch from all remotes
126 #[arg(long, conflicts_with = "remotes")]
127 all_remotes: bool,
128 }
129
130 #[tracing::instrument(skip_all)]
131 pub async fn cmd_git_fetch(
132 ui: &mut Ui,
133 command: &CommandHelper,
134 args: &GitFetchArgs,
135 ) -> Result<(), CommandError> {
136 if command.global_args().no_integrate_operation {
137 // TODO: Remove this restriction by fetching remote refs in memory or
138 // into a temporary namespace.
139 return Err(cli_error("--no-integrate-operation is not respected"));
140 }
141 let mut workspace_command = command.workspace_helper(ui).await?;
142 let remote_expr = if args.all_remotes {
143 StringExpression::all()
144 } else if let Some(remotes) = &args.remotes {
145 parse_union_name_patterns(ui, remotes)?
146 } else {
147 get_default_fetch_remotes(ui, &workspace_command)?
148 };
149 let remote_matcher = remote_expr.to_matcher();
150
151 let all_remotes = git::get_all_remote_names(workspace_command.repo().store())?;
152 let matching_remotes: Vec<&RemoteName> = all_remotes
153 .iter()
154 .filter(|r| remote_matcher.is_match(r.as_str()))
155 .map(AsRef::as_ref)
156 .collect();
157 let mut unmatched_remotes = remote_expr
158 .exact_strings()
159 .map(RemoteName::new)
160 // do linear search. all_remotes should be small.
161 .filter(|&name| all_remotes.iter().all(|r| r != name))
162 .peekable();
163 if unmatched_remotes.peek().is_some() {
164 writeln!(
165 ui.warning_default(),
166 "No matching remotes for names: {}",
167 unmatched_remotes.map(|name| name.as_symbol()).join(", ")
168 )?;
169 }
170 if matching_remotes.is_empty() {
171 return Err(user_error("No git remotes to fetch from"));
172 }
173
174 let mut tx = workspace_command.start_transaction();
175 let remote_settings = tx.settings().remote_settings()?;
176
177 let is_specific = args.branches.is_some() || args.tags.is_some();
178 let common_bookmark_expr = match &args.branches {
179 Some(texts) => Some(parse_union_name_patterns(ui, texts)?),
180 None => is_specific.then(StringExpression::none),
181 };
182 let common_tag_expr = match &args.tags {
183 Some(texts) => Some(parse_union_name_patterns(ui, texts)?),
184 None => is_specific.then(StringExpression::none),
185 };
186 let mut expansions = Vec::with_capacity(matching_remotes.len());
187 if args.tracked {
188 for remote in &matching_remotes {
189 let bookmark = StringExpression::union_all(
190 tx.repo()
191 .view()
192 .local_remote_bookmarks(remote)
193 .filter(|(_, targets)| targets.remote_ref.is_tracked())
194 .map(|(name, _)| StringExpression::exact(name))
195 .collect(),
196 );
197 let tag = StringExpression::union_all(
198 tx.repo()
199 .view()
200 .local_remote_tags(remote)
201 .filter(|(_, targets)| targets.remote_ref.is_tracked())
202 .map(|(name, _)| StringExpression::exact(name))
203 .collect(),
204 );
205 let ref_expr = GitFetchRefExpression { bookmark, tag };
206 let expanded = expand_fetch_refspecs(remote, ref_expr)?;
207 expansions.push((remote, expanded));
208 }
209 } else {
210 let git_repo = get_git_backend(tx.repo_mut().store())?.git_repo();
211 for remote in &matching_remotes {
212 let bookmark = if let Some(expr) = &common_bookmark_expr {
213 expr.clone()
214 } else if let Some(expr) = parse_remote_fetch_bookmarks(ui, &remote_settings, remote)? {
215 expr
216 } else {
217 let (ignored, expr) = load_default_fetch_bookmarks(remote, &git_repo)?;
218 warn_ignored_refspecs(ui, remote, ignored)?;
219 expr
220 };
221 let tag = if let Some(expr) = &common_tag_expr {
222 expr.clone()
223 } else if let Some(expr) = parse_remote_fetch_tags(ui, &remote_settings, remote)? {
224 expr
225 } else {
226 StringExpression::all()
227 };
228 let ref_expr = GitFetchRefExpression { bookmark, tag };
229 let expanded = expand_fetch_refspecs(remote, ref_expr)?;
230 expansions.push((remote, expanded));
231 }
232 }
233
234 let git_settings = GitSettings::from_settings(tx.settings())?;
235 let import_options = load_git_import_options(ui, &git_settings, &remote_settings)?;
236 let mut git_fetch = GitFetch::new(
237 tx.repo_mut(),
238 git_settings.to_subprocess_options(),
239 &import_options,
240 )?;
241
242 for (remote, expanded) in expansions {
243 let mut callback = GitSubprocessUi::new(ui);
244 git_fetch.fetch(remote, expanded, &mut callback, None)?;
245 }
246
247 let import_stats = git_fetch.import_refs().await?;
248 print_git_import_stats(ui, &tx, &import_stats)?;
249
250 if let Some(bookmark_expr) = &common_bookmark_expr {
251 warn_if_branches_not_found(ui, &tx, bookmark_expr, &matching_remotes)?;
252 }
253 // TODO: warn_if_tags_not_found()
254 tx.finish(
255 ui,
256 format!(
257 "fetch from git remote(s) {}",
258 matching_remotes.iter().map(|n| n.as_symbol()).join(",")
259 ),
260 )
261 .await?;
262 Ok(())
263 }
264
265 const DEFAULT_REMOTE: &RemoteName = RemoteName::new("origin");
266
267 fn get_default_fetch_remotes(
268 ui: &Ui,
269 workspace_command: &WorkspaceCommandHelper,
270 ) -> Result<StringExpression, CommandError> {
271 const KEY: &str = "git.fetch";
272 let settings = workspace_command.settings();
273 if let Ok(remotes) = settings.get::<Vec<String>>(KEY) {
274 parse_union_name_patterns(ui, &remotes)
275 } else if let Some(remote) = settings.get_string(KEY).optional()? {
276 parse_union_name_patterns(ui, [&remote])
277 } else if let Some(remote) = get_single_remote(workspace_command.repo().store())? {
278 // if nothing was explicitly configured, try to guess
279 if remote != DEFAULT_REMOTE {
280 writeln!(
281 ui.hint_default(),
282 "Fetching from the only existing remote: {remote}",
283 remote = remote.as_symbol()
284 )?;
285 }
286 Ok(StringExpression::exact(remote))
287 } else {
288 Ok(StringExpression::exact(DEFAULT_REMOTE))
289 }
290 }
291
292 fn warn_if_branches_not_found(
293 ui: &mut Ui,
294 tx: &WorkspaceCommandTransaction,
295 bookmark_expr: &StringExpression,
296 remotes: &[&RemoteName],
297 ) -> io::Result<()> {
298 let bookmark_matcher = bookmark_expr.to_matcher();
299 let mut missing_branches = bookmark_expr
300 .exact_strings()
301 .filter(|name| bookmark_matcher.is_match(name)) // exclude negative patterns
302 .map(RefName::new)
303 .filter(|name| {
304 remotes.iter().all(|&remote| {
305 let symbol = name.to_remote_symbol(remote);
306 let view = tx.repo().view();
307 let base_view = tx.base_repo().view();
308 view.get_remote_bookmark(symbol).is_absent()
309 && base_view.get_remote_bookmark(symbol).is_absent()
310 })
311 })
312 .peekable();
313 if missing_branches.peek().is_none() {
314 return Ok(());
315 }
316 writeln!(
317 ui.warning_default(),
318 "No matching branches found on any specified/configured remote: {}",
319 missing_branches.map(|name| name.as_symbol()).join(", ")
320 )
321 }
322
323 fn warn_ignored_refspecs(
324 ui: &Ui,
325 remote_name: &RemoteName,
326 IgnoredRefspecs(ignored_refspecs): IgnoredRefspecs,
327 ) -> Result<(), CommandError> {
328 let remote_name = remote_name.as_symbol();
329 for IgnoredRefspec { refspec, reason } in ignored_refspecs {
330 writeln!(
331 ui.warning_default(),
332 "Ignored refspec `{refspec}` from `{remote_name}`: {reason}",
333 )?;
334 }
335
336 Ok(())
337 }