feat: use clap and add setup command
This commit is contained in:
parent
bc24fe35b6
commit
057e095d90
3 changed files with 274 additions and 16 deletions
62
src/main.rs
62
src/main.rs
|
|
@ -1,5 +1,5 @@
|
|||
use std::{
|
||||
env::{args, current_dir, home_dir, var},
|
||||
env::{current_dir, home_dir, var},
|
||||
ffi::{OsStr, OsString},
|
||||
fs::create_dir_all,
|
||||
path::{Path, PathBuf},
|
||||
|
|
@ -7,11 +7,26 @@ use std::{
|
|||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use url::Url;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
const MAX_DEPTH: usize = 5;
|
||||
|
||||
fn setup_shell(code_root: &Path) {
|
||||
println!(
|
||||
r##"
|
||||
h() {{
|
||||
_h_dir=$(command repo resolve --root "#{}" "$@")
|
||||
_h_ret=$?
|
||||
[ "$_h_dir" != "$PWD" ] && cd "$_h_dir"
|
||||
return $_h_ret
|
||||
}}
|
||||
"##,
|
||||
code_root.display()
|
||||
);
|
||||
}
|
||||
|
||||
struct SrcRoot<T: AsRef<Path> + AsRef<OsStr>> {
|
||||
path: T,
|
||||
}
|
||||
|
|
@ -81,18 +96,16 @@ impl<T: AsRef<Path> + AsRef<OsStr>> SrcRoot<T> {
|
|||
}
|
||||
|
||||
fn src_root() -> Result<PathBuf> {
|
||||
if let Ok(src_root) = var("REPO_SRC_ROOT").map(PathBuf::from) {
|
||||
if let Ok(src_root) = var("REPO_CODE_ROOT").map(PathBuf::from) {
|
||||
Ok(src_root)
|
||||
} else {
|
||||
let mut src_root = home_dir().unwrap_or(current_dir()?);
|
||||
src_root.push("git");
|
||||
src_root.push("code");
|
||||
Ok(src_root)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let arg = args().next_back().context("Missing URL / name")?;
|
||||
let src_root = src_root()?;
|
||||
fn resolve_repo(arg: String, src_root: PathBuf) -> Result<(), anyhow::Error> {
|
||||
let src_root = SrcRoot::new(src_root);
|
||||
let path = if let Ok(url) = Url::parse(&arg) {
|
||||
src_root.ensure_repo_checkout(&url)
|
||||
|
|
@ -103,3 +116,40 @@ fn main() -> Result<()> {
|
|||
println!("{}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
#[command(propagate_version = true)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
Resolve {
|
||||
#[arg(long)]
|
||||
root: Option<PathBuf>,
|
||||
repo: String,
|
||||
},
|
||||
Setup {
|
||||
#[arg(long)]
|
||||
root: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
Commands::Resolve { root, repo } => {
|
||||
let root = root.context("").or_else(|_e| src_root())?;
|
||||
resolve_repo(repo, root)?;
|
||||
}
|
||||
Commands::Setup { root } => {
|
||||
let root = root.context("").or_else(|_e| src_root())?;
|
||||
setup_shell(&root);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue