use crate::error_mod::{Error, Result};
use crate::public_api_mod::{BLUE, RED, RESET};
pub fn git_has_remote() -> Result<bool> {
let output = std::process::Command::new("git").arg("remote").output()?;
Ok(!(String::from_utf8(output.stdout)?).is_empty())
}
pub fn git_is_local_repository() -> Result<bool> {
let output = std::process::Command::new("git").arg("status").output()?;
let output = String::from_utf8(output.stderr)?;
Ok(!output.contains("not a git repository"))
}
pub fn process_git_remote() -> String {
fn git_remote_output() -> Result<String> {
let output = std::process::Command::new("git").arg("remote").arg("-v").output()?;
let output = String::from_utf8(output.stdout)?;
Ok(output)
}
fn regex_capture(output: String) -> Result<String> {
let reg = regex::Regex::new(r#"origin\s*(?:https://)?(?:git@)?([^:/]*?)[:/]([^/]*?)/([^. ]*?)(?:\.git)?\s*\(fetch\)"#)?;
let cap = reg.captures(&output).ok_or(Error::ErrorFromStr("Error: reg.captures is None"))?;
if cap.len() != 4 {
return Err(Error::ErrorFromStr(
"Error: cap len is not 4, because there are 4 capture groups in regex.",
));
}
Ok(format!("https://{}/{}/{}/", &cap[1], &cap[2], &cap[3]))
}
let output = match git_remote_output() {
Ok(s) => s,
Err(e) => {
eprintln!("{RED}{e}{RESET}");
return "".to_string();
}
};
match regex_capture(output) {
Ok(s) => s,
Err(_e) => {
"".to_string()
}
}
}
pub fn new_local_repository(message: &str) -> Result<()> {
println!("{BLUE}This project folder is not yet a Git repository.{RESET}");
let answer = inquire::Text::new(&format!("{BLUE}Do you want to initialize a new local git repository? (y/n){RESET}")).prompt()?;
if answer.to_lowercase() != "y" {
return Err(Error::ErrorFromStr("Ok. You don't want to initialize a new local git repository."));
}
if !camino::Utf8Path::new("docs").exists() {
std::fs::create_dir("docs")?;
std::fs::write("docs/index.html", "project docs")?;
}
crate::run_shell_command_static("git config --global init.defaultBranch main")?;
crate::run_shell_command_static("git init")?;
crate::run_shell_command_static("git add .")?;
crate::run_shell_command(&format!(r#"git commit -m "{message}""#))?;
crate::run_shell_command_static("git branch -M main")?;
Ok(())
}