Skip to content

Commit

Permalink
Fix all clippy lints
Browse files Browse the repository at this point in the history
  • Loading branch information
Hofer-Julian committed Dec 3, 2024
1 parent a641cfb commit 47a4383
Show file tree
Hide file tree
Showing 20 changed files with 47 additions and 53 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

7 changes: 0 additions & 7 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,6 @@ ignore-interior-mutability = [
"pixi::project::solve_group::SolveGroup",
]

disallowed-types = [
"std::fs::DirEntry",
"std::fs::File",
"std::fs::OpenOptions",
"std::fs::ReadDir",
]

disallowed-methods = [
"std::fs::canonicalize",
"std::fs::copy",
Expand Down
1 change: 1 addition & 0 deletions crates/pixi_config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ version = "0.1.0"
clap = { workspace = true, features = ["std", "derive", "env"] }
console = { workspace = true }
dirs = { workspace = true }
fs-err = { workspace = true }
itertools = { workspace = true }
miette = { workspace = true }
pixi_consts = { workspace = true }
Expand Down
7 changes: 3 additions & 4 deletions crates/pixi_config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use reqwest_middleware::ClientWithMiddleware;
use serde::{de::IntoDeserializer, Deserialize, Serialize};
use std::{
collections::{BTreeSet as Set, HashMap},
fs,
path::{Path, PathBuf},
process::{Command, Stdio},
str::FromStr,
Expand Down Expand Up @@ -747,7 +746,7 @@ impl Config {
/// I/O errors or parsing errors
pub fn from_path(path: &Path) -> miette::Result<Config> {
tracing::debug!("Loading config from {}", path.display());
let s = fs::read_to_string(path)
let s = fs_err::read_to_string(path)
.into_diagnostic()
.wrap_err(format!("failed to read config from '{}'", path.display()))?;

Expand Down Expand Up @@ -1201,13 +1200,13 @@ impl Config {
tracing::debug!("Saving config to: {}", to.display());

let parent = to.parent().expect("config path should have a parent");
fs::create_dir_all(parent)
fs_err::create_dir_all(parent)
.into_diagnostic()
.wrap_err(format!(
"failed to create directories in '{}'",
parent.display()
))?;
fs::write(to, contents)
fs_err::write(to, contents)
.into_diagnostic()
.wrap_err(format!("failed to write config to '{}'", to.display()))
}
Expand Down
8 changes: 3 additions & 5 deletions crates/pixi_glob/src/glob_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,8 @@ impl<'t> GlobSet<'t> {
#[cfg(test)]
mod tests {
use super::GlobSet;
use std::{
fs::{create_dir, File},
path::PathBuf,
};
use fs_err::File;
use std::path::PathBuf;
use tempfile::tempdir;

#[test]
Expand All @@ -111,7 +109,7 @@ mod tests {
File::create(root_path.join("include1.txt")).unwrap();
File::create(root_path.join("include2.log")).unwrap();
File::create(root_path.join("exclude.txt")).unwrap();
create_dir(root_path.join("subdir")).unwrap();
fs_err::create_dir(root_path.join("subdir")).unwrap();
File::create(root_path.join("subdir/include_subdir.txt")).unwrap();

// Test globs: include all .txt but exclude exclude.txt
Expand Down
4 changes: 2 additions & 2 deletions crates/pixi_manifest/src/pyproject.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, fs, path::PathBuf, str::FromStr};
use std::{collections::HashMap, path::PathBuf, str::FromStr};

use indexmap::IndexMap;
use miette::{Diagnostic, IntoDiagnostic, Report, WrapErr};
Expand Down Expand Up @@ -58,7 +58,7 @@ impl PyProjectManifest {

/// Parses a `pyproject.toml` file into a PyProjectManifest
pub fn from_path(path: &PathBuf) -> Result<Self, Report> {
let source = fs::read_to_string(path)
let source = fs_err::read_to_string(path)
.into_diagnostic()
.wrap_err_with(|| format!("Failed to read file: {:?}", path))?;
Self::from_toml_str(&source).into_diagnostic()
Expand Down
4 changes: 2 additions & 2 deletions crates/pixi_utils/src/conda_environment_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ fn parse_channels(channels: Vec<NamedChannelOrUrl>) -> Vec<NamedChannelOrUrl> {

#[cfg(test)]
mod tests {
use std::{fs, io::Write, path::Path, str::FromStr};
use std::{io::Write, path::Path, str::FromStr};

use rattler_conda_types::{MatchSpec, ParseStrictness::Strict};

Expand Down Expand Up @@ -271,7 +271,7 @@ mod tests {
.join("tests")
.join("environment_yamls");

let entries = match fs::read_dir(test_files_path) {
let entries = match fs_err::read_dir(test_files_path) {
Ok(entries) => entries,
Err(e) => panic!("Failed to read directory: {}", e),
};
Expand Down
2 changes: 1 addition & 1 deletion crates/pixi_utils/src/prefix_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl PrefixGuard {
let guard_path = prefix.join(GUARD_PATH);

// Ensure that the directory exists
std::fs::create_dir_all(guard_path.parent().unwrap())?;
fs_err::create_dir_all(guard_path.parent().unwrap())?;

// Open the file
Ok(Self {
Expand Down
12 changes: 7 additions & 5 deletions src/cli/info.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fmt::Display, fs, path::PathBuf};
use std::{fmt::Display, path::PathBuf};

use chrono::{DateTime, Local};
use clap::Parser;
Expand Down Expand Up @@ -316,24 +316,26 @@ impl Display for Info {

/// Returns the size of a directory
fn dir_size(path: impl Into<PathBuf>) -> miette::Result<String> {
fn dir_size(mut dir: fs::ReadDir) -> miette::Result<u64> {
fn dir_size(mut dir: fs_err::ReadDir) -> miette::Result<u64> {
dir.try_fold(0, |acc, file| {
let file = file.into_diagnostic()?;
let size = match file.metadata().into_diagnostic()? {
data if data.is_dir() => dir_size(fs::read_dir(file.path()).into_diagnostic()?)?,
data if data.is_dir() => {
dir_size(fs_err::read_dir(file.path()).into_diagnostic()?)?
}
data => data.len(),
};
Ok(acc + size)
})
}

let size = dir_size(fs::read_dir(path.into()).into_diagnostic()?)?;
let size = dir_size(fs_err::read_dir(path.into()).into_diagnostic()?)?;
Ok(format!("{} MiB", size / 1024 / 1024))
}

/// Returns last update time of file, formatted: DD-MM-YYYY H:M:S
fn last_updated(path: impl Into<PathBuf>) -> miette::Result<String> {
let time = fs::metadata(path.into())
let time = fs_err::metadata(path.into())
.into_diagnostic()?
.modified()
.into_diagnostic()?;
Expand Down
6 changes: 3 additions & 3 deletions src/cli/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
}

// Fail silently if the directory already exists or cannot be created.
fs::create_dir_all(&dir).ok();
fs_err::create_dir_all(&dir).ok();

let default_name = get_name_from_dir(&dir).unwrap_or_else(|_| String::from("new_project"));
let version = "0.1.0";
Expand Down Expand Up @@ -484,7 +484,7 @@ fn render_project(

/// Save the rendered template to a file, and print a message to the user.
fn save_manifest_file(path: &Path, content: String) -> miette::Result<()> {
fs::write(path, content).into_diagnostic()?;
fs_err::write(path, content).into_diagnostic()?;
eprintln!(
"{}Created {}",
console::style(console::Emoji("✔ ", "")).green(),
Expand All @@ -510,7 +510,7 @@ fn get_name_from_dir(path: &Path) -> miette::Result<String> {
// When the specific template is not in the file or the file does not exist.
// Make the file and append the template to the file.
fn create_or_append_file(path: &Path, template: &str) -> std::io::Result<()> {
let file = fs::read_to_string(path).unwrap_or_default();
let file = fs_err::read_to_string(path).unwrap_or_default();

if !file.contains(template) {
fs::OpenOptions::new()
Expand Down
2 changes: 1 addition & 1 deletion src/cli/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ where
let mut result = 0;

if path.as_ref().is_dir() {
for entry in std::fs::read_dir(&path)? {
for entry in fs_err::read_dir(path.as_ref())? {
let _path = entry?.path();
if _path.is_file() {
result += _path.metadata()?.len();
Expand Down
7 changes: 3 additions & 4 deletions src/cli/project/export/conda_explicit_spec.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
collections::HashSet,
fs,
path::{Path, PathBuf},
};

Expand Down Expand Up @@ -87,7 +86,7 @@ fn render_explicit_spec(
environment.push_str("# Generated by `pixi project export`\n");
environment.push_str(exp_env_spec.to_spec_string().as_str());

fs::write(target, environment)
fs_err::write(target, environment)
.into_diagnostic()
.with_context(|| format!("failed to write environment file: {}", target.display()))?;

Expand Down Expand Up @@ -212,7 +211,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {
}
}

fs::create_dir_all(&args.output_dir).ok();
fs_err::create_dir_all(&args.output_dir).ok();

for (env_name, env, plat) in env_platform {
render_env_platform(
Expand Down Expand Up @@ -259,7 +258,7 @@ mod tests {
.join(format!("{}_{}_conda_spec.txt", env_name, platform));
insta::assert_snapshot!(
format!("test_render_conda_explicit_spec_{}_{}", env_name, platform),
fs::read_to_string(file_path).unwrap()
fs_err::read_to_string(file_path).unwrap()
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ fn create_prefix_location_file(environment_dir: &Path) -> miette::Result<()> {

// Read existing contents to determine if an update is necessary
if prefix_file_path.exists() {
let existing_contents = fs::read_to_string(&prefix_file_path).into_diagnostic()?;
let existing_contents = fs_err::read_to_string(&prefix_file_path).into_diagnostic()?;
if existing_contents == contents {
tracing::info!("No update needed for the prefix file.");
return Ok(());
Expand Down
4 changes: 2 additions & 2 deletions src/global/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ mod tests {
#[cfg(unix)]
#[tokio::test]
async fn test_extract_executable_from_script_unix() {
use std::{fs, path::Path};
use std::path::Path;

use crate::global::trampoline::GlobalExecutable;

Expand All @@ -520,7 +520,7 @@ export CONDA_PREFIX="/home/user/.pixi/envs/nushell"
let script_path = Path::new("nu");
let tempdir = tempfile::tempdir().unwrap();
let script_path = tempdir.path().join(script_path);
fs::write(&script_path, script).unwrap();
fs_err::write(&script_path, script).unwrap();
let script_global_bin = GlobalExecutable::Script(script_path);
let executable_path = script_global_bin.executable().await.unwrap();
assert_eq!(
Expand Down
3 changes: 1 addition & 2 deletions src/global/project/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;

use fancy_display::FancyDisplay;
use fs_err as fs;
use fs_err::tokio as tokio_fs;
use indexmap::IndexSet;
use miette::IntoDiagnostic;
Expand Down Expand Up @@ -41,7 +40,7 @@ impl Manifest {
/// Creates a new manifest from a path
pub fn from_path(path: impl AsRef<Path>) -> miette::Result<Self> {
let manifest_path = dunce::canonicalize(path.as_ref()).into_diagnostic()?;
let contents = fs::read_to_string(path.as_ref()).into_diagnostic()?;
let contents = fs_err::read_to_string(path.as_ref()).into_diagnostic()?;
Self::from_str(manifest_path.as_ref(), contents)
}

Expand Down
6 changes: 3 additions & 3 deletions src/install_pypi/install_wheel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub(crate) fn get_wheel_info(
/// See: <https://github.com/pypa/pip/blob/36823099a9cdd83261fdbc8c1d2a24fa2eea72ca/src/pip/_internal/utils/wheel.py#L38>
fn find_dist_info(path: impl AsRef<Path>) -> miette::Result<String> {
// Iterate over `path` to find the `.dist-info` directory. It should be at the top-level.
let Some(dist_info) = fs::read_dir(path.as_ref())
let Some(dist_info) = fs_err::read_dir(path.as_ref())
.into_diagnostic()?
.find_map(|entry| {
let entry = entry.ok()?;
Expand Down Expand Up @@ -92,14 +92,14 @@ pub(crate) fn get_wheel_kind(
// > 1.a Parse distribution-1.0.dist-info/WHEEL.
// > 1.b Check that installer is compatible with Wheel-Version. Warn if minor version is greater, abort if major version is greater.
let wheel_file_path = wheel_path.join(format!("{dist_info_prefix}.dist-info/WHEEL"));
let wheel_text = fs::read_to_string(wheel_file_path).into_diagnostic()?;
let wheel_text = fs_err::read_to_string(wheel_file_path).into_diagnostic()?;
let lib_kind = parse_wheel_file(&wheel_text)?;
Ok(lib_kind)
}

use std::{
collections::HashMap,
fs::{self, File},
fs::File,
io::{BufRead, BufReader, Read},
path::{Path, PathBuf},
};
Expand Down
6 changes: 3 additions & 3 deletions src/project/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ pub(crate) fn find_project_manifest(current_dir: PathBuf) -> Option<PathBuf> {
match *manifest {
consts::PROJECT_MANIFEST => return Some(path),
consts::PYPROJECT_MANIFEST => {
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(content) = fs_err::read_to_string(&path) {
if content.contains("[tool.pixi") {
return Some(path);
}
Expand Down Expand Up @@ -1523,13 +1523,13 @@ mod tests {
writeln!(file, "[project]").unwrap();

// Pixi child manifest is pyproject.toml with pixi tool
std::fs::create_dir_all(&pixi_child_dir).unwrap();
fs_err::create_dir_all(&pixi_child_dir).unwrap();
let mut file = File::create(&manifest_path_pixi_child).unwrap();
writeln!(file, "[project]").unwrap();
writeln!(file, "[tool.pixi.project]").unwrap();

// Non pixi child manifest is pyproject.toml without pixi tool
std::fs::create_dir_all(&non_pixi_child_dir).unwrap();
fs_err::create_dir_all(&non_pixi_child_dir).unwrap();
let mut file = File::create(&manifest_path_non_pixi_child).unwrap();
writeln!(file, "[project]").unwrap();

Expand Down
3 changes: 2 additions & 1 deletion src/task/executable_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::{
task::task_graph::{TaskGraph, TaskId},
Project,
};
use fs_err::tokio as tokio_fs;
use pixi_consts::consts;

use crate::activation::CurrentEnvVarBehavior;
Expand Down Expand Up @@ -252,7 +253,7 @@ impl<'p> ExecutableTask<'p> {
let cache_name = self.cache_name();
let cache_file = self.project().task_cache_folder().join(cache_name);
if cache_file.exists() {
let cache = tokio::fs::read_to_string(&cache_file).await?;
let cache = tokio_fs::read_to_string(&cache_file).await?;
let cache: TaskCache = serde_json::from_str(&cache)?;
let hash = TaskHash::from_task(self, lock_file).await;
if let Ok(Some(hash)) = hash {
Expand Down
Loading

0 comments on commit 47a4383

Please sign in to comment.