Delay inside_vcs_repo check until Git initialization

This commit is contained in:
mo8it 2026-03-14 18:22:27 +01:00
parent 802dcfc987
commit a28b9eda84

View File

@ -5,7 +5,7 @@ use crossterm::{
}; };
use serde::Deserialize; use serde::Deserialize;
use std::{ use std::{
env::set_current_dir, env::{current_dir, set_current_dir},
fs::{self, create_dir}, fs::{self, create_dir},
io::{self, Write}, io::{self, Write},
path::Path, path::Path,
@ -29,21 +29,6 @@ pub fn init() -> Result<()> {
bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR); bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR);
} }
let is_inside_vcs_repository = 'detect_repo: {
let Ok(mut dir) = std::env::current_dir() else {
break 'detect_repo false;
};
loop {
if dir.join(".git").exists() || dir.join(".jj").exists() {
break 'detect_repo true;
}
match dir.parent() {
Some(parent) => dir = parent.into(),
None => break 'detect_repo false,
}
}
};
let locate_project_output = Command::new("cargo") let locate_project_output = Command::new("cargo")
.arg("locate-project") .arg("locate-project")
.arg("-q") .arg("-q")
@ -74,7 +59,7 @@ pub fn init() -> Result<()> {
} }
let mut stdout = io::stdout().lock(); let mut stdout = io::stdout().lock();
let mut init_git = !is_inside_vcs_repository; let mut init_git = true;
if locate_project_output.status.success() { if locate_project_output.status.success() {
if Path::new("exercises").exists() && Path::new("solutions").exists() { if Path::new("exercises").exists() && Path::new("solutions").exists() {
@ -184,14 +169,27 @@ pub fn init() -> Result<()> {
fs::write(".vscode/extensions.json", VS_CODE_EXTENSIONS_JSON) fs::write(".vscode/extensions.json", VS_CODE_EXTENSIONS_JSON)
.context("Failed to create the file `rustlings/.vscode/extensions.json`")?; .context("Failed to create the file `rustlings/.vscode/extensions.json`")?;
if init_git { if init_git && let Ok(dir) = current_dir() {
// Ignore any Git error because Git initialization is not required. let mut dir = dir.as_path();
let _ = Command::new("git")
.arg("init") loop {
.stdin(Stdio::null()) if dir.join(".git").exists() || dir.join(".jj").exists() {
.stdout(Stdio::null()) break;
.stderr(Stdio::null()) }
.status();
if let Some(parent) = dir.parent() {
dir = parent;
} else {
// Ignore any Git error because Git initialization is not required.
let _ = Command::new("git")
.arg("init")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
break;
}
}
} }
stdout.queue(SetForegroundColor(Color::Green))?; stdout.queue(SetForegroundColor(Color::Green))?;