use std::path::{Path, PathBuf};
use std::process::Command;
use std::{fmt, fs};
use crate::choices::{
Choices, Removal, branch_for, project_path, removals_for, remove_marked_lines, 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)?;
let removals = removals_for(choices);
for removal in &removals {
remove_left_out(path, removal)?;
}
if !removals.is_empty() {
tidy_after_removals(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 remove_left_out(path: &Path, removal: &Removal) -> Result<(), ScaffoldError> {
let mut found = false;
for file in removal.files {
let file = path.join(file);
let removed = if file.is_dir() {
fs::remove_dir_all(&file)
} else if file.is_file() {
fs::remove_file(&file)
} else {
continue;
};
removed.map_err(|error| ScaffoldError::RemoveFailed(error.to_string()))?;
found = true;
}
if !found {
let first = removal.files.first().copied().unwrap_or_default();
return Err(ScaffoldError::TemplateChanged(path.join(first)));
}
let mut sources = vec![path.join("Cargo.toml")];
collect_rust_files(&path.join("src"), &mut sources)?;
for source in sources {
let text = fs::read_to_string(&source)
.map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
let (new_text, dropped) = remove_marked_lines(&text, removal.marker);
if dropped {
fs::write(&source, new_text)
.map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
}
}
Ok(())
}
fn collect_rust_files(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), ScaffoldError> {
let entries =
fs::read_dir(dir).map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
for entry in entries {
let entry = entry.map_err(|error| ScaffoldError::EditFailed(error.to_string()))?;
let entry_path = entry.path();
if entry_path.is_dir() {
collect_rust_files(&entry_path, files)?;
} else if entry_path
.extension()
.is_some_and(|extension| extension == "rs")
{
files.push(entry_path);
}
}
Ok(())
}
fn tidy_after_removals(path: &Path) {
for args in [&["fmt"][..], &["metadata", "--format-version", "1"]] {
let _ = Command::new("cargo").args(args).current_dir(path).output();
}
}
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());
}
#[test]
fn what_is_left_out_goes_with_its_lines() {
let game = fresh_test_dir("create-bevy-starter-left-out");
fs::create_dir_all(game.join("src/multiplayer")).expect("a folder can be created");
fs::write(game.join("src/multiplayer.rs"), "").expect("a file can be written");
fs::write(
game.join("src/main.rs"),
"mod multiplayer; // multiplayer\nmod ui;\n",
)
.expect("a file can be written");
fs::write(
game.join("Cargo.toml"),
"[dependencies]\nlightyear = \"0.31\" # multiplayer\n",
)
.expect("a file can be written");
assert!(remove_left_out(&game, &crate::choices::MULTIPLAYER).is_ok());
assert!(!game.join("src/multiplayer.rs").exists());
assert!(!game.join("src/multiplayer").exists());
let main = fs::read_to_string(game.join("src/main.rs")).expect("main.rs is there");
assert_eq!(main, "mod ui;\n");
let manifest = fs::read_to_string(game.join("Cargo.toml")).expect("Cargo.toml is there");
assert_eq!(manifest, "[dependencies]\n");
}
#[test]
fn a_removal_whose_files_moved_is_refused() {
let game = fresh_test_dir("create-bevy-starter-moved");
fs::create_dir(game.join("src")).expect("a folder can be created");
assert!(matches!(
remove_left_out(&game, &crate::choices::MULTIPLAYER),
Err(ScaffoldError::TemplateChanged(_))
));
}
fn every_combination(folder: &Path) -> Vec<Choices> {
use crate::choices::{Camera, Kind, Player3d};
let mut kinds = vec![
Kind::Empty,
Kind::ThreeD(None),
Kind::TwoD(false),
Kind::TwoD(true),
];
let camera_sets = [
vec![Camera::FirstPerson],
vec![Camera::ThirdPerson],
vec![Camera::FirstPerson, Camera::ThirdPerson],
];
for cameras in camera_sets {
for split_screen in [false, true] {
kinds.push(Kind::ThreeD(Some(Player3d {
cameras: cameras.clone(),
split_screen,
})));
}
}
let mut every = Vec::new();
for kind in kinds {
for multiplayer in [false, true] {
let name = format!("combo-{}", every.len() + 1);
every.push(Choices {
title: name.clone(),
name,
folder: folder.to_path_buf(),
kind: kind.clone(),
multiplayer,
});
}
}
every
}
#[test]
#[ignore = "clones the template and runs each game's `just check`, for an hour or so: \
`just check-combos`"]
fn every_combination_passes_the_games_own_check() {
let folder = fresh_test_dir("create-bevy-starter-combos");
let target = std::env::temp_dir().join("create-bevy-starter-combos-target");
let mut failed = Vec::new();
for choices in every_combination(&folder) {
let label = format!(
"{}: {:?}, multiplayer {}",
choices.name, choices.kind, choices.multiplayer
);
println!("==== {label}");
if let Err(error) = create_game(&choices) {
failed.push(format!("{label}: {error}"));
continue;
}
let checked = Command::new("just")
.arg("check")
.current_dir(project_path(&choices.folder, &choices.name))
.env("CARGO_TARGET_DIR", &target)
.status();
if !checked.is_ok_and(|status| status.success()) {
failed.push(label);
}
}
assert!(
failed.is_empty(),
"these games fail their check: {failed:#?}"
);
}
}