1const SOFT_DIFF_LIMIT: usize = 15_000;
2
3#[derive(Debug, thiserror::Error)]
4pub enum PreflightError {
5 #[error("Not a git repository")]
6 NotGitRepo,
7 #[error("Git command failed: {command}")]
8 GitCommandFailed {
9 command: String,
10 source: std::io::Error,
11 },
12 #[error("No staged files")]
13 NoStagedFiles { unstaged: Vec<UnstagedFile> },
14 #[error("Working tree clean — nothing to commit")]
15 WorkingTreeClean,
16 #[error("Diff too large: {size} chars")]
17 DiffTooLarge { size: usize },
18}
19
20#[derive(Debug, Clone)]
21pub struct UnstagedFile {
22 pub status: String,
23 pub path: String,
24}
25
26#[derive(Debug)]
27#[allow(dead_code)]
28pub struct PreflightSuccess {
29 pub diff_content: String,
30}
31
32fn is_git_repo() -> bool {
33 std::process::Command::new("git")
34 .args(["rev-parse", "--is-inside-work-tree"])
35 .output()
36 .map(|output| {
37 let stdout = String::from_utf8_lossy(&output.stdout);
38 stdout.trim() == "true"
39 })
40 .unwrap_or(false)
41}
42
43fn get_staged_files() -> Result<Vec<String>, std::io::Error> {
44 let output = std::process::Command::new("git")
45 .args(["diff", "--cached", "--name-only"])
46 .output()?;
47 Ok(String::from_utf8_lossy(&output.stdout)
48 .lines()
49 .map(String::from)
50 .collect())
51}
52
53fn get_unstaged_files() -> Result<Vec<UnstagedFile>, std::io::Error> {
54 let output = std::process::Command::new("git")
55 .args(["status", "-s"])
56 .output()?;
57 Ok(String::from_utf8_lossy(&output.stdout)
58 .lines()
59 .filter_map(|line| {
60 let bytes = line.as_bytes();
61 if bytes.len() < 4 {
62 return None; }
64 let c1 = bytes[0] as char;
68 let c2 = bytes[1] as char;
69 let path = line[3..].to_string();
70 if (c1 == ' ' && c2 == ' ') || path.is_empty() {
72 return None;
73 }
74 Some(UnstagedFile {
75 status: format!("{}{}", c1, c2),
76 path,
77 })
78 })
79 .collect())
80}
81
82fn get_diff_content() -> Result<String, std::io::Error> {
83 let output = std::process::Command::new("git")
84 .args(["diff", "--cached"])
85 .output()?;
86 Ok(String::from_utf8_lossy(&output.stdout).to_string())
87}
88
89fn is_working_tree_clean() -> Result<bool, std::io::Error> {
90 let output = std::process::Command::new("git")
91 .args(["status", "--porcelain"])
92 .output()?;
93 let clean = String::from_utf8_lossy(&output.stdout)
94 .lines()
95 .all(|line| line.trim().is_empty());
96 Ok(clean)
97}
98
99pub fn run() -> Result<PreflightSuccess, PreflightError> {
104 if !is_git_repo() {
105 return Err(PreflightError::NotGitRepo);
106 }
107
108 if is_working_tree_clean().unwrap_or(false) {
109 return Err(PreflightError::WorkingTreeClean);
110 }
111
112 let staged = get_staged_files().map_err(|e| PreflightError::GitCommandFailed {
113 command: "git diff --cached --name-only".into(),
114 source: e,
115 })?;
116
117 if staged.is_empty() {
118 let unstaged = get_unstaged_files().map_err(|e| PreflightError::GitCommandFailed {
119 command: "git status -s".into(),
120 source: e,
121 })?;
122 return Err(PreflightError::NoStagedFiles { unstaged });
123 }
124
125 let diff_content = get_diff_content().map_err(|e| PreflightError::GitCommandFailed {
126 command: "git diff --cached".into(),
127 source: e,
128 })?;
129
130 if diff_content.len() > SOFT_DIFF_LIMIT {
131 return Err(PreflightError::DiffTooLarge {
132 size: diff_content.len(),
133 });
134 }
135
136 Ok(PreflightSuccess { diff_content })
137}
138
139pub fn run_with_diff_bypass() -> Result<PreflightSuccess, PreflightError> {
142 if !is_git_repo() {
143 return Err(PreflightError::NotGitRepo);
144 }
145
146 if is_working_tree_clean().unwrap_or(false) {
147 return Err(PreflightError::WorkingTreeClean);
148 }
149
150 let staged = get_staged_files().map_err(|e| PreflightError::GitCommandFailed {
151 command: "git diff --cached --name-only".into(),
152 source: e,
153 })?;
154 if staged.is_empty() {
155 let unstaged = get_unstaged_files().map_err(|e| PreflightError::GitCommandFailed {
156 command: "git status -s".into(),
157 source: e,
158 })?;
159 return Err(PreflightError::NoStagedFiles { unstaged });
160 }
161 let diff_content = get_diff_content().map_err(|e| PreflightError::GitCommandFailed {
162 command: "git diff --cached".into(),
163 source: e,
164 })?;
165 Ok(PreflightSuccess { diff_content })
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 #[test]
173 fn test_unstaged_file_parse_status_M() {
174 let file = UnstagedFile {
175 status: "M".to_string(),
176 path: "src/main.rs".to_string(),
177 };
178 assert_eq!(file.status, "M");
179 assert_eq!(file.path, "src/main.rs");
180 }
181
182 #[test]
183 fn test_unstaged_file_parse_status_UU() {
184 let file = UnstagedFile {
185 status: "??".to_string(),
186 path: ".env.example".to_string(),
187 };
188 assert_eq!(file.status, "??");
189 assert_eq!(file.path, ".env.example");
190 }
191
192 #[test]
193 fn test_preflight_error_display() {
194 let err = PreflightError::NotGitRepo;
195 assert_eq!(err.to_string(), "Not a git repository");
196 }
197
198 #[test]
199 fn test_diff_too_large_error_display() {
200 let err = PreflightError::DiffTooLarge { size: 23450 };
201 assert_eq!(err.to_string(), "Diff too large: 23450 chars");
202 }
203}