use crate::style::LogMessage;
use ::std::io::BufRead;
use anyhow::Result;
use online::check;
use std::env;
use std::fs;
use std::io::BufReader;
use std::process::Command;
use std::process::Stdio;
use std::str;
pub struct CliCommands;
impl CliCommands {
pub async fn upgrade() -> anyhow::Result<()> {
let internet_connection_exist: bool = check(None).is_ok();
if !internet_connection_exist {
LogMessage::error("Please connect to the internet and retry");
std::process::exit(1)
}
let cargo_exist = is_program_in_path("cargo");
let npm_exists = is_program_in_path("npm");
if !cargo_exist && !npm_exists {
LogMessage::error("Cargo or NPM is required");
std::process::exit(1)
}
let mut output = Command::new("cargo")
.args(["install", "utils-cli"])
.stdout(Stdio::piped())
.spawn()
.unwrap();
let stream_output = output.stdout.take().unwrap();
let lines = BufReader::new(stream_output).lines();
for line in lines {
println!("{}", line.unwrap());
}
Ok(())
}
pub async fn uninstall() -> Result<()> {
let cargo_exist = is_program_in_path("cargo");
let npm_exists = is_program_in_path("npm");
if !cargo_exist && !npm_exists {
LogMessage::error("Cargo or NPM is required");
std::process::exit(1)
}
let mut output = Command::new("cargo")
.args(["uninstall", "utils-cli"])
.stdout(Stdio::piped())
.spawn()
.unwrap();
let stream_output = output.stdout.take().unwrap();
let lines = BufReader::new(stream_output).lines();
for line in lines {
println!("{}", line.unwrap());
}
Ok(())
}
pub async fn sync() {
println!("synchrinizing data")
}
}
#[cfg(target_family = "unix")]
fn is_program_in_path(program: &str) -> bool {
if let Ok(path) = env::var("PATH") {
for p in path.split(':') {
let p_str = format!("{}/{}", p, program);
if fs::metadata(p_str).is_ok() {
return true;
}
}
}
false
}
#[cfg(target_family = "windows")] fn is_program_in_path(program: &str) -> bool {
if let Ok(path) = env::var("PATH") {
for p in path.split(":") {
let p_str = format!("{}/{}", p, program);
if fs::metadata(p_str).is_ok() {
return true;
}
}
}
false
}