Skip to content

Commit

Permalink
feat: show upt version/tools in help txt (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigoden authored Mar 18, 2024
1 parent b1046e2 commit d584540
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 29 deletions.
8 changes: 4 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::fmt;
pub enum UptError {
NoVendor(String),
NoTask,
NotFoundTool,
NoDetectVendor,
InvalidAction(String),
InvalidArgs(String),
DisplyHelp(String),
Expand All @@ -17,11 +17,11 @@ impl fmt::Display for UptError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use UptError::*;
match self {
NoVendor(v) => write!(f, "The vendor {} is not supported.", v),
NoVendor(v) => write!(f, "The package management tool '{}' is not supported.", v),
NoTask => write!(f, "The package management tool cannot perform the task."),
NotFoundTool => write!(
NoDetectVendor => write!(
f,
"No found package management tool, use `$UPT_TOOL` to specify one."
"No package management tool avaiable, use `$UPT_TOOL` to specify one."
),
InvalidAction(v) => write!(f, "Invalid action '{}'.", v),
InvalidArgs(v) => write!(f, "Invalid arguments.\n\n{}", v),
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ mod utils;
mod vendor;

pub use error::UptError;
pub use vendor::{detect_tool, init as init_vendor, Vendor};
pub use vendor::{detect_vendor, init_vendor, Vendor};
10 changes: 5 additions & 5 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ macro_rules! vendors {
},
)+
) => {
pub fn init(name: &str) -> Result<$crate::Vendor, $crate::UptError> {
pub fn init_vendor(name: &str) -> Result<$crate::Vendor, $crate::UptError> {
use $crate::action::must_from_str;
match name {
$(
Expand Down Expand Up @@ -58,9 +58,9 @@ macro_rules! vendors {
}
}

macro_rules! os_tools {
macro_rules! os_vendors {
($($os:literal => $($tool:literal),+);+$(;)?) => {
pub fn detect_tool() -> std::result::Result<$crate::Vendor, $crate::UptError> {
pub fn detect_vendor() -> std::result::Result<$crate::Vendor, $crate::UptError> {
let os = crate::utils::detect_os().unwrap_or_default();
let tools: Vec<&str> = match os.as_str() {
$(
Expand All @@ -69,8 +69,8 @@ macro_rules! os_tools {
_ => vec!["apt", "dnf", "pacman"],
};
match $crate::utils::find_tool(&tools) {
Some(tool) => $crate::vendor::init(&tool),
None => Err(UptError::NotFoundTool),
Some(tool) => $crate::vendor::init_vendor(&tool),
None => Err(UptError::NoDetectVendor),
}
}
};
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::env;
use std::path::Path;
use std::process::{self, Command};
use upt::{detect_tool, init_vendor, UptError, Vendor};
use upt::{detect_vendor, init_vendor, UptError, Vendor};

fn main() {
match run() {
Expand Down Expand Up @@ -34,11 +34,11 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
}

fn create_cmd(vendor: &Vendor, args: &[String]) -> Result<String, UptError> {
let task = vendor.parse(args)?;
let tool = match std::env::var("UPT_TOOL") {
Ok(v) => init_vendor(&v)?,
Err(_) => detect_tool()?,
Err(_) => detect_vendor()?,
};
let task = vendor.parse(args, tool.name())?;
let cmd = tool.eval(&task)?;
Ok(cmd)
}
Expand Down
38 changes: 22 additions & 16 deletions src/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::action::Action;
use crate::error::UptError;
use crate::task::Task;

os_tools!(
os_vendors!(
"windows" => "scoop", "choco", "winget";
"macos" => "brew", "port";
// apt
Expand Down Expand Up @@ -407,10 +407,14 @@ pub struct Vendor {
}

impl Vendor {
pub fn name(&self) -> &str {
&self.name
}

/// Parse command line, figure out the task to perform
pub fn parse(&self, args: &[String]) -> Result<Task, UptError> {
pub fn parse(&self, args: &[String], upt_tool: &str) -> Result<Task, UptError> {
if self.is_help(args) {
return Err(UptError::DisplyHelp(self.help()));
return Err(UptError::DisplyHelp(self.help(upt_tool)));
}
if let Some((Some(pkg), yes)) = self.install.parse(args, &self.confirm) {
return Ok(Task::Install { pkg, confirm: yes });
Expand All @@ -436,7 +440,7 @@ impl Vendor {
if self.list_installed.parse(args, "").is_some() {
return Ok(Task::ListInstalled);
}
Err(UptError::InvalidArgs(self.help()))
Err(UptError::InvalidArgs(self.help(upt_tool)))
}

/// Convert the task to command line, which invokes the os's package management tool.
Expand Down Expand Up @@ -473,7 +477,7 @@ impl Vendor {
}

/// Dump help message
fn help(&self) -> String {
fn help(&self, upt_tool: &str) -> String {
let mut lines: Vec<String> = Vec::new();
lines.push(String::from("Usage: "));
let helps = vec![
Expand All @@ -495,9 +499,11 @@ impl Vendor {
for (cmd, description) in &helps {
lines.push(format!(" {:<width$} {}", cmd, description, width = width));
}
lines.push(String::new());
lines.push(format!("Upt version: {}", env!("CARGO_PKG_VERSION")));
lines.push(format!("Upt tool: {}", upt_tool));
if !self.confirm.is_empty() {
lines.push(String::new());
lines.push(format!("Automatic answer yes to prompts: {}", self.confirm));
lines.push(format!("Confirm options: {}", self.confirm));
}
lines.join("\n")
}
Expand All @@ -509,25 +515,25 @@ mod tests {

macro_rules! check_parse {
($vendor:expr, [$($arg:expr),*], ($task:tt, $pkg:expr, $confirm:expr)) => {
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ]).unwrap(), Task::$task { pkg: $pkg.to_string(), confirm: $confirm })
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ], "-").unwrap(), Task::$task { pkg: $pkg.to_string(), confirm: $confirm })
};
($vendor:expr, [$($arg:expr),*], ($task:tt, pkg=$pkg:expr)) => {
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ]).unwrap(), Task::$task { pkg: $pkg.to_string() })
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ], "-").unwrap(), Task::$task { pkg: $pkg.to_string() })
};
($vendor:expr, [$($arg:expr),*], ($task:tt, confirm=$confirm:expr)) => {
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ]).unwrap(), Task::$task { confirm: $confirm })
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ], "-").unwrap(), Task::$task { confirm: $confirm })
};
($vendor:expr, [$($arg:expr),*], $task:tt) => {
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ]).unwrap(), Task::$task)
assert_eq!($vendor.parse(&vec![ $($arg.to_string()),* ], "-").unwrap(), Task::$task)
};
($vendor:expr, [$($arg:expr),*]) => {
assert!($vendor.parse(&vec![ $($arg.to_string()),* ]).is_err())
assert!($vendor.parse(&vec![ $($arg.to_string()),* ], "-").is_err())
}
}

#[test]
fn test_parse() {
let upt = init("upt").unwrap();
let upt = init_vendor("upt").unwrap();
check_parse!(upt, ["upt", "install", "vim"], (Install, "vim", false));
check_parse!(upt, ["upt", "install", "-y", "vim"], (Install, "vim", true));
check_parse!(
Expand Down Expand Up @@ -600,7 +606,7 @@ mod tests {

#[test]
fn test_eval() {
let upt = init("upt").unwrap();
let upt = init_vendor("upt").unwrap();
check_eval!(upt, (Install, "vim", false), "upt install vim");
check_eval!(upt, (Install, "vim jq", true), "upt install -y vim jq");
check_eval!(upt, (Remove, "vim jq", false), "upt remove vim jq");
Expand All @@ -612,7 +618,7 @@ mod tests {
check_eval!(upt, (UpgradeAll, confirm = true), "upt upgrade -y");
check_eval!(upt, ListInstalled, "upt list");

let pacman = init("pacman").unwrap();
let pacman = init_vendor("pacman").unwrap();
check_eval!(pacman, (Install, "vim", false), "pacman -S vim");
check_eval!(
pacman,
Expand All @@ -636,7 +642,7 @@ mod tests {
#[test]
fn test_vendors() {
for tool in support_tools() {
init(tool).unwrap();
init_vendor(tool).unwrap();
}
}
}

0 comments on commit d584540

Please sign in to comment.