Skip to content

Commit 0c8da51

Browse files
Add JSON output for uv pip install and uv pip sync (#21893)
## Summary Add `--output-format json` to `uv pip install` and `uv pip sync` so callers can inspect package changes without parsing progress messages. It works for regular operations, `--dry-run`, and `--check`, writes JSON to stdout, and leaves diagnostics on stderr. Like `uv sync`, check mode emits the proposed changes even when it exits with code 1 because the environment is outdated. Both commands use the experimental package-change schema shared with `uv sync`, including installs, removals, and reinstalls. The report includes whether the command was a dry run and returns an empty change list when no changes are made or planned. --------- Co-authored-by: Charlie Marsh <[email protected]>
1 parent 0714322 commit 0c8da51

12 files changed

Lines changed: 431 additions & 91 deletions

File tree

‎crates/uv-cli/src/lib.rs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,15 @@ pub enum SyncFormat {
6868
Json,
6969
}
7070

71+
#[derive(Debug, Default, Clone, Copy, clap::ValueEnum)]
72+
pub enum PipInstallFormat {
73+
/// Display the result in a human-readable format.
74+
#[default]
75+
Text,
76+
/// Display the result in JSON format.
77+
Json,
78+
}
79+
7180
#[derive(Debug, Default, Clone, Copy, clap::ValueEnum)]
7281
pub enum AuditOutputFormat {
7382
/// Display the result in a human-readable format.
@@ -2185,6 +2194,13 @@ pub struct PipSyncArgs {
21852194
#[arg(long, conflicts_with = "dry_run")]
21862195
pub check: bool,
21872196

2197+
/// Select the output format.
2198+
///
2199+
/// JSON output is written to stdout; diagnostic messages are written to stderr.
2200+
/// The JSON schema is experimental and may change without warning.
2201+
#[arg(long, value_enum, default_value_t = PipInstallFormat::default())]
2202+
pub output_format: PipInstallFormat,
2203+
21882204
/// The backend to use when fetching packages in the PyTorch ecosystem (e.g., `cpu`, `cu126`, or `auto`).
21892205
///
21902206
/// When set, uv will ignore the configured index URLs for packages in the PyTorch ecosystem,
@@ -2537,6 +2553,13 @@ pub struct PipInstallArgs {
25372553
#[arg(long, conflicts_with = "dry_run")]
25382554
pub check: bool,
25392555

2556+
/// Select the output format.
2557+
///
2558+
/// JSON output is written to stdout; diagnostic messages are written to stderr.
2559+
/// The JSON schema is experimental and may change without warning.
2560+
#[arg(long, value_enum, default_value_t = PipInstallFormat::default())]
2561+
pub output_format: PipInstallFormat,
2562+
25402563
/// The backend to use when fetching packages in the PyTorch ecosystem (e.g., `cpu`, `cu126`, or `auto`)
25412564
///
25422565
/// When set, uv will ignore the configured index URLs for packages in the PyTorch ecosystem,
@@ -3803,6 +3826,9 @@ pub struct SyncArgs {
38033826
pub extra: Option<Vec<ExtraName>>,
38043827

38053828
/// Select the output format.
3829+
///
3830+
/// JSON output is written to stdout; diagnostic messages are written to stderr.
3831+
/// The JSON schema is experimental and may change without warning.
38063832
#[arg(long, value_enum, default_value_t = SyncFormat::default())]
38073833
pub output_format: SyncFormat,
38083834

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
use std::fmt::Write;
2+
3+
use serde::Serialize;
4+
5+
use uv_cli::PipInstallFormat;
6+
use uv_configuration::DryRun;
7+
use uv_distribution_types::Name;
8+
use uv_normalize::PackageName;
9+
10+
use crate::commands::pip::operations::{ChangedDist, Changelog};
11+
use crate::printer::Printer;
12+
13+
/// Write the package changes as JSON when requested.
14+
pub(crate) fn write_install_report(
15+
changelog: &Changelog,
16+
dry_run: DryRun,
17+
output_format: PipInstallFormat,
18+
printer: Printer,
19+
) -> anyhow::Result<()> {
20+
match output_format {
21+
PipInstallFormat::Text => {}
22+
PipInstallFormat::Json => {
23+
let report = InstallReport {
24+
schema: SchemaReport::default(),
25+
changes: PackageChangesReport::from_changelog(changelog),
26+
dry_run: dry_run.enabled(),
27+
};
28+
writeln!(
29+
printer.stdout_important(),
30+
"{}",
31+
serde_json::to_string_pretty(&report)?
32+
)?;
33+
}
34+
}
35+
Ok(())
36+
}
37+
38+
/// A report of the changes made or planned by `uv pip install` or `uv pip sync`.
39+
#[derive(Debug, Serialize)]
40+
struct InstallReport {
41+
schema: SchemaReport,
42+
changes: PackageChangesReport,
43+
dry_run: bool,
44+
}
45+
46+
#[derive(Serialize, Debug, Default)]
47+
#[serde(rename_all = "snake_case")]
48+
enum SchemaVersion {
49+
/// An unstable, experimental schema.
50+
#[default]
51+
Preview,
52+
}
53+
54+
#[derive(Serialize, Debug, Default)]
55+
pub(crate) struct SchemaReport {
56+
/// The version of the schema.
57+
version: SchemaVersion,
58+
}
59+
60+
/// A summary of all package changes made or planned during an installation.
61+
#[derive(Serialize, Debug, Clone, Default)]
62+
pub(crate) struct PackageChangesReport(Vec<PackageChangeReport>);
63+
64+
impl PackageChangesReport {
65+
pub(crate) fn from_changelog(changelog: &Changelog) -> Self {
66+
let mut changes: Vec<_> =
67+
changelog
68+
.uninstalled
69+
.iter()
70+
.map(|dist| PackageChangeReport::from_dist(dist, PackageChangeAction::Uninstalled))
71+
.chain(changelog.installed.iter().map(|dist| {
72+
PackageChangeReport::from_dist(dist, PackageChangeAction::Installed)
73+
}))
74+
.chain(changelog.reinstalled.iter().map(|dist| {
75+
PackageChangeReport::from_dist(dist, PackageChangeAction::Reinstalled)
76+
}))
77+
.collect();
78+
79+
changes.sort_by(|a, b| {
80+
a.name
81+
.cmp(&b.name)
82+
.then_with(|| a.action.cmp(&b.action))
83+
.then_with(|| a.version.cmp(&b.version))
84+
});
85+
Self(changes)
86+
}
87+
}
88+
89+
/// A summary of a single package change made or planned during an installation.
90+
#[derive(Serialize, Debug, Clone)]
91+
struct PackageChangeReport {
92+
/// The normalized package name.
93+
name: PackageName,
94+
/// The resolved version of the package.
95+
#[serde(skip_serializing_if = "Option::is_none")]
96+
version: Option<uv_pep440::Version>,
97+
/// The action that was taken for the package.
98+
action: PackageChangeAction,
99+
}
100+
101+
impl PackageChangeReport {
102+
fn from_dist(dist: &ChangedDist, action: PackageChangeAction) -> Self {
103+
Self {
104+
name: dist.name().clone(),
105+
version: dist.version().cloned(),
106+
action,
107+
}
108+
}
109+
}
110+
111+
/// The action taken or planned for an individual package.
112+
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
113+
#[serde(rename_all = "snake_case")]
114+
enum PackageChangeAction {
115+
Uninstalled,
116+
Installed,
117+
Reinstalled,
118+
}

‎crates/uv/src/commands/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ mod cache_size;
9090
pub(crate) mod diagnostics;
9191
mod editable;
9292
mod help;
93+
mod install_report;
9394
mod locked_requirements;
9495
pub(crate) mod pip;
9596
mod project;

‎crates/uv/src/commands/pip/install.rs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use tracing::{Level, debug, enabled, warn};
99
use uv_errors::{Hinted, Hints};
1010

1111
use uv_cache::Cache;
12+
use uv_cli::PipInstallFormat;
1213
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
1314
use uv_configuration::{
1415
BuildIsolation, BuildOptions, Concurrency, Constraints, DryRun, EditableMode,
@@ -46,8 +47,9 @@ use uv_workspace::WorkspaceCache;
4647
use uv_workspace::pyproject::ExtraBuildDependencies;
4748

4849
use crate::commands::editable::apply_editable_mode;
50+
use crate::commands::install_report::write_install_report;
4951
use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger, InstallLogger};
50-
use crate::commands::pip::operations::Modifications;
52+
use crate::commands::pip::operations::{Changelog, Modifications};
5153
use crate::commands::pip::operations::{report_interpreter, report_target_environment};
5254
use crate::commands::pip::{operations, resolution_markers, resolution_tags};
5355
use crate::commands::pylock::{read_pylock_toml, resolve_pylock_toml};
@@ -130,6 +132,7 @@ pub(crate) async fn pip_install(
130132
cache: Cache,
131133
workspace_cache: WorkspaceCache,
132134
dry_run: DryRun,
135+
output_format: PipInstallFormat,
133136
printer: Printer,
134137
preview: Preview,
135138
) -> anyhow::Result<ExitStatus> {
@@ -376,6 +379,7 @@ pub(crate) async fn pip_install(
376379
)?;
377380
}
378381

382+
write_install_report(&Changelog::default(), dry_run, output_format, printer)?;
379383
return Ok(ExitStatus::Success);
380384
}
381385
SatisfiesResult::Unsatisfied(requirement) => {
@@ -630,7 +634,7 @@ pub(crate) async fn pip_install(
630634
);
631635

632636
// Sync the environment.
633-
match operations::install(
637+
let changelog = match operations::install(
634638
&resolution,
635639
site_packages,
636640
InstallationStrategy::Permissive,
@@ -655,12 +659,15 @@ pub(crate) async fn pip_install(
655659
)
656660
.await
657661
{
658-
Ok(..) => {}
659-
Err(operations::Error::OutdatedEnvironment(_)) => return Ok(ExitStatus::Failure),
662+
Ok(changelog) => changelog,
663+
Err(operations::Error::OutdatedEnvironment(changelog)) => {
664+
write_install_report(&changelog, dry_run, output_format, printer)?;
665+
return Ok(ExitStatus::Failure);
666+
}
660667
Err(err) => {
661668
return Err(UvError::from(err).into());
662669
}
663-
}
670+
};
664671

665672
// Notify the user of any resolution diagnostics.
666673
operations::diagnose_resolution(resolution.diagnostics(), printer)?;
@@ -677,5 +684,6 @@ pub(crate) async fn pip_install(
677684
)?;
678685
}
679686

687+
write_install_report(&changelog, dry_run, output_format, printer)?;
680688
Ok(ExitStatus::Success)
681689
}

‎crates/uv/src/commands/pip/sync.rs‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use owo_colors::OwoColorize;
66
use tracing::{debug, warn};
77

88
use uv_cache::Cache;
9+
use uv_cli::PipInstallFormat;
910
use uv_client::{BaseClientBuilder, RegistryClientBuilder};
1011
use uv_configuration::{
1112
BuildIsolation, BuildOptions, Concurrency, Constraints, DryRun, ExtrasSpecification,
@@ -41,8 +42,9 @@ use uv_warnings::warn_user;
4142
use uv_workspace::WorkspaceCache;
4243
use uv_workspace::pyproject::ExtraBuildDependencies;
4344

45+
use crate::commands::install_report::write_install_report;
4446
use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger};
45-
use crate::commands::pip::operations::Modifications;
47+
use crate::commands::pip::operations::{Changelog, Modifications};
4648
use crate::commands::pip::operations::{report_interpreter, report_target_environment};
4749
use crate::commands::pip::{operations, resolution_markers, resolution_tags};
4850
use crate::commands::pylock::{read_pylock_toml, resolve_pylock_toml};
@@ -95,6 +97,7 @@ pub(crate) async fn pip_sync(
9597
cache: Cache,
9698
workspace_cache: WorkspaceCache,
9799
dry_run: DryRun,
100+
output_format: PipInstallFormat,
98101
printer: Printer,
99102
preview: Preview,
100103
) -> Result<ExitStatus> {
@@ -164,6 +167,7 @@ pub(crate) async fn pip_sync(
164167
printer.stderr(),
165168
"No requirements found (hint: use `--allow-empty-requirements` to clear the environment)"
166169
)?;
170+
write_install_report(&Changelog::default(), dry_run, output_format, printer)?;
167171
return Ok(ExitStatus::Success);
168172
}
169173
}
@@ -501,7 +505,7 @@ pub(crate) async fn pip_sync(
501505
);
502506

503507
// Sync the environment.
504-
match operations::install(
508+
let changelog = match operations::install(
505509
&resolution,
506510
site_packages,
507511
InstallationStrategy::Permissive,
@@ -526,14 +530,15 @@ pub(crate) async fn pip_sync(
526530
)
527531
.await
528532
{
529-
Ok(_) => {}
530-
Err(operations::Error::OutdatedEnvironment(_)) => {
533+
Ok(changelog) => changelog,
534+
Err(operations::Error::OutdatedEnvironment(changelog)) => {
535+
write_install_report(&changelog, dry_run, output_format, printer)?;
531536
return Ok(ExitStatus::Failure);
532537
}
533538
Err(err) => {
534539
return Err(UvError::from(err).into());
535540
}
536-
}
541+
};
537542

538543
// Notify the user of any resolution diagnostics.
539544
operations::diagnose_resolution(resolution.diagnostics(), printer)?;
@@ -550,5 +555,6 @@ pub(crate) async fn pip_sync(
550555
)?;
551556
}
552557

558+
write_install_report(&changelog, dry_run, output_format, printer)?;
553559
Ok(ExitStatus::Success)
554560
}

0 commit comments

Comments
 (0)