Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions crates/socket-patch-cli/src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,7 +1088,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed {
more; `socket-patch remove {}` removes that entry alone",
pin.files.join(", "),
pin.purl,
pin.purl
crate::ui::shell_word(&pin.purl)
)
} else {
format!(
Expand All @@ -1097,7 +1097,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed {
uv_metadata.join(", "),
pin.purl,
pin.files.join(", "),
pin.purl
crate::ui::shell_word(&pin.purl)
)
};
if args.common.json {
Expand Down
62 changes: 58 additions & 4 deletions crates/socket-patch-cli/src/commands/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,18 +351,26 @@ async fn patched_in_other_scope(

/// `rollback`'s pointer at the scope that still holds a patched copy: a
/// rollback of just that purl, naming `--cwd` when the run used one (the record lives in that
/// project's manifest).
/// project's manifest). The command names the release without the record's
/// qualifiers (`?platform=ruby`, `?artifact_id=...`): the record was kept
/// with its whole variant group, a base purl selects that group, and a `?`
/// is a glob character to the shell. The purl and the directory are quoted
/// where a shell would otherwise read them as more than one word.
fn patched_in_other_scope_warning(purl: &str, path: &Path, common: &GlobalArgs) -> String {
let word = crate::ui::shell_word(strip_purl_qualifiers(purl));
let (scope, mut command) = if common.is_global() {
("the project", format!("socket-patch rollback {purl}"))
("the project", format!("socket-patch rollback {word}"))
} else {
(
"the global install",
format!("socket-patch rollback {purl} -g"),
format!("socket-patch rollback {word} -g"),
)
};
if common.cwd != Path::new(".") {
command.push_str(&format!(" --cwd {}", common.cwd.display()));
command.push_str(&format!(
" --cwd {}",
crate::ui::shell_word(&common.cwd.to_string_lossy())
));
}
format!(
"{purl}: its copy in {scope} ({}) is still patched or could not be \
Expand Down Expand Up @@ -4496,6 +4504,52 @@ mod tests {
use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord};
use std::collections::HashMap;

/// The command this warning tells the user to run is one they paste.
/// A record's purl can carry qualifiers (`?platform=ruby`,
/// `?artifact_id=...`), and `?` is a glob character: the command names
/// the release, which selects the variant group the run kept. What is
/// left that a shell reads specially (`%40`, a space in `--cwd`) is
/// quoted (#2182).
#[test]
fn other_scope_warning_prints_a_command_a_shell_reads_as_written() {
let quoted = |word: &str| {
if cfg!(windows) {
format!("\"{word}\"")
} else {
format!("'{word}'")
}
};
let purl = "pkg:gem/rack@3.1.8?platform=ruby";
let path = Path::new("/gems/rack-3.1.8");
let local = crate::args::GlobalArgs::default();
let warning = patched_in_other_scope_warning(purl, path, &local);
assert!(
warning.contains("run `socket-patch rollback pkg:gem/rack@3.1.8 -g` to"),
"{warning}"
);
// The message's own naming of the record stays its full purl.
assert!(
warning.starts_with(&format!("{purl}: its copy in")),
"{warning}"
);

let scoped = "pkg:npm/%40scope/a@1.0.0";
let global = crate::args::GlobalArgs {
global: true,
cwd: PathBuf::from("my app"),
..crate::args::GlobalArgs::default()
};
let warning = patched_in_other_scope_warning(scoped, path, &global);
assert!(
warning.contains(&format!(
"run `socket-patch rollback {} --cwd {}` to",
quoted(scoped),
quoted("my app")
)),
"{warning}"
);
}

// The legacy path-taking delegation shape, kept for the unit tests below
// (`remove` now threads its already-loaded manifest and ledger straight
// into `rollback_patches_inner`; this wrapper reads them from disk). The
Expand Down
6 changes: 4 additions & 2 deletions crates/socket-patch-cli/src/commands/scan/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,13 @@ async fn keep_patched_cargo_copies(
prunable.retain(|p| !kept.contains(p));
kept.into_iter()
.map(|purl| {
let word = crate::ui::shell_word(&purl);
(
"cargo_cache_patch_kept",
format!(
"kept {purl}: the project no longer resolves it, but its copy in the \
shared Cargo registry cache is still patched (or could not be \
read to tell); run `socket-patch rollback {purl}` (with `--global` \
read to tell); run `socket-patch rollback {word}` (with `--global` \
when a `cargo vendor` dir hides the registry cache) to restore \
that copy and drop the entry"
),
Expand Down Expand Up @@ -435,12 +436,13 @@ async fn keep_patched_pypi_copies(
prunable.retain(|p| !kept.contains(p));
kept.into_iter()
.map(|purl| {
let word = crate::ui::shell_word(&purl);
(
"pypi_installed_patch_kept",
format!(
"kept {purl}: the scan no longer reports it as one of the project's \
packages, but an installed copy is still patched (or could not be \
read to tell); run `socket-patch rollback {purl}` (with `--global` \
read to tell); run `socket-patch rollback {word}` (with `--global` \
when the copy is in another interpreter or a tool's environment) \
to restore that copy and drop the entry"
),
Expand Down
68 changes: 58 additions & 10 deletions crates/socket-patch-cli/src/commands/scan/hosted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ fn mirror_pins_not_moved(
`socket-patch rollback {}` and then this command again",
c.purl,
mirror_sources.base(),
c.purl
// As `rollback` selects a hosted pin: no qualifiers.
crate::ui::shell_word(socket_patch_core::utils::purl::strip_purl_qualifiers(
&c.purl
))
),
))
})
Expand Down Expand Up @@ -3277,23 +3280,32 @@ fn format_gem_hold_note(
if dry_run {
return Some(note);
}
// The one gem's own purl, when exactly one confirmed pin carries its
// name; else the shape of one, for the user to fill in.
// The one gem's own pin, when the confirmed pins of its name are one
// release; else the shape of one, for the user to fill in. A pin is
// named as `rollback` selects it, without the record's qualifiers
// (`?platform=ruby` on every gem record): with them the command
// matches no hosted pin, and under bash's `nullglob` the unquoted `?`
// drops the argument, leaving the bare `rollback` this note must not
// give.
let purl = one.and_then(|name| {
let prefix = format!("pkg:gem/{name}@");
let mut pins = confirmed
let mut pins: Vec<&str> = confirmed
.iter()
.map(|(purl, _)| purl.as_str())
.filter(|purl| purl.starts_with(&prefix));
match (pins.next(), pins.next()) {
(Some(purl), None) => Some(purl),
.map(|(purl, _)| socket_patch_core::utils::purl::strip_purl_qualifiers(purl))
.filter(|purl| purl.starts_with(&prefix))
.collect();
pins.sort_unstable();
pins.dedup();
match pins.as_slice() {
[purl] => Some(crate::ui::shell_word(purl)),
_ => None,
}
});
let placeholder = || "pkg:gem/<gem>@<version>".to_string();
let (move_one, target, update_arg) = match (one, purl) {
(Some(name), Some(purl)) => ("it", purl, name),
(Some(name), None) => ("it", "pkg:gem/<gem>@<version>", name),
(None, _) => ("one", "pkg:gem/<gem>@<version>", "<gem>"),
(Some(name), None) => ("it", placeholder(), name),
(None, _) => ("one", placeholder(), "<gem>"),
};
let again = if command == "scan" {
"then `socket-patch scan` again"
Expand Down Expand Up @@ -5938,6 +5950,42 @@ mod tests {
`socket-patch scan` again."
)
);
// A gem record's purl carries `?platform=ruby`. The note names the
// pin as `rollback` selects it, without the qualifier: with it the
// command matches no hosted pin, and its `?` is a glob character
// that zsh refuses and bash under `nullglob` drops, leaving a bare
// `rollback` (#2182).
let qualified = [
pin("pkg:gem/rack@3.1.8?platform=ruby"),
pin("pkg:gem/nokogiri@1.16.0?platform=x86_64-linux"),
];
for command in ["scan", "get"] {
let note =
super::format_gem_hold_note(&edits[..1], &qualified, command, false).unwrap();
assert!(
note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"),
"{note}"
);
assert!(!note.contains('?'), "{note}");
}
// Two records of the one release (a ruby and a platform build) are
// one pin, so the note still names it.
let builds = [
pin("pkg:gem/rack@3.1.8?platform=ruby"),
pin("pkg:gem/rack@3.1.8?platform=x86_64-linux"),
];
let note = super::format_gem_hold_note(&edits[..1], &builds, "scan", false).unwrap();
assert!(
note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"),
"{note}"
);
// Two versions of it are two pins: the user fills in which.
let versions = [pin("pkg:gem/rack@3.1.8"), pin("pkg:gem/rack@2.2.8")];
let note = super::format_gem_hold_note(&edits[..1], &versions, "scan", false).unwrap();
assert!(
note.contains("run `socket-patch rollback pkg:gem/<gem>@<version>`, then"),
"{note}"
);
// No bare `socket-patch rollback` anywhere: it unwinds every patch.
for edits in [&edits[..], &edits[..1]] {
for confirmed in [&confirmed[..], &[]] {
Expand Down
4 changes: 3 additions & 1 deletion crates/socket-patch-cli/src/commands/scan/withdrawn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ pub(super) async fn sweep(
"{} is pinned to patch {}, which is no longer published \
({status}), but it was not restored: {message}; re-run, or run \
`socket-patch rollback {}`",
pin.purl, pin.uuid, pin.purl
pin.purl,
pin.uuid,
crate::ui::shell_word(&pin.purl)
),
);
}
Expand Down
113 changes: 112 additions & 1 deletion crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6345,13 +6345,84 @@ async fn release_upstream_1_1_0(fx: &RedirectFixture) {
}
}

/// Serve the patch record's purl the way the patch service spells a gem
/// record's: with its `?platform=ruby` qualifier, on every route that
/// carries it (the package a batch result is filed under stays bare). Each
/// route answers what the fixture's own does, respelled, and outranks it.
async fn serve_record_purl_with_platform(fx: &RedirectFixture) {
let api = fx._server.uri();
let bare = format!("\"purl\":\"{PURL}\"");
let qualified = format!("\"purl\":\"{PURL}?platform=ruby\"");
let client = reqwest::Client::new();
let post = |route: &str| client.post(format!("{api}{route}")).body("{}");
let get = |route: &str| client.get(format!("{api}{route}"));
let batch = format!("/v0/orgs/{ORG}/patches/batch");
let by_package = format!("/v0/orgs/{ORG}/patches/by-package/{DEP}");
let reference = format!("/v0/orgs/{ORG}/patches/package");
let view = format!("/v0/orgs/{ORG}/patches/view/{UUID}");
for (verb, route, request, keep_first) in [
("POST", batch.as_str(), post(&batch), true),
("GET", by_package.as_str(), get(&by_package), false),
("POST", reference.as_str(), post(&reference), false),
("GET", view.as_str(), get(&view), false),
] {
let body = request
.send()
.await
.expect("fixture API reachable")
.text()
.await
.expect("fixture API body");
assert!(body.contains(&bare), "{route} carries the purl: {body}");
let respelled = if keep_first {
let (head, tail) = body.split_once(&bare).expect("checked above");
format!("{head}{bare}{}", tail.replace(&bare, &qualified))
} else {
body.replace(&bare, &qualified)
};
assert!(respelled.contains(&qualified), "{route}: {respelled}");
let matcher = if route == by_package {
Mock::given(method(verb)).and(path_regex(format!(
"^/v0/orgs/{ORG}/patches/by-package/.+$"
)))
} else {
Mock::given(method(verb)).and(path(route))
};
matcher
.respond_with(ResponseTemplate::new(200).set_body_raw(respelled, "application/json"))
.with_priority(1)
.mount(&fx._server)
.await;
}
}

/// The words a bash with `nullglob` set reads `command` as: a word that
/// holds an unquoted glob character and matches no file is dropped.
fn bash_nullglob_words(cwd: &Path, command: &str) -> Vec<String> {
let out = Command::new("bash")
.args(["-O", "nullglob", "-c", &format!("printf '%s\\n' {command}")])
.current_dir(cwd)
.output()
.expect("bash runs");
assert!(out.status.success(), "bash reads `{command}`: {out:?}");
String::from_utf8(out.stdout)
.expect("utf8 words")
.lines()
.map(str::to_owned)
.collect()
}

/// A hosted gem's only source is its patch's registry, which serves one
/// version, so the gem leaves `bundle outdated` and `bundle update` cannot
/// move it (#2070). The scan has to say so, and what it says has to be true
/// of the real Bundler: with a newer upstream release out, `bundle outdated`
/// lists the gem before the scan and not after, `bundle update` leaves the
/// scanned lock at the patched version, and the way past the hold the scan
/// names (`rollback`, then `bundle update <gem>`) does move the gem.
///
/// The `rollback` it names is run as printed, through a shell (#2182): the
/// record's purl carries `?platform=ruby`, which selects no hosted pin and
/// which a shell globs, so the command names the pin without it.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17); \
the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"]
Expand Down Expand Up @@ -6430,6 +6501,7 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() {

// The scan, in human output: it names the gem it now holds and the way
// past the hold.
serve_record_purl_with_platform(&fx).await;
let (code, stdout, stderr) = run_socket(
&fx.proj,
&[
Expand Down Expand Up @@ -6477,8 +6549,47 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() {
);

// And the way past it works: roll back, then `bundle update <gem>`.
// The rollback is the command the note printed, as a shell reads it.
std::fs::write(&lock_path, &scanned_lock).unwrap();
rollback();
let printed = stdout
.lines()
.find(|line| line.starts_with("Bundler now takes "))
.and_then(|line| {
line.split('`')
.find(|span| span.starts_with("socket-patch rollback "))
})
.expect("the scan's hold line names a rollback");
let words = bash_nullglob_words(&fx.proj, printed);
assert_eq!(
words,
["socket-patch", "rollback", PURL],
"a shell passes the printed command on whole"
);
let mut argv: Vec<&str> = words[1..].iter().map(String::as_str).collect();
argv.extend([
"--json",
"--cwd",
cwd,
"--api-url",
&api,
"--org",
ORG,
"--api-token",
"fake",
"--patch-server-url",
&api,
]);
let (code, stdout, stderr) =
run_socket_env(&fx.proj, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]);
assert_eq!(
code, 0,
"`{printed}`:\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert_eq!(
String::from_utf8_lossy(&std::fs::read(&lock_path).unwrap()),
String::from_utf8_lossy(&fx.pristine_lock),
"`{printed}` hands the lock back byte for byte"
);
let (updated, update) = bundle_cold(&["update", DEP]);
assert!(updated, "`bundle update {DEP}` after rollback:\n{update}");
assert!(
Expand Down
Loading