chore: refactor into lib
This commit is contained in:
parent
430d988f31
commit
9628bf9b71
4 changed files with 148 additions and 126 deletions
91
src/root.rs
Normal file
91
src/root.rs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
use anyhow::{Context, Result};
|
||||
use std::{
|
||||
ffi::{OsStr, OsString},
|
||||
fs::create_dir_all,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use url::Url;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
const MAX_DEPTH: usize = 5;
|
||||
|
||||
pub struct SrcRoot {
|
||||
root_path: PathBuf,
|
||||
}
|
||||
|
||||
impl SrcRoot {
|
||||
fn clone_repo(url: &Url, destination: &Path) -> Result<()> {
|
||||
let url = OsString::from(url.as_ref());
|
||||
Command::new("git")
|
||||
.args([
|
||||
OsString::from("clone").as_os_str(),
|
||||
url.as_os_str(),
|
||||
destination.as_os_str(),
|
||||
])
|
||||
.status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn as_repo_path(&self, url: &Url) -> PathBuf {
|
||||
let mut dir = PathBuf::new();
|
||||
dir.push::<&Path>(self.root_path.as_ref());
|
||||
dir.push(url.host_str().unwrap_or("misc"));
|
||||
url.path_segments()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|s| !s.is_empty())
|
||||
.for_each(|s| dir.push(s.trim_end_matches(".git")));
|
||||
dir
|
||||
}
|
||||
|
||||
fn ensure_repo_checkout(&self, url: &Url) -> Result<PathBuf> {
|
||||
let repo_path = self.as_repo_path(url);
|
||||
if !repo_path.is_dir() {
|
||||
create_dir_all(&repo_path)?;
|
||||
}
|
||||
Self::clone_repo(url, &repo_path)?;
|
||||
Ok(repo_path)
|
||||
}
|
||||
|
||||
fn search_repo<S: AsRef<OsStr>>(&self, slug: S) -> Result<Option<PathBuf>> {
|
||||
let walker = WalkDir::new(&self.root_path)
|
||||
.follow_links(false)
|
||||
.max_depth(MAX_DEPTH)
|
||||
.follow_root_links(false)
|
||||
.max_open(1)
|
||||
.sort_by_file_name()
|
||||
.contents_first(false)
|
||||
.same_file_system(true);
|
||||
for path in walker {
|
||||
let p = path?;
|
||||
let git = {
|
||||
let mut g = p.clone().into_path();
|
||||
g.push(".git");
|
||||
g
|
||||
};
|
||||
if let Some(file_name) = p.path().file_name() {
|
||||
if file_name == slug.as_ref() && git.is_dir() {
|
||||
return Ok(Some(p.into_path()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// File system errors
|
||||
pub fn resolve_repo(&self, arg: String) -> Result<impl AsRef<Path>> {
|
||||
if let Ok(url) = Url::parse(&arg) {
|
||||
self.ensure_repo_checkout(&url)
|
||||
} else {
|
||||
let slug: OsString = arg.into();
|
||||
self.search_repo(slug)?.context("Repo not found")
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(path: PathBuf) -> Self {
|
||||
Self { root_path: path }
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue