Debian Codegraph @

cli/src/commands/run.rs

raw
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 //! This file contains the internal implementation of `run`.
16
17 use std::cmp::min;
18 use std::collections::HashMap;
19 use std::fmt;
20 use std::fs;
21 use std::io;
22 use std::io::Write as _;
23 use std::num::NonZeroUsize;
24 use std::path::Path;
25 use std::path::PathBuf;
26 use std::process::ExitStatus;
27 use std::process::Output;
28 use std::process::Stdio;
29 use std::sync::Arc;
30 use std::time::Duration;
31
32 use futures::StreamExt as _;
33 use futures::TryStreamExt as _;
34 use itertools::Itertools as _;
35 use jj_lib::backend::BackendError;
36 use jj_lib::backend::CommitId;
37 use jj_lib::commit::Commit;
38 use jj_lib::commit::CommitIteratorExt as _;
39 use jj_lib::conflicts::ConflictMarkerStyle;
40 use jj_lib::fsmonitor::FsmonitorSettings;
41 use jj_lib::gitignore::GitIgnoreFile;
42 use jj_lib::local_working_copy::EolConversionMode;
43 use jj_lib::local_working_copy::ExecChangeSetting;
44 use jj_lib::local_working_copy::TreeState;
45 use jj_lib::local_working_copy::TreeStateError;
46 use jj_lib::local_working_copy::TreeStateSettings;
47 use jj_lib::lock::FileLock;
48 use jj_lib::lock::FileLockError;
49 use jj_lib::matchers::EverythingMatcher;
50 use jj_lib::matchers::Matcher;
51 use jj_lib::matchers::NothingMatcher;
52 use jj_lib::merge::Merge;
53 use jj_lib::merged_tree::MergedTree;
54 use jj_lib::object_id::ObjectId as _;
55 use jj_lib::repo::Repo as _;
56 use jj_lib::working_copy::SnapshotOptions;
57 use tokio::runtime::Builder;
58 use tokio::sync::mpsc;
59 use tokio::sync::mpsc::Sender;
60 use tokio::task::JoinError;
61 use tokio::task::JoinSet;
62 use tokio::time::sleep;
63
64 use crate::cli_util::CommandHelper;
65 use crate::cli_util::RevisionArg;
66 use crate::cli_util::WorkspaceCommandHelper;
67 use crate::cli_util::WorkspaceCommandTransaction;
68 use crate::command_error::CommandError;
69 use crate::command_error::CommandErrorKind;
70 use crate::ui::Ui;
71
72 #[derive(Debug, thiserror::Error)]
73 enum RunError {
74 #[error("failed to checkout the commit {}", .0)]
75 FailedCheckout(CommitId),
76 #[error("the command '{}' failed with {}", .0, .1)]
77 CommandFailure(String, ExitStatus),
78 #[error(transparent)]
79 IoError(#[from] io::Error),
80 #[error("failed to create path {}: {}", .0.to_string_lossy(), .1)]
81 PathCreationFailure(PathBuf, io::Error),
82 #[error("failed to delete path {}: {}", .0.to_string_lossy(), .1)]
83 PathDeletionFailure(PathBuf, io::Error),
84 #[error("failed to load a commit's tree")]
85 TreeState(#[from] TreeStateError),
86 #[error(transparent)]
87 Backend(#[from] BackendError),
88 #[error(transparent)]
89 JobFailure(#[from] JoinError),
90 #[error(transparent)]
91 FileLock(#[from] FileLockError),
92 #[error("invalid value for `run.jobs`: {0} (must be a positive integer)")]
93 InvalidJobCount(i64),
94 }
95
96 impl From<RunError> for CommandError {
97 fn from(value: RunError) -> Self {
98 Self::new(CommandErrorKind::User, Box::new(value))
99 }
100 }
101
102 fn default_tree_state_settings() -> TreeStateSettings {
103 TreeStateSettings {
104 conflict_marker_style: ConflictMarkerStyle::Snapshot,
105 eol_conversion_mode: EolConversionMode::None,
106 exec_change_setting: ExecChangeSetting::Auto,
107 fsmonitor_settings: FsmonitorSettings::None,
108 }
109 }
110
111 /// A workspace that's ready for a single job to run against.
112 ///
113 /// Dropping the workspace releases its interprocess lock, freeing the slot for
114 /// the next worker.
115 struct RunWorkspace {
116 working_copy_dir: PathBuf,
117 tree_state: TreeState,
118 /// Holds the slot's interprocess lock for the duration of the job.
119 _lock: FileLock,
120 }
121
122 impl RunWorkspace {
123 /// Persist the post-snapshot tree state to disk so the next slot
124 /// acquisition can diff against it and only touch changed files.
125 fn persist(&mut self) -> Result<(), RunError> {
126 self.tree_state.save()?;
127 Ok(())
128 }
129 }
130
131 /// A command, its arguments, and the workspace-relative directory it should
132 /// run in.
133 struct CommandSpec {
134 program: String,
135 args: Vec<String>,
136 /// Working directory for the subprocess, relative to the workspace root.
137 /// Empty means run from the workspace root.
138 subdir: Option<PathBuf>,
139 }
140
141 impl fmt::Display for CommandSpec {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str(&self.program)?;
144 for arg in &self.args {
145 f.write_str(" ")?;
146 f.write_str(arg)?;
147 }
148 Ok(())
149 }
150 }
151
152 /// Manages a fixed-size pool of workspaces under `.jj/run/default/`.
153 ///
154 /// Each workspace lives at `.jj/run/default/N/` with subdirs `working_copy/`
155 /// and `state/`. Its lockfile is the sibling `.jj/run/default/N.lock`.
156 /// Workspaces persist between `jj run` invocations so build artifacts can be
157 /// reused. Acquisition picks the first free workspace, so multiple concurrent
158 /// `jj run` processes cooperatively share the pool.
159 struct WorkspacePool {
160 base_path: PathBuf,
161 size: NonZeroUsize,
162 /// Determines which untracked files left in a slot get pulled into the
163 /// rewritten commit. Loaded once from `snapshot.auto-track`; essentially
164 /// the user's `.gitignore` story for what counts as a build artifact.
165 auto_tracking_matcher: Box<dyn Matcher>,
166 /// When true, wipe each slot's working copy on acquisition so every commit
167 /// starts from a freshly checked-out tree (no artifact reuse).
168 clean: bool,
169 }
170
171 impl WorkspacePool {
172 fn new(
173 repo_path: &Path,
174 size: NonZeroUsize,
175 auto_tracking_matcher: Box<dyn Matcher>,
176 clean: bool,
177 ) -> Result<Self, RunError> {
178 // The parent() call is needed to not write under `.jj/repo/`.
179 let base_path = repo_path.parent().unwrap().join("run").join("default");
180 fs::create_dir_all(&base_path)?;
181 Ok(Self {
182 base_path,
183 size,
184 auto_tracking_matcher,
185 clean,
186 })
187 }
188
189 async fn acquire(
190 &self,
191 commit: &Commit,
192 base_ignores: Arc<GitIgnoreFile>,
193 ) -> Result<RunWorkspace, RunError> {
194 // Find a free slot. The first iteration may fail if another worker
195 // (this process or another) holds every slot; sleep and retry.
196 let mut cur_sleep = Duration::from_millis(10);
197 let max_sleep = Duration::from_millis(250);
198 let (slot_index, lock) = loop {
199 if let Some(found) = self.try_acquire_any_slot()? {
200 break found;
201 }
202 sleep(cur_sleep).await;
203 cur_sleep = min(cur_sleep.saturating_mul(2), max_sleep);
204 };
205
206 let slot_path = self.slot_path(slot_index);
207 let working_copy_dir = slot_path.join("working_copy");
208 let state_dir = slot_path.join("state");
209 let tree_state_path = state_dir.join("tree_state");
210
211 let is_reused_workspace = tree_state_path.exists();
212 let settings = default_tree_state_settings();
213 let mut tree_state = if !self.clean && is_reused_workspace {
214 // Load the persisted tree state so `check_out` below can diff
215 // against it, only touching files that changed and removing files
216 // no longer present in the new tree.
217 //
218 // Delete `tree_state` from disk before checkout to act as a dirty
219 // marker. If we crash between here and the save at the end of the
220 // job, the next acquisition will see the file absent and wipe the
221 // slot rather than trusting inconsistent state.
222 let ts = TreeState::load(
223 commit.store().clone(),
224 working_copy_dir.clone(),
225 state_dir.clone(),
226 &settings,
227 )?;
228 fs::remove_file(&tree_state_path)?;
229 ts
230 } else {
231 // This is the first use of the workspace, the previous job crashed,
232 // or --clean was passed. Wipe any leftover working copy so we start
233 // from a clean slate, then use an in-memory empty tree state.
234 // `tree_state` stays absent on disk until a successful job writes
235 // it via `persist()`.
236 fs::remove_file(&tree_state_path).or_else(|e| match e {
237 e if e.kind() == io::ErrorKind::NotFound => Ok(()),
238 e => Err(RunError::PathDeletionFailure(tree_state_path.clone(), e)),
239 })?;
240 fs::remove_dir_all(&working_copy_dir).or_else(|e| match e {
241 e if e.kind() == io::ErrorKind::NotFound => Ok(()),
242 e => Err(RunError::PathDeletionFailure(working_copy_dir.clone(), e)),
243 })?;
244 fs::remove_dir_all(&state_dir).or_else(|e| match e {
245 e if e.kind() == io::ErrorKind::NotFound => Ok(()),
246 e => Err(RunError::PathDeletionFailure(state_dir.clone(), e)),
247 })?;
248 fs::create_dir_all(&working_copy_dir)
249 .map_err(|e| RunError::PathCreationFailure(working_copy_dir.clone(), e))?;
250 fs::create_dir_all(&state_dir)
251 .map_err(|e| RunError::PathCreationFailure(state_dir.clone(), e))?;
252 TreeState::init_without_saving(
253 commit.store().clone(),
254 working_copy_dir.clone(),
255 state_dir,
256 &settings,
257 )
258 };
259
260 tree_state
261 .check_out(&commit.tree())
262 .map_err(|_| RunError::FailedCheckout(commit.id().clone()))?;
263
264 // If we checked out a revision with a completely empty tree,
265 // TreeState::check_out() deletes the working_copy directory because it
266 // recursively deletes empty directories until it reaches an error. In
267 // normal workspaces, the .jj directory prevents the root directory from
268 // being deleted, but our slots don't have that. It might be better to
269 // make check_out explicitly avoid deleting the root directory, but that
270 // needs to be a carefully considered change.
271 fs::create_dir_all(&working_copy_dir)
272 .map_err(|e| RunError::PathCreationFailure(working_copy_dir.clone(), e))?;
273
274 // Remove files from a previous run that were ignored in the previous
275 // revision but are not ignored in the new commit:
276 // - Check out the new revsision
277 // - Snapshot to discover any new files in the working copy
278 // - Delete any new files
279 // - Check out again to reset tree state
280 if is_reused_workspace {
281 let options = self.snapshot_options(base_ignores);
282 tree_state.snapshot(&options).await.unwrap();
283 let post_snapshot_tree = tree_state.current_tree().clone();
284 let original_tree = commit.tree();
285 let mut diff = original_tree.diff_stream(&post_snapshot_tree, &EverythingMatcher);
286 let mut added_paths = Vec::new();
287 while let Some(entry) = diff.next().await {
288 let values = entry.values?;
289 if values.before.is_absent() && values.after.is_present() {
290 added_paths.push(entry.path);
291 }
292 }
293 drop(diff);
294 for path in &added_paths {
295 let abs = path.to_fs_path_unchecked(&working_copy_dir);
296 if let Err(err) = fs::remove_file(&abs)
297 && err.kind() != io::ErrorKind::NotFound
298 {
299 return Err(err.into());
300 }
301 }
302 if !added_paths.is_empty() {
303 tree_state
304 .check_out(&original_tree)
305 .map_err(|_| RunError::FailedCheckout(commit.id().clone()))?;
306 }
307 }
308
309 Ok(RunWorkspace {
310 working_copy_dir,
311 tree_state,
312 _lock: lock,
313 })
314 }
315
316 fn snapshot_options(&self, base_ignores: Arc<GitIgnoreFile>) -> SnapshotOptions<'_> {
317 SnapshotOptions {
318 base_ignores,
319 start_tracking_matcher: self.auto_tracking_matcher.as_ref(),
320 progress: None,
321 // TODO: read from current wc/settings
322 max_new_file_size: 64_000_u64, // 64 MB for now
323 force_tracking_matcher: &NothingMatcher,
324 }
325 }
326
327 fn slot_path(&self, index: usize) -> PathBuf {
328 self.base_path.join(index.to_string())
329 }
330
331 fn slot_lock_path(&self, index: usize) -> PathBuf {
332 self.base_path.join(format!("{index}.lock"))
333 }
334
335 /// Try to acquire any slot's lock without blocking. Returns the slot
336 /// index and the held lock if one was available, `Ok(None)` if every
337 /// slot was contended.
338 fn try_acquire_any_slot(&self) -> Result<Option<(usize, FileLock)>, RunError> {
339 for slot in 1..=self.size.get() {
340 let slot_path = self.slot_path(slot);
341 fs::create_dir_all(&slot_path)
342 .map_err(|e| RunError::PathCreationFailure(slot_path.clone(), e))?;
343 if let Some(lock) = FileLock::try_lock(self.slot_lock_path(slot))? {
344 tracing::debug!(slot, "acquired pool slot");
345 return Ok(Some((slot, lock)));
346 }
347 }
348 Ok(None)
349 }
350 }
351
352 /// The result of a single command invocation.
353 struct RunJob {
354 /// The old `CommitId` of the commit.
355 old_id: CommitId,
356 /// The original tree of the commit before the command ran.
357 old_tree: MergedTree,
358 /// The new tree generated from the commit. `None` when the command wasn't
359 /// run (i.e. the commit was skipped). May be a conflicted tree when the
360 /// command left conflicts in the working copy.
361 new_tree: Option<MergedTree>,
362 /// Bytes the subprocess wrote to its stdout, captured in full.
363 stdout: Vec<u8>,
364 /// Bytes the subprocess wrote to its stderr, captured in full.
365 stderr: Vec<u8>,
366 /// True if the command wasn't run because the per-commit working directory
367 /// (the subdirectory `jj run` was invoked from) didn't exist in this
368 /// commit's tree.
369 skipped: bool,
370 /// Exit status of the command, if it ran.
371 status: Option<ExitStatus>,
372 }
373
374 // TODO: make this more revset/commit stream friendly.
375 #[allow(clippy::too_many_arguments)]
376 async fn run_inner(
377 tx: &WorkspaceCommandTransaction<'_>,
378 sender: Sender<RunJob>,
379 handle: &tokio::runtime::Handle,
380 spec: Arc<CommandSpec>,
381 pool: Arc<WorkspacePool>,
382 commits: &[Commit],
383 jobs: usize,
384 passthrough: bool,
385 ignore_errors: bool,
386 ) -> Result<(), RunError> {
387 let base_ignores = tx.base_workspace_helper().base_ignores().unwrap().clone();
388 let mut command_futures: JoinSet<Result<RunJob, RunError>> = JoinSet::new();
389 let mut commits_iter = commits.iter().fuse();
390 loop {
391 // Launch commits in order, keeping at most `jobs` in flight so tasks
392 // start in commit order and the pool is never oversubscribed.
393 while command_futures.len() < jobs {
394 let Some(commit) = commits_iter.next() else {
395 break;
396 };
397 let base_ignores = base_ignores.clone();
398 let pool = pool.clone();
399 let commit = commit.clone();
400 let spec = spec.clone();
401 command_futures.spawn_on(
402 async move { rewrite_commit(base_ignores, pool, commit, spec, passthrough).await },
403 handle,
404 );
405 }
406
407 let Some(res) = command_futures.join_next().await else {
408 break;
409 };
410 let done = match res {
411 Ok(rj) => rj?,
412 Err(err) => return Err(RunError::JobFailure(err)),
413 };
414 let failed = done.status.is_some_and(|status| !status.success());
415 let should_quit = sender.send(done).await.is_err();
416 if should_quit {
417 tracing::debug!(
418 ?should_quit,
419 "receiver is no longer available, exiting loop"
420 );
421 break;
422 }
423 if failed && !ignore_errors {
424 // Kill any running processes and wait for them to exit so we don't
425 // leave zombie processes, which may not get cleaned up by Tokio
426 // before our process exits
427 command_futures.shutdown().await;
428 break;
429 }
430 }
431 Ok(())
432 }
433
434 /// Run `spec` against `commit`. The caller is responsible for committing any
435 /// returned new tree to the repo.
436 async fn rewrite_commit(
437 base_ignores: Arc<GitIgnoreFile>,
438 pool: Arc<WorkspacePool>,
439 commit: Commit,
440 spec: Arc<CommandSpec>,
441 passthrough: bool,
442 ) -> Result<RunJob, RunError> {
443 let mut workspace = pool.acquire(&commit, base_ignores.clone()).await?;
444 let working_copy_dir = workspace.working_copy_dir.clone();
445 let old_id = commit.id().clone();
446 let old_tree = commit.tree();
447
448 // Resolve where the command should run. If the subdir doesn't exist in this
449 // commit's checked-out tree, skip the commit entirely.
450 let exec_dir = if let Some(subdir) = &spec.subdir {
451 let exec_dir = working_copy_dir.join(subdir);
452 if !exec_dir.is_dir() {
453 tracing::debug!(
454 ?exec_dir,
455 commit = old_id.hex(),
456 "subdirectory does not exist in commit; skipping"
457 );
458 // Persist the post-checkout state so the next pool acquisition
459 // can diff from this tree even though no command ran.
460 workspace.persist()?;
461 return Ok(RunJob {
462 old_id,
463 old_tree,
464 new_tree: None,
465 stdout: Vec::new(),
466 stderr: Vec::new(),
467 skipped: true,
468 status: None,
469 });
470 }
471 exec_dir
472 } else {
473 working_copy_dir.clone()
474 };
475
476 // TODO: Later this should take some trait which allows `run` to integrate with
477 // something like Bazels RE protocol.
478 // e.g
479 // ```
480 // let mut executor /* Arc<dyn CommandExecutor> */ = store.get_executor();
481 // let command = executor.spawn(...)?; // RE or separate processes depending on impl.
482 // ...
483 // ```
484 tracing::debug!("trying to run command '{}' on commit {}", spec, commit.id());
485
486 let mut command = tokio::process::Command::new(&spec.program);
487 command
488 .args(&spec.args)
489 .current_dir(&exec_dir)
490 .env("JJ_WORKSPACE_ROOT", &working_copy_dir)
491 .env("JJ_CHANGE_ID", commit.change_id().reverse_hex())
492 .env("JJ_COMMIT_ID", commit.id().hex())
493 .stdin(Stdio::null())
494 .kill_on_drop(true);
495 let output = if passthrough {
496 // Connect stdout/stderr directly to the terminal so TTY-aware
497 // programs work as expected. Capture is not possible; we wait
498 // for the process to exit and return empty stdout/stderr.
499 command.stdout(Stdio::inherit()).stderr(Stdio::inherit());
500 let status = command.status().await?;
501 Output {
502 status,
503 stdout: Vec::new(),
504 stderr: Vec::new(),
505 }
506 } else {
507 // Pipe and buffer the subprocess's stdout/stderr so we can emit them
508 // atomically to the parent's stdout/stderr after the process exits.
509 // Writing concurrently from multiple jobs would interleave output.
510 command.stdout(Stdio::piped()).stderr(Stdio::piped());
511 command.spawn()?.wait_with_output().await?
512 };
513
514 let options = pool.snapshot_options(base_ignores);
515 tracing::debug!("trying to snapshot the new tree");
516 let (dirty, stats) = workspace.tree_state.snapshot(&options).await.unwrap();
517 if !dirty {
518 tracing::debug!(
519 "commit {} was not modified as the passed command did not modify any tracked files",
520 commit.id()
521 );
522 }
523
524 if !output.status.success() {
525 // Remove non-ignored untracked files left by the command. Ignored paths
526 // are absent from `untracked_paths` and survive for build-artifact reuse.
527 // This keeps the slot free of stale files that would cause silent
528 // `skipped_files` collisions in the next `check_out`.
529 for path in stats.untracked_paths.keys() {
530 let abs = path.to_fs_path_unchecked(&working_copy_dir);
531 if let Err(err) = fs::remove_file(&abs)
532 && err.kind() != io::ErrorKind::NotFound
533 {
534 return Err(err.into());
535 }
536 }
537 }
538
539 // Persist the post-snapshot tree state so the next pool acquisition can
540 // diff against it and only touch files that changed. Done unconditionally
541 // so the slot is reusable even when the command failed.
542 workspace.persist()?;
543
544 let new_tree = if output.status.success() {
545 // Keep the snapshot as-is. The command may have left (or introduced) a
546 // conflict, and jj stores conflicts in the tree, so preserve the whole
547 // `MergedTree` rather than assuming it resolved to a single tree.
548 Some(workspace.tree_state.current_tree().clone())
549
550 // TODO: Serialize the new tree into /output/{id-tree} for a cache
551 // lookup TODO: supersede with a custom workspace implementation
552 } else {
553 None
554 };
555
556 Ok(RunJob {
557 old_id,
558 old_tree,
559 new_tree,
560 stdout: output.stdout,
561 stderr: output.stderr,
562 skipped: false,
563 status: Some(output.status),
564 })
565 }
566
567 /// Run a command across a set of revisions.
568 ///
569 /// Checks out each revision in an isolated working copy, runs the command, then
570 /// amends the revision with the resulting working copy. By default, descendants
571 /// are rebased on top of the amended revisions, propagating the diff. Use
572 /// `--restore-descendants` to keep descendants' content unchanged instead, or
573 /// `--ignore-changes` to run the command without rewriting any commits.
574 ///
575 /// The command is executed with the following environment variables set:
576 ///
577 /// - JJ_CHANGE_ID
578 /// - JJ_COMMIT_ID
579 /// - JJ_WORKSPACE_ROOT
580 ///
581 /// ### Example
582 ///
583 /// ```shell
584 /// # Run pre-commit on your local work
585 /// $ jj run -j 4 -- pre-commit run .github/pre-commit.yaml
586 /// ```
587 #[derive(clap::Args, Clone, Debug)]
588 #[command(verbatim_doc_comment)]
589 pub struct RunArgs {
590 /// Command to run across all selected revisions
591 #[arg(value_name = "COMMAND")]
592 command: String,
593
594 /// Arguments to pass to the command
595 ///
596 /// Hint: Use a `--` separator to allow passing arguments starting with `-`.
597 /// For example `jj run --revisions=... -- cargo build --release`.
598 #[arg(value_name = "ARGS")]
599 args: Vec<String>,
600
601 /// The revisions to change
602 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
603 revisions: Vec<RevisionArg>,
604
605 /// A no-op option to match the interface of `git rebase -x`
606 #[arg(short = 'x', hide = true)]
607 exec: bool,
608
609 /// How many processes should run in parallel
610 ///
611 /// Overrides the `run.jobs` config setting. Defaults to 1 if neither is
612 /// set.
613 #[arg(long, short)]
614 jobs: Option<usize>,
615
616 /// Run the command from the working-copy root in each commit instead of
617 /// from the subdirectory `jj run` was invoked from.
618 #[arg(long)]
619 root: bool,
620
621 /// Delete each working copy before running the command
622 ///
623 /// By default `jj run` reuses working copies between invocations so build
624 /// artifacts are preserved. With `--clean`, every commit starts from a
625 /// freshly checked-out tree.
626 #[arg(long)]
627 clean: bool,
628
629 /// Preserve the content (not the diff) when rebasing descendants
630 #[arg(long)]
631 restore_descendants: bool,
632
633 /// Pass through stdout and stderr directly to the terminal
634 ///
635 /// The command's stdout and stderr are connected directly to the
636 /// terminal (instead of being captured), so programs that behave
637 /// differently on a TTY (e.g. colored output, progress bars) work
638 /// as expected. Stdin is not inherited. Only one job is allowed
639 /// since parallel jobs would interleave their output.
640 #[arg(long)]
641 passthrough: bool,
642
643 /// Run the command without rewriting any commits.
644 ///
645 /// Each revision is checked out and the command is executed, but changes
646 /// made to the working copy are discarded. Useful for read-only checks
647 /// (tests, linters).
648 ///
649 /// This option permits running on immutable commits without passing
650 /// `--ignore-immutable`.
651 #[arg(long, conflicts_with = "restore_descendants")]
652 ignore_changes: bool,
653
654 /// Continue with remaining revisions when a command's exit code indicates
655 /// failure
656 ///
657 /// Any changes made by a failed command will not be saved, but changes from
658 /// successful commands are still applied atomically at the end.
659 ///
660 /// The exit code from any failed command will not impact the exit code of
661 /// `jj run` itself.
662 #[arg(long)]
663 ignore_errors: bool,
664 }
665
666 /// Precedence: `--jobs`, `run.jobs` config, 1.
667 fn resolve_jobs(
668 workspace_command: &WorkspaceCommandHelper,
669 jobs: Option<usize>,
670 ) -> Result<NonZeroUsize, CommandError> {
671 if let Some(j) = jobs {
672 return NonZeroUsize::new(j).ok_or_else(|| {
673 CommandError::new(
674 CommandErrorKind::Cli,
675 Box::new(RunError::InvalidJobCount(
676 i64::try_from(j).unwrap_or(i64::MAX),
677 )),
678 )
679 });
680 }
681 if let Ok(size) = workspace_command.settings().get_int("run.jobs") {
682 let size: usize = size
683 .try_into()
684 .map_err(|_| RunError::InvalidJobCount(size))?;
685 return NonZeroUsize::new(size).ok_or_else(|| {
686 CommandError::new(
687 CommandErrorKind::Config,
688 Box::new(RunError::InvalidJobCount(0)),
689 )
690 });
691 }
692 Ok(NonZeroUsize::MIN)
693 }
694
695 pub async fn cmd_run(
696 ui: &mut Ui,
697 command: &CommandHelper,
698 args: &RunArgs,
699 ) -> Result<(), CommandError> {
700 let repo_path = command.workspace_loader()?.repo_path().to_path_buf();
701 // TODO: should be stored in a backend and not hardcoded.
702 let base_path = repo_path.parent().unwrap().join("run").join("default");
703 fs::create_dir_all(&base_path)?;
704
705 let mut workspace_command = command.workspace_helper(ui).await?;
706 let mut resolved_commits: Vec<_> = if args.revisions.is_empty() {
707 let revs = workspace_command.settings().get_string("revsets.run")?;
708 workspace_command
709 .parse_revset(ui, &RevisionArg::from(revs))?
710 .evaluate_to_commits()?
711 .try_collect()
712 .await?
713 } else {
714 workspace_command
715 .parse_union_revsets(ui, &args.revisions)?
716 .evaluate_to_commits()?
717 .try_collect()
718 .await?
719 };
720 resolved_commits.reverse();
721
722 if !args.ignore_changes {
723 workspace_command
724 .check_rewritable(resolved_commits.iter().ids())
725 .await?;
726 }
727
728 let jobs = resolve_jobs(&workspace_command, args.jobs)?;
729
730 if args.passthrough && jobs.get() > 1 {
731 return Err(CommandError::new(
732 CommandErrorKind::Cli,
733 "cannot use --passthrough with more than one job".to_string(),
734 ));
735 }
736
737 tracing::debug!(?jobs, "starting `jj run`");
738
739 // Run each command from the subdirectory the user invoked `jj run` from,
740 // unless `--root` overrides that. The subdir is relative to the workspace
741 // root, which is canonical (per `CommandHelper::cwd` docs).
742 let subdir = if args.root {
743 None
744 } else {
745 Some(
746 command
747 .cwd()
748 .strip_prefix(workspace_command.workspace_root())
749 .map(Path::to_path_buf)
750 .unwrap_or_default(),
751 )
752 };
753
754 let store = workspace_command.repo().store().clone();
755 let auto_tracking_matcher = workspace_command.auto_tracking_matcher(ui)?;
756
757 let mut tx = workspace_command.start_transaction();
758
759 let rt = {
760 let mut builder = Builder::new_multi_thread();
761 builder.enable_io();
762 builder.enable_time();
763 builder.build().unwrap()
764 };
765 let (sender_tx, mut receiver) = mpsc::channel(jobs.get());
766
767 let pool = Arc::new(WorkspacePool::new(
768 &repo_path,
769 jobs,
770 auto_tracking_matcher,
771 args.clean,
772 )?);
773
774 let spec = Arc::new(CommandSpec {
775 program: args.command.clone(),
776 args: args.args.clone(),
777 subdir,
778 });
779 let mut rewritten_commits = HashMap::new();
780
781 // Drive the producer (run_inner) and consumer (receive loop) concurrently
782 // so that each subprocess's output is emitted as soon as it finishes rather
783 // than after all subprocesses complete.
784 futures::try_join!(
785 async {
786 run_inner(
787 &tx,
788 sender_tx,
789 rt.handle(),
790 spec.clone(),
791 pool.clone(),
792 &resolved_commits,
793 jobs.get(),
794 args.passthrough,
795 args.ignore_errors,
796 )
797 .await
798 .map_err(CommandError::from)
799 },
800 async {
801 while let Some(res) = receiver.recv().await {
802 if res.skipped {
803 writeln!(
804 ui.status(),
805 "Skipped commit {}: directory does not exist: {}",
806 res.old_id.hex(),
807 spec.subdir.as_deref().unwrap_or(Path::new("")).display()
808 )?;
809 } else {
810 if let Some(status) = res.status {
811 // Emit the subprocess's captured streams. Acquiring
812 // `ui.stdout()` / `ui.stderr()` for the duration of the
813 // write keeps each commit's output from interleaving with
814 // another's.
815 if !res.stdout.is_empty() {
816 let mut out = ui.stdout();
817 out.write_all(&res.stdout)?;
818 }
819 if !res.stderr.is_empty() {
820 let mut err = ui.stderr();
821 err.write_all(&res.stderr)?;
822 }
823 if !status.success() && !args.ignore_errors {
824 let commit = store.get_commit_async(&res.old_id).await?;
825 let mut error: CommandError =
826 RunError::CommandFailure(spec.to_string(), status).into();
827 error.add_formatted_hint_with(|formatter| {
828 write!(formatter, "Failed revision: ")?;
829 tx.write_commit_summary(formatter, &commit)
830 });
831 return Err(error);
832 }
833 }
834 if let Some(new_tree) = res.new_tree
835 && new_tree.tree_ids_and_labels() != res.old_tree.tree_ids_and_labels()
836 {
837 rewritten_commits.insert(res.old_id.clone(), (res.old_tree, new_tree));
838 }
839 }
840 }
841 Ok::<_, CommandError>(())
842 },
843 )?;
844
845 // The operation was a no-op, bail.
846 if args.ignore_changes || rewritten_commits.is_empty() {
847 tx.finish(ui, "run: nothing changed").await?;
848 return Ok(());
849 }
850
851 // The command did something, so rewrite the commits.
852 let restore_descendants = args.restore_descendants;
853 let mut count: u32 = 0;
854 let mut num_rebased: u32 = 0;
855 tx.repo_mut()
856 .transform_descendants(
857 resolved_commits.iter().ids().cloned().collect_vec(),
858 async |rewriter| {
859 let old_id = rewriter.old_commit().id().clone();
860 match (rewritten_commits.get(&old_id), restore_descendants) {
861 (Some((_, new_tree)), true) => {
862 let builder = rewriter.rebase().await?;
863 count += 1;
864 // Use the command result on top of the commit's
865 // original tree, ignoring rewrites of its ancestors.
866 builder.set_tree(new_tree.clone()).write().await?;
867 }
868 (Some((old_tree, new_tree)), false) => {
869 let builder = rewriter.rebase().await?;
870 count += 1;
871 // Apply the diff the command introduced (new_tree -
872 // old_tree) on top of the rebased tree, propagating
873 // ancestor rewrites via the normal rebase merge.
874 let rebased_tree = builder.tree();
875 let merged = MergedTree::merge(Merge::from_vec(vec![
876 (new_tree.clone(), "command result".to_owned()),
877 (old_tree.clone(), "original commit".to_owned()),
878 (rebased_tree, "rebased".to_owned()),
879 ]))
880 .await?;
881 builder.set_tree(merged).write().await?;
882 }
883 (None, restore_descendants) => {
884 // Descendant outside the run set
885 if rewriter.parents_changed() {
886 if restore_descendants {
887 rewriter.reparent().write().await?;
888 } else {
889 rewriter.rebase().await?.write().await?;
890 }
891 num_rebased += 1;
892 }
893 }
894 }
895 Ok(())
896 },
897 )
898 .await?;
899 writeln!(ui.status(), "Rewrote {count} commits.")?;
900 if num_rebased > 0 {
901 if restore_descendants {
902 writeln!(
903 ui.status(),
904 "Rebased {num_rebased} descendant commits (while preserving their content)."
905 )?;
906 } else {
907 writeln!(ui.status(), "Rebased {num_rebased} descendant commits.")?;
908 }
909 }
910 tx.finish(ui, format!("run: rewrite {count} commits"))
911 .await?;
912
913 Ok(())
914 }