| 1 |
// Copyright 2024 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::fmt::Debug; |
| 17 |
use std::io::Write as _; |
| 18 |
use std::sync::Arc; |
| 19 |
|
| 20 |
use bstr::BStr; |
| 21 |
use futures::TryStreamExt as _; |
| 22 |
use jj_lib::backend::CommitId; |
| 23 |
use jj_lib::commit::Commit; |
| 24 |
use jj_lib::git; |
| 25 |
use jj_lib::git::GitPushOptions; |
| 26 |
use jj_lib::git::GitRefUpdate; |
| 27 |
use jj_lib::git::GitSubprocessOptions; |
| 28 |
use jj_lib::merge::Diff; |
| 29 |
use jj_lib::object_id::ObjectId as _; |
| 30 |
use jj_lib::repo::Repo as _; |
| 31 |
use jj_lib::revset::RevsetExpression; |
| 32 |
use jj_lib::settings::UserSettings; |
| 33 |
use jj_lib::store::Store; |
| 34 |
use jj_lib::trailer::Trailer; |
| 35 |
use jj_lib::trailer::parse_description_trailers; |
| 36 |
use percent_encoding::NON_ALPHANUMERIC; |
| 37 |
use percent_encoding::utf8_percent_encode; |
| 38 |
|
| 39 |
use crate::cli_util::CommandHelper; |
| 40 |
use crate::cli_util::RevisionArg; |
| 41 |
use crate::cli_util::short_change_hash; |
| 42 |
use crate::command_error::CommandError; |
| 43 |
use crate::command_error::internal_error; |
| 44 |
use crate::command_error::user_error; |
| 45 |
use crate::command_error::user_error_with_message; |
| 46 |
use crate::git_util::GitSubprocessUi; |
| 47 |
use crate::git_util::print_push_stats; |
| 48 |
use crate::ui::Ui; |
| 49 |
|
| 50 |
/// Upload changes to Gerrit for code review, or update existing changes |
| 51 |
/// |
| 52 |
/// Uploading a set of revisions to Gerrit creates a single "change" for each |
| 53 |
/// revision included in the revset and all their mutable ancestors. These |
| 54 |
/// changes will then be available for review on your Gerrit instance. |
| 55 |
/// |
| 56 |
/// If a change already exists for a given revision (i.e. it contains the |
| 57 |
/// same `Change-Id`), this command will update the contents of the existing |
| 58 |
/// change to match. |
| 59 |
/// |
| 60 |
/// Note: Any commit in the given revset that does not have a `Change-Id` |
| 61 |
/// trailer will have one generated based on the Jujutsu change ID. This trailer |
| 62 |
/// is only added to the uploaded commit, which means the resulting commit ID |
| 63 |
/// uploaded to Gerrit may not match your local commit ID. As a result, you may |
| 64 |
/// encounter divergence when you fetch a merged change into your local repo. To |
| 65 |
/// address this, you can abandon your local change or rebase it on top of trunk |
| 66 |
/// with `jj rebase --skip-emptied ...`, which will resolve the divergence. |
| 67 |
/// Alternatively, you can add the following to your Jujutsu config to add |
| 68 |
/// `Change-Id` trailers to your local commits automatically before `jj gerrit |
| 69 |
/// upload` does: |
| 70 |
/// ```toml |
| 71 |
/// [templates] |
| 72 |
/// commit_trailers = ''' |
| 73 |
/// if( |
| 74 |
/// !trailers.contains_key("Change-Id"), |
| 75 |
/// format_gerrit_change_id_trailer(self) |
| 76 |
/// ) |
| 77 |
/// ''' |
| 78 |
/// ``` |
| 79 |
/// |
| 80 |
/// Also see the [Jujutsu docs on Gerrit]. |
| 81 |
/// |
| 82 |
/// [Jujutsu docs on Gerrit]: https://docs.jj-vcs.dev/latest/gerrit |
| 83 |
#[derive(clap::Args, Clone, Debug, Default)] |
| 84 |
#[command(verbatim_doc_comment)] |
| 85 |
pub struct UploadArgs { |
| 86 |
/// The revisions to upload to Gerrit |
| 87 |
/// |
| 88 |
/// All mutable ancestors of specified revisions will also be pushed. This |
| 89 |
/// means that `jj gerrit upload -r foo` is equivalent to `jj gerrit upload |
| 90 |
/// -r 'mutable()::foo'`. |
| 91 |
/// |
| 92 |
/// If this is not provided, `@` will be uploaded if it has a description, |
| 93 |
/// and `@-` will be uploaded otherwise. |
| 94 |
#[arg(long = "revision", short, value_name = "REVSETS", alias = "revision")] |
| 95 |
revisions: Vec<RevisionArg>, |
| 96 |
|
| 97 |
/// The location where your changes are intended to land |
| 98 |
/// |
| 99 |
/// This should be a branch on the remote. The default is the |
| 100 |
/// `gerrit.default-remote-branch` setting. |
| 101 |
#[arg(long, short = 'b')] |
| 102 |
remote_branch: Option<String>, |
| 103 |
|
| 104 |
/// The Gerrit remote to push to |
| 105 |
/// |
| 106 |
/// This can point to any configured Git remote, or can be a full SSH URL. |
| 107 |
/// The default is the `gerrit.default-remote` setting. |
| 108 |
#[arg(long)] |
| 109 |
remote: Option<String>, |
| 110 |
|
| 111 |
/// Only display what will change on the remote; do not push changes to |
| 112 |
/// Gerrit |
| 113 |
#[arg(long, short = 'n')] |
| 114 |
dry_run: bool, |
| 115 |
|
| 116 |
// The following flags are options Gerrit supports during upload. |
| 117 |
// They are documented at |
| 118 |
// https://gerrit-review.googlesource.com/Documentation/user-upload.html. |
| 119 |
/// Add these emails as a reviewer (can be repeated) |
| 120 |
#[arg(long)] |
| 121 |
reviewer: Vec<String>, |
| 122 |
|
| 123 |
/// CC these emails on the change (can be repeated) |
| 124 |
#[arg(long)] |
| 125 |
cc: Vec<String>, |
| 126 |
|
| 127 |
/// Add the following labels configured by Gerrit (can be repeated) |
| 128 |
/// |
| 129 |
/// Each label can have a suffix of the value to set, such as "+2". The |
| 130 |
/// default is "+1" if no value is set. |
| 131 |
/// |
| 132 |
/// Note that Gerrit silently ignores labels not present on your Gerrit |
| 133 |
/// host. |
| 134 |
/// |
| 135 |
/// Examples: |
| 136 |
/// - `--label=Commit-Queue` will set the `Commit-Queue` label to +1. |
| 137 |
/// - `--label=Commit-Queue+2` will set it to +2. |
| 138 |
#[arg(long, short, verbatim_doc_comment)] |
| 139 |
label: Vec<String>, |
| 140 |
|
| 141 |
/// Apply a topic to the change |
| 142 |
/// |
| 143 |
/// Changes can be grouped by topic, and Gerrit can be configured to submit |
| 144 |
/// all changes in a topic together in a single click. |
| 145 |
/// |
| 146 |
/// See https://gerrit-review.googlesource.com/Documentation/intro-user.html#topics. |
| 147 |
#[arg(long)] |
| 148 |
topic: Option<String>, |
| 149 |
|
| 150 |
/// Apply a hashtag to the change (can be repeated) |
| 151 |
/// |
| 152 |
/// Hashtags are freeform strings associated with a change, like on social |
| 153 |
/// media platforms. Similar to topics, hashtags can be used to group |
| 154 |
/// related changes together, and to search using the `hashtag:` operator. |
| 155 |
/// Unlike topics, a change can have multiple hashtags, and they are only |
| 156 |
/// used for informational grouping. Changes with the same hashtags are |
| 157 |
/// not necessarily submitted together. |
| 158 |
/// |
| 159 |
/// See https://gerrit-review.googlesource.com/Documentation/intro-user.html#hashtags. |
| 160 |
#[arg(long)] |
| 161 |
hashtag: Vec<String>, |
| 162 |
|
| 163 |
/// The description for the patch set |
| 164 |
#[arg(long, short)] |
| 165 |
message: Option<String>, |
| 166 |
|
| 167 |
/// Push the change as a change edit |
| 168 |
/// |
| 169 |
/// To push a change edit the underlying change needs to already exist on |
| 170 |
/// the Gerrit server. Change edits don't immediately create a new patch |
| 171 |
/// set, but need to be published from the web UI first. There can only be |
| 172 |
/// one edit for each change. Pushing a new change edit will replace the |
| 173 |
/// previous one. |
| 174 |
#[arg(long)] |
| 175 |
edit: bool, |
| 176 |
|
| 177 |
/// Mark the change as WIP (work in progress) |
| 178 |
/// |
| 179 |
/// See https://gerrit-review.googlesource.com/Documentation/intro-user.html#wip. |
| 180 |
#[arg(long)] |
| 181 |
wip: bool, |
| 182 |
|
| 183 |
/// Mark the change as ready (no longer work in progress) |
| 184 |
#[arg(long)] |
| 185 |
ready: bool, |
| 186 |
|
| 187 |
/// Mark the change as private |
| 188 |
/// |
| 189 |
/// See https://gerrit-review.googlesource.com/Documentation/intro-user.html#private-changes. |
| 190 |
#[arg(long)] |
| 191 |
private: bool, |
| 192 |
|
| 193 |
/// Unmark the change as private |
| 194 |
#[arg(long)] |
| 195 |
remove_private: bool, |
| 196 |
|
| 197 |
/// Publish draft comments for the given change |
| 198 |
#[arg(long)] |
| 199 |
publish_comments: bool, |
| 200 |
|
| 201 |
/// Do not publish draft comments for the given change |
| 202 |
/// |
| 203 |
/// This is only useful if the user has configured Gerrit to publish |
| 204 |
/// comments by default. |
| 205 |
#[arg(long)] |
| 206 |
no_publish_comments: bool, |
| 207 |
|
| 208 |
/// Who to email notifications to (defaults to all) |
| 209 |
#[arg(long, value_enum)] |
| 210 |
notify: Option<EmailNotification>, |
| 211 |
|
| 212 |
/// Directly submit the changes, bypassing code review |
| 213 |
#[arg(long)] |
| 214 |
submit: bool, |
| 215 |
|
| 216 |
/// When --submit is provided, skip performing validations |
| 217 |
#[arg(long)] |
| 218 |
skip_validation: bool, |
| 219 |
|
| 220 |
/// Create a new change, even if the change has already been merged |
| 221 |
#[arg(long)] |
| 222 |
merged: bool, |
| 223 |
|
| 224 |
/// Do not modify the attention set upon uploading |
| 225 |
#[arg(long)] |
| 226 |
ignore_attention_set: bool, |
| 227 |
|
| 228 |
/// The deadline after which the push should be aborted |
| 229 |
#[arg(long)] |
| 230 |
deadline: Option<String>, |
| 231 |
|
| 232 |
/// Send the following custom keyed values to Gerrit (can be repeated) |
| 233 |
/// |
| 234 |
/// See https://gerrit-review.googlesource.com/Documentation/user-upload.html#custom_keyed_values |
| 235 |
#[arg(long)] |
| 236 |
custom: Vec<String>, |
| 237 |
|
| 238 |
/// Send a `git push -o` option (can be repeated) |
| 239 |
#[arg(long, short)] |
| 240 |
option: Vec<String>, |
| 241 |
|
| 242 |
/// For debugging Gerrit |
| 243 |
/// |
| 244 |
/// See https://gerrit-review.googlesource.com/Documentation/user-upload.html#trace |
| 245 |
#[arg(long)] |
| 246 |
trace: Option<String>, |
| 247 |
// Note: An option "message" exists on Gerrit hosts. It is currently not |
| 248 |
// implemented because it could be easy to confuse a "-m"/"--message" flag |
| 249 |
// for a patch set with a message for a commit description. |
| 250 |
// We can consider adding it later, but that will involve a more |
| 251 |
// comprehensive discussion about the option name. |
| 252 |
// See https://gerrit-review.googlesource.com/Documentation/user-upload.html#patch_set_description |
| 253 |
} |
| 254 |
|
| 255 |
/// Which emails receive an email notification about an update to the change. |
| 256 |
#[derive(clap::ValueEnum, Clone, Debug)] |
| 257 |
#[value(rename_all = "kebab_case")] |
| 258 |
pub enum EmailNotification { |
| 259 |
/// No emails |
| 260 |
None, |
| 261 |
/// Only the change owner is notified. |
| 262 |
Owner, |
| 263 |
/// Only the change owner and reviewers will be notified. |
| 264 |
OwnerReviewers, |
| 265 |
/// All relevant users, including owner, reviewers, cc'd, users that have |
| 266 |
/// starred the change, and users who have configured a watch on files in |
| 267 |
/// the change. |
| 268 |
All, |
| 269 |
} |
| 270 |
|
| 271 |
fn calculate_push_remote( |
| 272 |
store: &Arc<Store>, |
| 273 |
settings: &UserSettings, |
| 274 |
remote: Option<&str>, |
| 275 |
) -> Result<String, CommandError> { |
| 276 |
let git_repo = git::get_git_repo(store)?; // will fail if not a git repo |
| 277 |
let remotes = git_repo.remote_names(); |
| 278 |
|
| 279 |
// If --remote was provided, use that |
| 280 |
if let Some(remote) = remote { |
| 281 |
if remotes.contains(BStr::new(&remote)) { |
| 282 |
return Ok(remote.to_string()); |
| 283 |
} |
| 284 |
return Err(user_error(format!( |
| 285 |
"The remote '{remote}' (specified via `--remote`) does not exist", |
| 286 |
))); |
| 287 |
} |
| 288 |
|
| 289 |
// If the Gerrit-specific config was set, use that |
| 290 |
if let Ok(remote) = settings.get_string("gerrit.default-remote") { |
| 291 |
if remotes.contains(BStr::new(&remote)) { |
| 292 |
return Ok(remote); |
| 293 |
} |
| 294 |
return Err(user_error(format!( |
| 295 |
"The remote '{remote}' (configured via `gerrit.default-remote`) does not exist", |
| 296 |
))); |
| 297 |
} |
| 298 |
|
| 299 |
// If a general push remote was configured, use that |
| 300 |
if let Some(remote) = git_repo.remote_default_name(gix::remote::Direction::Push) { |
| 301 |
return Ok(remote.to_string()); |
| 302 |
} |
| 303 |
|
| 304 |
// If there is a Git remote called "gerrit", use that |
| 305 |
if remotes.iter().any(|r| r == "gerrit") { |
| 306 |
return Ok("gerrit".to_owned()); |
| 307 |
} |
| 308 |
|
| 309 |
// Otherwise error out |
| 310 |
Err(user_error( |
| 311 |
"No remote specified, and no 'gerrit' remote was found", |
| 312 |
)) |
| 313 |
} |
| 314 |
|
| 315 |
/// Determine what Gerrit ref and remote to use. The logic is: |
| 316 |
/// |
| 317 |
/// 1. If the user specifies `--remote-branch branch`, use that |
| 318 |
/// 2. If the user has 'gerrit.default-remote-branch' configured, use that |
| 319 |
/// 3. Otherwise, bail out |
| 320 |
fn calculate_push_ref( |
| 321 |
settings: &UserSettings, |
| 322 |
remote_branch: Option<String>, |
| 323 |
) -> Result<String, CommandError> { |
| 324 |
// case 1 |
| 325 |
if let Some(remote_branch) = remote_branch { |
| 326 |
return Ok(remote_branch); |
| 327 |
} |
| 328 |
|
| 329 |
// case 2 |
| 330 |
if let Ok(branch) = settings.get_string("gerrit.default-remote-branch") { |
| 331 |
return Ok(branch); |
| 332 |
} |
| 333 |
|
| 334 |
// case 3 |
| 335 |
Err(user_error( |
| 336 |
"No target branch specified via --remote-branch, and no 'gerrit.default-remote-branch' \ |
| 337 |
was found", |
| 338 |
)) |
| 339 |
} |
| 340 |
|
| 341 |
fn encode_message(message: &str) -> String { |
| 342 |
utf8_percent_encode(message, NON_ALPHANUMERIC).to_string() |
| 343 |
} |
| 344 |
|
| 345 |
fn push_options(args: &UploadArgs) -> Result<Vec<String>, CommandError> { |
| 346 |
for c in &args.custom { |
| 347 |
if !c.contains(':') { |
| 348 |
return Err(user_error(format!( |
| 349 |
"Custom values must be of the form 'key:value'. Got {c}" |
| 350 |
))); |
| 351 |
} |
| 352 |
} |
| 353 |
if args.wip && args.ready { |
| 354 |
return Err(user_error("--wip and --ready are mutually exclusive")); |
| 355 |
} |
| 356 |
if args.private && args.remove_private { |
| 357 |
return Err(user_error( |
| 358 |
"--private and --remove-private are mutually exclusive", |
| 359 |
)); |
| 360 |
} |
| 361 |
if args.publish_comments && args.no_publish_comments { |
| 362 |
return Err(user_error( |
| 363 |
"--publish-comments and --no-publish-comments are mutually exclusive", |
| 364 |
)); |
| 365 |
} |
| 366 |
if args.skip_validation && !args.submit { |
| 367 |
return Err(user_error( |
| 368 |
"--skip-validation is only supported for --submit", |
| 369 |
)); |
| 370 |
} |
| 371 |
|
| 372 |
// Note: invalid push options will be ignored rather than erroring out, so |
| 373 |
// we need to be careful when adding new options. |
| 374 |
Ok([ |
| 375 |
args.notify.clone().map(|arg| { |
| 376 |
( |
| 377 |
"notify", |
| 378 |
match arg { |
| 379 |
EmailNotification::None => "NONE", |
| 380 |
EmailNotification::All => "ALL", |
| 381 |
EmailNotification::Owner => "OWNER", |
| 382 |
EmailNotification::OwnerReviewers => "OWNER_REVIEWERS", |
| 383 |
} |
| 384 |
.to_string(), |
| 385 |
) |
| 386 |
}), |
| 387 |
args.topic.clone().map(|arg| ("topic", arg)), |
| 388 |
args.trace.clone().map(|arg| ("trace", arg)), |
| 389 |
args.deadline.clone().map(|arg| ("deadline", arg)), |
| 390 |
args.message |
| 391 |
.as_ref() |
| 392 |
.map(|arg| ("message", encode_message(arg))), |
| 393 |
] |
| 394 |
.into_iter() |
| 395 |
// TODO: In a future version, we could consider adding a list of supported |
| 396 |
// labels to the config, so we can list it for the user. |
| 397 |
.chain(args.label.iter().map(|arg| Some(("label", arg.clone())))) |
| 398 |
.chain( |
| 399 |
args.hashtag |
| 400 |
.iter() |
| 401 |
.map(|arg| Some(("hashtag", arg.clone()))), |
| 402 |
) |
| 403 |
.chain( |
| 404 |
args.custom |
| 405 |
.iter() |
| 406 |
.map(|arg| Some(("custom-keyed-value", arg.clone()))), |
| 407 |
) |
| 408 |
.chain( |
| 409 |
args.reviewer |
| 410 |
.iter() |
| 411 |
.map(|arg| Some(("reviewer", arg.clone()))), |
| 412 |
) |
| 413 |
.chain(args.cc.iter().map(|arg| Some(("cc", arg.clone())))) |
| 414 |
.flatten() |
| 415 |
.map(|(k, v)| format!("{k}={v}")) |
| 416 |
.chain( |
| 417 |
[ |
| 418 |
args.edit.then_some("edit"), |
| 419 |
args.wip.then_some("wip"), |
| 420 |
args.ready.then_some("ready"), |
| 421 |
args.private.then_some("private"), |
| 422 |
args.remove_private.then_some("remove-private"), |
| 423 |
args.publish_comments.then_some("publish-comments"), |
| 424 |
args.no_publish_comments.then_some("no-publish-comments"), |
| 425 |
args.skip_validation.then_some("skip-validation"), |
| 426 |
args.ignore_attention_set.then_some("ignore-attention-set"), |
| 427 |
args.submit.then_some("submit"), |
| 428 |
] |
| 429 |
.into_iter() |
| 430 |
.flatten() |
| 431 |
.chain(args.option.iter().map(|s| s.as_str())) |
| 432 |
.map(str::to_string), |
| 433 |
) |
| 434 |
.collect()) |
| 435 |
} |
| 436 |
|
| 437 |
pub async fn cmd_gerrit_upload( |
| 438 |
ui: &mut Ui, |
| 439 |
command: &CommandHelper, |
| 440 |
args: &UploadArgs, |
| 441 |
) -> Result<(), CommandError> { |
| 442 |
// Do this first because the validation is cheap. |
| 443 |
let push_options = GitPushOptions { |
| 444 |
remote_push_options: push_options(args)?, |
| 445 |
}; |
| 446 |
|
| 447 |
let mut workspace_command = command.workspace_helper(ui).await?; |
| 448 |
|
| 449 |
let revisions: Vec<_> = if args.revisions.is_empty() { |
| 450 |
match workspace_command |
| 451 |
.get_wc_commit_id() |
| 452 |
.map(|id| workspace_command.repo().store().get_commit(id)) |
| 453 |
.transpose()? |
| 454 |
{ |
| 455 |
None => { |
| 456 |
return Err(user_error("No revision provided") |
| 457 |
.hinted("Explicitly specify a revision to upload with `-r`")); |
| 458 |
} |
| 459 |
// This distinguishes between the "squash workflow" and "edit workflow". |
| 460 |
Some(commit) => { |
| 461 |
let revisions = if commit.description().is_empty() { |
| 462 |
let parents = commit.parent_ids(); |
| 463 |
if parents.len() != 1 { |
| 464 |
return Err(user_error( |
| 465 |
"No revision provided, and @ is a merge commit with no description. \ |
| 466 |
Unable to determine a suitable default commit to upload.", |
| 467 |
) |
| 468 |
.hinted("Explicitly specify a revision to upload with `-r`")); |
| 469 |
} |
| 470 |
writeln!( |
| 471 |
ui.status(), |
| 472 |
"No revision provided and @ has no description. Defaulting to @-" |
| 473 |
)?; |
| 474 |
parents.to_vec() |
| 475 |
} else { |
| 476 |
writeln!(ui.status(), "No revision provided. Defaulting to @")?; |
| 477 |
vec![commit.id().clone()] |
| 478 |
}; |
| 479 |
|
| 480 |
workspace_command.check_rewritable(&revisions).await?; |
| 481 |
revisions |
| 482 |
} |
| 483 |
} |
| 484 |
} else { |
| 485 |
let target_expr = workspace_command |
| 486 |
.parse_union_revsets(ui, &args.revisions)? |
| 487 |
.resolve()?; |
| 488 |
workspace_command |
| 489 |
.check_rewritable_expr(&target_expr) |
| 490 |
.await?; |
| 491 |
target_expr |
| 492 |
.evaluate(workspace_command.repo().as_ref())? |
| 493 |
.stream() |
| 494 |
.try_collect() |
| 495 |
.await? |
| 496 |
}; |
| 497 |
if revisions.is_empty() { |
| 498 |
writeln!(ui.status(), "No revisions to upload.")?; |
| 499 |
return Ok(()); |
| 500 |
} |
| 501 |
|
| 502 |
// If you have the changes main -> A -> B, then `jj gerrit upload -r B` |
| 503 |
// uploads both A and B. Thus, we need to ensure that A also has a |
| 504 |
// `Change-Id` trailer. |
| 505 |
// We make an assumption here that all immutable commits already have a |
| 506 |
// `Change-Id` trailer. |
| 507 |
let to_upload: Vec<Commit> = workspace_command |
| 508 |
.attach_revset_evaluator( |
| 509 |
workspace_command |
| 510 |
.env() |
| 511 |
.immutable_expression() |
| 512 |
.range(&RevsetExpression::commits(revisions.clone())), |
| 513 |
) |
| 514 |
.evaluate_to_commits()? |
| 515 |
.try_collect() |
| 516 |
.await?; |
| 517 |
|
| 518 |
// Note: This transaction is intentionally never finished. This way, the |
| 519 |
// `Change-Id` trailer is never part of the commit description in the user's |
| 520 |
// local repo. This avoids scenarios where you have many commits with the |
| 521 |
// same `Change-Id` or a single commit with many `Change-Id`s (e.g., after |
| 522 |
// running `jj split` / `jj squash` respectively). |
| 523 |
let mut tx = workspace_command.start_transaction(); |
| 524 |
let base_repo = tx.base_repo(); |
| 525 |
let store = base_repo.store().clone(); |
| 526 |
|
| 527 |
let old_heads = base_repo |
| 528 |
.index() |
| 529 |
.heads(&mut revisions.iter()) |
| 530 |
.await |
| 531 |
.map_err(internal_error)?; |
| 532 |
|
| 533 |
let subprocess_options = GitSubprocessOptions::from_settings(command.settings())?; |
| 534 |
let remote = calculate_push_remote(&store, command.settings(), args.remote.as_deref())?; |
| 535 |
let remote_branch = calculate_push_ref(command.settings(), args.remote_branch.clone())?; |
| 536 |
|
| 537 |
// Immediately error and reject any commits that shouldn't be uploaded. |
| 538 |
for commit in &to_upload { |
| 539 |
if commit.is_empty(tx.repo_mut()).await? { |
| 540 |
return Err(user_error(format!( |
| 541 |
"Refusing to upload revision {} because it is empty", |
| 542 |
short_change_hash(commit.change_id()) |
| 543 |
)) |
| 544 |
.hinted( |
| 545 |
"Perhaps you squashed then ran upload? Maybe you meant to upload the parent \ |
| 546 |
commit instead (eg. @-)", |
| 547 |
)); |
| 548 |
} |
| 549 |
if commit.description().is_empty() { |
| 550 |
return Err(user_error(format!( |
| 551 |
"Refusing to upload revision {} because it is has no description", |
| 552 |
short_change_hash(commit.change_id()) |
| 553 |
)) |
| 554 |
.hinted("Maybe you meant to upload the parent commit instead (eg. @-)")); |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
let mut old_to_new: HashMap<CommitId, Commit> = HashMap::new(); |
| 559 |
for original_commit in to_upload.into_iter().rev() { |
| 560 |
let trailers = parse_description_trailers(original_commit.description()); |
| 561 |
|
| 562 |
let change_id_trailers: Vec<&Trailer> = trailers |
| 563 |
.iter() |
| 564 |
.filter(|trailer| trailer.key == "Change-Id" || trailer.key == "Link") |
| 565 |
.collect(); |
| 566 |
|
| 567 |
// There shouldn't be multiple `Change-Id` fields. |
| 568 |
if change_id_trailers.len() > 1 { |
| 569 |
return Err(user_error(format!( |
| 570 |
"Multiple Change-Id trailers in revision {}", |
| 571 |
short_change_hash(original_commit.change_id()) |
| 572 |
))); |
| 573 |
} |
| 574 |
|
| 575 |
// The user can choose to explicitly set their own `Change-Id` to |
| 576 |
// override the generated one based on the jj change ID. |
| 577 |
let new_description = if let Some(trailer) = change_id_trailers.first() { |
| 578 |
// Check the `Change-Id` format is correct. Intentionally do not |
| 579 |
// modify the invalid ones. |
| 580 |
if trailer.key == "Change-Id" |
| 581 |
&& (trailer.value.len() != 41 || !trailer.value.starts_with('I')) |
| 582 |
{ |
| 583 |
writeln!( |
| 584 |
ui.warning_default(), |
| 585 |
"Invalid Change-Id trailer in revision {}", |
| 586 |
short_change_hash(original_commit.change_id()), |
| 587 |
)?; |
| 588 |
} |
| 589 |
if trailer.key == "Link" |
| 590 |
&& !matches!(trailer.value.split_once("/id/I"), Some((_url, id)) if id.len() == 40) |
| 591 |
{ |
| 592 |
writeln!( |
| 593 |
ui.warning_default(), |
| 594 |
"Invalid Link trailer in revision {}", |
| 595 |
short_change_hash(original_commit.change_id()), |
| 596 |
)?; |
| 597 |
} |
| 598 |
|
| 599 |
original_commit.description().to_owned() |
| 600 |
} else { |
| 601 |
// Gerrit `Change-Id` is 40 chars, jj change ID is 32, so we need |
| 602 |
// padding. To be consistent with `format_gerrit_change_id_trailer`, |
| 603 |
// we pad with 6a6a6964 (hex of "jjid") at the end. |
| 604 |
let gerrit_change_id = format!("I{}6a6a6964", original_commit.change_id().hex()); |
| 605 |
|
| 606 |
let change_id_trailer = |
| 607 |
if let Ok(review_url) = command.settings().get_string("gerrit.review-url") { |
| 608 |
format!( |
| 609 |
"Link: {}/id/{gerrit_change_id}", |
| 610 |
review_url.trim_end_matches('/'), |
| 611 |
) |
| 612 |
} else { |
| 613 |
format!("Change-Id: {gerrit_change_id}") |
| 614 |
}; |
| 615 |
|
| 616 |
format!( |
| 617 |
"{}{}{}\n", |
| 618 |
original_commit.description().trim(), |
| 619 |
if trailers.is_empty() { "\n\n" } else { "\n" }, |
| 620 |
change_id_trailer, |
| 621 |
) |
| 622 |
}; |
| 623 |
|
| 624 |
let new_parents = original_commit |
| 625 |
.parent_ids() |
| 626 |
.iter() |
| 627 |
.map(|id| old_to_new.get(id).map_or(id, |p| p.id()).clone()) |
| 628 |
.collect(); |
| 629 |
|
| 630 |
if new_description == original_commit.description() |
| 631 |
&& new_parents == original_commit.parent_ids() |
| 632 |
{ |
| 633 |
// map the old commit to itself |
| 634 |
old_to_new.insert(original_commit.id().clone(), original_commit); |
| 635 |
continue; |
| 636 |
} |
| 637 |
|
| 638 |
// rewrite the set of parents to point to the commits that were |
| 639 |
// previously rewritten in toposort order |
| 640 |
let new_commit = tx |
| 641 |
.repo_mut() |
| 642 |
.rewrite_commit(&original_commit) |
| 643 |
.set_description(new_description) |
| 644 |
.set_parents(new_parents) |
| 645 |
// Set the timestamp back to the timestamp of the original commit. |
| 646 |
// Otherwise, `jj gerrit upload @ && jj gerrit upload @` will upload |
| 647 |
// two patch sets with the only difference being the timestamp. |
| 648 |
.set_committer(original_commit.committer().clone()) |
| 649 |
.set_author(original_commit.author().clone()) |
| 650 |
.write() |
| 651 |
.await?; |
| 652 |
|
| 653 |
old_to_new.insert(original_commit.id().clone(), new_commit); |
| 654 |
} |
| 655 |
|
| 656 |
let remote_ref = format!("refs/for/{remote_branch}"); |
| 657 |
writeln!( |
| 658 |
ui.status(), |
| 659 |
"Found {} heads to push to Gerrit (remote '{}'), target branch '{}'.", |
| 660 |
old_heads.len(), |
| 661 |
remote, |
| 662 |
remote_branch, |
| 663 |
)?; |
| 664 |
|
| 665 |
// NOTE (aseipp): because we are pushing everything to the same remote ref, |
| 666 |
// we have to loop and push each commit one at a time, even though |
| 667 |
// push_updates in theory supports multiple GitRefUpdates at once, because |
| 668 |
// we obviously can't push multiple heads to the same ref. |
| 669 |
for head in &old_heads { |
| 670 |
if let Some(mut formatter) = ui.status_formatter() { |
| 671 |
if args.dry_run { |
| 672 |
write!(formatter, "Dry-run: Would push ")?; |
| 673 |
} else { |
| 674 |
write!(formatter, "Pushing ")?; |
| 675 |
} |
| 676 |
// We have to write the old commit here, because until we finish |
| 677 |
// the transaction (which we don't), the new commit is labeled as |
| 678 |
// "hidden". |
| 679 |
tx.base_workspace_helper().write_commit_summary( |
| 680 |
formatter.as_mut(), |
| 681 |
&store.get_commit_async(head).await.unwrap(), |
| 682 |
)?; |
| 683 |
writeln!(formatter)?; |
| 684 |
} |
| 685 |
|
| 686 |
if args.dry_run { |
| 687 |
continue; |
| 688 |
} |
| 689 |
|
| 690 |
let new_commit = old_to_new.get(head).unwrap(); |
| 691 |
|
| 692 |
// how do we get better errors from the remote? 'git push' tells us |
| 693 |
// about rejected refs AND ALSO '(nothing changed)' when there are no |
| 694 |
// changes to push, but we don't get that here. |
| 695 |
let push_stats = git::push_updates( |
| 696 |
tx.repo_mut(), |
| 697 |
subprocess_options.clone(), |
| 698 |
remote.as_ref(), |
| 699 |
&[GitRefUpdate { |
| 700 |
qualified_name: remote_ref.clone().into(), |
| 701 |
targets: Diff::new( |
| 702 |
None, |
| 703 |
Some(gix::ObjectId::from_bytes_or_panic( |
| 704 |
new_commit.id().as_bytes(), |
| 705 |
)), |
| 706 |
), |
| 707 |
}], |
| 708 |
&mut GitSubprocessUi::new(ui), |
| 709 |
&push_options, |
| 710 |
) |
| 711 |
// Despite the fact that a manual git push will error out with 'no new |
| 712 |
// changes' if you're up to date, this git backend appears to silently |
| 713 |
// succeed - no idea why. |
| 714 |
// It'd be nice if we could distinguish this. We should ideally succeed, |
| 715 |
// but give the user a warning. |
| 716 |
.map_err(|err| match err { |
| 717 |
git::GitPushError::NoSuchRemote(_) |
| 718 |
| git::GitPushError::RemoteName(_) |
| 719 |
| git::GitPushError::UnexpectedBackend(_) => user_error(err), |
| 720 |
git::GitPushError::Subprocess(_) => { |
| 721 |
user_error_with_message("Internal git error while pushing to gerrit", err) |
| 722 |
} |
| 723 |
})?; |
| 724 |
print_push_stats(ui, &push_stats)?; |
| 725 |
if !push_stats.all_ok() { |
| 726 |
return Err(user_error("Failed to push all changes to gerrit")); |
| 727 |
} |
| 728 |
} |
| 729 |
Ok(()) |
| 730 |
} |
| 731 |
|
| 732 |
#[cfg(test)] |
| 733 |
mod tests { |
| 734 |
use super::*; |
| 735 |
|
| 736 |
#[test] |
| 737 |
fn test_gerrit_push_options() { |
| 738 |
assert_eq!( |
| 739 |
push_options(&Default::default()).unwrap(), |
| 740 |
Vec::<String>::new(), |
| 741 |
); |
| 742 |
|
| 743 |
assert_eq!( |
| 744 |
push_options(&UploadArgs { |
| 745 |
message: Some("Uploaded with jj!".to_string()), |
| 746 |
notify: Some(EmailNotification::None), |
| 747 |
topic: Some("my-topic".to_string()), |
| 748 |
reviewer: vec!["[email protected]".to_string()], |
| 749 |
cc: vec!["[email protected]".to_string(), "[email protected]".to_string()], |
| 750 |
edit: true, |
| 751 |
wip: true, |
| 752 |
private: true, |
| 753 |
publish_comments: true, |
| 754 |
..Default::default() |
| 755 |
}) |
| 756 |
.unwrap(), |
| 757 |
[ |
| 758 |
"notify=NONE", |
| 759 |
"topic=my-topic", |
| 760 |
"message=Uploaded%20with%20jj%21", |
| 761 |
"[email protected]", |
| 762 |
"[email protected]", |
| 763 |
"[email protected]", |
| 764 |
"edit", |
| 765 |
"wip", |
| 766 |
"private", |
| 767 |
"publish-comments", |
| 768 |
] |
| 769 |
.into_iter() |
| 770 |
.map(|s| s.to_string()) |
| 771 |
.collect::<Vec<_>>(), |
| 772 |
); |
| 773 |
|
| 774 |
assert_eq!( |
| 775 |
push_options(&UploadArgs { |
| 776 |
notify: Some(EmailNotification::All), |
| 777 |
trace: Some("my-trace".to_string()), |
| 778 |
hashtag: vec!["my-hashtag".to_string(), "my-second-hashtag".to_string()], |
| 779 |
deadline: Some("yesterday".to_string()), |
| 780 |
label: vec!["Auto-Submit".to_string(), "Commit-Queue+2".to_string()], |
| 781 |
custom: vec!["foo:bar".to_string(), "baz:quux".to_string()], |
| 782 |
ready: true, |
| 783 |
remove_private: true, |
| 784 |
no_publish_comments: true, |
| 785 |
skip_validation: true, |
| 786 |
ignore_attention_set: true, |
| 787 |
submit: true, |
| 788 |
option: vec!["hello".to_string(), "world".to_string()], |
| 789 |
..Default::default() |
| 790 |
}) |
| 791 |
.unwrap(), |
| 792 |
[ |
| 793 |
"notify=ALL", |
| 794 |
"trace=my-trace", |
| 795 |
"deadline=yesterday", |
| 796 |
"label=Auto-Submit", |
| 797 |
"label=Commit-Queue+2", |
| 798 |
"hashtag=my-hashtag", |
| 799 |
"hashtag=my-second-hashtag", |
| 800 |
"custom-keyed-value=foo:bar", |
| 801 |
"custom-keyed-value=baz:quux", |
| 802 |
"ready", |
| 803 |
"remove-private", |
| 804 |
"no-publish-comments", |
| 805 |
"skip-validation", |
| 806 |
"ignore-attention-set", |
| 807 |
"submit", |
| 808 |
"hello", |
| 809 |
"world", |
| 810 |
] |
| 811 |
.into_iter() |
| 812 |
.map(|s| s.to_string()) |
| 813 |
.collect::<Vec<_>>(), |
| 814 |
); |
| 815 |
} |
| 816 |
} |