gitai/
app.rs

1use crate::common::CommonParams;
2use crate::core::llm::get_available_provider_names;
3use crate::features::changelog::{handle_changelog_command, handle_release_notes_command};
4use crate::features::commit;
5use clap::builder::{Styles, styling::AnsiColor};
6use clap::{Parser, Subcommand, crate_version};
7use colored::Colorize;
8use log::debug;
9
10/// CLI structure defining the available commands and global arguments
11#[derive(Parser)]
12#[command(
13    author,
14    version = crate_version!(),
15    about = "GitAI: AI-powered Git workflow assistant",
16    disable_version_flag = true,
17    after_help = get_dynamic_help(),
18    styles = get_styles(),
19)]
20pub struct Cli {
21    /// Subcommands available for the CLI
22    #[command(subcommand)]
23    pub command: Option<GitAI>,
24
25    /// Log debug messages to a file
26    #[arg(
27        short = 'l',
28        long = "log",
29        global = true,
30        help = "Log debug messages to a file"
31    )]
32    pub log: bool,
33
34    /// Specify a custom log file path
35    #[arg(
36        long = "log-file",
37        global = true,
38        help = "Specify a custom log file path"
39    )]
40    pub log_file: Option<String>,
41
42    /// Suppress non-essential output (spinners, waiting messages, etc.)
43    #[arg(
44        short = 'q',
45        long = "quiet",
46        global = true,
47        help = "Suppress non-essential output"
48    )]
49    pub quiet: bool,
50
51    /// Display the version
52    #[arg(
53        short = 'v',
54        long = "version",
55        global = true,
56        help = "Display the version"
57    )]
58    pub version: bool,
59
60    /// Repository URL to use instead of local repository
61    #[arg(
62        short = 'r',
63        long = "repo",
64        global = true,
65        help = "Repository URL to use instead of local repository"
66    )]
67    pub repository_url: Option<String>,
68}
69
70/// Enumeration of available subcommands
71#[derive(Subcommand)]
72#[command(subcommand_negates_reqs = true)]
73#[command(subcommand_precedence_over_arg = true)]
74pub enum GitAI {
75    // Feature commands first
76    /// Generate a commit message using AI
77    #[command(
78        about = "Generate a commit message using AI",
79        long_about = "Generate a commit message using AI based on the current Git context.",
80        after_help = get_dynamic_help()
81    )]
82    Message {
83        #[command(flatten)]
84        common: CommonParams,
85
86        /// Automatically commit with the generated message
87        #[arg(short, long, help = "Automatically commit with the generated message")]
88        auto_commit: bool,
89
90        /// Print the generated message to stdout and exit
91        #[arg(short, long, help = "Print the generated message to stdout and exit")]
92        print: bool,
93
94        /// Skip the verification step (pre/post commit hooks)
95        #[arg(long, help = "Skip verification steps (pre/post commit hooks)")]
96        no_verify: bool,
97
98        /// Amend the last commit or a specific commit with a new AI-generated message
99        #[arg(
100            long,
101            help = "Amend the last commit or a specific commit with a new AI-generated message"
102        )]
103        amend: bool,
104
105        /// Specific commit to amend (hash, branch, or reference). Defaults to HEAD when --amend is used
106        #[arg(
107            long,
108            help = "Specific commit to amend (hash, branch, or reference). Defaults to HEAD when --amend is used"
109        )]
110        commit: Option<String>,
111    },
112
113    /// Generate a pull request description
114    #[command(
115        about = "Generate a pull request description using AI",
116        long_about = "Generate a comprehensive pull request description based on commit ranges, branch differences, or single commits. Analyzes the overall changeset as an atomic unit and creates professional PR descriptions with summaries, detailed explanations, and testing notes.\\
117\\
118Usage examples:\\
119• Single commit: --from abc1234 or --to abc1234\\
120• Single commitish: --from HEAD~1 or --to HEAD~2\\
121• Multiple commits: --from HEAD~3 (reviews last 3 commits)\\
122• Commit range: --from abc1234 --to def5678\\
123• Branch comparison: --from main --to feature-branch\\
124• From main to branch: --to feature-branch\\
125\\
126Supported commitish syntax: HEAD~2, HEAD^, @~3, main~1, origin/main^, etc."
127    )]
128    Pr {
129        #[command(flatten)]
130        common: CommonParams,
131
132        /// Print the generated PR description to stdout and exit
133        #[arg(
134            short,
135            long,
136            help = "Print the generated PR description to stdout and exit"
137        )]
138        print: bool,
139
140        /// Starting branch, commit, or commitish for comparison
141        #[arg(
142            long,
143            help = "Starting branch, commit, or commitish for comparison. For single commit analysis, specify just this parameter with a commit hash (e.g., --from abc1234). For reviewing multiple commits, use commitish syntax (e.g., --from HEAD~3 to review last 3 commits)"
144        )]
145        from: Option<String>,
146
147        /// Target branch, commit, or commitish for comparison
148        #[arg(
149            long,
150            help = "Target branch, commit, or commitish for comparison. For single commit analysis, specify just this parameter with a commit hash or commitish (e.g., --to HEAD~2)"
151        )]
152        to: Option<String>,
153    },
154
155    /// Generate a changelog
156    #[command(
157        about = "Generate a changelog",
158        long_about = "Generate a changelog between two specified Git references."
159    )]
160    Changelog {
161        #[command(flatten)]
162        common: CommonParams,
163
164        /// Starting Git reference (commit hash, tag, or branch name)
165        #[arg(long, required = true)]
166        from: String,
167
168        /// Ending Git reference (commit hash, tag, or branch name). Defaults to HEAD if not specified.
169        #[arg(long)]
170        to: Option<String>,
171
172        /// Update the changelog file with the new changes
173        #[arg(long, help = "Update the changelog file with the new changes")]
174        update: bool,
175
176        /// Path to the changelog file
177        #[arg(long, help = "Path to the changelog file (defaults to CHANGELOG.md)")]
178        file: Option<String>,
179
180        /// Explicit version name to use in the changelog instead of getting it from Git
181        #[arg(long, help = "Explicit version name to use in the changelog")]
182        version_name: Option<String>,
183    },
184
185    /// Generate release notes
186    #[command(
187        about = "Generate release notes",
188        long_about = "Generate comprehensive release notes between two specified Git references."
189    )]
190    ReleaseNotes {
191        #[command(flatten)]
192        common: CommonParams,
193
194        /// Starting Git reference (commit hash, tag, or branch name)
195        #[arg(long, required = true)]
196        from: String,
197
198        /// Ending Git reference (commit hash, tag, or branch name). Defaults to HEAD if not specified.
199        #[arg(long)]
200        to: Option<String>,
201
202        /// Explicit version name to use in the release notes instead of getting it from Git
203        #[arg(long, help = "Explicit version name to use in the release notes")]
204        version_name: Option<String>,
205    },
206}
207
208/// Define custom styles for Clap
209fn get_styles() -> Styles {
210    Styles::styled()
211        .header(AnsiColor::Magenta.on_default().bold())
212        .usage(AnsiColor::Cyan.on_default().bold())
213        .literal(AnsiColor::Green.on_default().bold())
214        .placeholder(AnsiColor::Yellow.on_default())
215        .valid(AnsiColor::Blue.on_default().bold())
216        .invalid(AnsiColor::Red.on_default().bold())
217        .error(AnsiColor::Red.on_default().bold())
218}
219
220/// Parse the command-line arguments
221pub fn parse_args() -> Cli {
222    Cli::parse()
223}
224
225/// Generate dynamic help including available LLM providers
226fn get_dynamic_help() -> String {
227    let mut providers = get_available_provider_names();
228    providers.sort();
229
230    let providers_list = providers
231        .iter()
232        .map(|p| format!("{}", p.bold()))
233        .collect::<Vec<_>>()
234        .join(" • ");
235
236    format!(
237        "\\
238Available LLM Providers: {providers_list}"
239    )
240}
241
242/// Configuration for the cmsg command
243#[allow(clippy::struct_excessive_bools)]
244pub struct CmsgConfig {
245    pub auto_commit: bool,
246    pub print_only: bool,
247    pub verify: bool,
248    pub dry_run: bool,
249    pub amend: bool,
250    pub commit_ref: Option<String>,
251}
252
253#[allow(clippy::too_many_arguments)]
254pub async fn handle_message(
255    common: CommonParams,
256    config: CmsgConfig,
257    repository_url: Option<String>,
258    complete: bool,
259    prefix: Option<String>,
260    context_ratio: Option<f32>,
261    with_history: bool,
262    filter_restrictive: bool,
263) -> anyhow::Result<()> {
264    debug!(
265        "Handling 'message' command with common: {:?}, auto_commit: {}, print: {}, verify: {}, amend: {}, commit_ref: {:?}, complete: {}, prefix: {:?}, context_ratio: {:?}, with_history: {}, filter_restrictive: {}",
266        common,
267        config.auto_commit,
268        config.print_only,
269        config.verify,
270        config.amend,
271        config.commit_ref,
272        complete,
273        prefix,
274        context_ratio,
275        with_history,
276        filter_restrictive
277    );
278
279    if complete {
280        // Handle completion mode
281        let prefix_text =
282            prefix.ok_or_else(|| anyhow::anyhow!("Prefix is required for completion mode"))?;
283        let context_ratio_val = context_ratio.unwrap_or(0.5);
284
285        commit::handle_completion_command(
286            common,
287            prefix_text,
288            Some(context_ratio_val),
289            config.print_only,
290            config.verify,
291            config.dry_run,
292            config.amend,
293            config.commit_ref,
294            repository_url,
295        )
296        .await
297    } else {
298        // Handle generation mode
299        commit::handle_message_command(
300            common,
301            config.auto_commit,
302            config.print_only,
303            config.verify,
304            config.dry_run,
305            config.amend,
306            config.commit_ref,
307            repository_url,
308        )
309        .await
310    }
311}
312
313/// Handle the `Changelog` command
314pub async fn handle_changelog(
315    common: CommonParams,
316    from: String,
317    to: Option<String>,
318    repository_url: Option<String>,
319    update: bool,
320    file: Option<String>,
321    version_name: Option<String>,
322) -> anyhow::Result<()> {
323    debug!(
324        "Handling 'changelog' command with common: {common:?}, from: {from}, to: {to:?}, update: {update}, file: {file:?}, version_name: {version_name:?}"
325    );
326    handle_changelog_command(common, from, to, repository_url, update, file, version_name).await
327}
328
329/// Handle the `ReleaseNotes` command
330pub async fn handle_release_notes(
331    common: CommonParams,
332    from: String,
333    to: Option<String>,
334    repository_url: Option<String>,
335    version_name: Option<String>,
336) -> anyhow::Result<()> {
337    debug!(
338        "Handling 'release-notes' command with common: {common:?}, from: {from}, to: {to:?}, version_name: {version_name:?}"
339    );
340    handle_release_notes_command(common, from, to, repository_url, version_name).await
341}
342
343/// Handle the command based on parsed arguments
344pub async fn handle_command(command: GitAI, repository_url: Option<String>) -> anyhow::Result<()> {
345    match command {
346        GitAI::Message {
347            common,
348            auto_commit,
349            print,
350            no_verify,
351            amend,
352            commit,
353        } => {
354            handle_message(
355                common,
356                CmsgConfig {
357                    auto_commit,
358                    print_only: print,
359                    verify: !no_verify,
360                    dry_run: false,
361                    amend,
362                    commit_ref: commit,
363                },
364                repository_url,
365                false, // complete
366                None,  // prefix
367                None,  // context_ratio
368                false, // with_history
369                false, // filter_restrictive
370            )
371            .await
372        }
373        GitAI::Changelog {
374            common,
375            from,
376            to,
377            update,
378            file,
379            version_name,
380        } => handle_changelog(common, from, to, repository_url, update, file, version_name).await,
381        GitAI::ReleaseNotes {
382            common,
383            from,
384            to,
385            version_name,
386        } => handle_release_notes(common, from, to, repository_url, version_name).await,
387        GitAI::Pr {
388            common,
389            print,
390            from,
391            to,
392        } => handle_pr_command(common, print, from, to, repository_url).await,
393    }
394}
395
396/// Handle the `Pr` command
397pub async fn handle_pr_command(
398    common: CommonParams,
399    print: bool,
400    from: Option<String>,
401    to: Option<String>,
402    repository_url: Option<String>,
403) -> anyhow::Result<()> {
404    debug!(
405        "Handling 'pr' command with common: {common:?}, print: {print}, from: {from:?}, to: {to:?}"
406    );
407    commit::handle_pr_command(common, print, repository_url, from, to).await
408}