Skip to main content

cargo_prepost/
prepost_utils.rs

1use clap::{Parser, Subcommand};
2use std::env;
3use std::ffi::OsString;
4use std::path::PathBuf;
5
6#[derive(Parser, Debug)]
7#[command(version, about)]
8pub struct Cli {
9    #[command(subcommand)]
10    command: Option<Commands>,
11}
12
13#[derive(Subcommand, Debug)]
14pub enum Commands {
15    Setup {
16        #[arg(long, value_name = "PATH")]
17        path: Option<PathBuf>,
18    },
19}
20
21pub fn main(args: impl Iterator<Item = impl Into<OsString> + Clone>) {
22    let cli = Cli::parse_from(args);
23    match cli.command {
24        Some(Commands::Setup { path }) => {
25            let path = path.unwrap_or(crate::prepost_home_path().join("bin"));
26
27            let new_cargo = path.join("cargo");
28            if new_cargo.exists() {
29                log::warn!("It seems that cargo-prepost is already setup");
30            } else {
31                crate::create_alias(new_cargo);
32            }
33
34            let mut new_path: std::collections::VecDeque<_> =
35                match env::var("PATH").map(|v| env::split_paths(&v).collect()) {
36                    Ok(v) => v,
37                    _ => {
38                        log::error!("Failed to get PATH");
39                        std::process::exit(1);
40                    }
41                };
42            new_path.push_front(path);
43            let new_path = match env::join_paths(new_path) {
44                Ok(v) => v,
45                Err(e) => {
46                    log::error!("Failed to get new PATH: {e}");
47                    std::process::exit(1);
48                }
49            };
50            println!("{}", new_path.display());
51        }
52        _ => {
53            println!("cargo-prepost");
54        }
55    }
56}