Skip to content

Commit f8a6b69

Browse files
authored
chore: run cargo clippy --fix + manual fixes (#20)
1 parent dbb7a51 commit f8a6b69

File tree

7 files changed

+85
-91
lines changed

7 files changed

+85
-91
lines changed

.github/workflows/ci.yml

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,8 @@ on:
66
pull_request:
77
branches: ["main"]
88

9-
env:
10-
CARGO_TERM_COLOR: always
11-
129
jobs:
13-
build:
10+
test:
1411
strategy:
1512
matrix:
1613
os:
@@ -29,6 +26,19 @@ jobs:
2926

3027
- run: cargo test
3128

29+
clippy:
30+
runs-on: ubuntu-latest
31+
steps:
32+
- uses: taiki-e/checkout-action@v1
33+
34+
- uses: oxc-project/[email protected]
35+
with:
36+
save-cache: ${{ github.ref_name == 'main' }}
37+
cache-key: clippy
38+
components: clippy
39+
40+
- run: cargo clippy --all-targets --all-features -- -D warnings
41+
3242
fmt:
3343
runs-on: ubuntu-latest
3444
steps:

src/fs.rs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,14 @@ pub enum Error {
8080

8181
#[cfg(feature = "mmap")]
8282
pub fn open_zip_via_mmap<P: AsRef<Path>>(p: P) -> Result<Zip<mmap_rs::Mmap>, std::io::Error> {
83-
let file = fs::File::open(p)?;
83+
let file = std::fs::File::open(p)?;
8484

8585
let mmap_builder =
8686
mmap_rs::MmapOptions::new(file.metadata().unwrap().len().try_into().unwrap()).unwrap();
8787

88-
let mmap = unsafe { mmap_builder.with_file(file, 0).map().unwrap() };
88+
let mmap = unsafe { mmap_builder.with_file(&file, 0).map().unwrap() };
8989

90-
let zip = Zip::new(mmap).map_err(|_| {
91-
std::io::Error::new(std::io::ErrorKind::Other, "Failed to read the zip file")
92-
})?;
90+
let zip = Zip::new(mmap).map_err(|_| std::io::Error::other("Failed to read the zip file"))?;
9391

9492
Ok(zip)
9593
}
@@ -102,9 +100,7 @@ pub fn open_zip_via_mmap_p(p: &Path) -> Result<Zip<mmap_rs::Mmap>, std::io::Erro
102100
pub fn open_zip_via_read<P: AsRef<Path>>(p: P) -> Result<Zip<Vec<u8>>, std::io::Error> {
103101
let data = std::fs::read(p)?;
104102

105-
let zip = Zip::new(data).map_err(|_| {
106-
std::io::Error::new(std::io::ErrorKind::Other, "Failed to read the zip file")
107-
})?;
103+
let zip = Zip::new(data).map_err(|_| std::io::Error::other("Failed to read the zip file"))?;
108104

109105
Ok(zip)
110106
}
@@ -167,7 +163,7 @@ where
167163
p: P,
168164
cb: F,
169165
) -> Result<T, std::io::Error> {
170-
let zip = self.lru.get_or_try_init(p.as_ref().to_path_buf(), 1, |p| (self.open)(&p))?;
166+
let zip = self.lru.get_or_try_init(p.as_ref().to_path_buf(), 1, |p| (self.open)(p))?;
171167

172168
Ok(cb(zip.value()))
173169
}
@@ -315,7 +311,7 @@ mod tests {
315311

316312
#[test]
317313
fn test_zip_type_api() {
318-
let zip = open_zip_via_read(&PathBuf::from(
314+
let zip = open_zip_via_read(PathBuf::from(
319315
"data/@babel-plugin-syntax-dynamic-import-npm-7.8.3-fb9ff5634a-8.zip",
320316
))
321317
.unwrap();
@@ -327,7 +323,7 @@ mod tests {
327323
#[test]
328324
#[should_panic(expected = "Kind(NotFound)")]
329325
fn test_zip_type_api_not_exist_dir_with_slash() {
330-
let zip = open_zip_via_read(&PathBuf::from(
326+
let zip = open_zip_via_read(PathBuf::from(
331327
"data/@babel-plugin-syntax-dynamic-import-npm-7.8.3-fb9ff5634a-8.zip",
332328
))
333329
.unwrap();
@@ -338,7 +334,7 @@ mod tests {
338334
#[test]
339335
#[should_panic(expected = "Kind(NotFound)")]
340336
fn test_zip_type_api_not_exist_dir_without_slash() {
341-
let zip = open_zip_via_read(&PathBuf::from(
337+
let zip = open_zip_via_read(PathBuf::from(
342338
"data/@babel-plugin-syntax-dynamic-import-npm-7.8.3-fb9ff5634a-8.zip",
343339
))
344340
.unwrap();
@@ -348,7 +344,7 @@ mod tests {
348344

349345
#[test]
350346
fn test_zip_list() {
351-
let zip = open_zip_via_read(&PathBuf::from(
347+
let zip = open_zip_via_read(PathBuf::from(
352348
"data/@babel-plugin-syntax-dynamic-import-npm-7.8.3-fb9ff5634a-8.zip",
353349
))
354350
.unwrap();
@@ -382,7 +378,7 @@ mod tests {
382378

383379
#[test]
384380
fn test_zip_read() {
385-
let zip = open_zip_via_read(&PathBuf::from(
381+
let zip = open_zip_via_read(PathBuf::from(
386382
"data/@babel-plugin-syntax-dynamic-import-npm-7.8.3-fb9ff5634a-8.zip",
387383
))
388384
.unwrap();
@@ -472,10 +468,10 @@ mod tests {
472468

473469
match vpath(&PathBuf::from(input)) {
474470
Ok(res) => {
475-
assert_eq!(res, expectation, "input='{:?}'", input);
471+
assert_eq!(res, expectation, "input='{input:?}'");
476472
}
477473
Err(err) => {
478-
panic!("{:?}: {}", input, err);
474+
panic!("{input:?}: {err}");
479475
}
480476
}
481477
}

src/lib.rs

Lines changed: 41 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#![expect(clippy::result_large_err)] // TODO: FIXME
2+
13
pub mod fs;
24

35
mod builtins;
@@ -11,6 +13,7 @@ use serde::{Deserialize, Serialize};
1113
use serde_with::{DefaultOnNull, serde_as};
1214
use std::{
1315
collections::{HashMap, HashSet, hash_map::Entry},
16+
fmt,
1417
path::{Path, PathBuf},
1518
};
1619
use util::RegexDef;
@@ -63,15 +66,16 @@ pub enum Error {
6366
},
6467
}
6568

66-
impl ToString for Error {
67-
fn to_string(&self) -> String {
68-
match &self {
69+
impl fmt::Display for Error {
70+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71+
let message = match &self {
6972
Error::BadSpecifier { message, .. } => message.clone(),
7073
Error::FailedManifestHydration { message, .. } => message.clone(),
7174
Error::MissingPeerDependency { message, .. } => message.clone(),
7275
Error::UndeclaredDependency { message, .. } => message.clone(),
7376
Error::MissingDependency { message, .. } => message.clone(),
74-
}
77+
};
78+
write!(f, "{message}")
7579
}
7680
}
7781

@@ -82,6 +86,7 @@ pub enum Resolution {
8286
}
8387

8488
pub struct ResolutionHost {
89+
#[allow(clippy::type_complexity)]
8590
pub find_pnp_manifest: Box<dyn Fn(&Path) -> Result<Option<Manifest>, Error>>,
8691
}
8792

@@ -172,13 +177,9 @@ pub struct Manifest {
172177
fn parse_scoped_package_name(specifier: &str) -> Option<(String, Option<String>)> {
173178
let mut segments = specifier.splitn(3, '/');
174179

175-
let Some(scope) = segments.next() else {
176-
return None;
177-
};
180+
let scope = segments.next()?;
178181

179-
let Some(name) = segments.next() else {
180-
return None;
181-
};
182+
let name = segments.next()?;
182183

183184
let package_name = specifier[..scope.len() + name.len() + 1].to_string();
184185

@@ -190,9 +191,7 @@ fn parse_scoped_package_name(specifier: &str) -> Option<(String, Option<String>)
190191
fn parse_global_package_name(specifier: &str) -> Option<(String, Option<String>)> {
191192
let mut segments = specifier.splitn(2, '/');
192193

193-
let Some(name) = segments.next() else {
194-
return None;
195-
};
194+
let name = segments.next()?;
196195

197196
let package_name = name.to_string();
198197

@@ -229,8 +228,7 @@ pub fn load_pnp_manifest<P: AsRef<Path>>(p: P) -> Result<Manifest, Error> {
229228
let manifest_content =
230229
std::fs::read_to_string(p.as_ref()).map_err(|err| Error::FailedManifestHydration {
231230
message: format!(
232-
"We failed to read the content of the manifest.\n\nOriginal error: {}",
233-
err.to_string()
231+
"We failed to read the content of the manifest.\n\nOriginal error: {err}"
234232
),
235233
manifest_path: p.as_ref().to_path_buf(),
236234
})?;
@@ -270,7 +268,7 @@ pub fn load_pnp_manifest<P: AsRef<Path>>(p: P) -> Result<Manifest, Error> {
270268

271269
let mut manifest: Manifest = serde_json::from_str(&json_string.to_owned())
272270
.map_err(|err| Error::FailedManifestHydration {
273-
message: format!("We failed to parse the PnP data payload as proper JSON; Did you manually edit the file?\n\nOriginal error: {}", err.to_string()),
271+
message: format!("We failed to parse the PnP data payload as proper JSON; Did you manually edit the file?\n\nOriginal error: {err}"),
274272
manifest_path: p.as_ref().to_path_buf(),
275273
})?;
276274

@@ -288,7 +286,7 @@ pub fn init_pnp_manifest<P: AsRef<Path>>(manifest: &mut Manifest, p: P) {
288286
for (reference, info) in ranges.iter_mut() {
289287
let package_location = manifest.manifest_dir.join(info.package_location.clone());
290288

291-
let normalized_location = util::normalize_path(&package_location.to_string_lossy());
289+
let normalized_location = util::normalize_path(package_location.to_string_lossy());
292290

293291
info.package_location = PathBuf::from(normalized_location);
294292

@@ -366,7 +364,7 @@ pub fn find_broken_peer_dependencies(
366364
_dependency: &str,
367365
_initial_package: &PackageLocator,
368366
) -> Vec<PackageLocator> {
369-
vec![].to_vec()
367+
[].to_vec()
370368
}
371369

372370
pub fn resolve_to_unqualified_via_manifest<P: AsRef<Path>>(
@@ -425,32 +423,30 @@ pub fn resolve_to_unqualified_via_manifest<P: AsRef<Path>>(
425423
issuer_path = parent.as_ref().to_string_lossy(),
426424
)
427425
}
426+
} else if is_dependency_tree_root(manifest, parent_locator) {
427+
format!(
428+
"Your application tried to access {dependency_name}, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: {dependency_name}{via}\nRequired by: {issuer_path}",
429+
dependency_name = &ident,
430+
via = if ident != specifier {
431+
format!(" (via \"{}\")", &specifier)
432+
} else {
433+
String::from("")
434+
},
435+
issuer_path = parent.as_ref().to_string_lossy(),
436+
)
428437
} else {
429-
if is_dependency_tree_root(manifest, parent_locator) {
430-
format!(
431-
"Your application tried to access {dependency_name}, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: {dependency_name}{via}\nRequired by: {issuer_path}",
432-
dependency_name = &ident,
433-
via = if ident != specifier {
434-
format!(" (via \"{}\")", &specifier)
435-
} else {
436-
String::from("")
437-
},
438-
issuer_path = parent.as_ref().to_string_lossy(),
439-
)
440-
} else {
441-
format!(
442-
"{issuer_locator_name} tried to access {dependency_name}, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: {dependency_name}{via}\nRequired by: {issuer_locator_name}@{issuer_locator_reference} (via {issuer_path})",
443-
issuer_locator_name = &parent_locator.name,
444-
issuer_locator_reference = &parent_locator.reference,
445-
dependency_name = &ident,
446-
via = if ident != specifier {
447-
format!(" (via \"{}\")", &specifier)
448-
} else {
449-
String::from("")
450-
},
451-
issuer_path = parent.as_ref().to_string_lossy(),
452-
)
453-
}
438+
format!(
439+
"{issuer_locator_name} tried to access {dependency_name}, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: {dependency_name}{via}\nRequired by: {issuer_locator_name}@{issuer_locator_reference} (via {issuer_path})",
440+
issuer_locator_name = &parent_locator.name,
441+
issuer_locator_reference = &parent_locator.reference,
442+
dependency_name = &ident,
443+
via = if ident != specifier {
444+
format!(" (via \"{}\")", &specifier)
445+
} else {
446+
String::from("")
447+
},
448+
issuer_path = parent.as_ref().to_string_lossy(),
449+
)
454450
};
455451

456452
return Err(Error::UndeclaredDependency {
@@ -474,7 +470,7 @@ pub fn resolve_to_unqualified_via_manifest<P: AsRef<Path>>(
474470

475471
Ok(Resolution::Resolved(dependency_pkg.package_location.clone(), module_path))
476472
} else {
477-
let broken_ancestors = find_broken_peer_dependencies(&specifier, parent_locator);
473+
let broken_ancestors = find_broken_peer_dependencies(specifier, parent_locator);
478474

479475
let message = if is_dependency_tree_root(manifest, parent_locator) {
480476
format!(
@@ -523,7 +519,7 @@ pub fn resolve_to_unqualified_via_manifest<P: AsRef<Path>>(
523519
dependency_name: ident,
524520
issuer_locator: parent_locator.clone(),
525521
issuer_path: parent.as_ref().to_path_buf(),
526-
broken_ancestors: vec![].to_vec(),
522+
broken_ancestors: [].to_vec(),
527523
})
528524
}
529525
} else {

src/lib_tests.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use serde::Deserialize;
22

3-
use crate::{Manifest, Resolution, ResolutionConfig};
3+
use crate::{Manifest, Resolution};
44

55
#[derive(Deserialize)]
66
struct Test {
@@ -22,20 +22,18 @@ mod tests {
2222

2323
use super::*;
2424
use crate::{
25-
ResolutionHost, init_pnp_manifest, load_pnp_manifest, parse_bare_identifier,
26-
resolve_to_unqualified, resolve_to_unqualified_via_manifest,
25+
ResolutionConfig, ResolutionHost, init_pnp_manifest, load_pnp_manifest,
26+
parse_bare_identifier, resolve_to_unqualified, resolve_to_unqualified_via_manifest,
2727
};
2828

2929
#[test]
3030
fn example() {
3131
let manifest = load_pnp_manifest("data/pnp-yarn-v3.cjs").unwrap();
3232

33-
let host = ResolutionHost {
34-
find_pnp_manifest: Box::new(move |_| Ok(Some(manifest.clone()))),
35-
..Default::default()
36-
};
33+
let host =
34+
ResolutionHost { find_pnp_manifest: Box::new(move |_| Ok(Some(manifest.clone()))) };
3735

38-
let config = ResolutionConfig { host, ..Default::default() };
36+
let config = ResolutionConfig { host };
3937

4038
let resolution = resolve_to_unqualified(
4139
"lodash/cloneDeep",
@@ -85,7 +83,7 @@ mod tests {
8583

8684
for test_suite in test_suites.iter_mut() {
8785
let manifest = &mut test_suite.manifest;
88-
init_pnp_manifest(manifest, &PathBuf::from("/path/to/project/.pnp.cjs"));
86+
init_pnp_manifest(manifest, PathBuf::from("/path/to/project/.pnp.cjs"));
8987

9088
for test in test_suite.tests.iter() {
9189
let specifier = &test.imported;
@@ -95,10 +93,9 @@ mod tests {
9593

9694
let host = ResolutionHost {
9795
find_pnp_manifest: Box::new(move |_| Ok(Some(manifest_copy.clone()))),
98-
..Default::default()
9996
};
10097

101-
let config = ResolutionConfig { host, ..Default::default() };
98+
let config = ResolutionConfig { host };
10299

103100
let resolution = resolve_to_unqualified(specifier, parent, &config);
104101

@@ -110,7 +107,7 @@ mod tests {
110107
assert_eq!(specifier, &test.expected, "{}", test.it);
111108
}
112109
Err(err) => {
113-
assert_eq!(test.expected, "error!", "{}: {}", test.it, err.to_string());
110+
assert_eq!(test.expected, "error!", "{}: {err}", test.it);
114111
}
115112
}
116113
}

0 commit comments

Comments
 (0)