Skip to content

Commit 9ea6eae

Browse files
Add separate compile and install commands (#17)
Closes #9.
1 parent 4c30cb1 commit 9ea6eae

File tree

13 files changed

+304
-167
lines changed

13 files changed

+304
-167
lines changed

crates/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,7 @@ Types and functionality for working with Python packages, e.g., parsing wheel fi
1919
## [puffin-platform](./puffin-platform)
2020

2121
Functionality for detecting the current platform (operating system, architecture, etc.).
22+
23+
## [puffin-resolve](./puffin-resolve)
24+
25+
Functionality for resolving Python packages and their dependencies.

crates/puffin-cli/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ puffin-client = { path = "../puffin-client" }
88
puffin-interpreter = { path = "../puffin-interpreter" }
99
puffin-platform = { path = "../puffin-platform" }
1010
puffin-package = { path = "../puffin-package" }
11+
puffin-resolve = { path = "../puffin-resolve" }
1112

1213
anyhow = { version = "1.0.75" }
1314
clap = { version = "4.4.6", features = ["derive"] }
1415
colored = { version = "2.0.4" }
15-
memchr = { version = "2.6.4" }
1616
async-std = { version = "1.12.0", features = [
1717
"attributes",
1818
"tokio1",
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use std::path::Path;
2+
use std::str::FromStr;
3+
4+
use anyhow::Result;
5+
use tracing::debug;
6+
7+
use puffin_interpreter::PythonExecutable;
8+
use puffin_platform::Platform;
9+
use puffin_resolve::resolve;
10+
11+
use crate::commands::ExitStatus;
12+
13+
pub(crate) async fn compile(src: &Path, cache: Option<&Path>) -> Result<ExitStatus> {
14+
// Read the `requirements.txt` from disk.
15+
let requirements_txt = std::fs::read_to_string(src)?;
16+
17+
// Parse the `requirements.txt` into a list of requirements.
18+
let requirements = puffin_package::requirements::Requirements::from_str(&requirements_txt)?;
19+
20+
// Detect the current Python interpreter.
21+
let platform = Platform::current()?;
22+
let python = PythonExecutable::from_env(&platform)?;
23+
debug!(
24+
"Using Python interpreter: {}",
25+
python.executable().display()
26+
);
27+
28+
// Resolve the dependencies.
29+
let resolution = resolve(
30+
&requirements,
31+
python.version(),
32+
python.markers(),
33+
&platform,
34+
cache,
35+
)
36+
.await?;
37+
38+
for (name, version) in resolution.iter() {
39+
#[allow(clippy::print_stdout)]
40+
{
41+
println!("{name}=={version}");
42+
}
43+
}
44+
45+
Ok(ExitStatus::Success)
46+
}

crates/puffin-cli/src/commands/install.rs

Lines changed: 12 additions & 149 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,15 @@
1-
use std::collections::{HashMap, HashSet};
21
use std::path::Path;
32
use std::str::FromStr;
43

54
use anyhow::Result;
6-
use futures::future::Either;
7-
use futures::{StreamExt, TryFutureExt};
8-
use pep440_rs::Version;
9-
use pep508_rs::{Requirement, VersionOrUrl};
105
use tracing::debug;
116

12-
use puffin_client::{File, PypiClientBuilder, SimpleJson};
137
use puffin_interpreter::PythonExecutable;
14-
use puffin_package::metadata::Metadata21;
15-
use puffin_package::package_name::PackageName;
16-
use puffin_package::wheel::WheelFilename;
178
use puffin_platform::Platform;
9+
use puffin_resolve::resolve;
1810

1911
use crate::commands::ExitStatus;
2012

21-
#[derive(Debug)]
22-
enum Request {
23-
Package(Requirement),
24-
Version(Requirement, File),
25-
}
26-
27-
#[derive(Debug)]
28-
enum Response {
29-
Package(SimpleJson, Requirement),
30-
Version(Metadata21, Requirement),
31-
}
32-
3313
pub(crate) async fn install(src: &Path, cache: Option<&Path>) -> Result<ExitStatus> {
3414
// Read the `requirements.txt` from disk.
3515
let requirements_txt = std::fs::read_to_string(src)?;
@@ -45,134 +25,17 @@ pub(crate) async fn install(src: &Path, cache: Option<&Path>) -> Result<ExitStat
4525
python.executable().display()
4626
);
4727

48-
// Determine the compatible platform tags.
49-
let tags = platform.compatible_tags(python.version())?;
50-
51-
// Instantiate a client.
52-
let pypi_client = {
53-
let mut pypi_client = PypiClientBuilder::default();
54-
if let Some(cache) = cache {
55-
pypi_client = pypi_client.cache(cache);
56-
}
57-
pypi_client.build()
58-
};
59-
60-
// A channel to fetch package metadata (e.g., given `flask`, fetch all versions) and version
61-
// metadata (e.g., given `flask==1.0.0`, fetch the metadata for that version).
62-
let (package_sink, package_stream) = futures::channel::mpsc::unbounded();
63-
64-
// Initialize the package stream.
65-
let mut package_stream = package_stream
66-
.map(|request: Request| match request {
67-
Request::Package(requirement) => Either::Left(
68-
pypi_client
69-
.simple(requirement.name.clone())
70-
.map_ok(move |metadata| Response::Package(metadata, requirement)),
71-
),
72-
Request::Version(requirement, file) => Either::Right(
73-
pypi_client
74-
.file(file)
75-
.map_ok(move |metadata| Response::Version(metadata, requirement)),
76-
),
77-
})
78-
.buffer_unordered(32)
79-
.ready_chunks(32);
80-
81-
// Push all the requirements into the package sink.
82-
let mut in_flight: HashSet<PackageName> = HashSet::with_capacity(requirements.len());
83-
for requirement in &*requirements {
84-
debug!("--> adding root dependency: {}", requirement);
85-
package_sink.unbounded_send(Request::Package(requirement.clone()))?;
86-
in_flight.insert(PackageName::normalize(&requirement.name));
87-
}
88-
89-
// Resolve the requirements.
90-
let mut resolution: HashMap<PackageName, Version> = HashMap::with_capacity(requirements.len());
91-
92-
while let Some(chunk) = package_stream.next().await {
93-
for result in chunk {
94-
let result: Response = result?;
95-
match result {
96-
Response::Package(metadata, requirement) => {
97-
// TODO(charlie): Support URLs. Right now, we treat a URL as an unpinned dependency.
98-
let specifiers =
99-
requirement
100-
.version_or_url
101-
.as_ref()
102-
.and_then(|version_or_url| match version_or_url {
103-
VersionOrUrl::VersionSpecifier(specifiers) => Some(specifiers),
104-
VersionOrUrl::Url(_) => None,
105-
});
106-
107-
// Pick a version that satisfies the requirement.
108-
let Some(file) = metadata.files.iter().rev().find(|file| {
109-
// We only support wheels for now.
110-
let Ok(name) = WheelFilename::from_str(file.filename.as_str()) else {
111-
return false;
112-
};
113-
114-
let Ok(version) = Version::from_str(&name.version) else {
115-
return false;
116-
};
117-
118-
if !name.is_compatible(&tags) {
119-
return false;
120-
}
121-
122-
specifiers
123-
.iter()
124-
.all(|specifier| specifier.contains(&version))
125-
}) else {
126-
continue;
127-
};
128-
129-
package_sink.unbounded_send(Request::Version(requirement, file.clone()))?;
130-
}
131-
Response::Version(metadata, requirement) => {
132-
debug!(
133-
"--> selected version {} for {}",
134-
metadata.version, requirement
135-
);
136-
137-
// Add to the resolved set.
138-
let normalized_name = PackageName::normalize(&requirement.name);
139-
in_flight.remove(&normalized_name);
140-
resolution.insert(normalized_name, metadata.version);
141-
142-
// Enqueue its dependencies.
143-
for dependency in metadata.requires_dist {
144-
if !dependency.evaluate_markers(
145-
python.markers(),
146-
requirement.extras.clone().unwrap_or_default(),
147-
) {
148-
debug!("--> ignoring {dependency} due to environment mismatch");
149-
continue;
150-
}
151-
152-
let normalized_name = PackageName::normalize(&dependency.name);
153-
154-
if resolution.contains_key(&normalized_name) {
155-
continue;
156-
}
157-
158-
if !in_flight.insert(normalized_name) {
159-
continue;
160-
}
161-
162-
debug!("--> adding transitive dependency: {}", dependency);
163-
164-
package_sink.unbounded_send(Request::Package(dependency))?;
165-
}
166-
}
167-
}
168-
}
169-
170-
if in_flight.is_empty() {
171-
break;
172-
}
173-
}
174-
175-
for (name, version) in resolution {
28+
// Resolve the dependencies.
29+
let resolution = resolve(
30+
&requirements,
31+
python.version(),
32+
python.markers(),
33+
&platform,
34+
cache,
35+
)
36+
.await?;
37+
38+
for (name, version) in resolution.iter() {
17639
#[allow(clippy::print_stdout)]
17740
{
17841
println!("{name}=={version}");

crates/puffin-cli/src/commands/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use std::process::ExitCode;
22

3+
pub(crate) use compile::compile;
34
pub(crate) use install::install;
45

6+
mod compile;
57
mod install;
68

79
#[derive(Copy, Clone)]

crates/puffin-cli/src/main.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,25 @@ struct Cli {
2020

2121
#[derive(Subcommand)]
2222
enum Commands {
23-
/// Install dependencies from a `requirements.text` file.
23+
/// Compile a `requirements.in` file to a `requirements.txt` file.
24+
Compile(CompileArgs),
25+
/// Install dependencies from a `requirements.txt` file.
2426
Install(InstallArgs),
2527
}
2628

29+
#[derive(Args)]
30+
struct CompileArgs {
31+
/// Path to the `requirements.txt` file to compile.
32+
src: PathBuf,
33+
34+
/// Avoid reading from or writing to the cache.
35+
#[arg(long)]
36+
no_cache: bool,
37+
}
38+
2739
#[derive(Args)]
2840
struct InstallArgs {
29-
/// Path to the `requirements.text` file to install.
41+
/// Path to the `requirements.txt` file to install.
3042
src: PathBuf,
3143

3244
/// Avoid reading from or writing to the cache.
@@ -43,12 +55,21 @@ async fn main() -> ExitCode {
4355
let dirs = ProjectDirs::from("", "", "puffin");
4456

4557
let result = match &cli.command {
46-
Commands::Install(install) => {
58+
Commands::Compile(args) => {
59+
commands::compile(
60+
&args.src,
61+
dirs.as_ref()
62+
.map(directories::ProjectDirs::cache_dir)
63+
.filter(|_| !args.no_cache),
64+
)
65+
.await
66+
}
67+
Commands::Install(args) => {
4768
commands::install(
48-
&install.src,
69+
&args.src,
4970
dirs.as_ref()
5071
.map(directories::ProjectDirs::cache_dir)
51-
.filter(|_| !install.no_cache),
72+
.filter(|_| !args.no_cache),
5273
)
5374
.await
5475
}

crates/puffin-interpreter/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ anyhow = { version = "1.0.75" }
1616
pep508_rs = { version = "0.2.3", features = ["serde"] }
1717
serde_json = { version = "1.0.107" }
1818
tracing = { version = "0.1.37" }
19+
pep440_rs = "0.3.12"

crates/puffin-interpreter/src/lib.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::path::{Path, PathBuf};
22

33
use anyhow::Result;
4+
use pep440_rs::Version;
45
use pep508_rs::MarkerEnvironment;
56

67
use puffin_platform::Platform;
@@ -42,13 +43,8 @@ impl PythonExecutable {
4243
&self.markers
4344
}
4445

45-
/// Returns the Python version as a tuple of (major, minor).
46-
pub fn version(&self) -> (u8, u8) {
47-
// TODO(charlie): Use `Version`.
48-
let python_version = &self.markers.python_version;
49-
(
50-
u8::try_from(python_version.release[0]).expect("Python major version is too large"),
51-
u8::try_from(python_version.release[1]).expect("Python minor version is too large"),
52-
)
46+
/// Returns the Python version.
47+
pub fn version(&self) -> &Version {
48+
&self.markers.python_version.version
5349
}
5450
}

crates/puffin-package/benches/parser.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::str::FromStr;
22

33
use criterion::{black_box, criterion_group, criterion_main, Criterion};
44

5-
use puffin_package::Requirements;
5+
use puffin_package::requirements::Requirements;
66

77
const REQUIREMENTS_TXT: &str = r"
88
#

crates/puffin-platform/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ license.workspace = true
1414
[dependencies]
1515
glibc_version = "0.1.2"
1616
goblin = "0.6.0"
17+
pep440_rs = "0.3.12"
1718
platform-info = "2.0.2"
1819
plist = "1.5.0"
1920
regex = "1.9.6"

0 commit comments

Comments
 (0)