git-cli 0.4.1

A CLI tool that translates natural-language task descriptions into git commands using a local Ollama LLM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use colored::Colorize;
use regex::Regex;
use std::collections::HashMap;
use std::process::Command;

pub struct ParsedOutput {
    pub lines: Vec<OutputLine>,
}

pub enum OutputLine {
    Comment(String),
    GitCommand(String),
    Other(String),
}

const DESTRUCTIVE_PATTERNS: &[&str] = &[
    "push --force",
    "push -f ",
    "reset --hard",
    "clean -f",
    "clean -df",
    "clean -fd",
    "clean -xf",
    "branch -D ",
];

pub fn parse_response(response: &str) -> ParsedOutput {
    let cleaned = sanitize_response(response);

    let lines = cleaned
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|line| {
            let trimmed = line.trim();
            if trimmed.starts_with('#') {
                OutputLine::Comment(trimmed.to_string())
            } else if trimmed.starts_with("git ") || trimmed.starts_with("gh ") {
                if is_safe_command(trimmed) {
                    OutputLine::GitCommand(trimmed.to_string())
                } else {
                    OutputLine::Other(format!("[BLOCKED] {trimmed}"))
                }
            } else {
                OutputLine::Other(trimmed.to_string())
            }
        })
        .collect();

    ParsedOutput { lines }
}

fn sanitize_response(response: &str) -> String {
    let mut result = response.to_string();

    result = result.replace("```bash", "");
    result = result.replace("```shell", "");
    result = result.replace("```sh", "");
    result = result.replace("```", "");

    let lines: Vec<String> = result
        .lines()
        .map(|line| {
            let trimmed = line.trim();
            if let Some(rest) = strip_numbering(trimmed) {
                rest.to_string()
            } else {
                trimmed.to_string()
            }
        })
        .collect();

    let joined = join_multiline_commands(&lines).join("\n");
    fix_case_globs(&joined)
}

fn fix_case_globs(cmd: &str) -> String {
    if let Ok(re) = Regex::new(r"([0-9a-f]{7,40})\)") {
        re.replace_all(cmd, "${1}*)").to_string()
    } else {
        cmd.to_string()
    }
}

fn join_multiline_commands(lines: &[String]) -> Vec<String> {
    let mut merged: Vec<String> = Vec::new();
    let mut accumulator = String::new();
    let mut open_single = false;
    let mut open_double = false;

    for line in lines {
        if accumulator.is_empty() {
            if line.trim().starts_with('#') || line.trim().is_empty() {
                merged.push(line.clone());
                continue;
            }
            accumulator = line.clone();
        } else {
            accumulator.push(' ');
            accumulator.push_str(line.trim());
        }

        open_single = false;
        open_double = false;
        for ch in accumulator.chars() {
            match ch {
                '\'' if !open_double => open_single = !open_single,
                '"' if !open_single => open_double = !open_double,
                _ => {}
            }
        }

        if !open_single && !open_double {
            merged.push(accumulator.clone());
            accumulator.clear();
        }
    }

    if !accumulator.is_empty() {
        merged.push(accumulator);
    }

    merged
}

fn strip_numbering(line: &str) -> Option<&str> {
    let bytes = line.as_bytes();
    let mut i = 0;

    while i < bytes.len() && bytes[i].is_ascii_digit() {
        i += 1;
    }
    if i == 0 {
        return None;
    }

    if i + 1 < bytes.len() && (bytes[i] == b'.' || bytes[i] == b')' || bytes[i] == b':') {
        let rest = &line[i + 1..];
        return Some(rest.trim_start());
    }

    let lower = line.to_lowercase();
    if lower.starts_with("step ") {
        if let Some(colon_pos) = line.find(':') {
            return Some(line[colon_pos + 1..].trim_start());
        }
    }

    None
}

fn is_safe_command(cmd: &str) -> bool {
    if !cmd.starts_with("git ") && !cmd.starts_with("gh ") {
        return false;
    }

    if cmd.starts_with("gh ") {
        return true;
    }

    // Check for injection patterns only OUTSIDE of quotes
    let unquoted = strip_quoted_sections(cmd);
    let injection_patterns = ["&&", "||", ";", "$(", "`", "|"];
    for pat in &injection_patterns {
        if unquoted.contains(pat) {
            return false;
        }
    }

    if let Some(n) = extract_head_offset(cmd) {
        let commit_count = get_commit_count();
        if n > commit_count {
            eprintln!(
                "  {} HEAD~{} but repo only has {} commit(s). Skipping.",
                "Warning:".yellow().bold(),
                n,
                commit_count
            );
            return false;
        }
    }

    if cmd.contains("git push") && cmd.contains(':') {
        let parts: Vec<&str> = cmd.split_whitespace().collect();
        if let Some(refspec) = parts.last() {
            if refspec.contains(':') && !refspec.contains("refs/tags/") {
                eprintln!(
                    "  {} Blocked push with refspec `{}`. Use `git push origin <branch>` and `gh pr create` instead.",
                    "Warning:".yellow().bold(),
                    refspec
                );
                return false;
            }
        }
    }

    if cmd.contains("rebase -i") || cmd.contains("rebase --interactive") {
        eprintln!(
            "  {} Blocked `rebase -i` (no interactive editor available). Use `git reset --soft` or `git filter-branch`.",
            "Warning:".yellow().bold(),
        );
        return false;
    }

    // Block commit with trailing bare hash references (LLM hallucination)
    if cmd.contains("git commit") {
        if let Ok(re) = Regex::new(r"[0-9a-f]{7,}\^?\s*$") {
            let after_message = if let Some(pos) = cmd.find("-m ") {
                let rest = &cmd[pos + 3..];
                // Skip past the quoted message
                if rest.starts_with('"') {
                    rest[1..].find('"').map(|end| &rest[end + 2..])
                } else if rest.starts_with('\'') {
                    rest[1..].find('\'').map(|end| &rest[end + 2..])
                } else {
                    rest.split_whitespace().nth(1).map(|s| s)
                }
            } else {
                None
            };

            if let Some(trailing) = after_message {
                let trailing = trailing.trim();
                if !trailing.is_empty() && re.is_match(trailing) {
                    eprintln!(
                        "  {} Malformed commit command with trailing hash. Skipping.",
                        "Warning:".yellow().bold(),
                    );
                    return false;
                }
            }
        }
    }

    true
}

fn strip_quoted_sections(cmd: &str) -> String {
    let mut result = String::new();
    let mut in_single = false;
    let mut in_double = false;

    for ch in cmd.chars() {
        match ch {
            '\'' if !in_double => {
                in_single = !in_single;
            }
            '"' if !in_single => {
                in_double = !in_double;
            }
            _ if !in_single && !in_double => {
                result.push(ch);
            }
            _ => {}
        }
    }
    result
}

fn extract_head_offset(cmd: &str) -> Option<u32> {
    Regex::new(r"HEAD~(\d+)")
        .ok()?
        .captures(cmd)
        .and_then(|c| c.get(1))
        .and_then(|m| m.as_str().parse().ok())
}

fn get_commit_count() -> u32 {
    Command::new("git")
        .args(["rev-list", "--count", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
        .unwrap_or(0)
}

fn shell_split(cmd: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut in_single_quote = false;
    let mut in_double_quote = false;

    for ch in cmd.chars() {
        match ch {
            '\'' if !in_double_quote => {
                in_single_quote = !in_single_quote;
            }
            '"' if !in_single_quote => {
                in_double_quote = !in_double_quote;
            }
            ' ' if !in_single_quote && !in_double_quote => {
                if !current.is_empty() {
                    parts.push(current.clone());
                    current.clear();
                }
            }
            _ => {
                current.push(ch);
            }
        }
    }
    if !current.is_empty() {
        parts.push(current);
    }

    parts
}

pub fn has_destructive_commands(parsed: &ParsedOutput) -> bool {
    parsed.lines.iter().any(|line| {
        if let OutputLine::GitCommand(cmd) = line {
            DESTRUCTIVE_PATTERNS.iter().any(|p| cmd.contains(p))
        } else {
            false
        }
    })
}

pub fn display(parsed: &ParsedOutput) {
    println!();
    for line in &parsed.lines {
        match line {
            OutputLine::Comment(c) => println!("  {}", c.dimmed()),
            OutputLine::GitCommand(cmd) => {
                if DESTRUCTIVE_PATTERNS.iter().any(|p| cmd.contains(p)) {
                    println!("  {} {}", "âš ".yellow(), cmd.red().bold());
                } else {
                    println!("  {}", cmd.green().bold());
                }
            }
            OutputLine::Other(text) => println!("  {}", text.yellow()),
        }
    }
    println!();
}

pub fn execute_commands(parsed: &ParsedOutput, force: bool) -> Result<(), String> {
    let commands: Vec<&str> = parsed
        .lines
        .iter()
        .filter_map(|l| match l {
            OutputLine::GitCommand(cmd) => Some(cmd.as_str()),
            _ => None,
        })
        .collect();

    if commands.is_empty() {
        println!("{}", "No git commands found to execute.".yellow());
        return Ok(());
    }

    if !force && has_destructive_commands(parsed) {
        eprintln!(
            "  {} Contains destructive commands. Use {} to override.",
            "Blocked:".red().bold(),
            "--force".bold()
        );
        return Ok(());
    }

    let has_creates = commands.iter().any(|c| c.starts_with("gh pr create"));
    let has_merges = commands.iter().any(|c| c.starts_with("gh pr merge"));

    let mut pr_number_map: HashMap<u32, u32> = HashMap::new();
    let mut created_prs: Vec<u32> = Vec::new();

    let predicted_merge_numbers: Vec<u32> = if has_creates && has_merges {
        let open_prs = get_open_pr_numbers();
        commands
            .iter()
            .filter_map(|c| extract_pr_merge_number(c))
            .filter(|n| !open_prs.contains(n))
            .collect()
    } else {
        Vec::new()
    };

    let mut failed_cmds: Vec<String> = Vec::new();

    for cmd_str in commands {
        let actual_cmd = if cmd_str.starts_with("gh pr merge") {
            if let Some(n) = extract_pr_merge_number(cmd_str) {
                if let Some(&actual) = pr_number_map.get(&n) {
                    let replaced = cmd_str.replacen(&n.to_string(), &actual.to_string(), 1);
                    eprintln!(
                        "  {} PR #{} → #{} (actual)",
                        "Remapped:".yellow().bold(),
                        n,
                        actual
                    );
                    replaced
                } else {
                    cmd_str.to_string()
                }
            } else {
                cmd_str.to_string()
            }
        } else {
            cmd_str.to_string()
        };

        println!("  {} {}", "Running:".cyan().bold(), actual_cmd);

        let parts = shell_split(&actual_cmd);
        if parts.is_empty() {
            continue;
        }

        let (output, actual_cmd) = run_with_flag_retry(&actual_cmd)?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        if !stdout.trim().is_empty() {
            println!("{stdout}");
        }
        if !stderr.trim().is_empty() {
            eprintln!("{stderr}");
        }

        if !output.status.success() {
            let is_gh_merge = actual_cmd.starts_with("gh pr merge");
            let is_gh_create = actual_cmd.starts_with("gh pr create");

            if is_gh_merge {
                let stderr_str = stderr.to_string();
                if stderr_str.contains("not allowed") || stderr_str.contains("not mergeable") {
                    if retry_merge_with_fallback(&actual_cmd).is_some() {
                        continue;
                    }
                }
                eprintln!(
                    "  {} `{}` failed (exit code {}). Continuing with remaining commands...",
                    "Skipped:".yellow().bold(),
                    actual_cmd,
                    output.status.code().unwrap_or(-1)
                );
                failed_cmds.push(actual_cmd);
                continue;
            }

            if is_gh_create {
                eprintln!(
                    "  {} `{}` failed (exit code {}). Continuing with remaining commands...",
                    "Skipped:".yellow().bold(),
                    actual_cmd,
                    output.status.code().unwrap_or(-1)
                );
                failed_cmds.push(actual_cmd);
                continue;
            }

            let is_push_to_existing = actual_cmd.starts_with("git push")
                && (stderr.contains("non-fast-forward") || stderr.contains("already exists"));
            if is_push_to_existing {
                eprintln!(
                    "  {} Push failed but branch likely exists on remote. Continuing...",
                    "Note:".yellow().bold(),
                );
                continue;
            }

            return Err(format!(
                "Command `{actual_cmd}` failed with exit code {}",
                output.status.code().unwrap_or(-1)
            ));
        }

        if cmd_str.starts_with("gh pr create") {
            if let Some(pr_num) = parse_pr_number_from_output(&stdout) {
                let idx = created_prs.len();
                created_prs.push(pr_num);
                if let Some(&predicted) = predicted_merge_numbers.get(idx) {
                    pr_number_map.insert(predicted, pr_num);
                }
            }
        }
    }

    if failed_cmds.is_empty() {
        println!("  {}", "All commands completed successfully.".green().bold());
    } else {
        eprintln!();
        eprintln!(
            "  {} {} command(s) failed:",
            "Summary:".yellow().bold(),
            failed_cmds.len()
        );
        for cmd in &failed_cmds {
            eprintln!("    {} {}", "✗".red(), cmd);
        }
        eprintln!();
        return Err(format!("{} command(s) failed (see above)", failed_cmds.len()));
    }

    Ok(())
}

fn run_with_flag_retry(cmd: &str) -> Result<(std::process::Output, String), String> {
    let mut current_cmd = cmd.to_string();
    for _ in 0..3 {
        let parts = shell_split(&current_cmd);
        if parts.is_empty() {
            return Err("Empty command".to_string());
        }
        let output = Command::new(&parts[0])
            .args(&parts[1..])
            .output()
            .map_err(|e| format!("Failed to run `{current_cmd}`: {e}"))?;

        if output.status.success() {
            return Ok((output, current_cmd));
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        if let Some(bad_flag) = extract_bad_flag(&stderr) {
            eprintln!(
                "  {} Removing hallucinated flag `{}`",
                "Fix:".yellow().bold(),
                bad_flag
            );
            current_cmd = remove_flag(&current_cmd, &bad_flag);
            println!("  {} {}", "Retrying:".cyan().bold(), current_cmd);
        } else {
            return Ok((output, current_cmd));
        }
    }
    let parts = shell_split(&current_cmd);
    let output = Command::new(&parts[0])
        .args(&parts[1..])
        .output()
        .map_err(|e| format!("Failed to run `{current_cmd}`: {e}"))?;
    Ok((output, current_cmd))
}

fn extract_bad_flag(stderr: &str) -> Option<String> {
    for line in stderr.lines() {
        let line = line.trim();
        if line.contains("unrecognized argument:") {
            return line.split("unrecognized argument:").nth(1)
                .map(|s| s.trim().to_string());
        }
        if line.contains("unknown option:") {
            return line.split("unknown option:").nth(1)
                .map(|s| s.trim().trim_matches('\'').to_string());
        }
        if line.contains("unknown switch") {
            if let Some(flag) = line.split('`').nth(1) {
                return Some(flag.trim_matches('\'').to_string());
            }
        }
    }
    None
}

fn remove_flag(cmd: &str, flag: &str) -> String {
    let flag_with_space = format!(" {}", flag);
    let result = cmd.replace(&flag_with_space, "");
    if result == cmd {
        cmd.replace(flag, "").replace("  ", " ")
    } else {
        result
    }
}

fn retry_merge_with_fallback(original_cmd: &str) -> Option<()> {
    let strategies = ["--squash", "--rebase"];
    for strategy in &strategies {
        let retry_cmd = original_cmd
            .replace("--merge", strategy);
        eprintln!(
            "  {} Retrying with `{}`...",
            "Fallback:".cyan().bold(),
            strategy
        );
        let parts = shell_split(&retry_cmd);
        if parts.is_empty() {
            continue;
        }
        let output = Command::new(&parts[0])
            .args(&parts[1..])
            .output()
            .ok()?;
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        if !stdout.trim().is_empty() {
            println!("{stdout}");
        }
        if !stderr.trim().is_empty() {
            eprintln!("{stderr}");
        }
        if output.status.success() {
            eprintln!(
                "  {} Merged successfully with `{}`",
                "OK:".green().bold(),
                strategy
            );
            return Some(());
        }
    }
    None
}

fn extract_pr_merge_number(cmd: &str) -> Option<u32> {
    let parts: Vec<&str> = cmd.split_whitespace().collect();
    if parts.len() >= 4 && parts[0] == "gh" && parts[1] == "pr" && parts[2] == "merge" {
        parts[3].parse().ok()
    } else {
        None
    }
}

fn parse_pr_number_from_output(output: &str) -> Option<u32> {
    for line in output.lines() {
        let trimmed = line.trim();
        if trimmed.contains("/pull/") {
            return trimmed.rsplit('/').next()?.parse().ok();
        }
    }
    None
}

fn get_open_pr_numbers() -> Vec<u32> {
    Command::new("gh")
        .args([
            "pr", "list", "--state", "open", "--json", "number",
            "--template", "{{range .}}{{.number}}\n{{end}}",
        ])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter_map(|l| l.trim().parse().ok())
                .collect()
        })
        .unwrap_or_default()
}