use git_editor::args::Args;
use git_editor::utils::commit_history::get_commit_history;
use git_editor::utils::datetime::generate_timestamps;
use git_editor::utils::validator::validate_inputs;
use serial_test::serial;
use std::fs;
use tempfile::TempDir;
fn create_test_repo_with_commits() -> (TempDir, String) {
let temp_dir = TempDir::new().unwrap();
let repo_path = temp_dir.path().to_str().unwrap().to_string();
let repo = git2::Repository::init(&repo_path).unwrap();
for i in 1..=3 {
let file_path = temp_dir.path().join(format!("test{i}.txt"));
fs::write(&file_path, format!("test content {i}")).unwrap();
let mut index = repo.index().unwrap();
index
.add_path(std::path::Path::new(&format!("test{i}.txt")))
.unwrap();
index.write().unwrap();
let tree_id = index.write_tree().unwrap();
let tree = repo.find_tree(tree_id).unwrap();
let sig = git2::Signature::new(
"Test User",
"test@example.com",
&git2::Time::new(1234567890 + i as i64 * 3600, 0),
)
.unwrap();
let parents = if i == 1 {
vec![]
} else {
let head = repo.head().unwrap();
let parent_commit = head.peel_to_commit().unwrap();
vec![parent_commit]
};
repo.commit(
Some("HEAD"),
&sig,
&sig,
&format!("Commit {i}"),
&tree,
&parents.iter().collect::<Vec<_>>(),
)
.unwrap();
}
(temp_dir, repo_path)
}
#[test]
#[serial]
fn test_show_history_mode_integration() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
show_history: true,
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let history_result = get_commit_history(&args, false);
assert!(history_result.is_ok());
let commits = history_result.unwrap();
assert_eq!(commits.len(), 3);
assert_eq!(commits[0].message, "Commit 3");
assert_eq!(commits[1].message, "Commit 2");
assert_eq!(commits[2].message, "Commit 1");
}
#[test]
#[serial]
fn test_pick_specific_commits_mode_integration() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
pick_specific_commits: true,
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let history_result = get_commit_history(&args, false);
assert!(history_result.is_ok());
let commits = history_result.unwrap();
assert_eq!(commits.len(), 3);
for commit in &commits {
assert!(!commit.short_hash.is_empty());
assert!(!commit.author_name.is_empty());
assert!(!commit.author_email.is_empty());
assert!(!commit.message.is_empty());
}
}
#[test]
#[serial]
fn test_full_rewrite_mode_integration() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2025-01-01 00:00:00".to_string()),
end: Some("2025-01-10 00:00:00".to_string()),
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_ok());
let timestamps = timestamp_result.unwrap();
assert_eq!(timestamps.len(), 3);
for i in 1..timestamps.len() {
assert!(timestamps[i] >= timestamps[i - 1]);
}
let start_dt =
chrono::NaiveDateTime::parse_from_str("2025-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
let end_dt =
chrono::NaiveDateTime::parse_from_str("2025-01-10 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
for timestamp in ×tamps {
assert!(*timestamp >= start_dt);
assert!(*timestamp <= end_dt);
}
}
#[test]
#[serial]
fn test_invalid_repo_path_all_modes() {
let invalid_repo_path = "/nonexistent/path".to_string();
let args_show = Args {
repo_path: Some(invalid_repo_path.clone()),
show_history: true,
..Default::default()
};
let history_result = get_commit_history(&args_show, false);
assert!(history_result.is_err());
let args_pick = Args {
repo_path: Some(invalid_repo_path.clone()),
pick_specific_commits: true,
..Default::default()
};
let history_result = get_commit_history(&args_pick, false);
assert!(history_result.is_err());
let args_full = Args {
repo_path: Some(invalid_repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2023-01-01 00:00:00".to_string()),
end: Some("2023-01-10 00:00:00".to_string()),
..Default::default()
};
let timestamp_result = generate_timestamps(&args_full);
assert!(timestamp_result.is_err());
}
#[test]
#[serial]
fn test_full_rewrite_mode_insufficient_date_range() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2023-01-01 00:00:00".to_string()),
end: Some("2023-01-01 01:00:00".to_string()), ..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let args_mut = args;
let timestamp_result = generate_timestamps(&args_mut);
assert!(timestamp_result.is_err());
let err_msg = timestamp_result.unwrap_err().to_string();
assert!(
err_msg.contains("--skip-range-check"),
"Error should mention --skip-range-check, got: {err_msg}"
);
}
#[test]
#[serial]
fn test_skip_range_check_succeeds_with_small_range() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2023-01-01 00:00:00".to_string()),
end: Some("2023-01-01 01:00:00".to_string()), skip_range_check: true,
..Default::default()
};
let timestamp_result = generate_timestamps(&args);
assert!(
timestamp_result.is_ok(),
"Should succeed with --skip-range-check: {:?}",
timestamp_result.err()
);
let timestamps = timestamp_result.unwrap();
assert_eq!(timestamps.len(), 3);
for i in 1..timestamps.len() {
assert!(timestamps[i] >= timestamps[i - 1]);
}
let start_dt =
chrono::NaiveDateTime::parse_from_str("2023-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
let end_dt =
chrono::NaiveDateTime::parse_from_str("2023-01-01 01:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
for ts in ×tamps {
assert!(*ts >= start_dt);
assert!(*ts <= end_dt);
}
}
#[test]
#[serial]
fn test_skip_range_check_with_5min_minimum_gap() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2023-01-01 00:00:00".to_string()),
end: Some("2023-01-01 02:00:00".to_string()),
skip_range_check: true,
..Default::default()
};
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_ok());
let timestamps = timestamp_result.unwrap();
assert_eq!(timestamps.len(), 3);
for i in 1..timestamps.len() {
let gap = timestamps[i] - timestamps[i - 1];
assert!(
gap >= chrono::Duration::minutes(5),
"Gap between commit {} and {} is {} mins, expected >= 5",
i - 1,
i,
gap.num_minutes()
);
}
}
#[test]
#[serial]
fn test_full_rewrite_mode_invalid_date_format() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("invalid-date".to_string()),
end: Some("2023-01-10 00:00:00".to_string()),
..Default::default()
};
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_err());
}
#[test]
#[serial]
fn test_workflow_show_history_then_pick_commits() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args_show = Args {
repo_path: Some(repo_path.clone()),
show_history: true,
..Default::default()
};
let history_result = get_commit_history(&args_show, false);
assert!(history_result.is_ok());
let commits = history_result.unwrap();
assert_eq!(commits.len(), 3);
let args_pick = Args {
repo_path: Some(repo_path),
pick_specific_commits: true,
..Default::default()
};
let validation_result = validate_inputs(&args_pick);
assert!(validation_result.is_ok());
let history_result = get_commit_history(&args_pick, false);
assert!(history_result.is_ok());
let commits = history_result.unwrap();
assert_eq!(commits.len(), 3);
}
#[test]
#[serial]
fn test_simulation_mode_complete_args() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2025-01-01 00:00:00".to_string()),
end: Some("2025-01-10 00:00:00".to_string()),
simulate: true,
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_ok());
}
#[test]
#[serial]
fn test_simulation_mode_incomplete_args() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let mut args = Args {
repo_path: Some(repo_path),
simulate: true,
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
let ensure_result = args.ensure_all_args_present();
assert!(ensure_result.is_ok());
}
#[test]
#[serial]
fn test_simulation_mode_with_show_diff() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2025-01-01 00:00:00".to_string()),
end: Some("2025-01-10 00:00:00".to_string()),
simulate: true,
show_diff: true,
..Default::default()
};
let validation_result = validate_inputs(&args);
assert!(validation_result.is_ok());
}
#[test]
fn test_conflicting_modes_are_rejected_by_the_parser() {
use clap::Parser;
for argv in [
vec!["git-editor", "-s", "-x"],
vec!["git-editor", "-p", "-x"],
vec!["git-editor", "--docs", "-s"],
vec!["git-editor", "--simulate", "-s"],
vec!["git-editor", "--message"],
vec!["git-editor", "--select", "1-2"],
vec!["git-editor", "--commit", "1"],
] {
assert!(
Args::try_parse_from(&argv).is_err(),
"{argv:?} should be rejected"
);
}
for argv in [
vec!["git-editor", "-x", "--message"],
vec!["git-editor", "--simulate", "-x"],
vec!["git-editor", "--show-diff", "-x", "--select", "1"],
vec!["git-editor", "-p", "--commit", "1", "--set-message", "m"],
] {
assert!(Args::try_parse_from(&argv).is_ok(), "{argv:?} should parse");
}
}
#[test]
#[serial]
fn test_cli_execution_simulate_incomplete_args_no_panic() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let mut args = Args {
repo_path: Some(repo_path),
simulate: true,
..Default::default()
};
assert!(validate_inputs(&args).is_ok());
let ensure_result = args.ensure_all_args_present();
assert!(
ensure_result.is_ok(),
"ensure_all_args_present should pass for simulation mode"
);
}
#[test]
#[serial]
fn test_cli_execution_simulate_complete_args_success() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let mut args = Args {
repo_path: Some(repo_path),
email: Some("test@example.com".to_string()),
name: Some("Test User".to_string()),
start: Some("2025-01-01 00:00:00".to_string()),
end: Some("2025-01-10 00:00:00".to_string()),
simulate: true,
..Default::default()
};
assert!(args.ensure_all_args_present().is_ok());
assert!(validate_inputs(&args).is_ok());
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_ok());
}
#[test]
#[serial]
fn test_simulation_execution_function_missing_args() {
let (_temp_dir, repo_path) = create_test_repo_with_commits();
let args = Args {
repo_path: Some(repo_path),
email: None, name: None, start: None, end: None, simulate: true,
..Default::default()
};
let commit_history = get_commit_history(&args, false);
assert!(commit_history.is_ok());
let commits = commit_history.unwrap();
assert!(!commits.is_empty());
if args.email.is_some() && args.name.is_some() && args.start.is_some() && args.end.is_some() {
let timestamp_result = generate_timestamps(&args);
assert!(timestamp_result.is_ok());
} else {
assert!(
args.email.is_none()
|| args.name.is_none()
|| args.start.is_none()
|| args.end.is_none()
);
}
}
#[test]
#[serial]
fn test_docs_mode_execution() {
let output = std::process::Command::new("cargo")
.args(["run", "--", "--docs"])
.env("DISPLAY", ":0") .env("GIT_EDITOR_NO_BROWSER", "1") .output()
.expect("Failed to execute command");
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
stdout.contains("📚 Opening Git Editor Documentation")
|| stderr.contains("📚 Opening Git Editor Documentation"),
"Expected docs message not found. Stdout: {stdout}, Stderr: {stderr}"
);
assert!(
stdout.contains("✅ Documentation opened")
|| stdout.contains("⚠️ Could not open browser")
|| stderr.contains("✅ Documentation opened")
|| stderr.contains("⚠️ Could not open browser"),
"Expected either success or graceful failure message. Stdout: {stdout}, Stderr: {stderr}"
);
}
#[test]
#[serial]
fn test_docs_mode_no_repo_required() {
let temp_dir = TempDir::new().unwrap();
let project_root = std::env::current_dir().expect("Failed to get current dir");
let binary_path = project_root.join("target/debug/git-editor");
let output = std::process::Command::new(binary_path)
.args(["--docs"])
.current_dir(temp_dir.path())
.env("DISPLAY", ":0")
.env("GIT_EDITOR_NO_BROWSER", "1") .output()
.expect("Failed to execute command");
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
!stdout.contains("Repository not found") && !stderr.contains("Repository not found"),
"Docs mode should not require a repository. Stdout: {stdout}, Stderr: {stderr}"
);
}
#[test]
#[serial]
fn test_docs_mode_with_invalid_args() {
let output = std::process::Command::new("cargo")
.args([
"run",
"--",
"--docs",
"--email",
"invalid-email", "--begin",
"invalid-date", "--repo-path",
"/nonexistent/path", ])
.env("DISPLAY", ":0")
.env("GIT_EDITOR_NO_BROWSER", "1") .output()
.expect("Failed to execute command");
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
stdout.contains("📚 Opening Git Editor Documentation")
|| stderr.contains("📚 Opening Git Editor Documentation"),
"Expected docs message. Stdout: {stdout}, Stderr: {stderr}"
);
}
#[test]
#[serial]
fn test_docs_flag_in_help() {
let output = std::process::Command::new("cargo")
.args(["run", "--", "--help"])
.output()
.expect("Failed to execute command");
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(stdout.contains("--docs"));
assert!(stdout.contains("Open comprehensive documentation in the browser"));
}
#[test]
#[serial]
fn test_docs_mode_conflicts_with_other_modes() {
let output = std::process::Command::new("cargo")
.args(["run", "--", "--docs", "--show-history"])
.env("GIT_EDITOR_NO_BROWSER", "1") .output()
.expect("Failed to execute command");
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains("cannot be used with"), "stderr: {stderr}");
}