1use anyhow::{Context, Result};
4use clap::{Parser, Subcommand};
5
6#[derive(Parser)]
8pub struct GitCommand {
9 #[command(subcommand)]
11 pub command: GitSubcommands,
12}
13
14#[derive(Subcommand)]
16pub enum GitSubcommands {
17 Commit(CommitCommand),
19 Branch(BranchCommand),
21}
22
23#[derive(Parser)]
25pub struct CommitCommand {
26 #[command(subcommand)]
28 pub command: CommitSubcommands,
29}
30
31#[derive(Subcommand)]
33pub enum CommitSubcommands {
34 Message(MessageCommand),
36}
37
38#[derive(Parser)]
40pub struct MessageCommand {
41 #[command(subcommand)]
43 pub command: MessageSubcommands,
44}
45
46#[derive(Subcommand)]
48pub enum MessageSubcommands {
49 View(ViewCommand),
51 Amend(AmendCommand),
53}
54
55#[derive(Parser)]
57pub struct ViewCommand {
58 #[arg(value_name = "COMMIT_RANGE")]
60 pub commit_range: Option<String>,
61}
62
63#[derive(Parser)]
65pub struct AmendCommand {
66 #[arg(value_name = "YAML_FILE")]
68 pub yaml_file: String,
69}
70
71#[derive(Parser)]
73pub struct BranchCommand {
74 #[command(subcommand)]
76 pub command: BranchSubcommands,
77}
78
79#[derive(Subcommand)]
81pub enum BranchSubcommands {
82 Info(InfoCommand),
84}
85
86#[derive(Parser)]
88pub struct InfoCommand {
89 #[arg(value_name = "BASE_BRANCH")]
91 pub base_branch: Option<String>,
92}
93
94impl GitCommand {
95 pub fn execute(self) -> Result<()> {
97 match self.command {
98 GitSubcommands::Commit(commit_cmd) => commit_cmd.execute(),
99 GitSubcommands::Branch(branch_cmd) => branch_cmd.execute(),
100 }
101 }
102}
103
104impl CommitCommand {
105 pub fn execute(self) -> Result<()> {
107 match self.command {
108 CommitSubcommands::Message(message_cmd) => message_cmd.execute(),
109 }
110 }
111}
112
113impl MessageCommand {
114 pub fn execute(self) -> Result<()> {
116 match self.command {
117 MessageSubcommands::View(view_cmd) => view_cmd.execute(),
118 MessageSubcommands::Amend(amend_cmd) => amend_cmd.execute(),
119 }
120 }
121}
122
123impl ViewCommand {
124 pub fn execute(self) -> Result<()> {
126 use crate::data::{FieldExplanation, FileStatusInfo, RepositoryView, WorkingDirectoryInfo};
127 use crate::git::{GitRepository, RemoteInfo};
128
129 let commit_range = self.commit_range.as_deref().unwrap_or("HEAD");
130
131 let repo = GitRepository::open()
133 .context("Failed to open git repository. Make sure you're in a git repository.")?;
134
135 let wd_status = repo.get_working_directory_status()?;
137 let working_directory = WorkingDirectoryInfo {
138 clean: wd_status.clean,
139 untracked_changes: wd_status
140 .untracked_changes
141 .into_iter()
142 .map(|fs| FileStatusInfo {
143 status: fs.status,
144 file: fs.file,
145 })
146 .collect(),
147 };
148
149 let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
151
152 let commits = repo.get_commits_in_range(commit_range)?;
154
155 let repo_view = RepositoryView {
157 explanation: FieldExplanation::default(),
158 working_directory,
159 remotes,
160 commits,
161 branch_info: None,
162 pr_template: None,
163 branch_prs: None,
164 };
165
166 let yaml_output = crate::data::to_yaml(&repo_view)?;
168 println!("{}", yaml_output);
169
170 Ok(())
171 }
172}
173
174impl AmendCommand {
175 pub fn execute(self) -> Result<()> {
177 use crate::git::AmendmentHandler;
178
179 println!("🔄 Starting commit amendment process...");
180 println!("📄 Loading amendments from: {}", self.yaml_file);
181
182 let handler = AmendmentHandler::new().context("Failed to initialize amendment handler")?;
184
185 handler
186 .apply_amendments(&self.yaml_file)
187 .context("Failed to apply amendments")?;
188
189 Ok(())
190 }
191}
192
193impl BranchCommand {
194 pub fn execute(self) -> Result<()> {
196 match self.command {
197 BranchSubcommands::Info(info_cmd) => info_cmd.execute(),
198 }
199 }
200}
201
202impl InfoCommand {
203 pub fn execute(self) -> Result<()> {
205 use crate::data::{
206 BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, WorkingDirectoryInfo,
207 };
208 use crate::git::{GitRepository, RemoteInfo};
209
210 let repo = GitRepository::open()
212 .context("Failed to open git repository. Make sure you're in a git repository.")?;
213
214 let current_branch = repo.get_current_branch().context(
216 "Failed to get current branch. Make sure you're not in detached HEAD state.",
217 )?;
218
219 let base_branch = match self.base_branch {
221 Some(branch) => {
222 if !repo.branch_exists(&branch)? {
224 anyhow::bail!("Base branch '{}' does not exist", branch);
225 }
226 branch
227 }
228 None => {
229 if repo.branch_exists("main")? {
231 "main".to_string()
232 } else if repo.branch_exists("master")? {
233 "master".to_string()
234 } else {
235 anyhow::bail!("No default base branch found (main or master)");
236 }
237 }
238 };
239
240 let commit_range = format!("{}..HEAD", base_branch);
242
243 let wd_status = repo.get_working_directory_status()?;
245 let working_directory = WorkingDirectoryInfo {
246 clean: wd_status.clean,
247 untracked_changes: wd_status
248 .untracked_changes
249 .into_iter()
250 .map(|fs| FileStatusInfo {
251 status: fs.status,
252 file: fs.file,
253 })
254 .collect(),
255 };
256
257 let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
259
260 let commits = repo.get_commits_in_range(&commit_range)?;
262
263 let pr_template = Self::read_pr_template().ok();
265
266 let branch_prs = Self::get_branch_prs(¤t_branch)
268 .ok()
269 .filter(|prs| !prs.is_empty());
270
271 let repo_view = RepositoryView {
273 explanation: FieldExplanation::default(),
274 working_directory,
275 remotes,
276 commits,
277 branch_info: Some(BranchInfo {
278 branch: current_branch,
279 }),
280 pr_template,
281 branch_prs,
282 };
283
284 let yaml_output = crate::data::to_yaml(&repo_view)?;
286 println!("{}", yaml_output);
287
288 Ok(())
289 }
290
291 fn read_pr_template() -> Result<String> {
293 use std::fs;
294 use std::path::Path;
295
296 let template_path = Path::new(".github/pull_request_template.md");
297 if template_path.exists() {
298 fs::read_to_string(template_path)
299 .context("Failed to read .github/pull_request_template.md")
300 } else {
301 anyhow::bail!("PR template file does not exist")
302 }
303 }
304
305 fn get_branch_prs(branch_name: &str) -> Result<Vec<crate::data::PullRequest>> {
307 use serde_json::Value;
308 use std::process::Command;
309
310 let output = Command::new("gh")
312 .args([
313 "pr",
314 "list",
315 "--head",
316 branch_name,
317 "--json",
318 "number,title,state,url,body",
319 "--limit",
320 "50",
321 ])
322 .output()
323 .context("Failed to execute gh command")?;
324
325 if !output.status.success() {
326 anyhow::bail!(
327 "gh command failed: {}",
328 String::from_utf8_lossy(&output.stderr)
329 );
330 }
331
332 let json_str = String::from_utf8_lossy(&output.stdout);
333 let prs_json: Value =
334 serde_json::from_str(&json_str).context("Failed to parse PR JSON from gh")?;
335
336 let mut prs = Vec::new();
337 if let Some(prs_array) = prs_json.as_array() {
338 for pr_json in prs_array {
339 if let (Some(number), Some(title), Some(state), Some(url), Some(body)) = (
340 pr_json.get("number").and_then(|n| n.as_u64()),
341 pr_json.get("title").and_then(|t| t.as_str()),
342 pr_json.get("state").and_then(|s| s.as_str()),
343 pr_json.get("url").and_then(|u| u.as_str()),
344 pr_json.get("body").and_then(|b| b.as_str()),
345 ) {
346 prs.push(crate::data::PullRequest {
347 number,
348 title: title.to_string(),
349 state: state.to_string(),
350 url: url.to_string(),
351 body: body.to_string(),
352 });
353 }
354 }
355 }
356
357 Ok(prs)
358 }
359}