Debian Codegraph @

cli/src/commands/bookmark/move.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 clap_complete::ArgValueCandidates;
16 use clap_complete::ArgValueCompleter;
17 use itertools::Itertools as _;
18 use jj_lib::iter_util::fallible_any;
19 use jj_lib::iter_util::fallible_find;
20 use jj_lib::object_id::ObjectId as _;
21 use jj_lib::op_store::RefTarget;
22 use jj_lib::str_util::StringExpression;
23
24 use super::is_fast_forward;
25 use super::warn_unmatched_local_bookmarks;
26 use crate::cli_util::CommandHelper;
27 use crate::cli_util::RevisionArg;
28 use crate::command_error::CommandError;
29 use crate::command_error::user_error;
30 use crate::complete;
31 use crate::revset_util::parse_union_name_patterns;
32 use crate::ui::Ui;
33
34 /// Move existing bookmarks to target revision
35 ///
36 /// Unlike `jj bookmark set`, this command cannot create new bookmarks.
37 ///
38 /// If bookmark names are given, the specified bookmarks will be updated to
39 /// point to the target revision.
40 ///
41 /// If `--from` options are given, bookmarks currently pointing to the
42 /// specified revisions will be updated. The bookmarks can also be filtered by
43 /// names.
44 #[derive(clap::Args, Clone, Debug)]
45 #[command(group(clap::ArgGroup::new("source").multiple(true).required(true)))]
46 pub struct BookmarkMoveArgs {
47 /// Move bookmarks matching the given name patterns
48 ///
49 /// By default, the specified pattern matches bookmark names with glob
50 /// syntax. You can also use other [string pattern syntax].
51 ///
52 /// [string pattern syntax]:
53 /// https://docs.jj-vcs.dev/latest/revsets/#string-patterns
54 #[arg(group = "source")]
55 #[arg(add = ArgValueCandidates::new(complete::local_bookmarks))]
56 names: Option<Vec<String>>,
57
58 /// Move bookmarks from the given revisions
59 #[arg(long, short, group = "source", value_name = "REVSETS")]
60 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
61 from: Vec<RevisionArg>,
62
63 /// Move bookmarks to this revision
64 #[arg(long, short, default_value = "@", value_name = "REVSET")]
65 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
66 to: RevisionArg,
67
68 /// Allow moving bookmarks backwards or sideways
69 #[arg(long, short = 'B')]
70 allow_backwards: bool,
71 }
72
73 pub async fn cmd_bookmark_move(
74 ui: &mut Ui,
75 command: &CommandHelper,
76 args: &BookmarkMoveArgs,
77 ) -> Result<(), CommandError> {
78 let mut workspace_command = command.workspace_helper(ui).await?;
79 let repo = workspace_command.repo().clone();
80 let target_commit = workspace_command.resolve_single_rev(ui, &args.to).await?;
81 let matched_bookmarks = {
82 let is_source_commit = if !args.from.is_empty() {
83 Some(
84 workspace_command
85 .parse_union_revsets(ui, &args.from)?
86 .evaluate()?
87 .containing_fn(),
88 )
89 } else {
90 None
91 };
92 let is_source_ref =
93 async |target: &RefTarget| -> Result<bool, CommandError> {
94 match &is_source_commit {
95 Some(is_source_commit) => Ok(fallible_any(target.added_ids(), async |old| {
96 is_source_commit(old).await
97 })
98 .await?),
99 None => Ok(true),
100 }
101 };
102 let name_expr = match &args.names {
103 Some(texts) => parse_union_name_patterns(ui, texts)?,
104 None => StringExpression::all(),
105 };
106 let name_matcher = name_expr.to_matcher();
107 let mut bookmarks = vec![];
108 for (name, target) in repo.view().local_bookmarks_matching(&name_matcher) {
109 if is_source_ref(target).await? {
110 bookmarks.push((name, target));
111 }
112 }
113 warn_unmatched_local_bookmarks(ui, repo.view(), &name_expr)?;
114 // Noop matches aren't errors, but should be excluded from stats.
115 bookmarks.retain(|(_, old_target)| old_target.as_normal() != Some(target_commit.id()));
116 bookmarks
117 };
118
119 if matched_bookmarks.is_empty() {
120 writeln!(ui.status(), "No bookmarks to update.")?;
121 return Ok(());
122 }
123
124 if !args.allow_backwards
125 && let Some((name, _)) = fallible_find(
126 matched_bookmarks.iter(),
127 async |(_, old_target)| -> Result<_, CommandError> {
128 let is_ff = is_fast_forward(repo.as_ref(), old_target, target_commit.id()).await?;
129 Ok(!is_ff)
130 },
131 )
132 .await?
133 {
134 return Err(user_error(format!(
135 "Refusing to move bookmark backwards or sideways: {name}",
136 name = name.as_symbol()
137 ))
138 .hinted("Use --allow-backwards to allow it."));
139 }
140 if target_commit.is_discardable(repo.as_ref()).await? {
141 writeln!(ui.warning_default(), "Target revision is empty.")?;
142 }
143
144 let mut tx = workspace_command.start_transaction();
145 for (name, _) in &matched_bookmarks {
146 tx.repo_mut()
147 .set_local_bookmark_target(name, RefTarget::normal(target_commit.id().clone()));
148 }
149
150 if let Some(mut formatter) = ui.status_formatter() {
151 write!(formatter, "Moved {} bookmarks to ", matched_bookmarks.len())?;
152 tx.write_commit_summary(formatter.as_mut(), &target_commit)?;
153 writeln!(formatter)?;
154 }
155 if matched_bookmarks.len() > 1 && args.names.is_none() {
156 writeln!(
157 ui.hint_default(),
158 "Specify bookmark by name to update just one of the bookmarks."
159 )?;
160 }
161
162 tx.finish(
163 ui,
164 format!(
165 "point bookmark {names} to commit {id}",
166 names = matched_bookmarks
167 .iter()
168 .map(|(name, _)| name.as_symbol())
169 .join(", "),
170 id = target_commit.id().hex()
171 ),
172 )
173 .await?;
174 Ok(())
175 }