sax 0.1.0

Smart archiving and extracting utility
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};

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

use crate::extract::{self};

#[derive(Parser)]
#[command(name = "ax", version, about = "Smart archiving and extracting utility")]
pub struct Cli {
    pub args: Vec<String>,
}

impl Cli {
    pub fn run(&self) -> Result<()> {
        if self.args.is_empty() {
            bail!("No arguments were given");
        }

        if self.args.len() == 2 {
            let path = PathBuf::from_str(&self.args[0])
                .with_context(|| "Argument could not be parsed as path.")?;

            if !is_archive(&path) {
                bail!("{} is not an archive.", path.display());
            }

            let out = PathBuf::from_str(&self.args[1])
                .with_context(|| "Out could not be read as path.")?;

            extract::extract_archive(&path, &out).with_context(|| {
                format!(
                    "Could not extract archive {} to {}",
                    path.display(),
                    out.display()
                )
            })?;

            return Ok(());
        }

        if self.args.len() > 1 {
            // Create archive
            bail!("Not implemented")
        }

        // TODO: Lol
        bail!("Could not determine what the fuck you want to do")
    }
}

fn is_archive(p: &Path) -> bool {
    if !p.exists() {
        return false;
    }

    let s = p.display().to_string().to_lowercase();

    s.ends_with(".zip")
        || s.ends_with(".tar")
        || s.ends_with(".tar.gz")
        || s.ends_with(".tgz")
        || s.ends_with(".tar.bz2")
        || s.ends_with(".tbz2")
        || s.ends_with(".tar.xz")
        || s.ends_with(".txz")
        || s.ends_with(".7z")
}