Skip to content

Commit

Permalink
Merge pull request #233 from helsing-ai/ab/ci-fixes
Browse files Browse the repository at this point in the history
fix: Clippy, deny.toml and outdated deps
  • Loading branch information
mara-schulke authored Apr 19, 2024
2 parents ccd4cf8 + b886cb5 commit 023fb64
Show file tree
Hide file tree
Showing 10 changed files with 666 additions and 683 deletions.
1,108 changes: 555 additions & 553 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ reqwest = { version = "0.11", features = ["rustls-tls-native-roots"], default-fe
semver = { version = "1", features = ["serde"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_typename = "0.1"
tar = "0.4"
thiserror = "1.0.49"
tokio = { version = "^1.26", features = ["fs", "rt", "macros", "process", "io-std", "tracing"] }
Expand All @@ -66,6 +65,7 @@ tracing-subscriber = "0.3"
url = { version = "2.4", features = ["serde"] }
walkdir = "2"
sha2 = "0.10.8"
strum = { version = "0.26.2", features = ["derive"] }

[dev-dependencies]
assert_cmd = "2.0"
Expand Down
20 changes: 16 additions & 4 deletions deny.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
[licenses]
unlicensed = "deny"
allow = ["Apache-2.0", "BSD-3-Clause", "MIT", "Unicode-DFS-2016", "ISC"]
default = "deny"
version = 2
allow = ["Apache-2.0", "BSD-3-Clause", "MIT", "Unicode-DFS-2016", "ISC", "MPL-2.0"]

[[licenses.clarify]]
name = "ring"
Expand All @@ -12,5 +11,18 @@ license-files = [{ path = "LICENSE", hash = 0xbd0eed23 }]
multiple-versions = "warn"
wildcards = "deny"

skip = [
{ crate = "bitflags@1", reason = "used by `redox`, `security-framework` and `system-configuration`" },
{ crate = "hashbrown@0.12", reason = "used by `protobuf-parse`" },
{ crate = "heck@0.4", reason = "used by `strum` and `sqlx`" },
{ crate = "indexmap@1", reason = "used by `protobuf-parse`" },
{ crate = "syn@1", reason = "used by `diff_derive`" },
]

skip-tree = [
{ crate = "windows-sys", reason = "Several foundational crates are not yet up to date" },
{ crate = "windows-targets", reason = "Several foundational crates are not yet up to date" },
]

[advisories]
ignore = ["RUSTSEC-2024-0013"]
version = 2
30 changes: 15 additions & 15 deletions flake.lock

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

4 changes: 2 additions & 2 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
formatter = with pkgs;
writeShellApplication {
name = "nixfmt-nix-files";
runtimeInputs = [ fd nixfmt ];
runtimeInputs = [ fd nixfmt-classic ];
text = "fd \\.nix\\$ --hidden --type f | xargs nixfmt";
};

Expand All @@ -76,7 +76,7 @@
dontBuild = true;
src = ./.;
doCheck = true;
nativeBuildInputs = with pkgs; [ fd nixfmt ];
nativeBuildInputs = with pkgs; [ fd nixfmt-classic ];
checkPhase = ''
set -e
# find all nix files, and verify that they're formatted correctly
Expand Down
43 changes: 27 additions & 16 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

use std::{
io::ErrorKind,
path::{Path, PathBuf},
str::FromStr,
};
Expand All @@ -38,25 +39,35 @@ impl Cache {
/// Open the cache
pub async fn open() -> miette::Result<Self> {
if let Ok(cache) = std::env::var(CACHE_ENV_VAR).map(PathBuf::from) {
if let false = tokio::fs::try_exists(&cache)
.await
.into_diagnostic()
.wrap_err_with(|| {
let res = tokio::fs::create_dir_all(&cache).await;

match res {
Ok(()) => (),
// If the filesystem entry already exists, check if it's a directory,
// this allow us to give a nicer error message
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
let is_dir = tokio::fs::metadata(&cache)
.await
.into_diagnostic()
.wrap_err_with(|| miette!(
"internal: failed to get metadata for cache dir set by {CACHE_ENV_VAR} ({})",
cache.display()
))?
.is_dir();

if !is_dir {
return Err(miette!(
"internal: failed to initialize cache dir set by {CACHE_ENV_VAR}: '{}' exists but is not directory",
cache.display()
));
}
}
other => other.into_diagnostic().wrap_err_with(|| {
miette!(
"internal: failed to verify if cache set by {CACHE_ENV_VAR} ({}) exists",
"internal: failed to initialize cache dir set by {CACHE_ENV_VAR} ({})",
cache.display()
)
})?
{
tokio::fs::create_dir_all(&cache)
.await
.into_diagnostic()
.wrap_err_with(|| {
miette!(
"internal: failed to initialize cache dir set by {CACHE_ENV_VAR} ({})",
cache.display()
)
})?
})?,
}

let path = tokio::fs::canonicalize(cache)
Expand Down
30 changes: 8 additions & 22 deletions src/lock/digest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ use std::{fmt, str::FromStr};

use serde::{de::Visitor, Deserialize, Serialize};
use sha2::Digest as _;
use strum::{Display, EnumString};
use thiserror::Error;

/// Supported types of digest algorithms.
// Do not reorder variants; the ordering is significant, see #38 and #106.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, EnumString, Display,
)]
pub enum DigestAlgorithm {
/// SHA-2 with 256 bits
#[serde(rename = "sha256")]
#[strum(serialize = "sha256")]
SHA256,
}

Expand All @@ -49,32 +53,12 @@ pub enum DigestAlgorithmError {
UnsupportedAlgorithm(String),
}

impl FromStr for DigestAlgorithm {
type Err = DigestAlgorithmError;

fn from_str(input: &str) -> Result<Self, Self::Err> {
match serde_typename::from_str(input) {
Ok(value) => Ok(value),
_other => Err(DigestAlgorithmError::UnsupportedAlgorithm(input.into())),
}
}
}

#[test]
fn can_parse_digest_algorithm() {
assert!(matches!("sha256".parse(), Ok(DigestAlgorithm::SHA256)));
assert!("md5".parse::<DigestAlgorithm>().is_err());
}

impl fmt::Display for DigestAlgorithm {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match serde_typename::to_str(self) {
Ok(name) => fmt.write_str(name),
Err(error) => unreachable!("cannot convert DigestAlgorithm to string: {error}"),
}
}
}

#[test]
fn can_display_digest_algorithm() {
assert_eq!(DigestAlgorithm::SHA256.to_string(), "sha256");
Expand Down Expand Up @@ -121,7 +105,9 @@ impl FromStr for Digest {
let Some((algorithm_str, digest_str)) = input.split_once(':') else {
return Err(DigestError::MissingDelimiter);
};
let algorithm: DigestAlgorithm = algorithm_str.parse()?;
let algorithm: DigestAlgorithm = algorithm_str
.parse()
.map_err(|_| DigestAlgorithmError::UnsupportedAlgorithm(algorithm_str.into()))?;
let digest = hex::decode(digest_str)?;
Ok(Self { algorithm, digest })
}
Expand Down
74 changes: 25 additions & 49 deletions src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ pub const MANIFEST_FILE: &str = "Proto.toml";
pub const CANARY_EDITION: &str = concat!("0.", env!("CARGO_PKG_VERSION_MINOR"));

/// Edition of the buffrs manifest
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(into = "&str", from = "&str")]
pub enum Edition {
/// The canary edition of manifests
///
Expand All @@ -61,6 +62,26 @@ impl Edition {
}
}

impl From<&str> for Edition {
fn from(value: &str) -> Self {
match value {
self::CANARY_EDITION => Self::Canary,
"0.7" => Self::Canary07,
_ => Self::Unknown,
}
}
}

impl From<Edition> for &'static str {
fn from(value: Edition) -> Self {
match value {
Edition::Canary => CANARY_EDITION,
Edition::Canary07 => "0.7",
Edition::Unknown => "unknown",
}
}
}

/// A buffrs manifest format used for serialization and deserialization.
///
/// This contains the exact structure of the `Proto.toml` and skips
Expand Down Expand Up @@ -104,19 +125,6 @@ mod serializer {
use super::*;
use serde::{ser::SerializeStruct, Serializer};

impl Serialize for Edition {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Canary => serializer.serialize_str(CANARY_EDITION),
Self::Canary07 => serializer.serialize_str("0.7"),
Self::Unknown => serializer.serialize_str("unknown"),
}
}
}

impl Serialize for RawManifest {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down Expand Up @@ -155,36 +163,6 @@ mod deserializer {

use super::*;

impl<'de> Deserialize<'de> for Edition {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EditionVisitor;

impl<'de> serde::de::Visitor<'de> for EditionVisitor {
type Value = Edition;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid edition string")
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match value {
c if c == CANARY_EDITION => Ok(Edition::Canary),
"0.7" => Ok(Edition::Canary07),
_ => Ok(Edition::Unknown),
}
}
}

deserializer.deserialize_str(EditionVisitor)
}
}

impl<'de> Deserialize<'de> for RawManifest {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -227,14 +205,12 @@ mod deserializer {
});
};

let edition = serde_typename::from_str(&edition);

match edition {
Ok(Edition::Canary | Edition::Canary07) => Ok(RawManifest::Canary {
match Edition::from(edition.as_str()) {
Edition::Canary | Edition::Canary07 => Ok(RawManifest::Canary {
package,
dependencies,
}),
Ok(Edition::Unknown) | Err(_) => Err(de::Error::custom(
Edition::Unknown => Err(de::Error::custom(
format!("unsupported manifest edition, supported editions of {} are: {CANARY_EDITION}", env!("CARGO_PKG_VERSION"))
)),
}
Expand Down
4 changes: 2 additions & 2 deletions src/package/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@ mod test {
#[test]
fn snake_case() {
assert_eq!(
PackageName::new("serde_typename"),
Err(PackageNameError::InvalidCharacter('_', 5))
PackageName::new("with_underscore"),
Err(PackageNameError::InvalidCharacter('_', 4))
);
}
}
Loading

0 comments on commit 023fb64

Please sign in to comment.