Skip to content
Merged
49 changes: 48 additions & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

11 changes: 8 additions & 3 deletions crates/socket-patch-cli/src/commands/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ pub use crate::commands::agent_download::{
};
use crate::commands::apply::ApplyRunReport;
use crate::ecosystem_dispatch::{
crawl_ecosystems, find_packages_for_rollback, installed_target_matches, partition_purls,
crawl_ecosystems_for_name, find_packages_for_rollback, installed_target_matches,
partition_purls,
};
use crate::json_envelope::{
usage_error, Command as JsonCommand, Envelope, EnvelopeError, PatchAction as EventAction,
Expand Down Expand Up @@ -1465,9 +1466,13 @@ pub async fn run(args: GetArgs) -> i32 {
TargetKind::Name => {
status.set("Enumerating packages...");
// `--ecosystems` scopes the crawl, so a name can only resolve
// inside the selected ecosystems.
// inside the selected ecosystems. A name resolves among every
// installed package, as its PURL would: a Python project with
// no environment of its own is otherwise crawled only for the
// packages it declares.
let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty());
let (all_packages, _, _) = crawl_ecosystems(&args.common.crawler_options(), only).await;
let (all_packages, _, _) =
crawl_ecosystems_for_name(&args.common.crawler_options(), only).await;

if all_packages.is_empty() {
status.finish();
Expand Down
176 changes: 174 additions & 2 deletions crates/socket-patch-cli/src/commands/scan/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,8 @@ async fn apply_gc_locked(
};
let mut prunable = detect_prunable(&manifest, scanned_purls, vendored);
keep_project_entries(common, &mut prunable).await;
let kept = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await;
let mut kept = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await;
kept.extend(keep_patched_pypi_copies(common, &manifest, socket_dir, &mut prunable).await);
for purl in &prunable {
manifest.patches.remove(purl);
}
Expand Down Expand Up @@ -331,8 +332,12 @@ async fn keep_project_entries(common: &GlobalArgs, prunable: &mut Vec<String>) {
global_prefix: None,
..common.clone()
};
// Every package installed where the project installs, not only the
// ones a Python project with no environment of its own declares: a
// record for an undeclared one (`get <name>`) is the project's too.
let (installed, _, _) =
crate::ecosystem_dispatch::crawl_ecosystems(&project.crawler_options(), None).await;
crate::ecosystem_dispatch::crawl_ecosystems_for_name(&project.crawler_options(), None)
.await;
let ctx = crate::commands::context::ProjectContext::new(&project);
let locked = &ctx.locks().await.entries;
let accounted: HashSet<PurlKey> = installed
Expand Down Expand Up @@ -405,6 +410,64 @@ async fn keep_patched_cargo_copies(
.collect()
}

/// Drop from `prunable` every PyPI entry whose agent-mode patch is still
/// on disk in a copy the crawl does not report: a project with no
/// environment of its own is crawled for the packages it declares, in the
/// one interpreter it installs into, but a package it stopped declaring,
/// or one an earlier release patched in another interpreter or a tool's
/// environment, keeps its patched copy. The manifest record holds the only
/// before-blobs that can restore that copy, so it is kept, with one
/// `pypi_installed_patch_kept` warning per entry naming the `rollback` that
/// restores the copy and then drops the record.
async fn keep_patched_pypi_copies(
common: &GlobalArgs,
manifest: &PatchManifest,
socket_dir: &Path,
prunable: &mut Vec<String>,
) -> Vec<(&'static str, String)> {
let kept = crate::ecosystem_dispatch::pypi_copies_still_patched(
manifest,
prunable.iter(),
&common.crawler_options(),
&socket_dir.join("blobs"),
)
.await;
prunable.retain(|p| !kept.contains(p));
kept.into_iter()
.map(|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` \
when the copy is in another interpreter or a tool's environment) \
to restore that copy and drop the entry"
),
)
})
.collect()
}

/// The `pypi_installed_patch_kept` warnings of a `--prune` whose crawl
/// found nothing. The manifest half of the GC is skipped there, so no
/// record is dropped, but a recorded PyPI patch can still be on disk in a
/// copy the scan no longer reaches (another interpreter, a tool's
/// environment), and this warning is what names the `rollback` that
/// restores it. Read-only: no lock, nothing written.
pub(super) async fn kept_pypi_patch_warnings(
common: &GlobalArgs,
manifest_path: &Path,
socket_dir: &Path,
) -> Vec<(&'static str, String)> {
let Ok(Some(manifest)) = read_manifest(manifest_path).await else {
return Vec::new();
};
let mut recorded: Vec<String> = manifest.patches.keys().cloned().collect();
recorded.sort();
keep_patched_pypi_copies(common, &manifest, socket_dir, &mut recorded).await
}

/// The vendored-state half of the GC alone, for a `--prune` whose crawl
/// found nothing (the manifest half is skipped there: pruning against an
/// empty crawl would drop every entry). Reverting entries whose patch left
Expand Down Expand Up @@ -470,6 +533,7 @@ async fn preview_apply_gc(
let mut prunable = detect_prunable(&manifest, scanned_purls, vendored);
keep_project_entries(common, &mut prunable).await;
let _ = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await;
let _ = keep_patched_pypi_copies(common, &manifest, socket_dir, &mut prunable).await;
// The sweep derives the referenced set from this in-memory manifest.
for purl in &prunable {
manifest.patches.remove(purl);
Expand Down Expand Up @@ -1630,4 +1694,112 @@ mod tests {
]
);
}

/// A PyPI entry the crawl does not report is kept while an installed
/// copy still carries its patch. A project with no environment of its
/// own is crawled only for the packages it declares, so a package it
/// stopped declaring drops out of the crawl with its copy still
/// patched, and the record's before-blobs are the only way to restore
/// that copy. An entry whose copy is back to the original is pruned.
#[tokio::test]
async fn prune_keeps_a_pypi_entry_whose_installed_copy_is_still_patched() {
use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as hash;
const ORIGINAL: &[u8] = b"VERSION = 'original'\n";
const PATCHED: &[u8] = b"VERSION = 'patched'\n";

let tmp = tempfile::tempdir().unwrap();
let site = tmp.path().join("site-packages");
for (name, module) in [("stillpatched", PATCHED), ("restored", ORIGINAL)] {
let dist = site.join(format!("{name}-1.0.0.dist-info"));
std::fs::create_dir_all(&dist).unwrap();
std::fs::write(
dist.join("METADATA"),
format!("Metadata-Version: 2.1\nName: {name}\nVersion: 1.0.0\n"),
)
.unwrap();
std::fs::create_dir_all(site.join(name)).unwrap();
std::fs::write(site.join(name).join("__init__.py"), module).unwrap();
}

let project = tmp.path().join("project");
let socket_dir = project.join(".socket");
let blobs = socket_dir.join("blobs");
std::fs::create_dir_all(&blobs).unwrap();
for content in [ORIGINAL, PATCHED] {
std::fs::write(blobs.join(hash(content)), content).unwrap();
}
let record = |name: &str, uuid: &str| {
serde_json::json!({
"uuid": uuid,
"exportedAt": "2026-01-01T00:00:00Z",
"files": { format!("{name}/__init__.py"): {
"beforeHash": hash(ORIGINAL),
"afterHash": hash(PATCHED),
}},
"vulnerabilities": {},
"description": "seed",
"license": "MIT",
"tier": "free",
})
};
let kept = "pkg:pypi/stillpatched@1.0.0";
let pruned = "pkg:pypi/restored@1.0.0";
let manifest_path = socket_dir.join("manifest.json");
let manifest = serde_json::json!({ "patches": {
kept: record("stillpatched", "22222222-2222-4222-8222-222222222222"),
pruned: record("restored", "33333333-3333-4333-8333-333333333333"),
}});
std::fs::write(
&manifest_path,
serde_json::to_vec_pretty(&manifest).unwrap(),
)
.unwrap();

// The crawl reported neither package. `--global-prefix` names the
// site dir their copies are looked up in by PURL.
let scanned = scanned(&["pkg:pypi/declared@1.0.0"]);
for dry_run in [true, false] {
let common = crate::args::GlobalArgs {
cwd: project.clone(),
global_prefix: Some(site.clone()),
dry_run,
..Default::default()
};
let gc = if dry_run {
preview_apply_gc(
&common,
&manifest_path,
&socket_dir,
&scanned,
&no_vendored(),
)
.await
} else {
run_apply_gc(
&common,
&manifest_path,
&socket_dir,
&scanned,
&no_vendored(),
)
.await
};
assert_eq!(gc.pruned, vec![pruned.to_string()], "dry_run={dry_run}");
if !dry_run {
assert!(
gc.warnings.iter().any(|(code, detail)| {
*code == "pypi_installed_patch_kept" && detail.contains(kept)
}),
"the kept entry must be explained: {gc:?}"
);
}
}
let manifest = read_manifest(&manifest_path).await.unwrap().unwrap();
assert!(manifest.patches.contains_key(kept), "{manifest:?}");
assert!(!manifest.patches.contains_key(pruned), "{manifest:?}");
assert!(
blobs.join(hash(ORIGINAL)).exists(),
"the kept entry's before-blob is its only restore data"
);
}
}
46 changes: 38 additions & 8 deletions crates/socket-patch-cli/src/commands/scan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2914,6 +2914,18 @@ async fn scan_project(
projects_left_warnings(&left),
);
}
// The prune is skipped on an empty crawl, so no record is dropped
// here. A recorded PyPI patch can still be on disk in a copy this
// scan no longer reaches, and its warning is what names the
// `rollback` that restores it.
if prune && !hosted {
layout_refusals.extend(
gc::kept_pypi_patch_warnings(&args.common, &manifest_path, &socket_dir)
.await
.into_iter()
.map(|(code, detail)| (code.to_string(), detail)),
);
}
status.finish();
if human {
print_layout_refusals(&layout_refusals, &project_patch_notice, args.common.silent);
Expand Down Expand Up @@ -3027,14 +3039,32 @@ async fn scan_project(
)
);
} else if !policy.root_excluded() {
println!(
"{}",
render::no_packages_message(
args.common.is_global(),
args.common.ecosystems.as_deref(),
&args.paths,
)
);
// Nothing was crawled at all, yet the Python on PATH holds
// packages the project does not declare: say that they
// were left out, not that nothing is installed.
let undeclared = if scanned_purls.is_empty()
&& args.paths.is_empty()
&& !args.common.is_global()
&& args.common.ecosystem_selected(Ecosystem::Pypi)
{
socket_patch_core::crawlers::PythonCrawler::new()
.undeclared_installed(&crawler_options)
.await
} else {
0
};
if undeclared > 0 {
println!("{}", render::no_declared_python_packages(undeclared));
} else {
println!(
"{}",
render::no_packages_message(
args.common.is_global(),
args.common.ecosystems.as_deref(),
&args.paths,
)
);
}
}
policy.print_human(args.common.silent, args.common.verbose);
}
Expand Down
38 changes: 38 additions & 0 deletions crates/socket-patch-cli/src/commands/scan/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@ pub(crate) fn no_packages_unreadable(warnings: usize) -> String {
}
}

/// What an empty crawl says when the Python on `PATH` does hold packages,
/// `undeclared` of them, and the project declares none: they are left out
/// as not the project's (a project with no environment of its own shares
/// that interpreter), and "install first" alone would not say so.
pub(crate) fn no_declared_python_packages(undeclared: usize) -> String {
let (installed, them) = if undeclared == 1 {
(
"the 1 package installed in the Python on PATH is not one".to_string(),
"it",
)
} else {
(
format!("the {undeclared} packages installed in the Python on PATH are not ones"),
"them",
)
};
format!(
"No packages found: {installed} this project declares. Install its requirements \
first; `--global` scans {them} with every other package on the machine."
)
}

/// What an empty crawl says, naming the filter that emptied it when there
/// was one (`--ecosystems`, PATH scoping) instead of a generic
/// "install first" hint.
Expand Down Expand Up @@ -903,6 +925,22 @@ mod tests {
);
}

#[test]
fn an_empty_crawl_says_when_installed_packages_were_left_out_as_undeclared() {
assert_eq!(
no_declared_python_packages(18),
"No packages found: the 18 packages installed in the Python on PATH are not ones \
this project declares. Install its requirements first; `--global` scans them \
with every other package on the machine."
);
assert_eq!(
no_declared_python_packages(1),
"No packages found: the 1 package installed in the Python on PATH is not one this \
project declares. Install its requirements first; `--global` scans it with every \
other package on the machine."
);
}

#[test]
fn no_packages_message_names_the_filter() {
assert_eq!(
Expand Down
8 changes: 6 additions & 2 deletions crates/socket-patch-cli/src/commands/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use socket_patch_core::utils::purl::normalize_purl;
use socket_patch_core::utils::target::{Target, TargetKind};

use crate::args::{apply_env_toggles, GlobalArgs};
use crate::ecosystem_dispatch::{crawl_ecosystems, installed_target_matches};
use crate::ecosystem_dispatch::{crawl_ecosystems_for_name, installed_target_matches};
use crate::ui::diff::{file_diff, FileDiff};
use crate::ui::{self, plural, select_one, Style};

Expand Down Expand Up @@ -587,8 +587,12 @@ async fn candidates(args: &ShowArgs, target: &Target, client: &ApiClient) -> Res
TargetKind::Ghsa => client.search_patches_by_ghsa(target.as_str()).await,
TargetKind::Purl => client.search_patches_by_package(target.as_str()).await,
TargetKind::Uuid | TargetKind::Name => {
// A name resolves among every installed package, as `get`
// resolves it: a Python project with no environment of its own
// is otherwise crawled only for the packages it declares.
let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty());
let (packages, _, _) = crawl_ecosystems(&args.common.crawler_options(), only).await;
let (packages, _, _) =
crawl_ecosystems_for_name(&args.common.crawler_options(), only).await;
let matched = installed_target_matches(target, &packages);
if matched.is_empty() {
return Err(Lookup::Target(format!(
Expand Down
Loading
Loading