Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various Slimming Changes #2

Merged
merged 3 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 232 additions & 12 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ serde_json = "1.0"
toml = "0.8"
derive_more = "0.99"
itertools = "0.12"
dirs = "5.0.1"
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 = dirs::home_dir()
.context("getting the home directory")?
ripytide marked this conversation as resolved.
Show resolved Hide resolved
.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
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");

InnocentZero marked this conversation as resolved.
Show resolved Hide resolved
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};
97 changes: 7 additions & 90 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,109 +14,26 @@
missing_docs
)]

use std::path::Path;
use std::process::{ExitCode, Termination};

use anyhow::{bail, Context, Result};
use anyhow::{Context, Result};

use clap::Parser;
use pacdef::cli::MainArguments;
use pacdef::path::{get_config_path, get_config_path_old_version};
use pacdef::{Config, Error as PacdefError, Groups};

const MAJOR_UPDATE_MESSAGE: &str = "VERSION UPGRADE
You seem to have used version 1.x of pacdef before.
In version 2.0 the config file needed to be changed from yaml to toml.
Check out https://github.com/steven-omaha/pacdef/blob/main/README.md#configuration for new syntax information.
This message will not appear again.
------";

struct PacdefLogger;

impl log::Log for PacdefLogger {
fn enabled(&self, _: &log::Metadata) -> bool {
true
}

fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
eprintln!("{} - {}", record.level(), record.args());
}
}

fn flush(&self) {}
}

fn main() -> ExitCode {
log::set_boxed_logger(Box::new(PacdefLogger))
.map(|()| log::set_max_level(log::LevelFilter::Info))
.expect("no other loggers should have been set");

handle_final_result(main_inner())
}
use pacdef::{Config, Groups};

/// Skip printing the error chain if its a pacdef error,
/// otherwise report error chain.
#[allow(clippy::option_if_let_else)]
fn handle_final_result(result: Result<()>) -> ExitCode {
match result {
Ok(_) => ExitCode::SUCCESS,
Err(ref e) => {
if let Some(root_error) = e.root_cause().downcast_ref::<PacdefError>() {
log::error!("{root_error}");
ExitCode::FAILURE
} else {
result.report()
}
}
}
}
fn main() -> Result<()> {
pretty_env_logger::init();

fn main_inner() -> Result<()> {
let main_arguments = MainArguments::parse();

let mut config_file = get_config_path().context("getting config file")?;
let config = Config::load().context("loading config file")?;

let config = match Config::load(&config_file).context("loading config file") {
Ok(config) => config,
Err(e) => {
if let Some(crate_error) = e.downcast_ref::<PacdefError>() {
match crate_error {
PacdefError::ConfigFileNotFound => load_default_config(&config_file)?,
_ => bail!("unexpected error: {crate_error}"),
}
} else {
bail!("unexpected error: {e:?}");
}
}
};

config_file.pop();
config_file.push("groups");
let groups = Groups::load(&config_file, &config).context("failed to load groups")?;
let groups = Groups::load().context("failed to load groups")?;

if groups.is_empty() {
log::warn!("no group files found");
}

main_arguments.run(&groups, &config)
}

fn load_default_config(config_file: &Path) -> Result<Config> {
if get_config_path_old_version()?.exists() {
println!("{MAJOR_UPDATE_MESSAGE}");
}

if !config_file.exists() {
create_empty_config_file(config_file)?;
}

Ok(Config::default())
}
main_arguments.run(&groups, &config)?;

fn create_empty_config_file(config_file: &Path) -> Result<()> {
let config_dir = &config_file.parent().context("getting parent dir")?;
std::fs::create_dir_all(config_dir).context("creating parent dir")?;
std::fs::File::create(config_file).context("creating empty config file")?;
Ok(())
}
Loading
Loading