Debian Codegraph @

cli/src/commands/git/push.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::collections::HashSet;
17 use std::future;
18 use std::io;
19 use std::io::Write as _;
20 use std::iter;
21 use std::sync::Arc;
22
23 use clap::ArgGroup;
24 use clap_complete::ArgValueCandidates;
25 use clap_complete::ArgValueCompleter;
26 use futures::StreamExt as _;
27 use futures::TryStreamExt as _;
28 use futures::future::try_join_all;
29 use indexmap::IndexSet;
30 use itertools::Itertools as _;
31 use jj_lib::backend::CommitId;
32 use jj_lib::commit::Commit;
33 use jj_lib::config::ConfigGetResultExt as _;
34 use jj_lib::git;
35 use jj_lib::git::GitPushOptions;
36 use jj_lib::git::GitPushRefTargets;
37 use jj_lib::git::GitSettings;
38 use jj_lib::index::IndexResult;
39 use jj_lib::merge::Diff;
40 use jj_lib::op_store::RefTarget;
41 use jj_lib::operation::Operation;
42 use jj_lib::ref_name::RefName;
43 use jj_lib::ref_name::RefNameBuf;
44 use jj_lib::ref_name::RemoteName;
45 use jj_lib::ref_name::RemoteNameBuf;
46 use jj_lib::ref_name::RemoteRefSymbol;
47 use jj_lib::refs::LocalAndRemoteRef;
48 use jj_lib::refs::RefPushAction;
49 use jj_lib::refs::classify_ref_push_action;
50 use jj_lib::repo::Repo;
51 use jj_lib::revset::RemoteRefSymbolExpression;
52 use jj_lib::revset::ResolvedRevsetExpression;
53 use jj_lib::revset::RevsetContainingFn;
54 use jj_lib::revset::RevsetEvaluationError;
55 use jj_lib::revset::RevsetExpression;
56 use jj_lib::revset::RevsetStreamExt as _;
57 use jj_lib::revset::UserRevsetExpression;
58 use jj_lib::rewrite::CommitRewriter;
59 use jj_lib::signing::SignBehavior;
60 use jj_lib::str_util::StringExpression;
61 use jj_lib::view::View;
62
63 use crate::cli_util::CommandHelper;
64 use crate::cli_util::RevisionArg;
65 use crate::cli_util::WorkspaceCommandHelper;
66 use crate::cli_util::WorkspaceCommandTransaction;
67 use crate::cli_util::has_tracked_remote_bookmarks;
68 use crate::cli_util::has_tracked_remote_tags;
69 use crate::cli_util::print_updated_commits;
70 use crate::cli_util::short_change_hash;
71 use crate::cli_util::short_commit_hash;
72 use crate::command_error::CommandError;
73 use crate::command_error::cli_error;
74 use crate::command_error::cli_error_with_message;
75 use crate::command_error::user_error;
76 use crate::command_error::user_error_with_message;
77 use crate::commands::git::get_single_remote;
78 use crate::complete;
79 use crate::formatter::Formatter;
80 use crate::git_util::GitSubprocessUi;
81 use crate::git_util::print_push_stats;
82 use crate::progress::ProgressWriter;
83 use crate::revset_util::parse_bookmark_name;
84 use crate::revset_util::parse_union_name_patterns;
85 use crate::ui::Ui;
86
87 /// Push to a Git remote
88 ///
89 /// By default, pushes tracking bookmarks and tags pointing to
90 /// `remote_bookmarks(remote=<remote>)..@`. Use `--bookmark`/`--tag` to push
91 /// specific bookmarks or tags. Use `--all` to push all bookmarks and tags. Use
92 /// `--change` to generate bookmark names based on the change IDs of specific
93 /// commits.
94 ///
95 /// When pushing a bookmark or tag, the command pushes all commits in the range
96 /// from the remote's current position up to and including its target
97 /// commit. Any descendant commits beyond the reference are not pushed.
98 ///
99 /// If the local reference has changed from the last fetch, push will update the
100 /// remote reference to the new position after passing safety checks. This is
101 /// similar to `git push --force-with-lease` - the remote is updated only if its
102 /// current state matches what Jujutsu last fetched.
103 ///
104 /// Unlike in Git, the remote to push to is not derived from the tracked remote
105 /// bookmarks. Use `--remote` to select the remote Git repository by name. There
106 /// is no option to push to multiple remotes.
107 ///
108 /// Before the command actually moves, creates, or deletes a remote bookmark, it
109 /// makes several [safety checks]. If there is a problem, you may need to run
110 /// `jj git fetch --remote <remote name>` and/or resolve some [bookmark
111 /// conflicts].
112 ///
113 /// [safety checks]:
114 /// https://docs.jj-vcs.dev/latest/bookmarks/#pushing-bookmarks-safety-checks
115 ///
116 /// [bookmark conflicts]:
117 /// https://docs.jj-vcs.dev/latest/bookmarks/#conflicts
118
119 #[derive(clap::Args, Clone, Debug)]
120 #[command(group(ArgGroup::new("specific").multiple(true)))]
121 #[command(group(ArgGroup::new("what").conflicts_with("specific")))]
122 pub struct GitPushArgs {
123 /// The remote to push to (only named remotes are supported)
124 ///
125 /// This defaults to the `git.push` setting. If that is not configured, and
126 /// if there are multiple remotes, the remote named "origin" will be used.
127 #[arg(long)]
128 #[arg(add = ArgValueCandidates::new(complete::git_remotes))]
129 remote: Option<RemoteNameBuf>,
130
131 /// Push only this bookmark, or bookmarks matching a pattern (can be
132 /// repeated)
133 ///
134 /// If a bookmark isn't tracking anything yet, the remote bookmark will be
135 /// tracked automatically.
136 ///
137 /// By default, the specified pattern matches bookmark names with glob
138 /// syntax. You can also use other [string pattern syntax].
139 ///
140 /// [string pattern syntax]:
141 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
142 #[arg(long, short, alias = "branch", group = "specific")]
143 #[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
144 bookmark: Vec<String>,
145
146 /// Push only this tag, or tags matching a pattern (can be repeated)
147 ///
148 /// If a tag isn't tracking anything yet, the remote tag will be tracked
149 /// automatically.
150 ///
151 /// By default, the specified pattern matches tag names with glob syntax.
152 /// You can also use other [string pattern syntax].
153 ///
154 /// [string pattern syntax]:
155 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
156 #[arg(long, short, group = "specific")]
157 tag: Vec<String>,
158
159 /// Push all bookmarks and tags (including new ones)
160 #[arg(long, group = "what")]
161 all: bool,
162
163 /// Push all tracked bookmarks and tags
164 ///
165 /// This usually means that the bookmark or tag was already pushed to or
166 /// fetched from the [relevant remote].
167 ///
168 /// [relevant remote]:
169 /// https://docs.jj-vcs.dev/latest/bookmarks#remotes-and-tracked-bookmarks
170 #[arg(long, group = "what")]
171 tracked: bool,
172
173 /// Push all deleted bookmarks and tags
174 ///
175 /// Only tracked bookmarks and tags can be successfully deleted on the
176 /// remote. A warning will be printed if any untracked bookmarks or tags on
177 /// the remote correspond to missing local bookmarks or tags.
178 #[arg(long, conflicts_with = "specific")]
179 deleted: bool,
180
181 /// Allow pushing commits with empty descriptions
182 #[arg(long)]
183 allow_empty_description: bool,
184
185 /// Allow pushing commits that are private
186 ///
187 /// The set of private commits can be configured by the
188 /// `git.private-commits` setting. The default is `none()`, meaning all
189 /// commits are eligible to be pushed.
190 #[arg(long)]
191 allow_private: bool,
192
193 /// Allow pushing commits that contain conflicts
194 #[arg(long)]
195 allow_conflicts: bool,
196
197 /// Push bookmarks and tags pointing to these commits (can be repeated)
198 #[arg(
199 long = "revision",
200 short,
201 group = "specific",
202 value_name = "REVSETS",
203 alias = "revisions"
204 )]
205 // While `-r` will often be used with mutable revisions, immutable revisions
206 // can be useful as parts of revsets or to push special-purpose branches.
207 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
208 revisions: Vec<RevisionArg>,
209
210 /// Push this commit by creating a bookmark (can be repeated)
211 ///
212 /// The created bookmark will be tracked automatically. Use the
213 /// `templates.git_push_bookmark` setting to customize the generated
214 /// bookmark name. The default is `"push-" ++ change_id.short()`.
215 #[arg(long, short, group = "specific", value_name = "REVSETS")]
216 // I'm guessing that `git push -c` is almost exclusively used with recently
217 // created mutable revisions, even though it can in theory be used with
218 // immutable ones as well. We can change it if the guess turns out to be
219 // wrong.
220 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
221 change: Vec<RevisionArg>,
222
223 /// Specify a new bookmark name and a revision to push under that name, e.g.
224 /// '--named myfeature=@'
225 ///
226 /// Automatically tracks the bookmark if it is new.
227 #[arg(long, group = "specific", value_name = "NAME=REVISION")]
228 #[arg(add = ArgValueCompleter::new(complete::branch_name_equals_any_revision))]
229 named: Vec<String>,
230
231 /// Only display what will change on the remote
232 #[arg(long)]
233 dry_run: bool,
234
235 /// Git push options
236 #[arg(long, short)]
237 option: Vec<String>,
238 }
239
240 fn make_updates_term(ref_updates: &GitPushRefTargets) -> String {
241 let kind_updates = [
242 ("bookmark", "bookmarks", &ref_updates.bookmarks),
243 ("tag", "tags", &ref_updates.tags),
244 ];
245 kind_updates
246 .into_iter()
247 .filter_map(|(kind, kinds, refs)| match &**refs {
248 [] => None,
249 [(name, _)] => Some(format!("{kind} {}", name.as_symbol())),
250 _ => Some(format!(
251 "{kinds} {}",
252 refs.iter().map(|(name, _)| name.as_symbol()).join(", ")
253 )),
254 })
255 .join(", ")
256 }
257
258 const DEFAULT_REMOTE: &RemoteName = RemoteName::new("origin");
259
260 const TX_DESC_PUSH: &str = "push ";
261
262 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
263 enum BookmarkMoveDirection {
264 Forward,
265 Backward,
266 Sideways,
267 }
268
269 pub async fn cmd_git_push(
270 ui: &mut Ui,
271 command: &CommandHelper,
272 args: &GitPushArgs,
273 ) -> Result<(), CommandError> {
274 if command.global_args().no_integrate_operation {
275 // Pushed refs shouldn't be left unintegrated.
276 return Err(cli_error(
277 "--no-integrate-operation is not respected; use --dry-run",
278 ));
279 }
280 let mut workspace_command = command.workspace_helper(ui).await?;
281
282 let default_remote;
283 let remote = if let Some(name) = &args.remote {
284 name
285 } else {
286 default_remote = get_default_push_remote(ui, &workspace_command)?;
287 &default_remote
288 };
289
290 let mut tx = workspace_command.start_transaction();
291 let view = tx.repo().view();
292 let mut ref_updates = GitPushRefTargets::default();
293 if args.all {
294 let mut commits_validator =
295 CommitsValidator::new(ui, tx.base_workspace_helper(), remote, args)?;
296 for (name, targets) in view.local_remote_bookmarks(remote) {
297 let remote_symbol = name.to_remote_symbol(remote);
298 let allow_new = true; // implied by --all
299 match classify_bookmark_update(remote_symbol, targets, allow_new, args.deleted) {
300 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
301 Ok(()) => ref_updates.bookmarks.push((name.to_owned(), update)),
302 Err(reason) => reason.print_bookmark(ui, tx.base_workspace_helper(), name)?,
303 },
304 Ok(None) => {}
305 Err(reason) => reason.print(ui)?,
306 }
307 }
308 for (name, targets) in view.local_remote_tags(remote) {
309 let remote_symbol = name.to_remote_symbol(remote);
310 let allow_new = true; // implied by --all
311 match classify_tag_update(remote_symbol, targets, allow_new, args.deleted) {
312 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
313 Ok(()) => ref_updates.tags.push((name.to_owned(), update)),
314 Err(reason) => reason.print_tag(ui, tx.base_workspace_helper(), name)?,
315 },
316 Ok(None) => {}
317 Err(reason) => reason.print(ui)?,
318 }
319 }
320 } else if args.tracked {
321 let mut commits_validator =
322 CommitsValidator::new(ui, tx.base_workspace_helper(), remote, args)?;
323 for (name, targets) in view.local_remote_bookmarks(remote) {
324 if !targets.remote_ref.is_tracked() {
325 continue;
326 }
327 let remote_symbol = name.to_remote_symbol(remote);
328 let allow_new = false; // doesn't matter
329 match classify_bookmark_update(remote_symbol, targets, allow_new, args.deleted) {
330 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
331 Ok(()) => ref_updates.bookmarks.push((name.to_owned(), update)),
332 Err(reason) => reason.print_bookmark(ui, tx.base_workspace_helper(), name)?,
333 },
334 Ok(None) => {}
335 Err(reason) => reason.print(ui)?,
336 }
337 }
338 for (name, targets) in view.local_remote_tags(remote) {
339 if !targets.remote_ref.is_tracked() {
340 continue;
341 }
342 let remote_symbol = name.to_remote_symbol(remote);
343 let allow_new = false; // doesn't matter
344 match classify_tag_update(remote_symbol, targets, allow_new, args.deleted) {
345 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
346 Ok(()) => ref_updates.tags.push((name.to_owned(), update)),
347 Err(reason) => reason.print_tag(ui, tx.base_workspace_helper(), name)?,
348 },
349 Ok(None) => {}
350 Err(reason) => reason.print(ui)?,
351 }
352 }
353 } else if args.deleted {
354 // There shouldn't be new heads to push, but we run validation for consistency.
355 let mut commits_validator =
356 CommitsValidator::new(ui, tx.base_workspace_helper(), remote, args)?;
357 for (name, targets) in view.local_remote_bookmarks(remote) {
358 if targets.local_target.is_present() {
359 continue;
360 }
361 let remote_symbol = name.to_remote_symbol(remote);
362 let allow_new = false; // doesn't matter
363 let allow_delete = true;
364 match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
365 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
366 Ok(()) => ref_updates.bookmarks.push((name.to_owned(), update)),
367 Err(reason) => reason.print_bookmark(ui, tx.base_workspace_helper(), name)?,
368 },
369 Ok(None) => {}
370 Err(reason) => reason.print(ui)?,
371 }
372 }
373 for (name, targets) in view.local_remote_tags(remote) {
374 if targets.local_target.is_present() {
375 continue;
376 }
377 let remote_symbol = name.to_remote_symbol(remote);
378 let allow_new = false; // doesn't matter
379 let allow_delete = true;
380 match classify_tag_update(remote_symbol, targets, allow_new, allow_delete) {
381 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
382 Ok(()) => ref_updates.tags.push((name.to_owned(), update)),
383 Err(reason) => reason.print_tag(ui, tx.base_workspace_helper(), name)?,
384 },
385 Ok(None) => {}
386 Err(reason) => reason.print(ui)?,
387 }
388 }
389 } else {
390 let mut seen_bookmarks: HashSet<&RefName> = HashSet::new();
391 let mut seen_tags: HashSet<&RefName> = HashSet::new();
392
393 // --change and --named don't move existing bookmarks. If they did, be
394 // careful to not select old state by -r/--revisions and bookmark names.
395 let change_bookmark_names = create_change_bookmarks(ui, &mut tx, &args.change).await?;
396 let named_bookmark_commits = try_join_all(args.named.iter().map(|arg| async {
397 let (name, revision_arg) = parse_named_bookmark(arg)?;
398 let commit = tx
399 .base_workspace_helper()
400 .resolve_single_rev(ui, &revision_arg)
401 .await?;
402 Ok::<_, CommandError>((name, commit))
403 }))
404 .await?;
405 for (name, commit) in &named_bookmark_commits {
406 ensure_new_bookmark_name(tx.repo(), name)?;
407 tx.repo_mut()
408 .set_local_bookmark_target(name, RefTarget::normal(commit.id().clone()));
409 }
410 let created_bookmarks = change_bookmark_names
411 .iter()
412 .chain(named_bookmark_commits.iter().map(|(name, _)| name))
413 .map(|name| {
414 let remote_symbol = name.to_remote_symbol(remote);
415 let targets = LocalAndRemoteRef {
416 local_target: tx.repo().view().get_local_bookmark(name),
417 remote_ref: tx.repo().view().get_remote_bookmark(remote_symbol),
418 };
419 (remote_symbol, targets)
420 });
421 for (remote_symbol, targets) in created_bookmarks {
422 let name = remote_symbol.name;
423 if !seen_bookmarks.insert(name) {
424 continue;
425 }
426 let allow_new = true; // --change implies creation of remote bookmark
427 let allow_delete = false; // doesn't matter
428 match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
429 Ok(Some(update)) => ref_updates.bookmarks.push((name.to_owned(), update)),
430 Ok(None) => writeln!(
431 ui.status(),
432 "Bookmark {remote_symbol} already matches {name}",
433 name = name.as_symbol()
434 )?,
435 Err(reason) => return Err(reason.into()),
436 }
437 }
438
439 let view = tx.repo().view();
440 let bookmarks_by_name = find_bookmarks_to_push(ui, view, &args.bookmark, remote)?;
441 for &(name, targets) in &bookmarks_by_name {
442 if !seen_bookmarks.insert(name) {
443 continue;
444 }
445 let remote_symbol = name.to_remote_symbol(remote);
446 // Override allow_new if the bookmark is not tracked with any remote
447 // already. The user has specified --bookmark, so their intent which
448 // bookmarks to push is clear.
449 let allow_new = !has_tracked_remote_bookmarks(tx.repo(), name);
450 let allow_delete = true; // named explicitly, allow delete without --delete
451 match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
452 Ok(Some(update)) => ref_updates.bookmarks.push((name.to_owned(), update)),
453 Ok(None) => writeln!(
454 ui.status(),
455 "Bookmark {remote_symbol} already matches {name}",
456 name = name.as_symbol()
457 )?,
458 Err(reason) => return Err(reason.into()),
459 }
460 }
461
462 let tags_by_name = find_tags_to_push(ui, view, &args.tag, remote)?;
463 for &(name, targets) in &tags_by_name {
464 if !seen_tags.insert(name) {
465 continue;
466 }
467 let remote_symbol = name.to_remote_symbol(remote);
468 // named explicitly, allow track or delete
469 let allow_new = !has_tracked_remote_tags(tx.repo(), name);
470 let allow_delete = true;
471 match classify_tag_update(remote_symbol, targets, allow_new, allow_delete) {
472 Ok(Some(update)) => ref_updates.tags.push((name.to_owned(), update)),
473 Ok(None) => writeln!(
474 ui.status(),
475 "Tag {remote_symbol} already matches {name}",
476 name = name.as_symbol()
477 )?,
478 Err(reason) => return Err(reason.into()),
479 }
480 }
481
482 let mut commits_validator =
483 CommitsValidator::new(ui, tx.base_workspace_helper(), remote, args)?;
484 // Error out if explicitly-specified targets can't be pushed.
485 commits_validator
486 .validate_updates(&ref_updates)
487 .await?
488 .map_err(|reason| reason.to_command_error(tx.base_workspace_helper()))?;
489
490 let use_default_revset = args.bookmark.is_empty()
491 && args.tag.is_empty()
492 && args.change.is_empty()
493 && args.revisions.is_empty()
494 && args.named.is_empty();
495 let target_revisions = if use_default_revset {
496 find_default_target_revisions(ui, tx.base_workspace_helper(), remote).await?
497 } else {
498 find_target_revisions(ui, tx.base_workspace_helper(), &args.revisions).await?
499 };
500 for (name, targets) in tx.base_repo().view().local_remote_bookmarks(remote) {
501 if !matches_local_target(targets, &target_revisions) || !seen_bookmarks.insert(name) {
502 continue;
503 }
504 let remote_symbol = name.to_remote_symbol(remote);
505 let allow_new = false;
506 let allow_delete = false;
507 match classify_bookmark_update(remote_symbol, targets, allow_new, allow_delete) {
508 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
509 Ok(()) => ref_updates.bookmarks.push((name.to_owned(), update)),
510 Err(reason) => reason.print_bookmark(ui, tx.base_workspace_helper(), name)?,
511 },
512 Ok(None) => {}
513 Err(reason) => reason.print(ui)?,
514 }
515 }
516 for (name, targets) in tx.base_repo().view().local_remote_tags(remote) {
517 if !matches_local_target(targets, &target_revisions) || !seen_tags.insert(name) {
518 continue;
519 }
520 let remote_symbol = name.to_remote_symbol(remote);
521 let allow_new = false;
522 let allow_delete = false;
523 match classify_tag_update(remote_symbol, targets, allow_new, allow_delete) {
524 Ok(Some(update)) => match commits_validator.validate_update(&update).await? {
525 Ok(()) => ref_updates.tags.push((name.to_owned(), update)),
526 Err(reason) => reason.print_tag(ui, tx.base_workspace_helper(), name)?,
527 },
528 Ok(None) => {}
529 Err(reason) => reason.print(ui)?,
530 }
531 }
532 }
533 if ref_updates.bookmarks.is_empty() && ref_updates.tags.is_empty() {
534 writeln!(ui.status(), "Nothing changed.")?;
535 return Ok(());
536 }
537
538 if !args.dry_run && tx.settings().get_bool("git.sign-on-push")? {
539 let to_push_expr = ready_to_push_revset_expression(&tx, remote, &ref_updates);
540 ref_updates = sign_commits_before_push(ui, &mut tx, to_push_expr, ref_updates).await?;
541 }
542
543 if let Some(mut formatter) = ui.status_formatter() {
544 writeln!(
545 formatter,
546 "Changes to push to {remote}:",
547 remote = remote.as_symbol()
548 )?;
549 print_commits_ready_to_push(formatter.as_mut(), tx.repo(), &ref_updates).await?;
550 }
551
552 if args.dry_run {
553 writeln!(ui.status(), "Dry-run requested, not pushing.")?;
554 return Ok(());
555 }
556
557 let git_settings = GitSettings::from_settings(tx.settings())?;
558 let options = GitPushOptions {
559 remote_push_options: args.option.clone(),
560 };
561 let push_stats = git::push_refs(
562 tx.repo_mut(),
563 git_settings.to_subprocess_options(),
564 remote,
565 &ref_updates,
566 &mut GitSubprocessUi::new(ui),
567 &options,
568 )?;
569 print_push_stats(ui, &push_stats)?;
570 // TODO: On partial success, locally-created --change/--named bookmarks will
571 // be committed. It's probably better to remove failed local bookmarks.
572 if push_stats.all_ok() || push_stats.some_exported() {
573 let description = if args.all {
574 format!(
575 "{TX_DESC_PUSH}all bookmarks/tags to git remote {remote}",
576 remote = remote.as_symbol()
577 )
578 } else if args.tracked {
579 format!(
580 "{TX_DESC_PUSH}all tracked bookmarks/tags to git remote {remote}",
581 remote = remote.as_symbol()
582 )
583 } else if args.deleted {
584 format!(
585 "{TX_DESC_PUSH}all deleted bookmarks/tags to git remote {remote}",
586 remote = remote.as_symbol()
587 )
588 } else {
589 format!(
590 "{TX_DESC_PUSH}{names} to git remote {remote}",
591 names = make_updates_term(&ref_updates),
592 remote = remote.as_symbol()
593 )
594 };
595 tx.finish(ui, description).await?;
596 }
597 if push_stats.all_ok() {
598 Ok(())
599 } else {
600 Err(user_error("Failed to push some bookmarks"))
601 }
602 }
603
604 #[derive(Clone, Debug)]
605 struct RejectedCommitReason {
606 commit: Commit,
607 message: String,
608 hint: Option<String>,
609 }
610
611 impl RejectedCommitReason {
612 fn print_bookmark(
613 &self,
614 ui: &Ui,
615 workspace_helper: &WorkspaceCommandHelper,
616 name: &RefName,
617 ) -> io::Result<()> {
618 self.print_inner(ui, workspace_helper, "bookmark", name)
619 }
620
621 fn print_tag(
622 &self,
623 ui: &Ui,
624 workspace_helper: &WorkspaceCommandHelper,
625 name: &RefName,
626 ) -> io::Result<()> {
627 self.print_inner(ui, workspace_helper, "tag", name)
628 }
629
630 fn print_inner(
631 &self,
632 ui: &Ui,
633 workspace_helper: &WorkspaceCommandHelper,
634 kind: &str,
635 name: &RefName,
636 ) -> io::Result<()> {
637 writeln!(
638 ui.warning_default(),
639 "Won't push {kind} {name}: commit {id} {message}",
640 name = name.as_symbol(),
641 id = short_commit_hash(self.commit.id()),
642 message = self.message,
643 )?;
644 if let Some(mut formatter) = ui.status_formatter() {
645 write!(formatter, " ")?;
646 workspace_helper.write_commit_summary(formatter.as_mut(), &self.commit)?;
647 writeln!(formatter)?;
648 }
649 if let Some(hint) = &self.hint {
650 writeln!(ui.hint_default(), "{hint}")?;
651 }
652 Ok(())
653 }
654
655 fn to_command_error(&self, workspace_helper: &WorkspaceCommandHelper) -> CommandError {
656 let mut error = user_error(format!(
657 "Won't push commit {id} since it {message}",
658 id = short_commit_hash(self.commit.id()),
659 message = self.message,
660 ));
661 error.add_formatted_hint_with(|formatter| {
662 write!(formatter, "Rejected commit: ")?;
663 workspace_helper.write_commit_summary(formatter, &self.commit)?;
664 Ok(())
665 });
666 error.extend_hints(self.hint.clone());
667 error
668 }
669 }
670
671 /// Validates that the commits that will be pushed are ready (have authorship
672 /// information, are not conflicted, etc.).
673 struct CommitsValidator<'repo> {
674 repo: &'repo dyn Repo,
675 known_heads: Vec<CommitId>,
676 immutable_heads: Arc<ResolvedRevsetExpression>,
677 private_commits: Option<(String, Box<RevsetContainingFn<'repo>>)>,
678 allow_empty_description: bool,
679 allow_conflicts: bool,
680 }
681
682 impl<'repo> CommitsValidator<'repo> {
683 fn new(
684 ui: &Ui,
685 workspace_helper: &'repo WorkspaceCommandHelper,
686 remote: &RemoteName,
687 args: &GitPushArgs,
688 ) -> Result<Self, CommandError> {
689 let repo = workspace_helper.repo().as_ref();
690 let known_heads = repo
691 .view()
692 .remote_bookmarks(remote)
693 .flat_map(|(_, old_head)| old_head.target.added_ids())
694 .cloned()
695 .collect();
696 let immutable_heads = workspace_helper
697 .attach_revset_evaluator(workspace_helper.env().immutable_heads_expression().clone())
698 .resolve()?;
699 let private_commits = if !args.allow_private {
700 let settings = workspace_helper.settings();
701 let revset_str = settings.get_string("git.private-commits")?;
702 let is_private = workspace_helper
703 .parse_revset(ui, &RevisionArg::from(revset_str.clone()))?
704 .evaluate()?
705 .containing_fn();
706 Some((revset_str, is_private))
707 } else {
708 None
709 };
710 Ok(Self {
711 repo,
712 known_heads,
713 immutable_heads,
714 private_commits,
715 allow_empty_description: args.allow_empty_description,
716 allow_conflicts: args.allow_conflicts,
717 })
718 }
719
720 async fn validate_update(
721 &mut self,
722 update: &Diff<Option<CommitId>>,
723 ) -> Result<Result<(), RejectedCommitReason>, RevsetEvaluationError> {
724 self.validate_commits(update.after.as_slice()).await
725 }
726
727 async fn validate_updates(
728 &mut self,
729 updates: &GitPushRefTargets,
730 ) -> Result<Result<(), RejectedCommitReason>, RevsetEvaluationError> {
731 let new_heads = itertools::chain(&updates.bookmarks, &updates.tags)
732 .filter_map(|(_, update)| update.after.clone())
733 .collect_vec();
734 self.validate_commits(&new_heads).await
735 }
736
737 async fn validate_commits(
738 &mut self,
739 new_heads: &[CommitId],
740 ) -> Result<Result<(), RejectedCommitReason>, RevsetEvaluationError> {
741 let new_commits = RevsetExpression::commits(self.known_heads.clone())
742 .union(&self.immutable_heads)
743 .range(&RevsetExpression::commits(new_heads.to_vec()));
744 let mut commit_stream = new_commits
745 .evaluate(self.repo)?
746 .stream()
747 .commits(self.repo.store());
748 while let Some(commit) = commit_stream.try_next().await? {
749 let mut reasons = vec![];
750 let mut hint = None;
751 if commit.description().is_empty() && !self.allow_empty_description {
752 reasons.push("has no description");
753 }
754 if commit.author().name.is_empty()
755 || commit.author().email.is_empty()
756 || commit.committer().name.is_empty()
757 || commit.committer().email.is_empty()
758 {
759 reasons.push("has no author and/or committer set");
760 }
761 if commit.has_conflict() && !self.allow_conflicts {
762 reasons.push("has conflicts");
763 }
764 if let Some((revset_str, is_private)) = &self.private_commits
765 && is_private(commit.id()).await?
766 {
767 reasons.push("is private");
768 hint = Some(format!("Configured git.private-commits: '{revset_str}'"));
769 }
770 if reasons.is_empty() {
771 continue;
772 }
773 return Ok(Err(RejectedCommitReason {
774 commit,
775 message: reasons.join(" and "),
776 hint,
777 }));
778 }
779
780 // No need to validate ancestors again
781 self.known_heads.extend(new_heads.iter().cloned());
782 Ok(Ok(()))
783 }
784 }
785
786 fn ready_to_push_revset_expression(
787 tx: &WorkspaceCommandTransaction,
788 remote: &RemoteName,
789 ref_updates: &GitPushRefTargets,
790 ) -> Arc<UserRevsetExpression> {
791 let workspace_helper = tx.base_workspace_helper();
792 let repo = workspace_helper.repo();
793 let new_heads = itertools::chain(&ref_updates.bookmarks, &ref_updates.tags)
794 .filter_map(|(_, update)| update.after.clone())
795 .collect_vec();
796 let old_heads = repo
797 .view()
798 .remote_bookmarks(remote)
799 .flat_map(|(_, old_head)| old_head.target.added_ids())
800 .cloned()
801 .collect_vec();
802 RevsetExpression::commits(old_heads).range(&RevsetExpression::commits(new_heads))
803 }
804
805 /// Signs commits before pushing.
806 ///
807 /// Warns about commits that need a signature but are immutable.
808 ///
809 /// Returns the updated list of bookmark names and corresponding
810 /// [`BookmarkPushUpdate`]s.
811 async fn sign_commits_before_push(
812 ui: &Ui,
813 tx: &mut WorkspaceCommandTransaction<'_>,
814 commits_to_push: Arc<UserRevsetExpression>,
815 ref_updates: GitPushRefTargets,
816 ) -> Result<GitPushRefTargets, CommandError> {
817 let mut sign_settings = tx.settings().sign_settings();
818 sign_settings.behavior = SignBehavior::Own;
819 // TODO: make filter condition configurable by revset?
820 let needs_signing = |commit: &Commit| {
821 future::ready(!commit.is_signed() && sign_settings.should_sign(commit.store_commit()))
822 };
823
824 let workspace_helper = tx.base_workspace_helper();
825 let immutable = workspace_helper.env().immutable_expression();
826 let skipped: Vec<Commit> = workspace_helper
827 .attach_revset_evaluator(commits_to_push.intersection(&immutable))
828 .evaluate_to_commits()?
829 .try_filter(needs_signing)
830 .take(11)
831 .try_collect()
832 .await?;
833 if !skipped.is_empty() {
834 let count = if skipped.len() > 10 {
835 "10+".to_owned()
836 } else {
837 skipped.len().to_string()
838 };
839 writeln!(
840 ui.warning_default(),
841 "Skipped signing {count} immutable commits:"
842 )?;
843 let mut formatter = ui.stderr_formatter();
844 print_updated_commits(
845 formatter.as_mut(),
846 &workspace_helper.commit_summary_template(),
847 &skipped,
848 )?;
849 }
850
851 let commit_ids: IndexSet<CommitId> = workspace_helper
852 .attach_revset_evaluator(commits_to_push.minus(&immutable))
853 .evaluate_to_commits()?
854 .try_filter(needs_signing)
855 .map_ok(|commit| commit.id().clone())
856 .try_collect()
857 .await?;
858 if commit_ids.is_empty() {
859 return Ok(ref_updates);
860 }
861
862 let mut old_to_new_commits_map: HashMap<CommitId, CommitId> = HashMap::new();
863 let mut num_rebased_descendants = 0;
864 {
865 let mut progress_writer = ProgressWriter::new(ui, "Signing");
866
867 tx.repo_mut()
868 .transform_descendants(
869 commit_ids.iter().cloned().collect_vec(),
870 async |rewriter: CommitRewriter<'_>| {
871 let old_commit = rewriter.old_commit();
872 let old_commit_id = old_commit.id().clone();
873 if let Some(writer) = &mut progress_writer {
874 writer
875 .display(&short_change_hash(old_commit.change_id()))
876 .ok();
877 }
878 if commit_ids.contains(&old_commit_id) {
879 let commit = rewriter
880 .reparent()
881 .set_sign_behavior(sign_settings.behavior)
882 .write()
883 .await?;
884 old_to_new_commits_map.insert(old_commit_id, commit.id().clone());
885 } else {
886 num_rebased_descendants += 1;
887 let commit = rewriter.reparent().write().await?;
888 old_to_new_commits_map.insert(old_commit_id, commit.id().clone());
889 }
890 Ok(())
891 },
892 )
893 .await?;
894 }
895
896 let map_to_new_commits = |updates: Vec<(RefNameBuf, Diff<Option<CommitId>>)>| {
897 updates
898 .into_iter()
899 .map(|(name, Diff { before, after })| {
900 let after = after.map(|id| old_to_new_commits_map.get(&id).cloned().unwrap_or(id));
901 (name, Diff { before, after })
902 })
903 .collect()
904 };
905 let ref_updates = GitPushRefTargets {
906 bookmarks: map_to_new_commits(ref_updates.bookmarks),
907 tags: map_to_new_commits(ref_updates.tags),
908 };
909
910 if let Some(mut formatter) = ui.status_formatter() {
911 let num_updated_signatures = commit_ids.len();
912 writeln!(
913 formatter,
914 "Updated signatures of {num_updated_signatures} commits."
915 )?;
916 if num_rebased_descendants > 0 {
917 writeln!(
918 formatter,
919 "Rebased {num_rebased_descendants} descendant commits."
920 )?;
921 }
922 }
923
924 Ok(ref_updates)
925 }
926
927 async fn print_commits_ready_to_push(
928 formatter: &mut dyn Formatter,
929 repo: &dyn Repo,
930 ref_updates: &GitPushRefTargets,
931 ) -> Result<(), CommandError> {
932 let to_direction = async |old_target: &CommitId,
933 new_target: &CommitId|
934 -> IndexResult<BookmarkMoveDirection> {
935 assert_ne!(old_target, new_target);
936 if repo.index().is_ancestor(old_target, new_target).await? {
937 Ok(BookmarkMoveDirection::Forward)
938 } else if repo.index().is_ancestor(new_target, old_target).await? {
939 Ok(BookmarkMoveDirection::Backward)
940 } else {
941 Ok(BookmarkMoveDirection::Sideways)
942 }
943 };
944 let describe_update = async |update: &Diff<Option<CommitId>>| -> IndexResult<String> {
945 let desc = match (&update.before, &update.after) {
946 (Some(old_target), Some(new_target)) => {
947 let old = short_commit_hash(old_target);
948 let new = short_commit_hash(new_target);
949 // TODO: People on Discord suggest "... forward by n commits",
950 // possibly "... sideways (X forward, Y back)".
951 match to_direction(old_target, new_target).await? {
952 BookmarkMoveDirection::Forward => {
953 format!("move forward from {old} to {new}")
954 }
955 BookmarkMoveDirection::Backward => {
956 format!("move backward from {old} to {new}")
957 }
958 BookmarkMoveDirection::Sideways => {
959 format!("move sideways from {old} to {new}")
960 }
961 }
962 }
963 (Some(old_target), None) => {
964 format!("delete from {old}", old = short_commit_hash(old_target))
965 }
966 (None, Some(new_target)) => {
967 format!("add to {new}", new = short_commit_hash(new_target))
968 }
969 (None, None) => {
970 panic!("Not pushing any change");
971 }
972 };
973 Ok(desc)
974 };
975
976 // TODO: Add color
977 let kind_updates = [
978 ("bookmark", &ref_updates.bookmarks),
979 ("tag", &ref_updates.tags),
980 ];
981 for (kind, updates) in kind_updates {
982 for (name, update) in updates {
983 let desc = describe_update(update).await?;
984 writeln!(
985 formatter,
986 " {kind}: {name} [{desc}]",
987 name = name.as_symbol()
988 )?;
989 }
990 }
991 Ok(())
992 }
993
994 fn get_default_push_remote(
995 ui: &Ui,
996 workspace_command: &WorkspaceCommandHelper,
997 ) -> Result<RemoteNameBuf, CommandError> {
998 let settings = workspace_command.settings();
999 if let Some(remote) = settings.get_string("git.push").optional()? {
1000 Ok(remote.into())
1001 } else if let Some(remote) = get_single_remote(workspace_command.repo().store())? {
1002 // similar to get_default_fetch_remotes
1003 if remote != DEFAULT_REMOTE {
1004 writeln!(
1005 ui.hint_default(),
1006 "Pushing to the only existing remote: {remote}",
1007 remote = remote.as_symbol()
1008 )?;
1009 }
1010 Ok(remote)
1011 } else {
1012 Ok(DEFAULT_REMOTE.to_owned())
1013 }
1014 }
1015
1016 #[derive(Clone, Debug)]
1017 struct RejectedRefUpdateReason {
1018 message: String,
1019 hint: Option<String>,
1020 }
1021
1022 impl RejectedRefUpdateReason {
1023 fn print(&self, ui: &Ui) -> io::Result<()> {
1024 writeln!(ui.warning_default(), "{}", self.message)?;
1025 if let Some(hint) = &self.hint {
1026 writeln!(ui.hint_default(), "{hint}")?;
1027 }
1028 Ok(())
1029 }
1030 }
1031
1032 impl From<RejectedRefUpdateReason> for CommandError {
1033 fn from(reason: RejectedRefUpdateReason) -> Self {
1034 let RejectedRefUpdateReason { message, hint } = reason;
1035 let mut cmd_err = user_error(message);
1036 cmd_err.extend_hints(hint);
1037 cmd_err
1038 }
1039 }
1040
1041 fn classify_bookmark_update(
1042 remote_symbol: RemoteRefSymbol<'_>,
1043 targets: LocalAndRemoteRef,
1044 allow_new: bool,
1045 allow_delete: bool,
1046 ) -> Result<Option<Diff<Option<CommitId>>>, RejectedRefUpdateReason> {
1047 let push_action = classify_ref_push_action(targets);
1048 match push_action {
1049 RefPushAction::AlreadyMatches => Ok(None),
1050 RefPushAction::LocalConflicted => Err(RejectedRefUpdateReason {
1051 message: format!(
1052 "Bookmark {name} is conflicted",
1053 name = remote_symbol.name.as_symbol()
1054 ),
1055 hint: Some(
1056 "Run `jj bookmark list` to inspect, and use `jj bookmark set` to fix it up."
1057 .to_owned(),
1058 ),
1059 }),
1060 RefPushAction::RemoteConflicted => Err(RejectedRefUpdateReason {
1061 message: format!("Bookmark {remote_symbol} is conflicted"),
1062 hint: Some("Run `jj git fetch` to update the conflicted remote bookmark.".to_owned()),
1063 }),
1064 RefPushAction::RemoteUntracked => Err(RejectedRefUpdateReason {
1065 message: format!("Non-tracking remote bookmark {remote_symbol} exists"),
1066 hint: Some(format!(
1067 "Run `jj bookmark track {remote_symbol}` to import the remote bookmark."
1068 )),
1069 }),
1070 RefPushAction::Update(_) if !targets.remote_ref.is_tracked() && !allow_new => {
1071 Err(RejectedRefUpdateReason {
1072 message: format!("Refusing to create new remote bookmark {remote_symbol}"),
1073 hint: Some(format!(
1074 "Run `jj bookmark track {remote_symbol}` and try again."
1075 )),
1076 })
1077 }
1078 RefPushAction::Update(update) if update.after.is_none() && !allow_delete => {
1079 Err(RejectedRefUpdateReason {
1080 message: format!(
1081 "Refusing to push deleted bookmark {name}",
1082 name = remote_symbol.name.as_symbol(),
1083 ),
1084 hint: Some(
1085 "Push deleted bookmarks with --deleted or forget the bookmark to suppress \
1086 this warning."
1087 .to_owned(),
1088 ),
1089 })
1090 }
1091 RefPushAction::Update(update) => Ok(Some(update)),
1092 }
1093 }
1094
1095 fn classify_tag_update(
1096 remote_symbol: RemoteRefSymbol<'_>,
1097 targets: LocalAndRemoteRef<'_>,
1098 allow_new: bool,
1099 allow_delete: bool,
1100 ) -> Result<Option<Diff<Option<CommitId>>>, RejectedRefUpdateReason> {
1101 let push_action = classify_ref_push_action(targets);
1102 match push_action {
1103 RefPushAction::AlreadyMatches => Ok(None),
1104 RefPushAction::LocalConflicted => Err(RejectedRefUpdateReason {
1105 message: format!(
1106 "Tag {name} is conflicted",
1107 name = remote_symbol.name.as_symbol()
1108 ),
1109 hint: Some(
1110 "Run `jj tag list` to inspect, and use `jj tag set` to fix it up.".to_owned(),
1111 ),
1112 }),
1113 RefPushAction::RemoteConflicted => Err(RejectedRefUpdateReason {
1114 message: format!("Tag {remote_symbol} is conflicted"),
1115 hint: Some("Run `jj git fetch` to update the conflicted remote tag.".to_owned()),
1116 }),
1117 RefPushAction::RemoteUntracked => Err(RejectedRefUpdateReason {
1118 message: format!("Non-tracking remote tag {remote_symbol} exists"),
1119 // No suggestion because tags are tracked by default
1120 hint: None,
1121 }),
1122 RefPushAction::Update(_) if !targets.remote_ref.is_tracked() && !allow_new => {
1123 Err(RejectedRefUpdateReason {
1124 message: format!("Refusing to create new remote tag {remote_symbol}"),
1125 hint: Some(format!("Run `jj tag track {remote_symbol}` and try again.")),
1126 })
1127 }
1128 RefPushAction::Update(update) if update.after.is_none() && !allow_delete => {
1129 Err(RejectedRefUpdateReason {
1130 message: format!(
1131 "Refusing to push deleted tag {name}",
1132 name = remote_symbol.name.as_symbol(),
1133 ),
1134 // TODO: suggest `jj tag forget`?
1135 hint: Some("Push deleted tags with --deleted.".to_owned()),
1136 })
1137 }
1138 RefPushAction::Update(update) => Ok(Some(update)),
1139 }
1140 }
1141
1142 fn ensure_new_bookmark_name(repo: &dyn Repo, name: &RefName) -> Result<(), CommandError> {
1143 let symbol = name.as_symbol();
1144 if repo.view().get_local_bookmark(name).is_present() {
1145 return Err(
1146 user_error(format!("Bookmark already exists: {symbol}")).hinted(format!(
1147 "Use 'jj bookmark move' to move it, and 'jj git push -b {symbol}' to push it"
1148 )),
1149 );
1150 }
1151 if has_tracked_remote_bookmarks(repo, name) {
1152 return Err(user_error(format!(
1153 "Tracked remote bookmarks exist for deleted bookmark: {symbol}"
1154 ))
1155 .hinted(format!(
1156 "Use `jj bookmark set` to recreate the local bookmark. Run `jj bookmark untrack \
1157 {symbol}` to disassociate them."
1158 )));
1159 }
1160 Ok(())
1161 }
1162
1163 fn parse_named_bookmark(name_revision: &str) -> Result<(RefNameBuf, RevisionArg), CommandError> {
1164 let hint = "For example, `--named myfeature=@` is valid syntax";
1165 let Some((name_str, revision_str)) = name_revision.split_once('=') else {
1166 return Err(cli_error(format!(
1167 "Argument '{name_revision}' must include '=' and have the form NAME=REVISION"
1168 ))
1169 .hinted(hint));
1170 };
1171 if name_str.is_empty() || revision_str.is_empty() {
1172 return Err(cli_error(format!(
1173 "Argument '{name_revision}' must have the form NAME=REVISION, with both NAME and \
1174 REVISION non-empty"
1175 ))
1176 .hinted(hint));
1177 }
1178 let name = parse_bookmark_name(name_str).map_err(|err| {
1179 cli_error_with_message(
1180 format!("Could not parse '{name_str}' as a bookmark name"),
1181 err,
1182 )
1183 .hinted(hint)
1184 })?;
1185 Ok((name, RevisionArg::from(revision_str.to_owned())))
1186 }
1187
1188 /// Creates bookmarks based on the change IDs.
1189 async fn create_change_bookmarks(
1190 ui: &Ui,
1191 tx: &mut WorkspaceCommandTransaction<'_>,
1192 changes: &[RevisionArg],
1193 ) -> Result<Vec<RefNameBuf>, CommandError> {
1194 if changes.is_empty() {
1195 // NOTE: we don't want resolve_some_revsets_default_single to fail if the
1196 // changes argument wasn't provided, so handle that
1197 return Ok(vec![]);
1198 }
1199
1200 let all_commits = try_join_all(
1201 tx.base_workspace_helper()
1202 .resolve_some_revsets(ui, changes)
1203 .await?
1204 .iter()
1205 .map(|id| tx.repo().store().get_commit_async(id)),
1206 )
1207 .await?;
1208 let bookmark_names: Vec<_> = {
1209 let template_text = tx.settings().get_string("templates.git_push_bookmark")?;
1210 let template = tx.parse_commit_template(ui, &template_text)?;
1211 all_commits
1212 .iter()
1213 .map(|commit| {
1214 let output = template.format_plain_text(commit);
1215 let name = String::from_utf8(output).map_err(|err| {
1216 user_error_with_message("Invalid character in bookmark name", err.utf8_error())
1217 })?;
1218 if name.is_empty() {
1219 return Err(user_error("Empty bookmark name generated"));
1220 }
1221 Ok(RefNameBuf::from(name))
1222 })
1223 .try_collect()?
1224 };
1225
1226 for (commit, name) in iter::zip(&all_commits, &bookmark_names) {
1227 let target = RefTarget::normal(commit.id().clone());
1228 if tx.repo().view().get_local_bookmark(name) == &target {
1229 // Existing bookmark pointing to the commit, which is allowed
1230 continue;
1231 }
1232 ensure_new_bookmark_name(tx.repo(), name)?;
1233 writeln!(
1234 ui.status(),
1235 "Creating bookmark {name} for revision {change_id:.12}",
1236 name = name.as_symbol(),
1237 change_id = commit.change_id()
1238 )?;
1239 tx.repo_mut().set_local_bookmark_target(name, target);
1240 }
1241 Ok(bookmark_names)
1242 }
1243
1244 fn find_bookmarks_to_push<'a>(
1245 ui: &Ui,
1246 view: &'a View,
1247 bookmark_patterns: &[String],
1248 remote: &RemoteName,
1249 ) -> Result<Vec<(&'a RefName, LocalAndRemoteRef<'a>)>, CommandError> {
1250 let bookmark_expr = parse_union_name_patterns(ui, bookmark_patterns)?;
1251 let bookmark_matcher = bookmark_expr.to_matcher();
1252 let matching_bookmarks = view
1253 .local_remote_bookmarks_matching(&bookmark_matcher, remote)
1254 .filter(|(_, targets)| {
1255 // If the remote exists but is not tracked, the absent local shouldn't
1256 // be considered a deleted bookmark.
1257 targets.local_target.is_present() || targets.remote_ref.is_tracked()
1258 })
1259 .collect();
1260 let mut unmatched_names = bookmark_expr
1261 .exact_strings()
1262 .map(RefName::new)
1263 .filter(|&name| {
1264 let symbol = name.to_remote_symbol(remote);
1265 view.get_local_bookmark(name).is_absent()
1266 && !view.get_remote_bookmark(symbol).is_tracked()
1267 })
1268 .peekable();
1269 if unmatched_names.peek().is_some() {
1270 writeln!(
1271 ui.warning_default(),
1272 "No matching bookmarks for names: {}",
1273 unmatched_names.map(|name| name.as_symbol()).join(", ")
1274 )?;
1275 }
1276 Ok(matching_bookmarks)
1277 }
1278
1279 fn find_tags_to_push<'a>(
1280 ui: &Ui,
1281 view: &'a View,
1282 tag_patterns: &[String],
1283 remote: &RemoteName,
1284 ) -> Result<Vec<(&'a RefName, LocalAndRemoteRef<'a>)>, CommandError> {
1285 let tag_expr = parse_union_name_patterns(ui, tag_patterns)?;
1286 let tag_matcher = tag_expr.to_matcher();
1287 let matching_tags = view
1288 .local_remote_tags_matching(&tag_matcher, remote)
1289 .filter(|(_, targets)| {
1290 // If the remote exists but is not tracked, the absent local shouldn't
1291 // be considered a deleted tag.
1292 targets.local_target.is_present() || targets.remote_ref.is_tracked()
1293 })
1294 .collect();
1295 let mut unmatched_names = tag_expr
1296 .exact_strings()
1297 .map(RefName::new)
1298 .filter(|&name| {
1299 let symbol = name.to_remote_symbol(remote);
1300 view.get_local_tag(name).is_absent() && !view.get_remote_tag(symbol).is_tracked()
1301 })
1302 .peekable();
1303 if unmatched_names.peek().is_some() {
1304 writeln!(
1305 ui.warning_default(),
1306 "No matching tags for names: {}",
1307 unmatched_names.map(|name| name.as_symbol()).join(", ")
1308 )?;
1309 }
1310 Ok(matching_tags)
1311 }
1312
1313 async fn find_default_target_revisions(
1314 ui: &Ui,
1315 workspace_command: &WorkspaceCommandHelper,
1316 remote: &RemoteName,
1317 ) -> Result<HashSet<CommitId>, CommandError> {
1318 // remote_bookmarks(remote=<remote>)..@
1319 let workspace_name = workspace_command.workspace_name();
1320 let expression = RevsetExpression::remote_bookmarks(
1321 RemoteRefSymbolExpression {
1322 name: StringExpression::all(),
1323 remote: StringExpression::exact(remote),
1324 },
1325 None,
1326 )
1327 .range(&RevsetExpression::working_copy(workspace_name.to_owned()))
1328 .intersection(
1329 &RevsetExpression::bookmarks(StringExpression::all())
1330 .union(&RevsetExpression::tags(StringExpression::all())),
1331 );
1332 let commit_ids = workspace_command
1333 .attach_revset_evaluator(expression)
1334 .evaluate_to_commit_ids()?
1335 .peekable();
1336 let mut commit_ids = std::pin::pin!(commit_ids);
1337 if commit_ids.as_mut().peek().await.is_none() {
1338 writeln!(
1339 ui.warning_default(),
1340 "No bookmarks/tags found in the default push revset: \
1341 remote_bookmarks(remote={remote})..@",
1342 remote = remote.as_symbol()
1343 )?;
1344 }
1345 Ok(commit_ids.try_collect().await?)
1346 }
1347
1348 async fn find_target_revisions(
1349 ui: &Ui,
1350 workspace_command: &WorkspaceCommandHelper,
1351 revisions: &[RevisionArg],
1352 ) -> Result<HashSet<CommitId>, CommandError> {
1353 let mut revision_commit_ids = HashSet::new();
1354 for rev_arg in revisions {
1355 let mut expression = workspace_command.parse_revset(ui, rev_arg)?;
1356 expression.intersect_with(
1357 &RevsetExpression::bookmarks(StringExpression::all())
1358 .union(&RevsetExpression::tags(StringExpression::all())),
1359 );
1360 let commit_ids = expression.evaluate_to_commit_ids()?.peekable();
1361 let mut commit_ids = std::pin::pin!(commit_ids);
1362 if commit_ids.as_mut().as_mut().peek().await.is_none() {
1363 writeln!(
1364 ui.warning_default(),
1365 "No bookmarks/tags point to the specified revisions: {rev_arg}"
1366 )?;
1367 }
1368 while let Some(commit_id) = commit_ids.try_next().await? {
1369 revision_commit_ids.insert(commit_id);
1370 }
1371 }
1372 Ok(revision_commit_ids)
1373 }
1374
1375 fn matches_local_target(targets: LocalAndRemoteRef<'_>, revisions: &HashSet<CommitId>) -> bool {
1376 let mut local_ids = targets.local_target.added_ids();
1377 local_ids.any(|id| revisions.contains(id))
1378 }
1379
1380 pub fn is_push_operation(op: &Operation) -> bool {
1381 op.metadata().description.starts_with(TX_DESC_PUSH)
1382 }