Skip to content

Commit 9c14367

Browse files
committed
2024 edition update and other minor refactors
- Using edition 2024 for all crates - Fixed all checks/clippy warnings - [`clippy::wildcard_imports`](https://rust-lang.github.io/rust-clippy/stable/index.html#wildcard_imports) now warns for libnpins - `anyhow::Result` is now always fully qualified in libnpins - [Formatting code with the new edition](https://doc.rust-lang.org/edition-guide/rust-2024/rustfmt-formatting-fixes.html) - `cargo update` including snix version - Turn off default features for `nix-compat` and set exact revision
1 parent 6dc715e commit 9c14367

File tree

14 files changed

+239
-288
lines changed

14 files changed

+239
-288
lines changed

Cargo.lock

Lines changed: 112 additions & 180 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ tokio = "^1.0"
1111

1212
[workspace.package]
1313
version = "0.4.0"
14-
edition = "2021"
14+
edition = "2024"
1515
license = "EUPL-1.2"
1616

1717
[package]
@@ -30,7 +30,8 @@ log.workspace = true
3030
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
3131

3232
libnpins = { path = "libnpins" }
33-
futures-util = { version = "0.3.31", default-features = false }
33+
# Pin clap because the latest patch has a regression in the help output
3434
clap = { version = "=4.5.36", features = [ "derive", "env" ] }
35+
futures-util = { version = "0.3.31", default-features = false }
3536
crossterm = { version = "0.29", default-features = false }
3637
env_logger = { version = "^0.11.0", features = ["color", "auto-color", "regex"], default-features = false }

libnpins/Cargo.toml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,21 @@ version.workspace = true
44
edition.workspace = true
55
license.workspace = true
66

7+
[lints.clippy]
8+
wildcard_imports = "warn"
9+
710
[dependencies]
811
serde = { version = "^1.0", features = [ "derive" ] }
912
serde_json.workspace = true
10-
url.workspace = true
13+
url = { workspace = true, features = ["serde"] }
1114
anyhow.workspace = true
1215
tokio = { workspace = true, features = ["process"] }
1316
log.workspace = true
1417
reqwest = { version = "0.13.1", features = [ "rustls" ], default-features = false }
1518
async-trait = "0.1"
1619
lenient_semver_parser = { version = "0.4.2", default-features = false }
1720
lenient_version = { version = "0.4.2" }
18-
nix-compat = { git = "https://git.snix.dev/snix/snix", version = "0.1.0", features = ["serde"] }
21+
nix-compat = { git = "https://git.snix.dev/snix/snix", rev = "4918571f95d436d2e3da4665e8c1e9b77d9546e8", default-features = false, features = ["serde"] }
1922

2023
[dev-dependencies]
2124
env_logger = { version = "^0.11.0", features = ["color", "auto-color", "regex"], default-features = false }

libnpins/src/channel.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
//!
33
//! This should be preferred over pinning the equivaleng `nixpkgs` git branch.
44
5-
use crate::*;
65
use nix_compat::nixhash::NixHash;
6+
use serde::{Deserialize, Serialize};
7+
8+
use crate::{Updatable, build_client, diff, nix};
79

810
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
911
pub struct Pin {
@@ -49,7 +51,7 @@ impl Updatable for Pin {
4951
type Version = ChannelVersion;
5052
type Hashes = ChannelHash;
5153

52-
async fn update(&self, _old: Option<&ChannelVersion>) -> Result<ChannelVersion> {
54+
async fn update(&self, _old: Option<&ChannelVersion>) -> anyhow::Result<ChannelVersion> {
5355
/* We want to get from something like https://channels.nixos.org/nixos-21.11
5456
* to https://releases.nixos.org/nixos/21.11/nixos-21.11.335807.df4f1f7cc3f/nixexprs.tar.xz
5557
*/
@@ -66,7 +68,7 @@ impl Updatable for Pin {
6668
Ok(ChannelVersion { url })
6769
}
6870

69-
async fn fetch(&self, version: &ChannelVersion) -> Result<Self::Hashes> {
71+
async fn fetch(&self, version: &ChannelVersion) -> anyhow::Result<Self::Hashes> {
7072
/* Prefetch an URL that looks like
7173
* https://releases.nixos.org/nixos/21.11/nixos-21.11.335807.df4f1f7cc3f
7274
*/

libnpins/src/container.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
//! Pin an OCI container
22
3-
use crate::nix::nix_prefetch_docker;
4-
use crate::*;
5-
use anyhow::Result;
63
use serde::{Deserialize, Serialize};
74

5+
use crate::{Updatable, diff, nix::nix_prefetch_docker};
6+
87
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
98
pub struct Pin {
109
pub image_name: String,
@@ -47,15 +46,15 @@ impl Updatable for Pin {
4746
type Version = ContainerVersion;
4847
type Hashes = ContainerHash;
4948

50-
async fn update(&self, _old: Option<&ContainerVersion>) -> Result<ContainerVersion> {
49+
async fn update(&self, _old: Option<&ContainerVersion>) -> anyhow::Result<ContainerVersion> {
5150
Ok(ContainerVersion {
5251
image_digest: nix_prefetch_docker(&self.image_name, &self.image_tag, None)
5352
.await?
5453
.image_digest,
5554
})
5655
}
5756

58-
async fn fetch(&self, version: &ContainerVersion) -> Result<ContainerHash> {
57+
async fn fetch(&self, version: &ContainerVersion) -> anyhow::Result<ContainerHash> {
5958
Ok(ContainerHash {
6059
hash: nix_prefetch_docker(
6160
&self.image_name,
@@ -72,7 +71,7 @@ impl Updatable for Pin {
7271
mod test {
7372
use super::*;
7473

75-
const DEAD_TEST_CONTAINER: &'static str = "docker.io/dperson/torproxy";
74+
const DEAD_TEST_CONTAINER: &str = "docker.io/dperson/torproxy";
7675

7776
#[tokio::test]
7877
async fn update_and_fetch_container() {

libnpins/src/flake.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
//! Convert+Import Nix flake lock files
22
3-
use crate::*;
43
use anyhow::{Context, Result};
54
use git::fetch_default_branch;
65
use serde::{Deserialize, Serialize};
76
use url::Url;
87

8+
use crate::{Pin, git, tarball};
9+
910
/// Pin entry from a nix flake's lock file
1011
///
1112
/// Flake locks have a two-part structure: the input's specification, and the

libnpins/src/git.rs

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@
77
//! instance. This should be preferred over the generic Git API if possible. See [`Repository`]
88
//! for more on this.
99
10-
use crate::*;
1110
use anyhow::{Context, Result};
1211
use lenient_version::Version;
12+
use nix_compat::nixhash::NixHash;
1313
use serde::{Deserialize, Serialize};
1414
use tokio::process::Command;
1515
use url::Url;
1616

17+
use crate::{GenericVersion, Updatable, check_git_url, diff, get_and_deserialize, nix};
18+
1719
fn get_github_url() -> String {
1820
std::env::var("NPINS_GITHUB_HOST").unwrap_or_else(|_| String::from("https://github.com"))
1921
}
@@ -38,7 +40,7 @@ pub struct GitRevision {
3840

3941
impl GitRevision {
4042
pub fn new(revision: String) -> Result<Self> {
41-
if !revision.chars().all(|c| c.is_digit(16)) || revision.len() != 40 {
43+
if !revision.chars().all(|c| c.is_ascii_hexdigit()) || revision.len() != 40 {
4244
anyhow::bail!("'{revision}' is not a valid git revision (sha1 hash)");
4345
}
4446
Ok(Self { revision })
@@ -166,9 +168,8 @@ impl Repository {
166168
];
167169

168170
for (path, func) in distinct_api_endpoints {
169-
match probe(url.clone(), path).await {
170-
Ok(_) => return func(url),
171-
_ => {},
171+
if probe(url.clone(), path).await.is_ok() {
172+
return func(url);
172173
}
173174
}
174175
None
@@ -578,11 +579,9 @@ impl Updatable for GitReleasePin {
578579
match old_version {
579580
Ok(old_version) => {
580581
anyhow::ensure!(
581-
latest >= old_version,
582-
"Failed to ensure version monotonicity, latest found version is {} but current is {}",
583-
latest,
584-
old_version,
585-
);
582+
latest >= old_version,
583+
"Failed to ensure version monotonicity, latest found version is {latest} but current is {old_version}"
584+
);
586585
},
587586
Err(_) => {
588587
log::warn!(
@@ -737,8 +736,7 @@ pub async fn fetch_default_branch(repo: &Url) -> Result<String> {
737736

738737
let info = remotes
739738
.iter()
740-
.filter(|info| info.revision.starts_with("ref: refs/heads/") && info.ref_ == "HEAD")
741-
.next()
739+
.find(|info| info.revision.starts_with("ref: refs/heads/") && info.ref_ == "HEAD")
742740
.with_context(|| format!("Failed to resolve HEAD to a ref for {}", repo))?;
743741

744742
info.revision
@@ -1190,7 +1188,7 @@ mod test {
11901188
let version = pin.update(None).await?;
11911189
assert_eq!(
11921190
version,
1193-
git::GitRevision {
1191+
GitRevision {
11941192
revision: "e7145078163692697b843915a665d4f41139a65c".into(),
11951193
}
11961194
);
@@ -1285,7 +1283,7 @@ mod test {
12851283
let version = pin.update(None).await?;
12861284
assert_eq!(
12871285
version,
1288-
git::GitRevision {
1286+
GitRevision {
12891287
revision: "bca2071b6923d45d9aabac27b3ea1e40f5fa3006".into(),
12901288
}
12911289
);

libnpins/src/lib.rs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
//! Currently, it pretty much exposes the internals of the CLI 1:1, but in the future
44
//! this is supposed to evolve into a more standalone library.
55
6-
use anyhow::Result;
76
use diff::{Diff, OptionExt};
87
use nix_compat::nixhash::NixHash;
98
use reqwest::IntoUrl;
@@ -21,7 +20,7 @@ pub mod pypi;
2120
pub mod tarball;
2221
pub mod versions;
2322

24-
pub const DEFAULT_NIX: &'static str = include_str!("default.nix");
23+
pub const DEFAULT_NIX: &str = include_str!("default.nix");
2524

2625
/// Helper method to build you a client.
2726
// TODO make injectable via a configuration mechanism
@@ -129,10 +128,10 @@ pub trait Updatable:
129128
/// Fetch the latest applicable commit data
130129
///
131130
/// The old version may be passed to help guarantee monotonicity of the versions.
132-
async fn update(&self, old: Option<&Self::Version>) -> Result<Self::Version>;
131+
async fn update(&self, old: Option<&Self::Version>) -> anyhow::Result<Self::Version>;
133132

134133
/// Fetch hashes for a given version
135-
async fn fetch(&self, version: &Self::Version) -> Result<Self::Hashes>;
134+
async fn fetch(&self, version: &Self::Version) -> anyhow::Result<Self::Hashes>;
136135
}
137136

138137
/// Create the `Pin` type
@@ -178,7 +177,7 @@ macro_rules! mkPin {
178177
})*
179178

180179
/* If an error is returned, `self` remains unchanged */
181-
pub async fn update(&mut self) -> Result<Vec<diff::DiffEntry>> {
180+
pub async fn update(&mut self) -> ::anyhow::Result<Vec<diff::DiffEntry>> {
182181
Ok(match self {
183182
$(Self::$name { input, version, .. } => {
184183
/* Use very explicit syntax to force the correct types and get good compile errors */
@@ -191,7 +190,7 @@ macro_rules! mkPin {
191190
/* If an error is returned, `self` remains unchanged. This returns a double result: the outer one
192191
* indicates that `update` should be called first, the inner is from the actual operation.
193192
*/
194-
pub async fn fetch(&mut self) -> Result<Vec<diff::DiffEntry>> {
193+
pub async fn fetch(&mut self) -> ::anyhow::Result<Vec<diff::DiffEntry>> {
195194
Ok(match self {
196195
$(Self::$name { input, version, hashes, .. } => {
197196
let version = version.as_ref()
@@ -225,14 +224,14 @@ macro_rules! mkPin {
225224
/// Unfreeze a pin
226225
pub fn unfreeze(&mut self) {
227226
match self {
228-
$(Self::$name { ref mut frozen, .. } => frozen.unfreeze()),*
227+
$(Self::$name { frozen, .. } => frozen.unfreeze()),*
229228
}
230229
}
231230

232231
/// Freeze a pin
233232
pub fn freeze(&mut self) {
234233
match self {
235-
$(Self::$name { ref mut frozen, .. } => frozen.freeze()),*
234+
$(Self::$name { frozen, .. } => frozen.freeze()),*
236235
}
237236
}
238237

@@ -314,7 +313,7 @@ impl NixPins {
314313
}
315314

316315
/// Custom manual deserialize wrapper that checks the version
317-
pub fn from_json_versioned(value: serde_json::Value) -> Result<Self> {
316+
pub fn from_json_versioned(value: serde_json::Value) -> anyhow::Result<Self> {
318317
versions::from_value_versioned(value)
319318
}
320319

@@ -350,7 +349,7 @@ impl diff::Diff for GenericHash {
350349
}
351350

352351
/// The Frozen field in a Pin
353-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
352+
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
354353
pub struct Frozen(pub bool);
355354

356355
impl Frozen {
@@ -377,12 +376,6 @@ impl diff::Diff for Frozen {
377376
}
378377
}
379378

380-
impl std::default::Default for Frozen {
381-
fn default() -> Self {
382-
Frozen(false)
383-
}
384-
}
385-
386379
/// An URL and its hash
387380
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
388381
pub struct GenericUrlHashes {
@@ -404,6 +397,7 @@ mod tests {
404397
use super::*;
405398

406399
#[test]
400+
#[rustfmt::skip]
407401
fn test_frozen() {
408402
assert!(!Frozen::default().is_frozen());
409403
assert!(!{

libnpins/src/niv.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
//! Convert+Import Niv files
22
3-
use crate::*;
4-
use anyhow::Result;
53
use serde::{Deserialize, Serialize};
64
use std::convert::TryFrom;
75

6+
use crate::{Pin, git};
7+
88
/// Pin entry from Niv's sources.json
99
///
1010
/// We only take the minimum information required to get things working. This does not include
@@ -21,7 +21,7 @@ pub struct NivPin {
2121
impl TryFrom<NivPin> for Pin {
2222
type Error = anyhow::Error;
2323

24-
fn try_from(niv: NivPin) -> Result<Self> {
24+
fn try_from(niv: NivPin) -> anyhow::Result<Self> {
2525
Ok(match niv.owner {
2626
None => {
2727
git::GitPin::new(git::Repository::git(niv.repo.parse()?), niv.branch, false).into()

libnpins/src/nix.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
use crate::{check_git_url, check_url, DEFAULT_NIX};
21
use anyhow::{Context, Result};
32
use nix_compat::nixhash::{HashAlgo, NixHash};
43
use std::path::Path;
54

5+
use crate::{DEFAULT_NIX, check_git_url, check_url};
6+
67
#[allow(unused)]
78
pub struct PrefetchInfo {
89
store_path: String,
@@ -187,8 +188,8 @@ pub async fn nix_prefetch_docker(
187188
"nix-prefetch-git output: {}",
188189
String::from_utf8_lossy(&output.stdout)
189190
);
190-
Ok(serde_json::from_slice(&output.stdout)
191-
.context("Failed to deserialize nix-pfetch-git JSON response.")?)
191+
serde_json::from_slice(&output.stdout)
192+
.context("Failed to deserialize nix-pfetch-git JSON response.")
192193
}
193194
pub async fn nix_eval_pin(lockfile_path: &Path, pin: &str) -> Result<std::path::PathBuf> {
194195
let lockfile_path = lockfile_path.canonicalize()?;

0 commit comments

Comments
 (0)