use colored::Colorize;
use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::process::Command;
use crate::models::{EnvironmentState, ProjectStack};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fix {
pub id: String,
pub name: String,
pub description: String,
pub command: FixCommand,
pub reversible: bool,
pub requires_approval: bool,
}
impl Fix {
fn new(
id: impl Into<String>,
name: impl Into<String>,
description: impl Into<String>,
command: FixCommand,
reversible: bool,
requires_approval: bool,
) -> Self {
Self {
id: id.into(),
name: name.into(),
description: description.into(),
command,
reversible,
requires_approval,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FixCommand {
CopyFile { src: String, dst: String },
RunCommand { cmd: String, args: Vec<String> },
CreateFile { path: String, content: String },
KillProcess { pid: u32 },
DeleteFile { path: String },
}
const PERMISSION_HINT: &str = "\n Tip: this looks like a permission error — retry from an \
elevated terminal (sudo on macOS/Linux, \"Run as administrator\" on \
Windows).";
pub const DEFAULT_GITIGNORE: &str = "node_modules/\ntarget/\n__pycache__/\n.venv/\nvenv/\n\
.env\n.env.local\n.idea/\n.vscode/\n*.swp\n.DS_Store\n";
pub const DEFAULT_EDITORCONFIG: &str = "root = true\n\n\
[*]\ncharset = utf-8\nend_of_line = lf\nindent_style = space\nindent_size = 2\n\
insert_final_newline = true\ntrim_trailing_whitespace = true\n";
pub fn copy_env_from_example(src: &str, dst: &str) -> Option<Fix> {
let src = src.to_string();
let dst = dst.to_string();
Some(Fix::new(
"copy-env-from-example",
format!("Copy {src} to {dst}"),
format!("Copies the {src} template into {dst} so the app can read its configuration."),
FixCommand::CopyFile { src, dst },
true,
true,
))
}
pub fn kill_ghost_process(port: u16, pid: u32) -> Fix {
Fix::new(
format!("kill-ghost-{pid}"),
format!("Kill ghost process {pid}"),
format!(
"A leftover process (PID {pid}) is still holding port {port}. Killing it frees the \
port for your app."
),
FixCommand::KillProcess { pid },
false,
true,
)
}
pub fn install_fix_for_stack(stack: &ProjectStack) -> Option<Fix> {
let (cmd, args, display) = match stack {
ProjectStack::Node {
package_manager, ..
} => {
let pm = match package_manager.as_str() {
"yarn" => "yarn",
"pnpm" => "pnpm",
_ => "npm",
};
(pm, vec!["install".to_string()], package_manager.as_str())
}
ProjectStack::Python { .. } => (
"pip",
vec![
"install".to_string(),
"-r".to_string(),
"requirements.txt".to_string(),
],
"pip install -r requirements.txt",
),
ProjectStack::Rust { .. } => ("cargo", vec!["build".to_string()], "cargo build"),
ProjectStack::Go { .. } => (
"go",
vec!["mod".to_string(), "download".to_string()],
"go mod download",
),
ProjectStack::Java { .. } => ("mvn", vec!["install".to_string()], "mvn install"),
ProjectStack::Docker | ProjectStack::Unknown => return None,
};
Some(Fix::new(
format!("install-dependencies-{cmd}"),
format!("{display} for {}", stack.label()),
format!("Restores missing packages with `{display}`, so imports and builds resolve again."),
FixCommand::RunCommand {
cmd: cmd.to_string(),
args,
},
false,
true,
))
}
pub fn missing_config_files(repo_path: &str) -> Vec<Fix> {
let root = Path::new(repo_path);
let mut fixes = Vec::new();
if !root.join(".gitignore").is_file() {
fixes.push(Fix::new(
"create-gitignore",
"Create .gitignore",
"Adds a starter .gitignore so build artifacts and secrets stay out of version control.",
FixCommand::CreateFile {
path: ".gitignore".to_string(),
content: DEFAULT_GITIGNORE.to_string(),
},
true,
false,
));
}
if !root.join(".editorconfig").is_file() {
fixes.push(Fix::new(
"create-editorconfig",
"Create .editorconfig",
"Adds a starter .editorconfig to keep formatting consistent across editors.",
FixCommand::CreateFile {
path: ".editorconfig".to_string(),
content: DEFAULT_EDITORCONFIG.to_string(),
},
true,
false,
));
}
fixes
}
pub fn recommended_fixes(state: &EnvironmentState, repo_path: &str) -> Vec<Fix> {
let mut fixes = Vec::new();
if state.env_example_exists && !state.env_file_exists {
if let Some(fix) = copy_env_from_example(".env.example", ".env") {
fixes.push(fix);
}
}
for (port, pid) in &state.blocked_ports {
fixes.push(kill_ghost_process(*port, *pid));
}
if !state.dependencies_healthy {
if let Some(fix) = install_fix_for_stack(&state.detected_stack) {
fixes.push(fix);
}
}
fixes.extend(missing_config_files(repo_path));
fixes
}
impl Fix {
pub fn preview_fix(&self, repo_path: &str) -> String {
preview_fix(self, repo_path)
}
}
pub fn preview_fix(fix: &Fix, repo_path: &str) -> String {
let root = Path::new(repo_path);
let state = |rel: &str| {
if root.join(rel).exists() {
"present"
} else {
"missing"
}
};
match &fix.command {
FixCommand::CopyFile { src, dst } => format!(
"Before: {src} is {}, {dst} is {}\nAfter: copies {src} → {dst}",
state(src),
state(dst)
),
FixCommand::CreateFile { path, .. } => {
format!(
"Before: {path} is {}\nAfter: creates {path} with starter settings",
state(path)
)
}
FixCommand::DeleteFile { path } => {
format!("Before: {path} is {}\nAfter: deletes {path}", state(path))
}
FixCommand::KillProcess { pid } => format!(
"Before: process {pid} is {}\nAfter: terminates process {pid}",
if process_exists(*pid) {
"running"
} else {
"not running"
}
),
FixCommand::RunCommand { cmd, args } => format!(
"Before: dependency state unknown\nAfter: runs `{} {}`",
cmd,
args.join(" ")
),
}
}
pub async fn execute_fix(fix: &Fix, repo_path: &str) -> Result<String, String> {
execute_fix_with(fix, repo_path, false).await
}
pub async fn execute_fix_with(
fix: &Fix,
repo_path: &str,
allow_overwrite: bool,
) -> Result<String, String> {
validate_fix(fix)?;
let preview = preview_fix(fix, repo_path);
let result = match &fix.command {
FixCommand::CopyFile { src, dst } => run_copy(fix, repo_path, src, dst, allow_overwrite),
FixCommand::CreateFile { path, content } => {
run_create(fix, repo_path, path, content, allow_overwrite)
}
FixCommand::DeleteFile { path } => run_delete(fix, repo_path, path),
FixCommand::KillProcess { pid } => run_kill(fix, *pid).await,
FixCommand::RunCommand { cmd, args } => run_command(fix, cmd, args).await,
};
result.map(|log| format!("{preview}\n{log}"))
}
fn validate_fix(fix: &Fix) -> Result<(), String> {
match &fix.command {
FixCommand::CopyFile { src, dst } => {
if src.trim().is_empty() || dst.trim().is_empty() {
Err(format!(
"✗ {} — source and destination paths must not be empty.",
fix.name
))
} else {
Ok(())
}
}
FixCommand::CreateFile { path, .. } | FixCommand::DeleteFile { path } => {
if path.trim().is_empty() {
Err(format!("✗ {} — file path must not be empty.", fix.name))
} else {
Ok(())
}
}
FixCommand::KillProcess { pid } => {
if *pid == 0 {
Err(format!("✗ {} — PID 0 is never a real process.", fix.name))
} else {
Ok(())
}
}
FixCommand::RunCommand { cmd, .. } => {
if cmd.trim().is_empty() {
Err(format!("✗ {} — command must not be empty.", fix.name))
} else {
Ok(())
}
}
}
}
fn run_copy(
fix: &Fix,
repo_path: &str,
src: &str,
dst: &str,
allow_overwrite: bool,
) -> Result<String, String> {
let root = Path::new(repo_path);
let src_path = root.join(src);
let dst_path = root.join(dst);
if !src_path.is_file() {
return Err(format!(
"✗ {} — source {src} does not exist in {repo_path}.",
fix.name
));
}
let backup = read_opt(&dst_path);
let existed = backup.is_some();
if existed && !allow_overwrite {
return Err(format!(
"✗ {} — {dst} already exists. No changes were made; ask the user, then re-run \
with overwrite enabled.",
fix.name
));
}
if let Err(err) = fs::copy(&src_path, &dst_path) {
restore(&dst_path, &backup, !existed);
return Err(io_fail(&fix.name, &err, &format!("copy {src} → {dst}")));
}
if let Err(why) = verify_copy(&src_path, &dst_path) {
restore(&dst_path, &backup, !existed);
return Err(format!(
"✗ {} — verification failed after the copy ({why}); the previous state was restored.",
fix.name
));
}
Ok(format!(
"✓ {} — copied {src} → {dst} ({} bytes)\n ✓ Verified: {dst} matches {src}",
fix.name,
file_size(&dst_path)
))
}
fn run_create(
fix: &Fix,
repo_path: &str,
path: &str,
content: &str,
allow_overwrite: bool,
) -> Result<String, String> {
let dst_path = Path::new(repo_path).join(path);
let backup = read_opt(&dst_path);
let existed = backup.is_some();
if existed && !allow_overwrite {
return Err(format!(
"✗ {} — {path} already exists. No changes were made; ask the user, then re-run \
with overwrite enabled.",
fix.name
));
}
if let Err(err) = fs::write(&dst_path, content) {
restore(&dst_path, &backup, !existed);
return Err(io_fail(&fix.name, &err, &format!("create {path}")));
}
if let Err(why) = verify_written(&dst_path, content) {
restore(&dst_path, &backup, !existed);
return Err(format!(
"✗ {} — verification failed after writing ({why}); the previous state was restored.",
fix.name
));
}
Ok(format!(
"✓ {} — created {path} ({} bytes)\n ✓ Verified: {path} contains the expected content",
fix.name,
file_size(&dst_path)
))
}
fn run_delete(fix: &Fix, repo_path: &str, path: &str) -> Result<String, String> {
let dst_path = Path::new(repo_path).join(path);
if !dst_path.exists() {
return Err(format!(
"✗ {} — nothing to delete: {path} does not exist.",
fix.name
));
}
let backup = read_opt(&dst_path);
if let Err(err) = fs::remove_file(&dst_path) {
return Err(io_fail(&fix.name, &err, &format!("delete {path}")));
}
if let Err(why) = verify_deleted(&dst_path) {
restore(&dst_path, &backup, false);
return Err(format!(
"✗ {} — verification failed after deleting ({why}); the file was restored.",
fix.name
));
}
Ok(format!(
"✓ {} — deleted {path}\n ✓ Verified: {path} no longer exists",
fix.name
))
}
async fn run_kill(fix: &Fix, pid: u32) -> Result<String, String> {
if !process_exists(pid) {
return Ok(format!(
"✓ {} — skipped: process {pid} is not running.",
fix.name
));
}
let (tool, args) = kill_args(pid);
let output = match tokio::process::Command::new(tool).args(args).output().await {
Ok(output) => output,
Err(err) => return Err(describe_spawn_error(&fix.name, tool, &err)),
};
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
return Err(format!(
"✗ {} — could not terminate process {pid}:\n {} {}",
fix.name,
stderr.trim(),
permission_hint(&stderr)
));
}
let mut still_running = true;
for _ in 0..4 {
if !process_exists(pid) {
still_running = false;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
if still_running {
return Err(format!(
"✗ {} — process {pid} is still running after `{}` was issued.{}",
fix.name,
kill_display(pid),
PERMISSION_HINT
));
}
Ok(format!(
"✓ {} — terminated process {pid} via `{}`\n ✓ Verified: {pid} is no longer running",
fix.name,
kill_display(pid)
))
}
fn kill_args(pid: u32) -> (&'static str, Vec<String>) {
if cfg!(windows) {
(
"taskkill",
vec!["/PID".to_string(), pid.to_string(), "/F".to_string()],
)
} else {
("kill", vec![pid.to_string()])
}
}
fn kill_display(pid: u32) -> String {
if cfg!(windows) {
format!("taskkill /PID {pid} /F")
} else {
format!("kill {pid}")
}
}
fn resolve_executable(cmd: &str) -> String {
if cfg!(windows) && matches!(cmd, "npm" | "yarn" | "pnpm" | "npx") {
format!("{cmd}.cmd")
} else {
cmd.to_string()
}
}
#[cfg(target_os = "windows")]
pub fn process_exists(pid: u32) -> bool {
let filter = format!("PID eq {pid}");
match Command::new("tasklist")
.args(["/FI", &filter, "/NH"])
.output()
{
Ok(output) => {
let text = String::from_utf8_lossy(&output.stdout).to_lowercase();
output.status.success() && !text.contains("no tasks") && text.contains(&pid.to_string())
}
Err(_) => false,
}
}
#[cfg(not(target_os = "windows"))]
pub fn process_exists(pid: u32) -> bool {
Command::new("kill")
.args(["-0", &pid.to_string()])
.status()
.map(|status| status.success())
.unwrap_or(false)
}
async fn run_command(fix: &Fix, cmd: &str, args: &[String]) -> Result<String, String> {
let display = format!("{} {}", cmd, args.join(" "));
let exec_cmd = resolve_executable(cmd);
let output = match tokio::process::Command::new(&exec_cmd).args(args).output().await {
Ok(output) => output,
Err(err) => return Err(describe_spawn_error(&fix.name, cmd, &err)),
};
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let mut log = format!("✓ {} — ran `{display}`", fix.name);
if !stdout.is_empty() {
log.push_str(&format!("\n stdout: {stdout}"));
}
if !stderr.is_empty() {
log.push_str(&format!("\n stderr: {stderr}"));
}
if !output.status.success() {
let code = output
.status
.code()
.map(|c| c.to_string())
.unwrap_or_else(|| "?".to_string());
let hint = permission_hint(&stderr);
return Err(format!(
"✗ {} — `{display}` failed (exit {code})\n {}{}",
fix.name,
if stderr.is_empty() { stdout } else { stderr },
hint
));
}
log.push_str(&format!("\n ✓ Verified: `{display}` exited successfully"));
Ok(log)
}
pub fn verify_copy(src: &Path, dst: &Path) -> Result<(), String> {
if !dst.is_file() {
return Err(format!("{} was not created", dst.display()));
}
match (fs::read(src), fs::read(dst)) {
(Ok(a), Ok(b)) if a == b => Ok(()),
_ => Err(format!(
"{} content differs from {}",
dst.display(),
src.display()
)),
}
}
pub fn verify_written(path: &Path, expected: &str) -> Result<(), String> {
if !path.is_file() {
return Err(format!("{} was not created", path.display()));
}
let actual = fs::read_to_string(path)
.map_err(|err| format!("{} could not be read: {err}", path.display()))?;
if actual == expected {
Ok(())
} else {
Err(format!(
"{} content does not match the expected template",
path.display()
))
}
}
pub fn verify_deleted(path: &Path) -> Result<(), String> {
if path.exists() {
Err(format!("{} still exists", path.display()))
} else {
Ok(())
}
}
pub fn verify_process_gone(pid: u32) -> Result<(), String> {
if process_exists(pid) {
Err(format!("process {pid} is still running"))
} else {
Ok(())
}
}
fn describe_spawn_error(action: &str, cmd: &str, err: &std::io::Error) -> String {
match err.kind() {
ErrorKind::NotFound => format!(
"✗ {action} — `{cmd}` is not installed (or not on PATH). Install it first, then \
restart your terminal before retrying."
),
ErrorKind::PermissionDenied => {
format!("✗ {action} — permission denied starting `{cmd}`.{PERMISSION_HINT}")
}
_ => format!("✗ {action} — could not start `{cmd}`: {err}"),
}
}
fn io_fail(action: &str, err: &std::io::Error, context: &str) -> String {
match err.kind() {
ErrorKind::PermissionDenied => {
format!("✗ {action} — permission denied while trying to {context}.{PERMISSION_HINT}")
}
_ => format!("✗ {action} — could not {context}: {err}"),
}
}
fn permission_hint(text: &str) -> String {
let lower = text.to_lowercase();
if lower.contains("denied")
|| lower.contains("permission")
|| lower.contains("access is denied")
|| lower.contains("sudo")
{
PERMISSION_HINT.to_string()
} else {
String::new()
}
}
fn file_size(path: &Path) -> u64 {
fs::metadata(path).map(|m| m.len()).unwrap_or(0)
}
fn read_opt(path: &Path) -> Option<Vec<u8>> {
fs::read(path).ok()
}
fn restore(path: &Path, backup: &Option<Vec<u8>>, created_fresh: bool) {
match backup {
Some(bytes) => {
let _ = fs::write(path, bytes);
}
None if created_fresh => {
let _ = fs::remove_file(path);
}
None => {}
}
}
pub async fn run_fix(all: bool) {
println!("{}", "=== Auto-Fix ===".bold().cyan());
println!();
let state = crate::modules::diagnostics::build_snapshot(".");
let fixes = recommended_fixes(&state, ".");
if fixes.is_empty() {
println!(
" {} No issues detected — nothing to fix.",
"✓".green().bold()
);
println!();
println!("{}", "Fix scan complete!".green().bold());
return;
}
println!(
" Detected {} fixable issue{}.",
fixes.len(),
if fixes.len() == 1 { "" } else { "s" }
);
for (i, fix) in fixes.iter().enumerate() {
let dot = if fix.requires_approval {
"•".yellow()
} else {
"•".green()
};
let tag = if fix.requires_approval {
"approval required"
} else {
"safe"
};
println!(" {dot} {}. {} — {}", i + 1, fix.name, tag.dimmed());
}
println!();
let mut approved: Vec<&Fix> = Vec::new();
if all {
let message = format!("Apply all {} fixes automatically?", fixes.len());
if crate::modules::interactive_prompt::prompt_user_confirmation(&message, true) {
approved = fixes.iter().collect();
} else {
println!("{}", " Auto-fix cancelled.".yellow().bold());
println!();
println!("{}", "Fix scan complete!".green().bold());
return;
}
} else {
for fix in &fixes {
if !fix.requires_approval {
approved.push(fix);
continue;
}
let message = format!("{} — {}?", fix.name, fix.description);
if crate::modules::interactive_prompt::prompt_user_confirmation(&message, true) {
approved.push(fix);
} else {
println!(" {} skipping {}.", "↷".dimmed(), fix.name.dimmed());
}
}
}
if approved.is_empty() {
println!(
" {} No fixes were approved — nothing changed.",
"Note:".yellow()
);
println!();
println!("{}", "Fix scan complete!".green().bold());
return;
}
let mut succeeded = 0usize;
let mut failed = Vec::new();
for fix in approved {
println!(" {}", preview_fix(fix, "."));
match execute_fix_with(fix, ".", true).await {
Ok(log) => {
println!(" {log}");
succeeded += 1;
}
Err(err) => {
println!(" {err}");
failed.push((fix.name.clone(), err));
}
}
}
println!();
println!(
" {} {} fix{}, {} failed.",
if failed.is_empty() {
"✓".green()
} else {
"âš ".yellow()
},
succeeded,
if succeeded == 1 { "" } else { "es" },
failed.len()
);
for (name, err) in &failed {
println!(" • {}: {}", name.yellow(), err);
}
println!();
println!("{}", "Fix scan complete!".green().bold());
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{EnvironmentState, ProjectStack};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_nanos();
let path = std::env::temp_dir().join(format!("limitless_fixes_{label}_{stamp}"));
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn path(&self) -> &Path {
&self.path
}
fn write(self, relative: &str, content: &str) -> Self {
let full = self.path.join(relative);
if let Some(parent) = full.parent() {
fs::create_dir_all(parent).expect("create parent dirs");
}
fs::write(full, content).expect("write fixture file");
self
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn sample_state() -> EnvironmentState {
EnvironmentState {
detected_stack: ProjectStack::Node {
version: "18.12.0".into(),
package_manager: "npm".into(),
},
runtime_version: Some("v18.12.0".into()),
env_file_exists: false,
env_example_exists: true,
dependencies_healthy: false,
blocked_ports: vec![(3000, 9921)],
diagnostics: Vec::new(),
health_score: crate::models::HealthScore::default(),
}
}
#[test]
fn copy_env_fix_is_reversible_and_approved() {
let fix = copy_env_from_example(".env.example", ".env").unwrap();
assert_eq!(fix.id, "copy-env-from-example");
assert!(fix.reversible);
assert!(fix.requires_approval);
assert!(matches!(
fix.command,
FixCommand::CopyFile { ref src, ref dst } if src == ".env.example" && dst == ".env"
));
}
#[test]
fn kill_ghost_targets_the_blocked_pid() {
let fix = kill_ghost_process(3000, 9921);
assert_eq!(fix.id, "kill-ghost-9921");
assert!(!fix.reversible);
assert!(fix.requires_approval);
assert!(matches!(fix.command, FixCommand::KillProcess { pid: 9921 }));
}
#[test]
fn install_fix_maps_each_stack() {
let node = install_fix_for_stack(&ProjectStack::Node {
version: "22.9.0".into(),
package_manager: "npm".into(),
})
.unwrap();
assert!(matches!(
node.command,
FixCommand::RunCommand { ref cmd, ref args } if cmd == "npm" && args == &["install"]
));
let python = install_fix_for_stack(&ProjectStack::Python {
version: ">=3.12".into(),
})
.unwrap();
assert!(matches!(
python.command,
FixCommand::RunCommand { ref args, .. } if args == &["install", "-r", "requirements.txt"]
));
let rust = install_fix_for_stack(&ProjectStack::Rust {
version: "1.98.0".into(),
})
.unwrap();
assert!(matches!(
rust.command,
FixCommand::RunCommand { ref cmd, .. } if cmd == "cargo"
));
assert!(install_fix_for_stack(&ProjectStack::Docker).is_none());
assert!(install_fix_for_stack(&ProjectStack::Unknown).is_none());
}
#[test]
fn missing_config_files_only_for_absent_files() {
let dir = TempDir::new("cfg_missing").write(".gitignore", "node_modules/\n");
let fixes = missing_config_files(dir.path().to_str().unwrap());
let names: Vec<&str> = fixes.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, vec!["Create .editorconfig"]);
}
#[test]
fn missing_config_files_creates_both_when_absent() {
let dir = TempDir::new("cfg_absent");
let fixes = missing_config_files(dir.path().to_str().unwrap());
assert_eq!(fixes.len(), 2);
assert_eq!(fixes[0].id, "create-gitignore");
assert_eq!(fixes[1].id, "create-editorconfig");
assert!(fixes.iter().all(|f| !f.requires_approval));
}
#[test]
fn recommended_fixes_order_includes_copy_kill_install_create() {
let dir = TempDir::new("rec");
let fixes = recommended_fixes(&sample_state(), dir.path().to_str().unwrap());
let ids: Vec<&str> = fixes.iter().map(|f| f.id.as_str()).collect();
assert_eq!(ids[0], "copy-env-from-example");
assert_eq!(ids[1], "kill-ghost-9921");
assert_eq!(ids[2], "install-dependencies-npm");
assert!(ids.contains(&"create-gitignore"));
assert!(ids.contains(&"create-editorconfig"));
}
#[test]
fn copy_fix_absent_when_no_template_or_env_present() {
let mut state = sample_state();
state.env_example_exists = false;
let dir = TempDir::new("rec_no_copy");
let fixes = recommended_fixes(&state, dir.path().to_str().unwrap());
assert!(!fixes.iter().any(|f| f.id == "copy-env-from-example"));
}
#[test]
fn preview_describes_before_and_after() {
let dir = TempDir::new("preview").write(".env.example", "PORT=3000\n");
let fix = copy_env_from_example(".env.example", ".env").unwrap();
let preview = preview_fix(&fix, dir.path().to_str().unwrap());
assert!(preview.contains("Before: .env.example is present, .env is missing"));
assert!(preview.contains("After: copies .env.example → .env"));
}
#[tokio::test]
async fn copy_env_executes_and_verifies() {
let dir = TempDir::new("cop").write(".env.example", "API_KEY=abc\nPORT=3000\n");
let fix = copy_env_from_example(".env.example", ".env").unwrap();
let repo = dir.path().to_str().unwrap().to_string();
let log = execute_fix(&fix, &repo).await.unwrap();
assert!(log.contains("✓ Copy .env.example to .env"));
assert!(log.contains("Verified"));
let content = fs::read_to_string(dir.path().join(".env")).unwrap();
assert_eq!(content, "API_KEY=abc\nPORT=3000\n");
let err = execute_fix(&fix, &repo).await.unwrap_err();
assert!(err.contains(".env already exists"), "got: {err}");
let again = fs::read_to_string(dir.path().join(".env")).unwrap();
assert_eq!(again, "API_KEY=abc\nPORT=3000\n");
}
#[tokio::test]
async fn copy_env_refuses_overwrite_unless_approved() {
let dir = TempDir::new("overwrite")
.write(".env.example", "PORT=3000\n")
.write(".env", "PORT=9999\n");
let fix = copy_env_from_example(".env.example", ".env").unwrap();
let repo = dir.path().to_str().unwrap().to_string();
let err = execute_fix(&fix, &repo).await.unwrap_err();
assert!(err.contains("already exists"));
let ok = execute_fix_with(&fix, &repo, true).await.unwrap();
assert!(ok.contains("Verified"));
assert_eq!(
fs::read_to_string(dir.path().join(".env")).unwrap(),
"PORT=3000\n"
);
}
#[tokio::test]
async fn copy_env_missing_source_errors() {
let dir = TempDir::new("no_src");
let fix = copy_env_from_example(".env.example", ".env").unwrap();
let err = execute_fix(&fix, dir.path().to_str().unwrap())
.await
.unwrap_err();
assert!(err.contains("does not exist"));
}
#[tokio::test]
async fn create_file_writes_expected_content_and_verifies() {
let dir = TempDir::new("gitcreate");
let fix = Fix::new(
"create-gitignore",
"Create .gitignore",
"test",
FixCommand::CreateFile {
path: ".gitignore".to_string(),
content: DEFAULT_GITIGNORE.to_string(),
},
true,
false,
);
let repo = dir.path().to_str().unwrap().to_string();
let log = execute_fix(&fix, &repo).await.unwrap();
assert!(log.contains("created .gitignore"), "got: {log}");
assert!(log.contains("Verified"), "got: {log}");
assert_eq!(
fs::read_to_string(dir.path().join(".gitignore")).unwrap(),
DEFAULT_GITIGNORE
);
let err = execute_fix(&fix, &repo).await.unwrap_err();
assert!(err.contains(".gitignore already exists"));
let err2 = execute_fix_with(&fix, &repo, false).await.unwrap_err();
assert!(err2.contains("already exists"));
}
#[tokio::test]
async fn create_file_rolls_back_when_verification_fails() {
let dir = TempDir::new("roll").write(".env", "KEEP=me\n");
let fix = Fix::new(
"test-roll",
"Roll me",
"test",
FixCommand::CreateFile {
path: ".env".to_string(),
content: "NEW=value\n".to_string(),
},
true,
false,
);
let repo = dir.path().to_str().unwrap().to_string();
let _ = execute_fix(&fix, &repo).await.unwrap_err();
assert_eq!(
fs::read_to_string(dir.path().join(".env")).unwrap(),
"KEEP=me\n"
);
let log = execute_fix_with(&fix, &repo, true).await.unwrap();
assert!(log.contains("Verified"));
assert_eq!(
fs::read_to_string(dir.path().join(".env")).unwrap(),
"NEW=value\n"
);
}
#[tokio::test]
async fn delete_file_removes_and_verifies() {
let dir = TempDir::new("del").write("temp.log", "boom\n");
let fix = Fix::new(
"delete-temp",
"Delete temp.log",
"test",
FixCommand::DeleteFile {
path: "temp.log".to_string(),
},
false,
false,
);
let repo = dir.path().to_str().unwrap().to_string();
let log = execute_fix(&fix, &repo).await.unwrap();
assert!(log.contains("deleted temp.log"), "got: {log}");
assert!(log.contains("no longer exists"), "got: {log}");
assert!(!dir.path().join("temp.log").exists());
let err = execute_fix(&fix, &repo).await.unwrap_err();
assert!(err.contains("nothing to delete"));
}
#[tokio::test]
async fn delete_file_rolls_back_when_verification_fails() {
let dir = TempDir::new("del_roll");
let target = dir.path().join("dir_as_file");
fs::create_dir(&target).expect("place dir in the way");
fs::write(target.join("child"), "x").expect("child");
let fix = Fix::new(
"delete-dir",
"Delete",
"test",
FixCommand::DeleteFile {
path: "dir_as_file".to_string(),
},
true,
false,
);
let err = execute_fix(&fix, dir.path().to_str().unwrap())
.await
.unwrap_err();
assert!(err.contains("✗ Delete"), "got: {err}");
assert!(target.exists());
assert!(fs::read_to_string(target.join("child")).is_ok());
}
#[tokio::test]
async fn run_command_captures_output_and_verifies() {
let fix = Fix::new(
"test-run",
"Echo",
"test",
FixCommand::RunCommand {
cmd: "cmd".to_string(),
args: vec!["/C".into(), "echo".into(), "fix-ok".into()],
},
false,
false,
);
let log = execute_fix(&fix, ".").await.unwrap();
assert!(log.contains("ran `cmd /C echo fix-ok`"));
assert!(log.contains("fix-ok"));
assert!(log.contains("Verified"));
}
#[cfg(not(target_os = "windows"))]
#[tokio::test]
async fn run_command_captures_output_and_verifies_unix() {
let fix = Fix::new(
"test-run",
"Echo",
"test",
FixCommand::RunCommand {
cmd: "sh".to_string(),
args: vec!["-c".into(), "echo fix-ok".into()],
},
false,
false,
);
let log = execute_fix(&fix, ".").await.unwrap();
assert!(log.contains("fix-ok"));
}
#[tokio::test]
async fn run_command_not_found_suggests_install() {
let fix = Fix::new(
"test-run",
"Phantom",
"test",
FixCommand::RunCommand {
cmd: "definitely_not_an_installable_command_xyz".to_string(),
args: Vec::new(),
},
false,
false,
);
let err = execute_fix(&fix, ".").await.unwrap_err();
assert!(err.contains("not installed"), "got: {err}");
}
#[tokio::test]
async fn kill_missing_process_skips_gracefully() {
let fix = kill_ghost_process(3000, 999_999_999);
let log = execute_fix(&fix, ".").await.unwrap();
assert!(log.contains("not running"), "got: {log}");
}
#[tokio::test]
async fn kill_invalid_pid_zero_is_rejected() {
let fix = kill_ghost_process(3000, 0);
let err = execute_fix(&fix, ".").await.unwrap_err();
assert!(err.contains("PID 0"), "got: {err}");
}
#[test]
fn verify_helpers_report_truth() {
let dir = TempDir::new("verify")
.write("a.txt", "same\n")
.write("b.txt", "same\n");
assert!(verify_copy(&dir.path().join("a.txt"), &dir.path().join("b.txt")).is_ok());
assert!(verify_written(&dir.path().join("a.txt"), "same\n").is_ok());
assert!(verify_written(&dir.path().join("a.txt"), "other\n").is_err());
assert!(verify_deleted(&dir.path().join("gone.txt")).is_ok());
assert!(verify_deleted(&dir.path().join("a.txt")).is_err());
assert!(verify_process_gone(999_999_999).is_ok());
}
#[test]
fn default_templates_cover_common_stacks() {
assert!(DEFAULT_GITIGNORE.contains("node_modules"));
assert!(DEFAULT_GITIGNORE.contains(".env"));
assert!(DEFAULT_EDITORCONFIG.contains("root = true"));
}
#[tokio::test]
async fn test_copy_env_file() {
let dir = TempDir::new("named_copy").write(".env.example", "PORT=3000\nSECRET=x\n");
let fix = copy_env_from_example(".env.example", ".env").unwrap();
let repo = dir.path().to_str().unwrap().to_string();
let log = execute_fix(&fix, &repo).await.unwrap();
assert!(log.contains("Copy .env.example to .env"));
assert!(log.contains("Verified"));
assert_eq!(
fs::read_to_string(dir.path().join(".env")).unwrap(),
"PORT=3000\nSECRET=x\n"
);
let err = execute_fix(&fix, &repo).await.unwrap_err();
assert!(err.contains(".env already exists"), "got: {err}");
assert_eq!(
fs::read_to_string(dir.path().join(".env")).unwrap(),
"PORT=3000\nSECRET=x\n"
);
}
#[tokio::test]
async fn test_kill_process() {
let mut child = if cfg!(windows) {
std::process::Command::new("ping")
.args(["-n", "60", "127.0.0.1"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn long-lived child")
} else {
std::process::Command::new("sleep")
.arg("60")
.spawn()
.expect("spawn long-lived child")
};
let pid = child.id();
let fix = kill_ghost_process(3000, pid);
let log = execute_fix(&fix, ".").await.unwrap();
assert!(
log.contains(&pid.to_string()),
"kill log should mention PID {pid}: {log}"
);
assert!(log.contains("Killed") || log.contains("terminated"), "got: {log}");
let again = execute_fix(
&kill_ghost_process(3000, pid),
".",
)
.await
.unwrap();
assert!(again.contains("not running"), "got: {again}");
let _ = child.kill();
let _ = child.wait();
}
#[test]
fn test_install_dependencies() {
let node = install_fix_for_stack(&ProjectStack::Node {
version: String::new(),
package_manager: "npm".into(),
})
.expect("Node stacks map to an install fix");
assert!(matches!(
node.command,
FixCommand::RunCommand { ref cmd, .. } if cmd == "npm"
));
assert!(validate_fix(&node).is_ok());
assert!(install_fix_for_stack(&ProjectStack::Python {
version: String::new(),
})
.is_some());
assert!(install_fix_for_stack(&ProjectStack::Rust {
version: String::new(),
})
.is_some());
assert!(install_fix_for_stack(&ProjectStack::Docker).is_none());
assert!(install_fix_for_stack(&ProjectStack::Unknown).is_none());
}
#[tokio::test]
async fn test_fix_rollback_on_failure() {
let dir = TempDir::new("named_roll");
let blocker = dir.path().join("as_dir");
fs::create_dir(&blocker).expect("dir in the way");
fs::write(blocker.join("child"), "y").expect("child file");
let fix = Fix::new(
"create-into-dir",
"Create as_dir",
"test",
FixCommand::CreateFile {
path: "as_dir".to_string(),
content: "DATA\n".to_string(),
},
true,
false,
);
let err = execute_fix_with(&fix, dir.path().to_str().unwrap(), true)
.await
.unwrap_err();
assert!(!err.is_empty());
assert!(blocker.is_dir(), "offending path must survive: {err}");
assert_eq!(
fs::read_to_string(blocker.join("child")).unwrap(),
"y",
"no partial writes inside the blocked path"
);
let missing_src = TempDir::new("named_roll_copy");
let copy = copy_env_from_example(".env.example", ".env").unwrap();
let err2 = execute_fix(©, missing_src.path().to_str().unwrap())
.await
.unwrap_err();
assert!(err2.contains("does not exist"), "got: {err2}");
assert!(!missing_src.path().join(".env").exists());
}
}