Skip to content

Commit

Permalink
Merge pull request #183 from rust-secure-code/add-resolverver
Browse files Browse the repository at this point in the history
Add `resolverver` crate
  • Loading branch information
Shnatsel authored Jan 22, 2025
2 parents 77bc08b + 9702f03 commit 56b33fb
Show file tree
Hide file tree
Showing 9 changed files with 449 additions and 6 deletions.
71 changes: 66 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ members = [
"auditable-extract",
"auditable-serde",
"cargo-auditable",
"auditable-cyclonedx", "auditable2cdx",
"auditable-cyclonedx",
"auditable2cdx",
"resolverver",
]

# Config for 'cargo dist'
Expand Down
16 changes: 16 additions & 0 deletions resolverver/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "resolverver"
version = "0.1.0"
edition = "2021"
description = "Determines the Cargo resolver version for a workspace"
license = "MIT OR Apache-2.0"
authors = ["Sergey \"Shnatsel\" Davidoff <[email protected]>"]
repository = "https://github.com/rust-secure-code/cargo-auditable"

[dependencies]
serde = { version = "1.0.217", features = ["derive"] }
toml = { version = "0.8.19", default-features = false, features = ["parse"] }

[dev-dependencies]
cargo_metadata = "0.18.1"

38 changes: 38 additions & 0 deletions resolverver/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# resolverver: Get the Cargo resolver version

Knowing the [Cargo resolver version](https://doc.rust-lang.org/cargo/reference/resolver.html#resolver-versions)
used in a given workspace is important to some tooling that interfaces with Cargo.
You'll know it when you need it.

### Usage

Since resolver version is a global property for the entire workspace,
it is important that you read the **workspace** Cargo.toml rather than
the Cargo.toml of an individual package.

Here's how to locate it using the [`cargo_metadata`](https://crates.io/crates/cargo_metadata) crate:

```rust
use cargo_metadata;
use resolverver;

// Locate and load the Cargo.toml for the workspace
let metadata = cargo_metadata::MetadataCommand::new().no_deps().exec().unwrap();
let toml = std::fs::read_to_string(metadata.workspace_root.join("Cargo.toml")).unwrap();

// Deduce the resolver version in use
let resolver_version = resolverver::from_toml(&toml).unwrap();
println!("Resolver version in this workspace is: {resolver_version:?}");
```

### Caveats

Cargo has a config option [`resolver.incompatible-rust-versions`](https://doc.rust-lang.org/cargo/reference/config.html#resolverincompatible-rust-versions)
that may enable V3 resolver even when everything else would indicate that V2 resolver should be used.

The only difference between V2 and V3 resolvers is the selected versions of some dependencies.
As long as you're letting Cargo generate the Cargo.lock file and aren't doing version resolution yourself,
this distinction doesn't matter.

If this does matter for your use case, you can use [`cargo-config2`](https://crates.io/crates/cargo-config2)
to read and resolve Cargo configuration.
58 changes: 58 additions & 0 deletions resolverver/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::fmt;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnrecognizedValue {
UnknownResolver(String),
UnknownEdition(String),
}

impl std::fmt::Display for UnrecognizedValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UnrecognizedValue::UnknownResolver(resolver) => {
write!(f, "Unrecognized resolver version: {}", resolver)
}
UnrecognizedValue::UnknownEdition(edition) => {
write!(f, "Unrecognized Rust edition: {}", edition)
}
}
}
}

impl std::error::Error for UnrecognizedValue {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
UnrecognizedValue(UnrecognizedValue),
TomlParseError(toml::de::Error), // Adjust for the specific Serde library in use (e.g., `serde_json` or `serde_yaml`)
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::UnrecognizedValue(msg) => write!(f, "{}", msg),
Error::TomlParseError(err) => write!(f, "Failed to parse Cargo.toml: {}", err),
}
}
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::UnrecognizedValue(err) => Some(err),
Error::TomlParseError(err) => Some(err),
}
}
}

impl From<UnrecognizedValue> for Error {
fn from(value: UnrecognizedValue) -> Self {
Error::UnrecognizedValue(value)
}
}

impl From<toml::de::Error> for Error {
fn from(err: toml::de::Error) -> Self {
Error::TomlParseError(err)
}
}
29 changes: 29 additions & 0 deletions resolverver/src/fields.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::{error::UnrecognizedValue, Resolver};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TomlFields {
pub resolver: Option<String>,
pub edition: Option<String>,
}

impl TomlFields {
pub fn resolver(self) -> Result<Resolver, UnrecognizedValue> {
if let Some(ver) = self.resolver {
match ver.as_str() {
"1" => Ok(Resolver::V1),
"2" => Ok(Resolver::V2),
"3" => Ok(Resolver::V3),
_ => Err(UnrecognizedValue::UnknownResolver(ver)),
}
} else if let Some(ed) = self.edition {
match ed.as_str() {
"2015" => Ok(Resolver::V1),
"2018" | "2021" => Ok(Resolver::V2),
"2024" => Ok(Resolver::V3),
_ => Err(UnrecognizedValue::UnknownEdition(ed)),
}
} else {
Ok(Resolver::V1)
}
}
}
15 changes: 15 additions & 0 deletions resolverver/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#![doc = include_str!("../README.md")]

mod error;
mod fields;
mod raw_fields;
mod resolver;

pub use error::Error;
use raw_fields::RawTomlFields;
pub use resolver::Resolver;

pub fn from_toml(workspace_root_cargo_toml: &str) -> Result<Resolver, crate::Error> {
let parsed: RawTomlFields = toml::from_str(workspace_root_cargo_toml)?;
Ok(parsed.resolve().resolver()?)
}
Loading

0 comments on commit 56b33fb

Please sign in to comment.