forked from prefix-dev/pixi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupgrade.rs
311 lines (286 loc) · 10.7 KB
/
upgrade.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use std::cmp::Ordering;
use crate::cli::cli_config::ProjectConfig;
use crate::project::{MatchSpecs, PypiDeps};
use crate::Project;
use clap::Parser;
use fancy_display::FancyDisplay;
use itertools::Itertools;
use miette::MietteDiagnostic;
use miette::{Context, IntoDiagnostic};
use super::cli_config::PrefixUpdateConfig;
use crate::diff::LockFileJsonDiff;
use pep508_rs::MarkerTree;
use pep508_rs::Requirement;
use pixi_manifest::FeatureName;
use pixi_manifest::PyPiRequirement;
use pixi_manifest::SpecType;
use pixi_spec::PixiSpec;
use rattler_conda_types::{MatchSpec, StringMatcher};
/// Update the version of packages to the latest possible version, disregarding the manifest version constraints
#[derive(Parser, Debug, Default)]
pub struct Args {
#[clap(flatten)]
pub project_config: ProjectConfig,
#[clap(flatten)]
pub prefix_update_config: PrefixUpdateConfig,
#[clap(flatten)]
pub specs: UpgradeSpecsArgs,
/// Output the changes in JSON format.
#[clap(long)]
pub json: bool,
/// Only show the changes that would be made, without actually updating the manifest, lock file, or environment.
#[clap(short = 'n', long)]
pub dry_run: bool,
}
#[derive(Parser, Debug, Default)]
pub struct UpgradeSpecsArgs {
/// The packages to upgrade
pub packages: Option<Vec<String>>,
/// The feature to update
#[clap(long = "feature", short = 'f', default_value_t)]
pub feature: FeatureName,
/// The packages which should be excluded
#[clap(long, conflicts_with = "packages")]
pub exclude: Option<Vec<String>>,
}
pub async fn execute(args: Args) -> miette::Result<()> {
let mut project = Project::load_or_else_discover(args.project_config.manifest_path.as_deref())?
.with_cli_config(args.prefix_update_config.config.clone());
// Ensure that the given feature exists
let Some(feature) = project.manifest.feature(&args.specs.feature) else {
miette::bail!(
"could not find a feature named {}",
args.specs.feature.fancy_display()
)
};
let (match_specs, pypi_deps) = parse_specs(feature, &args, &project)?;
let update_deps = project
.update_dependencies(
match_specs,
pypi_deps,
&args.prefix_update_config,
&args.specs.feature,
&[],
false,
args.dry_run,
)
.await?;
// Is there something to report?
if let Some(update_deps) = update_deps {
let diff = update_deps.lock_file_diff;
// Format as json?
if args.json {
let json_diff = LockFileJsonDiff::new(&project, diff);
let json = serde_json::to_string_pretty(&json_diff).expect("failed to convert to json");
println!("{}", json);
} else {
diff.print()
.into_diagnostic()
.context("failed to print lock-file diff")?;
}
} else {
eprintln!(
"{}All packages are already up-to-date",
console::style(console::Emoji("✔ ", "")).green()
);
}
Project::warn_on_discovered_from_env(args.project_config.manifest_path.as_deref());
Ok(())
}
/// Parses the specifications for dependencies from the given feature, arguments, and project.
///
/// This function processes the dependencies and PyPi dependencies specified in the feature,
/// filters them based on the provided arguments, and returns the resulting match specifications
/// and PyPi dependencies.
fn parse_specs(
feature: &pixi_manifest::Feature,
args: &Args,
project: &Project,
) -> miette::Result<(MatchSpecs, PypiDeps)> {
let spec_type = SpecType::Run;
let match_spec_iter = feature
.dependencies(spec_type, None)
.into_iter()
.flat_map(|deps| deps.into_owned());
let pypi_deps_iter = feature
.pypi_dependencies(None)
.into_iter()
.flat_map(|deps| deps.into_owned());
if let Some(package_names) = &args.specs.packages {
let available_packages = match_spec_iter
.clone()
.map(|(name, _)| name.as_normalized().to_string())
.chain(
pypi_deps_iter
.clone()
.map(|(name, _)| name.as_normalized().to_string()),
)
.collect_vec();
for package in package_names {
ensure_package_exists(package, &available_packages)?
}
}
let match_specs = match_spec_iter
// Don't upgrade excluded packages
.filter(|(name, _)| match &args.specs.exclude {
None => true,
Some(exclude) if exclude.contains(&name.as_normalized().to_string()) => false,
_ => true,
})
// If specific packages have been requested, only upgrade those
.filter(|(name, _)| match &args.specs.packages {
None => true,
Some(packages) if packages.contains(&name.as_normalized().to_string()) => true,
_ => false,
})
// Only upgrade version specs
.filter_map(|(name, req)| match req {
PixiSpec::DetailedVersion(version_spec) => {
let mut nameless_match_spec = version_spec
.try_into_nameless_match_spec(&project.channel_config())
.ok()?;
// If it is a detailed spec, always unset version
nameless_match_spec.version = None;
// If the package as specifically requested, unset more fields
if let Some(packages) = &args.specs.packages {
if packages.contains(&name.as_normalized().to_string()) {
// If the build contains a wildcard, keep it
nameless_match_spec.build = match nameless_match_spec.build {
Some(
build @ StringMatcher::Glob(_) | build @ StringMatcher::Regex(_),
) => Some(build),
_ => None,
};
nameless_match_spec.build_number = None;
nameless_match_spec.md5 = None;
nameless_match_spec.sha256 = None;
// These are still to sensitive to be unset, so skipping these for now
// nameless_match_spec.url = None;
// nameless_match_spec.file_name = None;
// nameless_match_spec.channel = None;
// nameless_match_spec.subdir = None;
}
}
Some((
name.clone(),
(
MatchSpec::from_nameless(nameless_match_spec, Some(name)),
spec_type,
),
))
}
PixiSpec::Version(_) => Some((name.clone(), (MatchSpec::from(name), spec_type))),
_ => {
tracing::debug!("skipping non-version spec {:?}", req);
None
}
})
// Only upgrade in pyproject.toml if it is explicitly mentioned in `tool.pixi.dependencies.python`
.filter(|(name, _)| {
if name.as_normalized() == "python" {
if let pixi_manifest::ManifestSource::PyProjectToml(document) =
project.manifest.document.clone()
{
if document
.get_nested_table("[tool.pixi.dependencies.python]")
.is_err()
{
return false;
}
}
}
true
})
.collect();
let pypi_deps = pypi_deps_iter
// Don't upgrade excluded packages
.filter(|(name, _)| match &args.specs.exclude {
None => true,
Some(exclude) if exclude.contains(&name.as_normalized().to_string()) => false,
_ => true,
})
// If specific packages have been requested, only upgrade those
.filter(|(name, _)| match &args.specs.packages {
None => true,
Some(packages) if packages.contains(&name.as_normalized().to_string()) => true,
_ => false,
})
// Only upgrade version specs
.filter_map(|(name, req)| match req {
PyPiRequirement::Version { extras, .. } => Some((
name.clone(),
Requirement {
name: name.as_normalized().clone(),
extras,
// TODO: Add marker support here to avoid overwriting existing markers
marker: MarkerTree::default(),
origin: None,
version_or_url: None,
},
)),
PyPiRequirement::RawVersion(_) => Some((
name.clone(),
Requirement {
name: name.as_normalized().clone(),
extras: Vec::default(),
marker: MarkerTree::default(),
origin: None,
version_or_url: None,
},
)),
_ => None,
})
.map(|(name, req)| {
let location = project.manifest.document.pypi_dependency_location(
&name,
None, // TODO: add support for platforms
&args.specs.feature,
);
(name, (req, location))
})
.collect();
Ok((match_specs, pypi_deps))
}
/// Ensures the existence of the specified package
///
/// # Returns
///
/// Returns `miette::Result` with a descriptive error message
/// if the package does not exist.
fn ensure_package_exists(package_name: &str, available_packages: &[String]) -> miette::Result<()> {
let similar_names = available_packages
.iter()
.unique()
.filter_map(|name| {
let distance = strsim::jaro(package_name, name);
if distance > 0.6 {
Some((name, distance))
} else {
None
}
})
.sorted_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap_or(Ordering::Equal))
.take(5)
.map(|(name, _)| name)
.collect_vec();
if similar_names.first().map(|s| s.as_str()) == Some(package_name) {
return Ok(());
}
let message = format!("could not find a package named '{package_name}'");
Err(MietteDiagnostic {
message,
code: None,
severity: None,
help: if !similar_names.is_empty() {
Some(format!(
"did you mean '{}'?",
similar_names.iter().format("', '")
))
} else {
None
},
url: None,
labels: None,
}
.into())
}