omni_dev/cli/
git.rs

1//! Git-related CLI commands
2
3use anyhow::{Context, Result};
4use clap::{Parser, Subcommand};
5
6/// Git operations
7#[derive(Parser)]
8pub struct GitCommand {
9    /// Git subcommand to execute
10    #[command(subcommand)]
11    pub command: GitSubcommands,
12}
13
14/// Git subcommands
15#[derive(Subcommand)]
16pub enum GitSubcommands {
17    /// Commit-related operations
18    Commit(CommitCommand),
19    /// Branch-related operations
20    Branch(BranchCommand),
21}
22
23/// Commit operations
24#[derive(Parser)]
25pub struct CommitCommand {
26    /// Commit subcommand to execute
27    #[command(subcommand)]
28    pub command: CommitSubcommands,
29}
30
31/// Commit subcommands
32#[derive(Subcommand)]
33pub enum CommitSubcommands {
34    /// Commit message operations
35    Message(MessageCommand),
36}
37
38/// Message operations
39#[derive(Parser)]
40pub struct MessageCommand {
41    /// Message subcommand to execute
42    #[command(subcommand)]
43    pub command: MessageSubcommands,
44}
45
46/// Message subcommands
47#[derive(Subcommand)]
48pub enum MessageSubcommands {
49    /// Analyze commits and output repository information in YAML format
50    View(ViewCommand),
51    /// Amend commit messages based on a YAML configuration file
52    Amend(AmendCommand),
53}
54
55/// View command options
56#[derive(Parser)]
57pub struct ViewCommand {
58    /// Commit range to analyze (e.g., HEAD~3..HEAD, abc123..def456)
59    #[arg(value_name = "COMMIT_RANGE")]
60    pub commit_range: Option<String>,
61}
62
63/// Amend command options  
64#[derive(Parser)]
65pub struct AmendCommand {
66    /// YAML file containing commit amendments
67    #[arg(value_name = "YAML_FILE")]
68    pub yaml_file: String,
69}
70
71/// Branch operations
72#[derive(Parser)]
73pub struct BranchCommand {
74    /// Branch subcommand to execute
75    #[command(subcommand)]
76    pub command: BranchSubcommands,
77}
78
79/// Branch subcommands
80#[derive(Subcommand)]
81pub enum BranchSubcommands {
82    /// Analyze branch commits and output repository information in YAML format
83    Info(InfoCommand),
84}
85
86/// Info command options
87#[derive(Parser)]
88pub struct InfoCommand {
89    /// Base branch to compare against (defaults to main/master)
90    #[arg(value_name = "BASE_BRANCH")]
91    pub base_branch: Option<String>,
92}
93
94impl GitCommand {
95    /// Execute git command
96    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    /// Execute commit command
106    pub fn execute(self) -> Result<()> {
107        match self.command {
108            CommitSubcommands::Message(message_cmd) => message_cmd.execute(),
109        }
110    }
111}
112
113impl MessageCommand {
114    /// Execute message command
115    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    /// Execute view command
125    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        // Open git repository
132        let repo = GitRepository::open()
133            .context("Failed to open git repository. Make sure you're in a git repository.")?;
134
135        // Get working directory status
136        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        // Get remote information
150        let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
151
152        // Parse commit range and get commits
153        let commits = repo.get_commits_in_range(commit_range)?;
154
155        // Build repository view
156        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        // Output as YAML
167        let yaml_output = crate::data::to_yaml(&repo_view)?;
168        println!("{}", yaml_output);
169
170        Ok(())
171    }
172}
173
174impl AmendCommand {
175    /// Execute amend command
176    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        // Create amendment handler and apply amendments
183        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    /// Execute branch command
195    pub fn execute(self) -> Result<()> {
196        match self.command {
197            BranchSubcommands::Info(info_cmd) => info_cmd.execute(),
198        }
199    }
200}
201
202impl InfoCommand {
203    /// Execute info command
204    pub fn execute(self) -> Result<()> {
205        use crate::data::{
206            BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, WorkingDirectoryInfo,
207        };
208        use crate::git::{GitRepository, RemoteInfo};
209
210        // Open git repository
211        let repo = GitRepository::open()
212            .context("Failed to open git repository. Make sure you're in a git repository.")?;
213
214        // Get current branch name
215        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        // Determine base branch
220        let base_branch = match self.base_branch {
221            Some(branch) => {
222                // Validate that the specified base branch exists
223                if !repo.branch_exists(&branch)? {
224                    anyhow::bail!("Base branch '{}' does not exist", branch);
225                }
226                branch
227            }
228            None => {
229                // Default to main or master
230                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        // Calculate commit range: [base_branch]..HEAD
241        let commit_range = format!("{}..HEAD", base_branch);
242
243        // Get working directory status
244        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        // Get remote information
258        let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
259
260        // Parse commit range and get commits
261        let commits = repo.get_commits_in_range(&commit_range)?;
262
263        // Check for PR template
264        let pr_template = Self::read_pr_template().ok();
265
266        // Get PRs for current branch
267        let branch_prs = Self::get_branch_prs(&current_branch)
268            .ok()
269            .filter(|prs| !prs.is_empty());
270
271        // Build repository view with branch info
272        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        // Output as YAML
285        let yaml_output = crate::data::to_yaml(&repo_view)?;
286        println!("{}", yaml_output);
287
288        Ok(())
289    }
290
291    /// Read PR template file if it exists
292    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    /// Get pull requests for the current branch using gh CLI
306    fn get_branch_prs(branch_name: &str) -> Result<Vec<crate::data::PullRequest>> {
307        use serde_json::Value;
308        use std::process::Command;
309
310        // Use gh CLI to get PRs for the branch
311        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}