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
103 changes: 95 additions & 8 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

29 changes: 27 additions & 2 deletions crates/socket-patch-cli/src/commands/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1721,6 +1721,22 @@ pub(crate) async fn run_locked(
// rightly ignores it). It rides the run-warning channel so it
// is never silent.
let mut run_warnings = run_warnings;
// A Maven build whose `.mvn/maven.config` could not be read one
// way: no local repository was guessed at, so say why its
// `~/.m2` copies were not found.
let maven = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven);
if !args.common.is_global()
&& (unmatched.iter().any(|purl| maven(purl))
|| results.iter().any(|r| maven(&r.package_key)))
{
use socket_patch_core::crawlers::maven_crawler::JvmEnv;
if let Some(why) = JvmEnv::for_project(&args.common.cwd).m2_undetermined {
run_warnings.push(RunWarning {
code: "maven_local_repository_undetermined".to_string(),
detail: why,
});
}
}
// A nested apply's caller (get, scan) already reported the
// overrides it approved; repeating them would double each line.
// Skips are new to `get`, which checked only its selection; a
Expand Down Expand Up @@ -3702,10 +3718,19 @@ async fn apply_maven_base(m: &MavenBase<'_>) -> MavenApplied {
};
match Box::pin(jvm_jar::apply_jar_swap(&swap, &dirs, m.service)).await {
Err(refusal) => out.refuse(variant, &dirs[0], refusal.code, refusal.message),
Ok(results) => {
for mut result in results {
Ok(swapped) => {
for copy in swapped {
let jvm_jar::SwappedCopy {
mut result,
refusal,
} = copy;
check_derived_copies(&mut out, &mut result, &jar_leaf, args, m.derived)
.await;
// A copy's own coded refusal is a run warning too,
// as a whole-swap one is.
if let Some(refusal) = refusal {
out.warn(refusal.code, refusal.message);
}
out.record(args, result);
}
}
Expand Down
15 changes: 14 additions & 1 deletion crates/socket-patch-cli/src/commands/scan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1291,6 +1291,11 @@ pub(super) const GRADLE_MAVEN_LOCAL_UNDETERMINED: &str = "gradle_maven_local_und
/// `$HOME/.gradle`.
pub(super) const GRADLE_USER_HOME_DIFFERS: &str = "gradle_user_home_differs";

/// Run-level warning: the project's `.mvn/maven.config` names one local
/// repository to Maven before 3.9 and another to later Mavens, both exist
/// and nothing says which Maven builds it, so neither was scanned.
pub(crate) const MAVEN_LOCAL_REPOSITORY_UNDETERMINED: &str = "maven_local_repository_undetermined";

/// What a scan learned about the Gradle side of discovery.
#[derive(Default)]
struct GradleScan {
Expand Down Expand Up @@ -1381,7 +1386,11 @@ async fn gradle_scan(
&cwd,
socket_patch_core::vendor::jvm::layout::BuildTool::Gradle,
);
let env = JvmEnv::from_process();
let env = if global {
JvmEnv::from_process()
} else {
JvmEnv::for_project(&cwd)
};
let gate = (!global && gradle_build).then(|| m2_gate(&cwd, &env));
// The cwd's build locks annotate Gradle-cached packages in a global
// run too; without a Gradle build at the cwd there is nothing to
Expand Down Expand Up @@ -1455,6 +1464,10 @@ async fn gradle_scan(
}
_ => {}
}
if let Some(why) = &env.m2_undetermined {
out.notes
.push((MAVEN_LOCAL_REPOSITORY_UNDETERMINED.to_string(), why.clone()));
}
if let Some((home, passwd)) = mismatch {
out.notes.push((
GRADLE_USER_HOME_DIFFERS.to_string(),
Expand Down
6 changes: 6 additions & 0 deletions crates/socket-patch-cli/src/commands/vex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2381,6 +2381,11 @@ fn omission_phrase(reason: &str) -> &'static str {
"go_vendor_content_mismatch" => "the native Go vendor tree does not contain the patch; run go mod vendor (or go work vendor for a workspace)",
"vendor_artifact_missing" => "the vendored artifact is missing",
"vendor_artifact_unreadable" => "the vendored artifact cannot be read",
"vendor_artifact_too_large" => {
"the vendored jar is past the limits jars are read within (200,000 entries, or 1 GiB \
and 100 times its own size inflated), so its contents were not checked; run \
socket-patch repair to restore the recorded jar"
}
"vendor_artifact_non_canonical" => {
"the vendored tarball holds a second entry the package manager would extract \
over a patched file (another top-level directory, a second spelling of the \
Expand Down Expand Up @@ -2683,6 +2688,7 @@ mod tests {
"no_files",
"vendor_hash_mismatch",
"vendor_artifact_missing",
"vendor_artifact_too_large",
"vendor_manifest_unverifiable",
"stale_install",
STALE_INSTALL_UNVERIFIED,
Expand Down
5 changes: 3 additions & 2 deletions crates/socket-patch-cli/src/ecosystem_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1368,14 +1368,15 @@ impl JvmScope {
pub(crate) async fn of(common: &GlobalArgs) -> Self {
use socket_patch_core::crawlers::gradle_cache;
use socket_patch_core::crawlers::maven_crawler::{m2_gate, JvmEnv};
let env = JvmEnv::from_process();
if common.is_global() {
return Self {
env,
env: JvmEnv::from_process(),
gate: None,
verification_metadata: None,
};
}
// A project run: its `.mvn/maven.config` can name the repository.
let env = JvmEnv::for_project(&common.cwd);
let cwd = common.cwd.clone();
let probe_env = env.clone();
let probe = move || {
Expand Down
164 changes: 164 additions & 0 deletions crates/socket-patch-cli/tests/e2e_vendor_maven_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@
//! 5. The source project's `vendor --revert` restores every byte, and
//! nothing is left to attest.
//!
//! Another test pins which local repository a build uses when the
//! project's `.mvn/maven.config` names one (`-Dmaven.repo.local`): real
//! Maven resolves into it rather than the one `MAVEN_OPTS` names, the
//! command line (`MAVEN_ARGS`, Maven 3.9+) overrides it, and socket-patch
//! given the same environment patches the artifact in that same repository.
//!
//! Gated like the other real-toolchain capstones: `#[ignore]` (network to
//! Maven Central for the fixture), toolchain selection and the
//! `SOCKET_PATCH_MAVEN_E2E_{MVN,VERSION,REQUIRED}` gates in
Expand Down Expand Up @@ -1252,3 +1258,161 @@ mod mediation {
unselected(Shape::Ranged).expect("the local repository is warm");
}
}

/// Every file under `from`, copied to the same place under `to`.
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), &target).unwrap();
}
}
}

/// The local repository of a build is the one Maven itself takes: the
/// project's `.mvn/maven.config` (`-Dmaven.repo.local`) over `MAVEN_OPTS`,
/// and the command line (`MAVEN_ARGS`, which Maven 3.9+ reads) over the
/// config. Maven is asked first, with no repository on its command line;
/// socket-patch, in the same environment and with no `MAVEN_REPO_LOCAL`,
/// then patches and restores the artifact in that same repository.
#[test]
#[ignore = "real Maven + Maven Central (fixture); run with --ignored"]
fn maven_config_local_repository_is_the_one_maven_and_socket_patch_use() {
let Some(mvn) = Mvn::detect(SUITE) else {
return;
};
let tmp = tempfile::tempdir().unwrap();
let root: PathBuf = tmp.path().canonicalize().unwrap();
let proj = root.join("proj");
let home = root.join("home");
let [from_config, from_opts, from_args] =
["repo-config", "repo-opts", "repo-args"].map(|name| root.join(name));
let settings = root.join("settings.xml");
write_settings(&settings, &[]);
std::fs::create_dir_all(proj.join(".mvn")).unwrap();
std::fs::create_dir_all(&home).unwrap();
std::fs::write(proj.join("pom.xml"), consumer_pom(VERSION)).unwrap();
std::fs::write(
proj.join(".mvn/maven.config"),
format!("-Dmaven.repo.local={}\n", from_config.display()),
)
.unwrap();
// The JVM's own properties. `user.home` keeps a Maven that took none of
// these repositories out of the real `~/.m2`.
let opts = format!(
"-Duser.home={} -Dmaven.repo.local={}",
home.display(),
from_opts.display()
);
let goal = format!("{DEPENDENCY_PLUGIN}:copy-dependencies");
let resolve = |settings: &Path, extra: &[&str], maven_args: Option<&str>| {
let _ = std::fs::remove_dir_all(proj.join("target"));
let mut args = vec![goal.as_str(), "-DoutputDirectory=target/deps"];
args.extend_from_slice(extra);
mvn.run_unpinned(&proj, settings, &args, |cmd| {
cmd.env("MAVEN_OPTS", &opts);
if let Some(value) = maven_args {
cmd.env("MAVEN_ARGS", value);
}
})
};
let pom_leaf = format!("{ARTIFACT}-{VERSION}.pom");
let cached = |repo: &Path| repo_dir(repo, VERSION).join(&pom_leaf);

// 1. Maven: the config's repository, not the one MAVEN_OPTS names.
let out = with_central_fallback(SUITE, "maven.config resolution", &settings, |s, extra| {
resolve(s, extra, None)
});
if !ok(&out) {
skip(
SUITE,
&format!("resolving against Maven Central failed:\n{}", dump(&out)),
);
return;
}
assert!(
cached(&from_config).is_file(),
"Maven {} did not resolve into the repository .mvn/maven.config names:\n{}",
mvn.version,
dump(&out)
);
assert!(
!from_opts.exists() && !home.join(".m2/repository").exists(),
"Maven {} used another repository as well",
mvn.version
);

// 2. socket-patch: the same repository.
let pristine = std::fs::read(cached(&from_config)).unwrap();
let patched = [
pristine.as_slice(),
b"<!-- socket-patch maven.config e2e -->\n",
]
.concat();
stage_manifest_of(
&proj,
&purl(),
&format!("package/{pom_leaf}"),
&pristine,
&patched,
);
std::fs::write(
proj.join(".socket/blobs").join(git_sha256(&pristine)),
&pristine,
)
.unwrap();
// `--preserve-state`: a rollback otherwise drops the record it restored.
let agent = |command: &str, maven_args: Option<&str>| {
let mut cmd = hermetic::command(&binary());
hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Venv]);
prebuilt_common::jvm_env::isolate_cli(&mut cmd);
if command == "rollback" {
cmd.args(["rollback", "--preserve-state"]);
} else {
cmd.arg(command);
}
cmd.args(["--json", "--offline", "--cwd"])
.arg(&proj)
.env("MAVEN_OPTS", &opts)
.env_remove("MAVEN_REPO_LOCAL")
.env_remove("M2_HOME");
if let Some(value) = maven_args {
cmd.env("MAVEN_ARGS", value);
}
let out = cmd.output().expect("run socket-patch");
assert!(out.status.success(), "{command}: {}", dump(&out));
};
agent("apply", None);
assert_eq!(std::fs::read(cached(&from_config)).unwrap(), patched);
agent("rollback", None);
assert_eq!(std::fs::read(cached(&from_config)).unwrap(), pristine);

// 3. The command line is merged over the config. Maven before 3.9 does
// not read MAVEN_ARGS.
if mvn.numeric() < vec![3, 9, 0] {
println!(
"{SUITE}: Maven {} does not read MAVEN_ARGS; the command-line leg is skipped",
mvn.version
);
return;
}
copy_tree(&from_config, &from_args);
std::fs::remove_dir_all(repo_dir(&from_config, VERSION)).unwrap();
let args_value = format!("-Dmaven.repo.local={}", from_args.display());
// Offline, only the repository that still holds the artifact resolves.
let out = resolve(&settings, &["-o"], Some(&args_value));
assert!(
ok(&out),
"Maven {} did not take the repository MAVEN_ARGS names over the config's:\n{}",
mvn.version,
dump(&out)
);
agent("apply", Some(&args_value));
assert_eq!(std::fs::read(cached(&from_args)).unwrap(), patched);
agent("rollback", Some(&args_value));
assert_eq!(std::fs::read(cached(&from_args)).unwrap(), pristine);
}
Loading
Loading