use std::path::{Path, PathBuf};
use std::process::Command;
use std::{fmt, fs};
use crate::choices::{Choices, branch_for, project_path, remove_section, replace_line};
const TEMPLATE_URL: &str = "https://github.com/Heryk13/bevy-starter.git";
const FIRST_COMMIT_MESSAGE: &str = "build: start from bevy-starter";
const BRANCHES_HEADING: &str = "## Branches";
pub(crate) enum ScaffoldError {
FolderNotEmpty(PathBuf),
CloneFailed(String),
RemoveFailed(String),
TemplateChanged(PathBuf),
EditFailed(String),
GitFailed(String),
}
impl fmt::Display for ScaffoldError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScaffoldError::FolderNotEmpty(path) => {
write!(
f,
"{} already exists and is not empty. Choose another name or an empty folder.",
path.display()
)
}
ScaffoldError::CloneFailed(message) => {
write!(
f,
"Failed to clone the template: {}. Check your internet connection, or wait a \
moment, and try again.",
message
)
}
ScaffoldError::RemoveFailed(message) => {
write!(
f,
"Could not remove a file the template does not need: {}. Close any program \
using the folder, such as an editor or the file explorer, and try again.",
message
)
}
ScaffoldError::TemplateChanged(path) => {
write!(
f,
"{} is not what this create-bevy-starter expects: the template changed and the \
CLI did not follow. Update create-bevy-starter, or report it to its author.",
path.display()
)
}
ScaffoldError::EditFailed(message) => {
write!(
f,
"Could not edit a file of the new game: {}. Close any program using the \
folder, such as an editor or the file explorer, and try again.",
message
)
}
ScaffoldError::GitFailed(message) => {
write!(
f,
"Could not start the game's git history: {}. If git asks who you are, run \
`git config --global user.name \"Your Name\"` and `git config --global \
user.email you@example.com`, then try again.",
message
)
}
}
}
}
pub(crate) fn is_git_installed() -> bool {
let output = Command::new("git").arg("--version").output();
if let Ok(output) = output
&& output.status.success()
{
return true;
}
false
}
fn is_folder_free(path: &Path) -> bool {
!path.exists() || fs::read_dir(path).is_ok_and(|mut entries| entries.next().is_none())
}
pub(crate) fn create_game(choices: &Choices) -> Result<(), ScaffoldError> {
let path = project_path(&choices.folder, &choices.name);
if !is_folder_free(&path) {
return Err(ScaffoldError::FolderNotEmpty(path));
}
if let Err(error) = build_game(&path, choices) {
let _ = fs::remove_dir_all(&path);
return Err(error);
}
Ok(())
}
fn build_game(path: &Path, choices: &Choices) -> Result<(), ScaffoldError> {
let branch = branch_for(&choices.kind);
let output = Command::new("git")
.args(["clone", "--depth", "1", "--branch", branch, TEMPLATE_URL])
.arg(path)
.output()
.map_err(|error| ScaffoldError::CloneFailed(error.to_string()))?;
if !output.status.success() {
return Err(ScaffoldError::CloneFailed(
String::from_utf8_lossy(&output.stderr).trim().to_string(),
));
}
let git_dir = path.join(".git");
fs::remove_dir_all(git_dir).map_err(|error| ScaffoldError::RemoveFailed(error.to_string()))?;
edit_file(&path.join("Cargo.toml"), |text| {
replace_line(text, "name = ", &format!("name = \"{}\"", choices.name))
})?;
edit_file(&path.join("justfile"), |text| {
replace_line(text, "game := ", &format!("game := \"{}\"", choices.name))
})?;
edit_file(&path.join("src/main.rs"), |text| {
replace_line(
text,
"pub(crate) const GAME_TITLE",
&format!("pub(crate) const GAME_TITLE: &str = \"{}\";", choices.title),
)
})?;
let specs_dir = path.join("docs/specs");
fs::remove_dir_all(&specs_dir)
.map_err(|error| ScaffoldError::RemoveFailed(error.to_string()))?;
fs::create_dir(&specs_dir).map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
fs::write(specs_dir.join(".gitkeep"), "")
.map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
for file in ["README.md", "CONTRIBUTING.md"] {
edit_file(&path.join(file), |text| {
remove_section(text, BRANCHES_HEADING)
})?;
}
remove_tools(path)?;
run_git(path, &["init"])?;
run_git(path, &["add", "--all"])?;
run_git(path, &["commit", "--message", FIRST_COMMIT_MESSAGE])?;
Ok(())
}
fn edit_file(file: &Path, edit: impl FnOnce(&str) -> Option<String>) -> Result<(), ScaffoldError> {
let text =
fs::read_to_string(file).map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
let new_text = edit(&text).ok_or_else(|| ScaffoldError::TemplateChanged(file.to_path_buf()))?;
fs::write(file, new_text).map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
Ok(())
}
fn remove_tools(path: &Path) -> Result<(), ScaffoldError> {
let tools_dir = path.join("tools");
if !tools_dir.exists() {
return Ok(());
}
fs::remove_dir_all(tools_dir).map_err(|error| ScaffoldError::RemoveFailed(error.to_string()))
}
fn run_git(path: &Path, args: &[&str]) -> Result<(), ScaffoldError> {
let output = Command::new("git")
.args(args)
.current_dir(path)
.output()
.map_err(|error| ScaffoldError::GitFailed(error.to_string()))?;
if !output.status.success() {
return Err(ScaffoldError::GitFailed(
String::from_utf8_lossy(&output.stderr).trim().to_string(),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn fresh_test_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(name);
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("the test folder can be created");
dir
}
#[test]
fn a_game_keeps_no_tools_folder() {
let game = fresh_test_dir("create-bevy-starter-tools-removed");
fs::create_dir(game.join("tools")).expect("the tools folder can be created");
fs::write(game.join("tools/sync.sh"), "").expect("a tool can be written");
assert!(remove_tools(&game).is_ok());
assert!(!game.join("tools").exists());
}
#[test]
fn a_template_without_tools_still_makes_a_game() {
let game = fresh_test_dir("create-bevy-starter-no-tools");
assert!(remove_tools(&game).is_ok());
assert!(game.exists());
}
}