Skip to content

Commit

Permalink
fix: Remove allow(unused and fix resulting warnings (#2091)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hofer-Julian authored Sep 20, 2024
1 parent e04e20e commit ebda8b1
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 153 deletions.
70 changes: 3 additions & 67 deletions src/global/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,7 @@ use std::{

use itertools::Itertools;
use miette::{Context, IntoDiagnostic};
use pixi_progress::{await_in_progress, global_multi_progress};
use rattler::{
install::{DefaultProgressFormatter, IndicatifReporter, Installer},
package_cache::PackageCache,
};
use rattler_conda_types::{
Channel, ChannelConfig, PackageName, Platform, PrefixRecord, RepoDataRecord,
};
use rattler_shell::{
activation::{ActivationVariables, Activator, PathModificationBehavior},
shell::ShellEnum,
};
use reqwest_middleware::ClientWithMiddleware;
use tokio::io::AsyncReadExt;

use crate::{
cli::project::environment, prefix::Prefix, repodata, rlimit::try_increase_rlimit_to_sensible,
};
use pixi_config::home_path;

use super::{EnvironmentName, ExposedKey};
Expand Down Expand Up @@ -84,7 +67,7 @@ impl BinDir {
executable_script_path
}

pub(crate) async fn print_executables_available(
pub async fn print_executables_available(
&self,
executables: Vec<PathBuf>,
) -> miette::Result<()> {
Expand Down Expand Up @@ -206,7 +189,6 @@ impl EnvRoot {

/// A global environment directory
pub(crate) struct EnvDir {
root: EnvRoot,
path: PathBuf,
}

Expand All @@ -219,23 +201,7 @@ impl EnvDir {
let path = root.path().join(environment_name.as_str());
tokio::fs::create_dir_all(&path).await.into_diagnostic()?;

Ok(Self { root, path })
}

/// Initialize a global environment directory from an existing path
pub(crate) fn try_from_existing(
root: EnvRoot,
environment_name: EnvironmentName,
) -> miette::Result<Self> {
let path = root.path().join(environment_name.as_str());
if !path.is_dir() {
return Err(miette::miette!(
"Directory does not exist: {}",
path.display()
));
}

Ok(Self { root, path })
Ok(Self { path })
}

/// Construct the path to the env directory for the environment
Expand All @@ -245,36 +211,6 @@ impl EnvDir {
}
}

/// Get the friendly channel name of a [`PrefixRecord`]
///
/// # Returns
///
/// The friendly channel name of the given prefix record
pub(crate) fn channel_name_from_prefix(
prefix_package: &PrefixRecord,
channel_config: &ChannelConfig,
) -> String {
Channel::from_str(&prefix_package.repodata_record.channel, channel_config)
.map(|ch| repodata::friendly_channel_name(&ch))
.unwrap_or_else(|_| prefix_package.repodata_record.channel.clone())
}

/// Find the designated package in the given [`Prefix`]
///
/// # Returns
///
/// The PrefixRecord of the designated package
pub(crate) async fn find_designated_package(
prefix: &Prefix,
package_name: &PackageName,
) -> miette::Result<PrefixRecord> {
let prefix_records = prefix.find_installed_packages(None).await?;
prefix_records
.into_iter()
.find(|r| r.repodata_record.package_record.name == *package_name)
.ok_or_else(|| miette::miette!("could not find {} in prefix", package_name.as_source()))
}

/// Checks if a file is binary by reading the first 1024 bytes and checking for null bytes.
pub(crate) fn is_binary(file_path: impl AsRef<Path>) -> miette::Result<bool> {
let mut file = std::fs::File::open(&file_path)
Expand All @@ -298,7 +234,7 @@ pub(crate) fn is_text(file_path: impl AsRef<Path>) -> miette::Result<bool> {
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;

use tempfile::tempdir;

#[tokio::test]
Expand Down
30 changes: 9 additions & 21 deletions src/global/install.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
use std::{
borrow::Borrow,
collections::HashMap,
ffi::OsStr,
iter,
path::{Path, PathBuf},
str::FromStr,
time,
};
use std::{collections::HashMap, ffi::OsStr, path::PathBuf, str::FromStr};

use clap::Parser;
use distribution_types::Diagnostic;
use indexmap::IndexMap;
use itertools::Itertools;
use miette::{bail, Context, IntoDiagnostic};
use pixi_config::{self, default_channel_config, Config, ConfigCli};
use miette::{Context, IntoDiagnostic};
use pixi_config::{self, default_channel_config, Config};
use pixi_progress::{await_in_progress, global_multi_progress, wrap_in_progress};
use pixi_utils::reqwest::build_reqwest_clients;
use rattler::{
Expand All @@ -22,7 +12,7 @@ use rattler::{
};
use rattler_conda_types::{
GenericVirtualPackage, MatchSpec, Matches, PackageName, ParseStrictness, Platform,
PrefixRecord, RepoDataRecord,
RepoDataRecord,
};
use rattler_repodata_gateway::Gateway;
use rattler_shell::{
Expand All @@ -35,17 +25,14 @@ use reqwest_middleware::ClientWithMiddleware;

use super::{common::EnvRoot, project::ParsedEnvironment, EnvironmentName, ExposedKey};
use crate::{
cli::{cli_config::ChannelsConfig, has_specs::HasSpecs, project::platform},
global::{self, channel_name_from_prefix, find_designated_package, BinDir, EnvDir},
global::{self, BinDir, EnvDir},
prefix::Prefix,
rlimit::try_increase_rlimit_to_sensible,
task::ExecutableTask,
};

/// Installs global environment records
pub(crate) async fn install_environment(
specs: &IndexMap<PackageName, MatchSpec>,
env_name: &EnvironmentName,
parsed_environment: &ParsedEnvironment,
authenticated_client: ClientWithMiddleware,
prefix: &Prefix,
Expand Down Expand Up @@ -163,7 +150,7 @@ pub(crate) async fn expose_executables(
.map(|name| (name.to_string(), path.clone()))
})
// Filters tuples to include only those whose names are in the `exposed` values
.filter(|(name, path)| parsed_environment.exposed.values().contains(&name))
.filter(|(name, _)| parsed_environment.exposed.values().contains(&name))
.collect();

let script_mapping = parsed_environment
Expand Down Expand Up @@ -255,6 +242,7 @@ fn get_catch_all_arg(shell: &ShellEnum) -> &str {

/// For each executable provided, map it to the installation path for its global
/// executable script.
#[allow(unused)]
async fn map_executables_to_global_bin_scripts(
package_executables: impl IntoIterator<Item = PathBuf>,
bin_dir: &BinDir,
Expand Down Expand Up @@ -409,6 +397,7 @@ async fn create_executable_scripts(
}

/// Warn user on dangerous package installations, interactive yes no prompt
#[allow(unused)]
pub(crate) fn prompt_user_to_continue(
packages: &IndexMap<PackageName, MatchSpec>,
) -> miette::Result<bool> {
Expand Down Expand Up @@ -514,7 +503,6 @@ pub(crate) async fn sync(config: &Config, assume_yes: bool) -> Result<(), miette
if !specs_match_local_environment(&specs, prefix_records, parsed_environment.platform()) {
install_environment(
&specs,
&env_name,
&parsed_environment,
auth_client.clone(),
&prefix,
Expand Down Expand Up @@ -549,7 +537,7 @@ fn specs_match_local_environment<T: AsRef<RepoDataRecord>>(
) -> bool {
// Check whether all specs in the manifest are present in the installed
// environment
let specs_in_manifest_are_present = specs.iter().all(|(name, spec)| {
let specs_in_manifest_are_present = specs.values().all(|spec| {
prefix_records
.iter()
.any(|record| spec.matches(record.as_ref()))
Expand Down
9 changes: 2 additions & 7 deletions src/global/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
// TODO: remove this before merging to main
#![allow(unused)]

mod common;
mod install;
mod project;

use crate::prefix::Prefix;
pub(crate) use common::{
channel_name_from_prefix, find_designated_package, BinDir, EnvDir, EnvRoot,
};
pub(crate) use common::{BinDir, EnvDir, EnvRoot};
pub(crate) use install::sync;
pub(crate) use project::{EnvironmentName, ExposedKey, Project, MANIFEST_DEFAULT_NAME};
pub(crate) use project::{EnvironmentName, ExposedKey, Project};
use rattler_conda_types::PrefixRecord;
use std::path::{Path, PathBuf};

Expand Down
3 changes: 0 additions & 3 deletions src/global/project/environment.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::{fmt, str::FromStr};

use indexmap::IndexMap;
use miette::Diagnostic;
use pixi_spec::PixiSpec;
use rattler_conda_types::PackageName;
use regex::Regex;
use serde::{self, Deserialize, Deserializer, Serialize};
use thiserror::Error;
Expand Down
3 changes: 3 additions & 0 deletions src/global/project/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use super::error::ManifestError;
use super::MANIFEST_DEFAULT_NAME;
use super::{document::ManifestSource, parsed_manifest::ParsedManifest};

// TODO: remove
#[allow(unused)]

/// Handles the global project's manifest file.
/// This struct is responsible for reading, parsing, editing, and saving the
/// manifest. It encapsulates all logic related to the manifest's TOML format
Expand Down
57 changes: 18 additions & 39 deletions src/global/project/mod.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,26 @@
use std::{
env,
ffi::OsStr,
fmt::{Debug, Formatter},
path::{Path, PathBuf},
str::FromStr,
sync::OnceLock,
};

pub(crate) use environment::EnvironmentName;
use indexmap::IndexMap;
use itertools::Itertools;
use manifest::Manifest;
use miette::{miette, Context, IntoDiagnostic};
use miette::{Context, IntoDiagnostic};
use once_cell::sync::Lazy;
use parsed_manifest::ParsedManifest;
pub(crate) use parsed_manifest::{ExposedKey, ParsedEnvironment};
use pixi_config::{default_channel_config, home_path, Config};
use pixi_config::{home_path, Config};
use pixi_manifest::PrioritizedChannel;
use rattler_conda_types::{Channel, NamedChannelOrUrl, PackageName, Platform, PrefixRecord};
use rattler_digest::digest::typenum::Exp;
use rattler_repodata_gateway::Gateway;
use rattler_conda_types::{NamedChannelOrUrl, PackageName, Platform, PrefixRecord};
use regex::Regex;
use reqwest_middleware::ClientWithMiddleware;
use tokio_stream::{wrappers::ReadDirStream, StreamExt};
use url::Url;

use super::{find_executables, BinDir, EnvRoot};
use super::{BinDir, EnvRoot};
use crate::{
global::{common::is_text, EnvDir},
global::{common::is_text, find_executables, EnvDir},
prefix::Prefix,
};

Expand All @@ -47,12 +40,6 @@ pub(crate) const MANIFEST_DEFAULT_NAME: &str = "pixi-global.toml";
pub struct Project {
/// Root folder of the project
root: PathBuf,
/// Reqwest client shared for this project.
/// This is wrapped in a `OnceLock` to allow for lazy initialization.
client: OnceLock<(reqwest::Client, ClientWithMiddleware)>,
/// The repodata gateway to use for answering queries about repodata.
/// This is wrapped in a `OnceLock` to allow for lazy initialization.
repodata_gateway: OnceLock<Gateway>,
/// The manifest for the project
pub(crate) manifest: Manifest,
/// The global configuration as loaded from the config file(s)
Expand Down Expand Up @@ -189,8 +176,6 @@ async fn package_from_conda_meta(
executable: &str,
prefix: &Prefix,
) -> miette::Result<(Option<Platform>, PrioritizedChannel, PackageName)> {
let channel_config = default_channel_config();

let read_dir = tokio::fs::read_dir(conda_meta)
.await
.into_diagnostic()
Expand All @@ -206,35 +191,32 @@ async fn package_from_conda_meta(
.path();
// Check if the entry is a file and has a .json extension
if path.is_file() && path.extension().and_then(OsStr::to_str) == Some("json") {
let content = std::fs::read_to_string(&path).into_diagnostic()?;
let prefix_record = PrefixRecord::from_path(&path)
.into_diagnostic()
.wrap_err_with(|| format!("Could not parse json from {}", path.display()))?;

let binaries = find_executables(prefix, &prefix_record);
let Some(found_executable) = binaries
if find_executables(prefix, &prefix_record)
.iter()
.find(|exe_path| exe_path.file_stem().and_then(OsStr::to_str) == Some(executable))
else {
continue;
};

let platform =
match Platform::from_str(&prefix_record.repodata_record.package_record.subdir) {
.any(|exe_path| exe_path.file_stem().and_then(OsStr::to_str) == Some(executable))
{
let platform = match Platform::from_str(
&prefix_record.repodata_record.package_record.subdir,
) {
Ok(Platform::NoArch) => None,
Ok(platform) if platform == Platform::current() => None,
Err(_) => None,
Ok(p) => Some(p),
};

let channel: PrioritizedChannel =
NamedChannelOrUrl::from_str(&prefix_record.repodata_record.channel)
.into_diagnostic()?
.into();
let channel: PrioritizedChannel =
NamedChannelOrUrl::from_str(&prefix_record.repodata_record.channel)
.into_diagnostic()?
.into();

let name = prefix_record.repodata_record.package_record.name;
let name = prefix_record.repodata_record.package_record.name;

return Ok((platform, channel, name));
return Ok((platform, channel, name));
}
}
}

Expand All @@ -254,8 +236,6 @@ impl Project {

Self {
root,
client: Default::default(),
repodata_gateway: Default::default(),
manifest,
config,
}
Expand Down Expand Up @@ -286,7 +266,6 @@ impl Project {
let manifest_path = manifest_dir.join(MANIFEST_DEFAULT_NAME);

if !manifest_path.exists() {
let warn = console::style(console::Emoji("⚠️ ", "")).yellow();
let prompt = format!(
"{} You don't have a global manifest yet.\n\
Do you want to create one based on your existing installation?\n\
Expand Down
Loading

0 comments on commit ebda8b1

Please sign in to comment.