Skip to content

Commit

Permalink
Various Slimming Changes (#2)
Browse files Browse the repository at this point in the history
* slimmed down crate

* fix apt prelude imports and macro missing

* switch to home library for getting the cargo home directory
  • Loading branch information
ripytide authored Aug 29, 2024
1 parent a78bd15 commit 70d1f39
Show file tree
Hide file tree
Showing 14 changed files with 277 additions and 455 deletions.
254 changes: 242 additions & 12 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ serde_json = "1.0"
toml = "0.8"
derive_more = "0.99"
itertools = "0.12"
dirs = "5.0.1"
home = "0.5.9"
pretty_env_logger = "0.5.0"

[profile.release]
lto = "off"
Expand Down
15 changes: 5 additions & 10 deletions src/backend/cargo.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::collections::BTreeMap;
use std::io::ErrorKind::NotFound;
use std::path::PathBuf;
use std::{collections::BTreeMap, fs::read_to_string};

use anyhow::{bail, Context, Result};
use serde_json::Value;
Expand All @@ -23,9 +22,11 @@ impl Backend for Cargo {
return Ok(BTreeMap::new());
}

let file = get_crates_file().context("getting path to crates file")?;
let file = home::cargo_home()
.context("getting the cargo home directory")?
.join(".crates2.json");

let contents = match read_to_string(file) {
let contents = match std::fs::read_to_string(file) {
Ok(string) => string,
Err(err) if err.kind() == NotFound => {
log::warn!("no crates file found for cargo. Assuming no crates installed yet.");
Expand Down Expand Up @@ -89,9 +90,3 @@ fn extract_packages(contents: &str) -> Result<BTreeMap<String, ()>> {

Ok(result)
}

fn get_crates_file() -> Result<PathBuf> {
let mut result = crate::path::get_cargo_home().context("getting cargo home dir")?;
result.push(".crates2.json");
Ok(result)
}
2 changes: 1 addition & 1 deletion src/backend/dnf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct Dnf;

#[derive(Debug, Clone)]
pub struct DnfQueryInfo {
user: bool,
pub user: bool,
}

#[derive(Debug, Clone, Default)]
Expand Down
4 changes: 2 additions & 2 deletions src/backend/flatpak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub struct Flatpak;

#[derive(Debug, Clone)]
pub struct FlatpakQueryInfo {
explicit: bool,
systemwide: bool,
pub explicit: bool,
pub systemwide: bool,
}

impl Backend for Flatpak {
Expand Down
1 change: 0 additions & 1 deletion src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use std::{collections::BTreeMap, str::FromStr};

use crate::prelude::*;
use anyhow::{Context, Result};
use apt::Apt;

#[derive(Debug, Copy, Clone, derive_more::Display)]
pub enum AnyBackend {
Expand Down
20 changes: 9 additions & 11 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::fs::{create_dir_all, read_to_string, File};
use std::fs::{create_dir_all, File};
use std::io::{ErrorKind, Write};
use std::path::Path;

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};

use crate::prelude::*;

// Update the master README if fields change.
/// Config for the program, as listed in `$XDG_CONFIG_HOME/pacdef/pacdef.toml`.
#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -44,20 +42,20 @@ fn pip() -> String {
}

impl Config {
/// Load the config from the associated file.
/// Load the config file from a users pacdef config folder.
///
/// # Errors
///
/// This function will return an error if the config file exists but cannot be
/// read, its contents are not UTF-8, or the file is malformed.
pub fn load(config_file: &Path) -> Result<Self> {
let from_file = read_to_string(config_file);
/// - If a config file cannot be found.
pub fn load() -> Result<Self> {
let config_file = dirs::config_dir()
.context("getting the config directory")?
.join("pacdef/config.toml");

let content = match from_file {
let content = match std::fs::read_to_string(config_file) {
Ok(content) => content,
Err(e) => {
if e.kind() == ErrorKind::NotFound {
bail!(Error::ConfigFileNotFound)
bail!("config file not found")
}
bail!("unexpected error occurred: {e:?}");
}
Expand Down
44 changes: 0 additions & 44 deletions src/errors.rs

This file was deleted.

93 changes: 5 additions & 88 deletions src/groups.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
use crate::prelude::*;
use anyhow::{Context, Result};
use path_absolutize::Absolutize;
use walkdir::WalkDir;
use anyhow::Result;

use std::{
collections::BTreeMap,
fs::{create_dir, read_to_string},
ops::{Deref, DerefMut},
path::Path,
str::FromStr,
};

/// A type representing a users group files with all their packages
Expand All @@ -32,91 +27,13 @@ impl Groups {
Self(BTreeMap::new())
}

/// Loads and parses the [`Groups`] struct from a users group files
/// Loads Groups from a users pacdef config folder.
///
/// # Errors
///
/// Returns an error if a parsing error is encountered in a found group file.
///
/// # Panics
///
/// Cannot panic on Linux, since all path types will always be convertible to
/// valid Rust strings.
pub fn load(group_dir: &Path, _config: &Config) -> Result<Self> {
let mut groups = Self::new();

if !group_dir.is_dir() {
// other direcotories were already created with the config file
create_dir(group_dir).context("group dir does not exist, creating one")?;
}

let mut files = vec![];

for file in WalkDir::new(group_dir).follow_links(true) {
let path = file?.path().absolutize_from(group_dir)?.to_path_buf();
files.push(path);
}

for group_file in files.iter().filter(|path| path.is_file()) {
let group = parse_group(group_file).context(format!(
"Failed to parse the group file {}",
group_file.to_string_lossy()
))?;

let group_name = get_relative_path(group_file.as_path(), group_dir)
.iter()
.map(|p| p.to_string_lossy().to_string())
.reduce(|mut a, b| {
a.push('/');
a.push_str(&b);
a
})
.expect("must have at least one element")
.to_string();
groups.insert(group_name, group);
}

Ok(groups)
}
}

/// Parse the group and sections from the group file
fn parse_group(group_file: &Path) -> Result<PackagesInstall> {
let content = read_to_string(group_file).context("reading file contents")?;

let mut backends = PackagesIds::new();
let mut prev_backend: Option<AnyBackend> = None;
for (count, line) in content
.lines()
.enumerate()
.filter(|(_, line)| !line.trim_start().is_empty() && !line.trim_start().starts_with('#'))
{
if line.starts_with('[') {
let backend = line
.strip_prefix('[')
.expect("Won't error")
.strip_suffix(']')
.ok_or(Error::InvalidBackend(line.to_string()))
.context(format!("Invalid backend {}", line))?;

prev_backend = AnyBackend::from_str(backend).ok();
} else {
let package = line
.split_once('#')
.map_or(line, |value| value.0)
.trim()
.to_string();

prev_backend
.map(|backend| backends.insert_backend_package(backend, package))
.ok_or(Error::InvalidBackend(format!(
"Failed to parse {line} at line number {count} in file {}",
group_file.to_string_lossy()
)))??;
}
/// - If the Group config file cannot be found.
pub fn load() -> Result<Self> {
todo!()
}

Ok(PackagesInstall::from_packages_ids_defaults(&backends))
}

impl Deref for Groups {
Expand Down
5 changes: 1 addition & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ mod cmd;
mod config;
#[allow(clippy::unused_self, clippy::unnecessary_wraps)]
mod core;
mod errors;
mod groups;
mod packages;
mod review;
Expand All @@ -37,7 +36,5 @@ mod ui;
#[allow(unused_imports)]
mod prelude;

pub mod path;

pub use prelude::Config;
pub use prelude::Groups;
pub use prelude::{Config, Error};
Loading

0 comments on commit 70d1f39

Please sign in to comment.