Skip to content

Commit

Permalink
Warn when a user creates a new project inside a exisiting git repo
Browse files Browse the repository at this point in the history
  • Loading branch information
Assaf Sapir committed Mar 8, 2024
1 parent c3597ab commit 43f2014
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions loco-cli/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ fn main() -> eyre::Result<()> {

let res = match cli.command {
Commands::New { path } => {
if git::is_a_git_repo(&path).unwrap_or(false) {
prompt::warn_if_in_git_repo()?;
}

let app = prompt::app_name()?;

let args = generate::ArgsPlaceholder {
Expand Down
17 changes: 17 additions & 0 deletions loco-cli/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,23 @@ fn git_exists() -> bool {
}
}

pub fn is_a_git_repo(destination_path: &PathBuf) -> eyre::Result<bool> {
let destination_path = destination_path.canonicalize()?;
match Command::new("git")
.arg("-C")
.arg(destination_path)
.arg("rev-parse")
.arg("--is-inside-work-tree")
.output()
{
Ok(output) => Ok(output.status.success()),
Err(err) => {
tracing::debug!(error = err.to_string(), "git not found");
Ok(false)
}
}
}

#[cfg(feature = "git2")]
fn clone_repo_with_git2(temp_clone_dir: &Path) -> eyre::Result<()> {
let mut fetch_options = git2::FetchOptions::new();
Expand Down
30 changes: 30 additions & 0 deletions loco-cli/src/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,36 @@ pub fn template_selection(
}
}

/// Warn the user if they are inside a git repository.
///
/// If the `ALLOW_IN_GIT_REPO` environment variable is set, this test will be skipped.
/// If the environment variable is not set, the function will warn the user if they are inside a git
/// and will let them cancel the operation or continue.
///
/// # Errors
/// when could not prompt the question, or when the user choose not to continue.
pub fn warn_if_in_git_repo() -> eyre::Result<()> {
if let Ok(_) = env::var("ALLOW_IN_GIT_REPO") {
return Ok(());
}

let question = requestty::Question::confirm("allow_git_repo")
.message("❯ You are inside a git repository. Do you wish to continue?")
.default(false)
.build();

let res = requestty::prompt_one(question)?;
let answer = res
.as_bool()
.ok_or_else(|| eyre::eyre!("allow_git_repo is empty"))?;

if answer {
Ok(())
} else {
Err(eyre::eyre!("user choose not to continue"))
}
}

/// Validates the provided application name for compatibility with Rust library conventions.
///
/// Rust library names should adhere to specific conventions and avoid special characters to
Expand Down

0 comments on commit 43f2014

Please sign in to comment.