| 1 |
// Copyright 2025 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::ArgValueCompleter; |
| 16 |
use jj_lib::bisect::BisectionResult; |
| 17 |
use jj_lib::bisect::Bisector; |
| 18 |
use jj_lib::bisect::Evaluation; |
| 19 |
use jj_lib::commit::Commit; |
| 20 |
use jj_lib::object_id::ObjectId as _; |
| 21 |
use tracing::instrument; |
| 22 |
|
| 23 |
use crate::cli_util::CommandHelper; |
| 24 |
use crate::cli_util::RevisionArg; |
| 25 |
use crate::cli_util::WorkspaceCommandHelper; |
| 26 |
use crate::cli_util::short_operation_hash; |
| 27 |
use crate::command_error::CommandError; |
| 28 |
use crate::command_error::cli_error; |
| 29 |
use crate::command_error::internal_error_with_message; |
| 30 |
use crate::command_error::user_error; |
| 31 |
use crate::command_error::user_error_with_message; |
| 32 |
use crate::complete; |
| 33 |
use crate::config::CommandNameAndArgs; |
| 34 |
use crate::ui::Ui; |
| 35 |
|
| 36 |
/// Run a given command to find the first bad revision |
| 37 |
/// |
| 38 |
/// Uses binary search to find the first "bad" revision. Revisions are evaluated |
| 39 |
/// by running the given command (see the documentation for `<COMMAND>` for |
| 40 |
/// details). |
| 41 |
/// |
| 42 |
/// It is assumed that if a given revision is "bad", then all its descendants |
| 43 |
/// in the input range are also "bad". |
| 44 |
/// |
| 45 |
/// The target of the bisection can be inverted to look for the first "good" |
| 46 |
/// revision by passing `--find-good`. |
| 47 |
/// |
| 48 |
/// Hint: You can pass your shell as the command, then run manual tests in a |
| 49 |
/// script. When you're done, make sure to exit the shell with an appropriate |
| 50 |
/// error code depending on the desired outcome (e.g., `exit 0` to mark the |
| 51 |
/// revision as "good"). |
| 52 |
/// |
| 53 |
/// Example: To run `cargo test` with the changes from revision `xyz` applied: |
| 54 |
/// ```shell |
| 55 |
/// jj bisect run --range v1.0..main -- bash -c "jj duplicate xyz -B @ && |
| 56 |
/// cargo test" |
| 57 |
/// ``` |
| 58 |
#[derive(clap::Args, Clone, Debug)] |
| 59 |
#[command(verbatim_doc_comment)] |
| 60 |
pub(crate) struct BisectRunArgs { |
| 61 |
/// Range of revisions to bisect (can be repeated) |
| 62 |
/// |
| 63 |
/// This is typically a range like `v1.0..main`. The heads of the range are |
| 64 |
/// assumed to be bad. Ancestors of the range that are not also in the range |
| 65 |
/// are assumed to be good. |
| 66 |
/// |
| 67 |
/// The union of all given ranges are used as the input for the bisection. |
| 68 |
#[arg(long, short, value_name = "REVSETS", required = true)] |
| 69 |
#[arg(add = ArgValueCompleter::new(complete::revset_expression_all))] |
| 70 |
range: Vec<RevisionArg>, |
| 71 |
|
| 72 |
/// Deprecated. Use positional arguments instead. |
| 73 |
#[arg( |
| 74 |
long = "command", |
| 75 |
value_name = "COMMAND", |
| 76 |
hide = true, |
| 77 |
conflicts_with = "command" |
| 78 |
)] |
| 79 |
legacy_command: Option<CommandNameAndArgs>, |
| 80 |
|
| 81 |
/// Command to run to determine the status of a revision |
| 82 |
/// |
| 83 |
/// Each revision being checked will be directly edited (will become the |
| 84 |
/// current working copy) before running this command. The exit status of |
| 85 |
/// the command will be used to mark revisions as "good" or "bad": status 0 |
| 86 |
/// means "good", 125 means to skip the revision, 127 (command not found) |
| 87 |
/// will abort the bisection, and any other non-zero exit status means the |
| 88 |
/// revision is "bad". |
| 89 |
/// |
| 90 |
/// The target's commit ID is available to the command in the |
| 91 |
/// `$JJ_BISECT_TARGET` environment variable. |
| 92 |
#[arg(value_name = "COMMAND")] |
| 93 |
command: Option<String>, |
| 94 |
|
| 95 |
/// Arguments to pass to the command |
| 96 |
/// |
| 97 |
/// Hint: Use a `--` separator to allow passing arguments starting with `-`. |
| 98 |
/// For example: `jj bisect run --range=... -- test -f some-file`. |
| 99 |
#[arg(value_name = "ARGS")] |
| 100 |
args: Vec<String>, |
| 101 |
|
| 102 |
/// Find the first good revision instead |
| 103 |
/// |
| 104 |
/// The interpretation of exit statuses will be inverted (excluding special |
| 105 |
/// exit statuses), so status 0 means bad and other non-zero statuses mean |
| 106 |
/// good. |
| 107 |
#[arg(long, value_name = "TARGET", default_value_t = false)] |
| 108 |
find_good: bool, |
| 109 |
} |
| 110 |
|
| 111 |
#[instrument(skip_all)] |
| 112 |
pub(crate) async fn cmd_bisect_run( |
| 113 |
ui: &mut Ui, |
| 114 |
command: &CommandHelper, |
| 115 |
args: &BisectRunArgs, |
| 116 |
) -> Result<(), CommandError> { |
| 117 |
let mut workspace_command = command.workspace_helper(ui).await?; |
| 118 |
|
| 119 |
if let Some(command) = &args.legacy_command { |
| 120 |
writeln!( |
| 121 |
ui.warning_default(), |
| 122 |
"`--command` is deprecated; use positional arguments instead: `jj bisect run \ |
| 123 |
--range=... -- {command}`" |
| 124 |
)?; |
| 125 |
} else if args.command.is_none() { |
| 126 |
return Err(cli_error("Command argument is required")); |
| 127 |
} |
| 128 |
|
| 129 |
let input_range = workspace_command |
| 130 |
.parse_union_revsets(ui, &args.range)? |
| 131 |
.resolve()?; |
| 132 |
|
| 133 |
let initial_repo = workspace_command.repo().clone(); |
| 134 |
|
| 135 |
let mut bisector = Bisector::new(initial_repo.as_ref(), input_range).await?; |
| 136 |
let bisection_result = loop { |
| 137 |
match bisector.next_step().await? { |
| 138 |
jj_lib::bisect::NextStep::Evaluate(commit) => { |
| 139 |
{ |
| 140 |
let mut formatter = ui.stdout_formatter(); |
| 141 |
let (lower, upper) = bisector.remaining_revset().await?.count_estimate()?; |
| 142 |
let lower_steps = ((lower + 1) as f64).log2().ceil() as usize; |
| 143 |
if upper == Some(lower) { |
| 144 |
writeln!( |
| 145 |
formatter, |
| 146 |
"Bisecting: {lower} revisions left to test after this (roughly \ |
| 147 |
{lower_steps} steps)" |
| 148 |
)?; |
| 149 |
} else { |
| 150 |
writeln!( |
| 151 |
formatter, |
| 152 |
"Bisecting: at least {lower} revisions left to test after this (at \ |
| 153 |
least roughly {lower_steps} steps)" |
| 154 |
)?; |
| 155 |
} |
| 156 |
// TODO: Show a graph of the current range instead? |
| 157 |
let commit_template = workspace_command.commit_summary_template(); |
| 158 |
write!(formatter, "Now evaluating: ")?; |
| 159 |
commit_template.format(&commit, formatter.as_mut())?; |
| 160 |
writeln!(formatter)?; |
| 161 |
} |
| 162 |
|
| 163 |
let cmd = get_command(args); |
| 164 |
let evaluation = evaluate_commit(ui, &mut workspace_command, cmd, &commit).await?; |
| 165 |
|
| 166 |
{ |
| 167 |
let mut formatter = ui.stdout_formatter(); |
| 168 |
let message = match evaluation { |
| 169 |
Evaluation::Good => "The revision is good.", |
| 170 |
Evaluation::Bad => "The revision is bad.", |
| 171 |
Evaluation::Skip => { |
| 172 |
"It could not be determined if the revision is good or bad." |
| 173 |
} |
| 174 |
Evaluation::Abort => { |
| 175 |
"Evaluation command returned 127 (command not found) - aborting \ |
| 176 |
bisection." |
| 177 |
} |
| 178 |
}; |
| 179 |
writeln!(formatter, "{message}")?; |
| 180 |
writeln!(formatter)?; |
| 181 |
} |
| 182 |
|
| 183 |
if args.find_good { |
| 184 |
// If we're looking for the first good revision, |
| 185 |
// invert the evaluation result. |
| 186 |
bisector.mark(commit.id().clone(), evaluation.invert()); |
| 187 |
} else { |
| 188 |
bisector.mark(commit.id().clone(), evaluation); |
| 189 |
} |
| 190 |
|
| 191 |
// Reload the workspace because the evaluation command may run `jj` commands. |
| 192 |
workspace_command = command.workspace_helper(ui).await?; |
| 193 |
} |
| 194 |
jj_lib::bisect::NextStep::Done(bisection_result) => { |
| 195 |
break bisection_result; |
| 196 |
} |
| 197 |
} |
| 198 |
}; |
| 199 |
|
| 200 |
let mut formatter = ui.stdout_formatter(); |
| 201 |
writeln!( |
| 202 |
formatter, |
| 203 |
"Search complete. To discard any revisions created during search, run:" |
| 204 |
)?; |
| 205 |
writeln!( |
| 206 |
formatter, |
| 207 |
" jj op restore {}", |
| 208 |
short_operation_hash(initial_repo.op_id()) |
| 209 |
)?; |
| 210 |
|
| 211 |
let target = if args.find_good { "good" } else { "bad" }; |
| 212 |
match bisection_result { |
| 213 |
BisectionResult::Abort => { |
| 214 |
return Err(user_error("Bisection aborted")); |
| 215 |
} |
| 216 |
BisectionResult::Indeterminate => { |
| 217 |
return Err(user_error(format!( |
| 218 |
"Could not find the first {target} revision. Was the input range empty?" |
| 219 |
))); |
| 220 |
} |
| 221 |
BisectionResult::Found(first_target_commits) => { |
| 222 |
let commit_template = workspace_command.commit_summary_template(); |
| 223 |
if let [first_target_commit] = first_target_commits.as_slice() { |
| 224 |
write!(formatter, "The first {target} revision is: ")?; |
| 225 |
commit_template.format(first_target_commit, formatter.as_mut())?; |
| 226 |
writeln!(formatter)?; |
| 227 |
} else { |
| 228 |
writeln!(formatter, "The first {target} revisions are:")?; |
| 229 |
for first_target_commit in first_target_commits { |
| 230 |
commit_template.format(&first_target_commit, formatter.as_mut())?; |
| 231 |
writeln!(formatter)?; |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
BisectionResult::FoundDespiteSkips { |
| 236 |
bad_commits, |
| 237 |
possibly_bad, |
| 238 |
} => { |
| 239 |
let commit_template = workspace_command.commit_summary_template(); |
| 240 |
writeln!(formatter, "The first {target} revisions are:")?; |
| 241 |
for commit in bad_commits { |
| 242 |
commit_template.format(&commit, formatter.as_mut())?; |
| 243 |
writeln!(formatter)?; |
| 244 |
} |
| 245 |
writeln!( |
| 246 |
formatter, |
| 247 |
"These revisions may also be {target}, but couldn't be evaluated:" |
| 248 |
)?; |
| 249 |
for commit in possibly_bad { |
| 250 |
commit_template.format(&commit, formatter.as_mut())?; |
| 251 |
writeln!(formatter)?; |
| 252 |
} |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
Ok(()) |
| 257 |
} |
| 258 |
|
| 259 |
fn get_command(args: &BisectRunArgs) -> std::process::Command { |
| 260 |
if let Some(command) = &args.command { |
| 261 |
let mut cmd = std::process::Command::new(command); |
| 262 |
cmd.args(&args.args); |
| 263 |
cmd |
| 264 |
} else { |
| 265 |
args.legacy_command.as_ref().unwrap().to_command() |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
async fn evaluate_commit( |
| 270 |
ui: &mut Ui, |
| 271 |
workspace_command: &mut WorkspaceCommandHelper, |
| 272 |
mut cmd: std::process::Command, |
| 273 |
commit: &Commit, |
| 274 |
) -> Result<Evaluation, CommandError> { |
| 275 |
let mut tx = workspace_command.start_transaction(); |
| 276 |
let commit_id_hex = commit.id().hex(); |
| 277 |
tx.check_out(commit)?; |
| 278 |
tx.finish( |
| 279 |
ui, |
| 280 |
format!("Updated to revision {commit_id_hex} for bisection"), |
| 281 |
) |
| 282 |
.await?; |
| 283 |
|
| 284 |
let jj_executable_path = std::env::current_exe().map_err(|err| { |
| 285 |
internal_error_with_message("Could not get path for the jj executable", err) |
| 286 |
})?; |
| 287 |
tracing::info!(?cmd, "running bisection evaluation command"); |
| 288 |
let status = cmd |
| 289 |
.env("JJ_EXECUTABLE_PATH", jj_executable_path) |
| 290 |
.env("JJ_BISECT_TARGET", &commit_id_hex) |
| 291 |
.status() |
| 292 |
.map_err(|err| user_error_with_message("Failed to run evaluation command", err))?; |
| 293 |
let evaluation = if status.success() { |
| 294 |
Evaluation::Good |
| 295 |
} else { |
| 296 |
match status.code() { |
| 297 |
Some(125) => Evaluation::Skip, |
| 298 |
Some(127) => Evaluation::Abort, |
| 299 |
_ => Evaluation::Bad, |
| 300 |
} |
| 301 |
}; |
| 302 |
|
| 303 |
Ok(evaluation) |
| 304 |
} |