Skip to content
Merged
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ socket-patch scan --package lodash # limit selection to a package
socket-patch scan --max-new-patches 5 # introduce at most five new patches
socket-patch scan 'apps/*' # scan projects in a monorepo
socket-patch get pkg:npm/lodash@4.17.20 # target one package version
socket-patch show pkg:npm/lodash@4.17.20 # look inside a patch: fixes, measurements, diff
socket-patch list # what is patched here; in a terminal, browse and open patches
socket-patch vendor # eject an existing hosted patch set
socket-patch repair # restore agent or vendored patch artifacts
socket-patch rollback lodash # restore one package to upstream
Expand Down
47 changes: 36 additions & 11 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

105 changes: 57 additions & 48 deletions crates/socket-patch-cli/src/commands/agent_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,30 +309,40 @@ pub(crate) fn files_with_both_hashes(patch: &PatchResponse) -> HashMap<String, P
files
}

/// The summary after the multi-patch download loop. A run that changed
/// nothing says so instead of claiming the patches were "saved".
pub(crate) fn format_save_summary(
/// The result line of a download that applies nothing after the save
/// (`--save-only`): `Saved 2 patches to .socket/manifest.json (1 updated,
/// 1 skipped).` A run that changed nothing says so instead of claiming the
/// patches were saved.
pub(crate) fn format_save_line(
manifest_path: &Path,
added: usize,
updated: usize,
skipped: usize,
failed: usize,
) -> String {
let mut out = if added + updated > 0 {
format!("Patches saved to {}", manifest_path.display())
let saved = added + updated;
let mut out = if saved > 0 {
format!(
"Saved {} to {}",
crate::ui::plural(saved, "patch", "patches"),
manifest_path.display()
)
} else {
format!("No changes to {}", manifest_path.display())
};
out.push_str(&format!("\n Added: {added}"));
for (label, n) in [
("Updated", updated),
("Skipped", skipped),
("Failed", failed),
] {
if n > 0 {
out.push_str(&format!("\n {label}: {n}"));
}
}
let notes: Vec<String> = [
(updated, "updated"),
(skipped, "skipped"),
(failed, "failed"),
]
.into_iter()
.filter(|(n, _)| *n > 0)
.map(|(n, what)| format!("{n} {what}"))
.collect();
if !notes.is_empty() {
out.push_str(&format!(" ({})", notes.join(", ")));
}
out.push('.');
out
}

Expand Down Expand Up @@ -1298,7 +1308,7 @@ pub(crate) async fn fetch_selected_patches(
// The narrowing queries the API: show that something is happening
// once selection (and get's confirm prompt) is done.
let mut status = crate::ui::StatusLine::stderr(params.json, params.silent);
status.set("Preparing download...");
status.set("Preparing download");
let (selected, warnings, views) = filter_to_installed_releases(
selected,
params.all_releases,
Expand All @@ -1309,14 +1319,12 @@ pub(crate) async fn fetch_selected_patches(
.await;
status.finish();
prefetched.extend(views);
// No leading blank line: the caller's prompt or summary already ended
// its line.
if matches!(store, RecordStore::Manifest(_)) && !quiet {
eprintln!(
"Downloading {}...",
crate::ui::plural(selected.len(), "patch", "patches")
);
}
// The callers have already listed the patches (`scan`'s rows, `get`'s
// listing), so a downloaded patch is not named again here: the
// download shows on the status line. It shows only across each network
// wait below and is cleared before anything else can print, so a skip
// or error line never lands on it.
let mut progress = crate::ui::StatusLine::stderr(params.json, params.silent);

let mut batch = FetchBatch {
skipped: 0,
Expand Down Expand Up @@ -1357,7 +1365,7 @@ pub(crate) async fn fetch_selected_patches(
|uuid| async move { (uuid, hold_back_debug(api_client.fetch_patch(uuid)).await) },
));

for search_result in &selected {
for (done, search_result) in selected.iter().enumerate() {
let (purl, uuid) = (search_result.purl.as_str(), search_result.uuid.as_str());

// Refusal FIRST (the dry-run preview's precedence): a preserved
Expand Down Expand Up @@ -1414,18 +1422,23 @@ pub(crate) async fn fetch_selected_patches(
// these turns.
let view = match prefetched.remove(uuid) {
Some(patch) => Ok(Some(patch)),
None => match views.next().await {
Some((planned, view)) if planned == uuid => view.release(),
// Unreachable (the plan mirrors this loop's checks); a
// live fetch keeps the outcome right regardless.
_ => {
debug_assert!(
false,
"view prefetch plan out of step with the download loop"
);
api_client.fetch_patch(uuid).await
None => {
progress.progress("Downloading patches", done, selected.len());
let next = views.next().await;
progress.finish();
match next {
Some((planned, view)) if planned == uuid => view.release(),
// Unreachable (the plan mirrors this loop's checks); a
// live fetch keeps the outcome right regardless.
_ => {
debug_assert!(
false,
"view prefetch plan out of step with the download loop"
);
api_client.fetch_patch(uuid).await
}
}
},
}
};
let patch = match view {
Ok(Some(patch)) => patch,
Expand Down Expand Up @@ -1466,9 +1479,9 @@ pub(crate) async fn fetch_selected_patches(
},
};
if action == PatchAction::Skipped {
if !quiet {
eprintln!("{}", format_record_skip(&patch.purl, "already in manifest"));
}
// No line of its own: the caller has listed the patch, and the
// run's result says it (`Applied 0 of 1 patch: 1 already
// patched.`, `No changes to <manifest> (1 skipped).`).
batch.events.push(
PatchEvent::new(EventAction::Skipped, patch.purl.as_str())
.with_uuid(patch.uuid.as_str())
Expand Down Expand Up @@ -1542,6 +1555,7 @@ pub(crate) async fn fetch_selected_patches(
}
_ => PatchEvent::new(EventAction::Downloaded, patch.purl.as_str()),
};
// A replaced record is worth its line; a new one has been listed.
if let PatchAction::Updated { old_uuid } = &action {
if !quiet {
// Defensive: a malformed/short UUID in the store must not
Expand All @@ -1552,8 +1566,6 @@ pub(crate) async fn fetch_selected_patches(
crate::ui::short_uuid(old_uuid)
);
}
} else if !quiet {
eprintln!(" [{tag}] {}", normalize_purl(&patch.purl));
}
event = event.with_uuid(patch.uuid.as_str()).with_details(details);
batch.events.push(tag_mode(event, batch.mode));
Expand Down Expand Up @@ -2302,21 +2314,18 @@ pub async fn download_and_apply_patches_into(
}
env.warnings.extend(warnings);

if !quiet {
eprintln!();
// The apply below says the run's result. With no apply to follow
// (`--save-only`), the save is the result.
if !quiet && apply_lock.is_none() {
eprintln!(
"{}",
format_save_summary(&manifest_path, added, updated, batch.skipped, batch.failed)
format_save_line(&manifest_path, added, updated, batch.skipped, batch.failed)
);
}

// Auto-apply unless --save-only (the lock decision above).
let mut apply_report: Option<ApplyRunReport> = None;
if let Some(lock) = apply_lock {
if !quiet {
eprintln!();
eprintln!("Applying patches...");
}
// Past the network, about to write to installed packages: a
// hot-patch pass is no longer dropped at its time limit.
crate::hot_patch::mark_apply_started();
Expand Down
77 changes: 75 additions & 2 deletions crates/socket-patch-cli/src/commands/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1892,7 +1892,15 @@ pub(crate) async fn run_locked(
if !args.common.json && !args.common.silent {
let cwd = std::fs::canonicalize(&args.common.cwd)
.unwrap_or_else(|_| args.common.cwd.clone());
let block = format_results_block(&results, &caveats, args.common.dry_run, &cwd);
// A nested apply's caller (`scan`, `get`) has listed the
// packages itself: the block that names them again is left
// out, and the result is one short line.
let compact = args.nested.is_some();
let block = if compact {
Vec::new()
} else {
format_results_block(&results, &caveats, args.common.dry_run, &cwd)
};
let mut block = block.iter().peekable();
// A nested apply's caller already ended its stdout with a
// blank line (its listing or table), so the block's leading
Expand All @@ -1907,7 +1915,16 @@ pub(crate) async fn run_locked(
if args.common.verbose && !results.is_empty() {
print_verbose_verification(&results);
}
if show_summary {
if show_summary && compact {
println!(
"{}",
format_compact_summary(
&tally_results(&results, &caveats),
targeted,
unmatched.len()
)
);
} else if show_summary {
let tally = tally_results(&results, &caveats);
println!();
if args.common.dry_run {
Expand Down Expand Up @@ -2471,6 +2488,35 @@ fn format_summary_line(tally: &ApplyTally, targeted: usize, not_found: usize) ->
format!("Summary: {}", parts.join(", "))
}

/// [`format_summary_line`] for a nested apply, whose caller (`scan`, `get`)
/// lists the patched packages itself: `Applied 6 patches.`, and the other
/// buckets only when a patch landed in one
/// (`Applied 4 of 6 patches: 1 already patched, 1 failed.`).
fn format_compact_summary(tally: &ApplyTally, targeted: usize, not_found: usize) -> String {
let rest: Vec<String> = [
(tally.already, "already patched"),
(tally.vendored, "vendored"),
(tally.not_applicable, "not applicable"),
(tally.not_in_effect, "not in effect"),
(tally.failed, "failed"),
(not_found, "not found on disk"),
]
.into_iter()
.filter(|(n, _)| *n > 0)
.map(|(n, what)| format!("{n} {what}"))
.collect();
if rest.is_empty() {
format!("Applied {}.", plural(tally.applied, "patch", "patches"))
} else {
format!(
"Applied {} of {}: {}.",
tally.applied,
plural(targeted, "patch", "patches"),
rest.join(", ")
)
}
}

/// The dry-run summary block: what a wet run would do, per package.
fn format_dry_run_summary(tally: &ApplyTally, not_found: usize) -> Vec<String> {
let mut lines = vec![
Expand Down Expand Up @@ -4833,6 +4879,33 @@ mod tests {
format_summary_line(&failed, 1, 0),
"Summary: 0 of 1 targeted patch applied, 0 already patched, 1 failed, 0 not found on disk"
);
// The compact form names only the buckets a patch landed in.
let all = ApplyTally {
applied: 6,
..ApplyTally::default()
};
assert_eq!(format_compact_summary(&all, 6, 0), "Applied 6 patches.");
assert_eq!(format_compact_summary(&one, 1, 0), "Applied 1 patch.");
assert_eq!(
format_compact_summary(&mixed, 4, 1),
"Applied 1 of 4 patches: 2 already patched, 1 not found on disk."
);
assert_eq!(
format_compact_summary(&failed, 1, 0),
"Applied 0 of 1 patch: 1 failed."
);
// A patch written but not in effect never reads as applied, and
// one with nothing to patch in this build is named too.
let partial = ApplyTally {
applied: 1,
not_in_effect: 1,
not_applicable: 1,
..ApplyTally::default()
};
assert_eq!(
format_compact_summary(&partial, 3, 0),
"Applied 1 of 3 patches: 1 not applicable, 1 not in effect."
);
}

#[test]
Expand Down
Loading
Loading