patina-ai 0.23.0

Context orchestration for AI development - captures and evolves patterns over time
Documentation
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
//! Low-level git operations

use anyhow::{Context, Result};
use std::process::Command;

/// Check if current directory is a git repository
pub fn is_git_repo() -> Result<bool> {
    let output = Command::new("git")
        .args(["rev-parse", "--git-dir"])
        .output()
        .context("Failed to check if directory is a git repository")?;

    Ok(output.status.success())
}

/// Check if the repository has any commits
pub fn has_commits() -> Result<bool> {
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .context("Failed to check for commits")?;

    Ok(output.status.success())
}

/// Get the current branch name
pub fn current_branch() -> Result<String> {
    let output = Command::new("git")
        .args(["branch", "--show-current"])
        .output()
        .context("Failed to get current branch")?;

    if !output.status.success() {
        anyhow::bail!("Failed to get current branch");
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Get the default branch name (main or master)
pub fn default_branch() -> Result<String> {
    // Try to get from remote
    let output = Command::new("git")
        .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            let branch = String::from_utf8_lossy(&output.stdout);
            if let Some(name) = branch.trim().strip_prefix("refs/remotes/origin/") {
                return Ok(name.to_string());
            }
        }
    }

    // Fallback: check if main exists, otherwise master
    if branch_exists("main")? {
        Ok("main".to_string())
    } else if branch_exists("master")? {
        Ok("master".to_string())
    } else {
        // Last resort: use current branch
        current_branch()
    }
}

/// Check if a branch exists
pub fn branch_exists(name: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["rev-parse", "--verify", &format!("refs/heads/{}", name)])
        .output()
        .context("Failed to check if branch exists")?;

    Ok(output.status.success())
}

/// Check if working tree is clean
pub fn is_clean() -> Result<bool> {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .context("Failed to check git status")?;

    Ok(output.stdout.is_empty())
}

/// Count modified files
pub fn status_count() -> Result<usize> {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .context("Failed to get git status")?;

    let count = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter(|line| !line.is_empty())
        .count();

    Ok(count)
}

/// Get number of commits current branch is behind another
pub fn commits_behind(current: &str, other: &str) -> Result<usize> {
    let output = Command::new("git")
        .args(["rev-list", "--count", &format!("{}..{}", current, other)])
        .output()
        .context("Failed to count commits behind")?;

    if !output.status.success() {
        return Ok(0);
    }

    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    count_str.parse().context("Failed to parse commit count")
}

/// Create and checkout a new branch
pub fn checkout_new_branch(name: &str, from: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["checkout", "-b", name, from])
        .output()
        .context("Failed to create and checkout branch")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to create branch: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Rename a branch
pub fn branch_rename(old: &str, new: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["branch", "-m", old, new])
        .output()
        .context("Failed to rename branch")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to rename branch: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Rename the current branch (works even in empty repos with no commits)
pub fn rename_current_branch(new_name: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["branch", "-m", new_name])
        .output()
        .context("Failed to rename current branch")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to rename current branch: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Get remote URL
pub fn remote_url(remote: &str) -> Result<String> {
    let output = Command::new("git")
        .args(["remote", "get-url", remote])
        .output()
        .context("Failed to get remote URL")?;

    if !output.status.success() {
        anyhow::bail!("Remote '{}' not found", remote);
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Check if a remote URL exists in any remote
pub fn has_remote(url: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["remote", "-v"])
        .output()
        .context("Failed to list remotes")?;

    let remotes = String::from_utf8_lossy(&output.stdout);
    Ok(remotes.contains(url))
}

/// Add a git remote
pub fn add_remote(name: &str, url: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["remote", "add", name, url])
        .output()
        .context("Failed to add remote")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to add remote: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Get repository name from remote URL
pub fn repo_name() -> Result<String> {
    let url = remote_url("origin")?;
    let (_, repo) = parse_github_url(&url)?;
    Ok(repo)
}

/// Parse GitHub URL into (owner, repo)
pub fn parse_github_url(url: &str) -> Result<(String, String)> {
    // Handle both SSH and HTTPS formats
    // git@github.com:owner/repo.git
    // https://github.com/owner/repo.git

    let cleaned = url
        .trim()
        .strip_suffix(".git")
        .unwrap_or(url)
        .replace("git@github.com:", "")
        .replace("https://github.com/", "");

    let parts: Vec<&str> = cleaned.split('/').collect();
    if parts.len() >= 2 {
        Ok((parts[0].to_string(), parts[1].to_string()))
    } else {
        anyhow::bail!("Invalid GitHub URL format: {}", url)
    }
}

/// Stage all changes
pub fn add_all() -> Result<()> {
    let output = Command::new("git")
        .args(["add", "."])
        .output()
        .context("Failed to run git add")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Failed to stage changes: {}", stderr.trim());
    }

    Ok(())
}

/// Stage specific paths (safer for repos with nested git directories)
///
/// Skips paths that don't exist or are gitignored.
pub fn add_paths(paths: &[&str]) -> Result<()> {
    for path in paths {
        // Skip paths that don't exist
        if !std::path::Path::new(path).exists() {
            continue;
        }

        // Skip paths that are gitignored
        if is_ignored(path) {
            continue;
        }

        let output = Command::new("git")
            .args(["add", path])
            .output()
            .context(format!("Failed to run git add {}", path))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to stage {}: {}", path, stderr.trim());
        }
    }

    Ok(())
}

/// Check if a path is ignored by .gitignore
fn is_ignored(path: &str) -> bool {
    Command::new("git")
        .args(["check-ignore", "-q", path])
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

/// Check if there are staged changes ready to commit
pub fn has_staged_changes() -> Result<bool> {
    let output = Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .output()
        .context("Failed to check staged changes")?;

    // Exit code 1 means there ARE differences (staged changes exist)
    Ok(!output.status.success())
}

/// Create a commit
pub fn commit(message: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["commit", "-m", message])
        .output()
        .context("Failed to create commit")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to create commit: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Stash changes with a named message (includes untracked files)
pub fn stash_push(message: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["stash", "push", "--include-untracked", "-m", message])
        .output()
        .context("Failed to stash changes")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Failed to stash changes: {}", stderr);
    }

    Ok(())
}

/// Checkout an existing branch
pub fn checkout(branch: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["checkout", branch])
        .output()
        .context("Failed to checkout branch")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to checkout {}: {}",
            branch,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Rebase current branch onto another
/// Returns Ok(true) if rebase succeeded, Ok(false) if conflicts, Err on other failure
pub fn rebase(onto: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["rebase", onto])
        .output()
        .context("Failed to rebase")?;

    if output.status.success() {
        Ok(true)
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("CONFLICT") || stderr.contains("could not apply") {
            Ok(false) // Conflicts - caller should handle
        } else {
            anyhow::bail!("Failed to rebase onto {}: {}", onto, stderr);
        }
    }
}

/// Abort an in-progress rebase
pub fn rebase_abort() -> Result<()> {
    let output = Command::new("git")
        .args(["rebase", "--abort"])
        .output()
        .context("Failed to abort rebase")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to abort rebase: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Get the full SHA of HEAD
pub fn head_sha() -> Result<String> {
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .context("Failed to get HEAD SHA")?;

    if !output.status.success() {
        anyhow::bail!("Failed to get HEAD SHA (no commits?)");
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Get the short SHA of HEAD
pub fn short_sha() -> Result<String> {
    let output = Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .context("Failed to get short SHA")?;

    if !output.status.success() {
        anyhow::bail!("Failed to get short SHA (no commits?)");
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Check if a tag exists
pub fn tag_exists(name: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["tag", "-l", name])
        .output()
        .context("Failed to check if tag exists")?;

    let tags = String::from_utf8_lossy(&output.stdout);
    Ok(tags.trim() == name)
}

/// Check if current branch has an upstream tracking branch
pub fn has_upstream() -> Result<bool> {
    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "@{upstream}"])
        .output()
        .context("Failed to check for upstream")?;

    Ok(output.status.success())
}

/// Get number of commits current branch is ahead of its upstream
pub fn commits_ahead() -> Result<usize> {
    let output = Command::new("git")
        .args(["rev-list", "--count", "@{upstream}..HEAD"])
        .output()
        .context("Failed to count commits ahead")?;

    if !output.status.success() {
        return Ok(0);
    }

    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(count_str.parse().unwrap_or(0))
}

/// Get number of commits current branch is behind its upstream
pub fn commits_behind_upstream() -> Result<usize> {
    let output = Command::new("git")
        .args(["rev-list", "--count", "HEAD..@{upstream}"])
        .output()
        .context("Failed to count commits behind")?;

    if !output.status.success() {
        return Ok(0);
    }

    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(count_str.parse().unwrap_or(0))
}

/// Check if current branch has diverged from upstream (both ahead and behind)
pub fn is_diverged() -> Result<bool> {
    if !has_upstream()? {
        return Ok(false);
    }

    let ahead = commits_ahead()?;
    let behind = commits_behind_upstream()?;

    Ok(ahead > 0 && behind > 0)
}

/// Fetch from remote
pub fn fetch(remote: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["fetch", remote])
        .output()
        .context("Failed to fetch from remote")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to fetch {}: {}",
            remote,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Create an annotated git tag
pub fn create_tag(name: &str, message: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["tag", "-a", name, "-m", message])
        .output()
        .context("Failed to create git tag")?;

    if !output.status.success() {
        anyhow::bail!(
            "Failed to create tag '{}': {}",
            name,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    Ok(())
}

/// Count commits from a given SHA (exclusive) to HEAD
pub fn commits_since_count(since_sha: &str) -> Result<usize> {
    let range = format!("{}..HEAD", since_sha);
    let output = Command::new("git")
        .args(["rev-list", "--count", &range])
        .output()
        .context("Failed to count commits since SHA")?;

    if !output.status.success() {
        return Ok(0);
    }

    let count_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(count_str.parse().unwrap_or(0))
}

/// Get relative time of last commit (e.g., "2 hours ago")
pub fn last_commit_relative_time() -> Result<String> {
    let output = Command::new("git")
        .args(["log", "-1", "--format=%ar"])
        .output()
        .context("Failed to get last commit time")?;

    if !output.status.success() {
        anyhow::bail!("No commits found");
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Get the subject line of the last commit
pub fn last_commit_message() -> Result<String> {
    let output = Command::new("git")
        .args(["log", "-1", "--format=%s"])
        .output()
        .context("Failed to get last commit message")?;

    if !output.status.success() {
        anyhow::bail!("No commits found");
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Get the diff stat summary line (e.g., "3 files changed, 45 insertions(+), 10 deletions(-)")
pub fn diff_stat_summary() -> Result<String> {
    let output = Command::new("git")
        .args(["diff", "--stat"])
        .output()
        .context("Failed to get diff stat")?;

    let stat = String::from_utf8_lossy(&output.stdout);
    // Last non-empty line is the summary
    Ok(stat
        .lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("")
        .trim()
        .to_string())
}

/// Get git status in porcelain format (machine-parseable)
pub fn status_porcelain() -> Result<String> {
    let output = Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .context("Failed to get git status")?;

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Get list of files changed between a ref and HEAD
pub fn files_changed_since(from_ref: &str) -> Result<Vec<String>> {
    let range = format!("{}..HEAD", from_ref);
    let output = Command::new("git")
        .args(["diff", "--name-only", &range])
        .output()
        .context("Failed to get files changed since ref")?;

    if !output.status.success() {
        return Ok(vec![]);
    }

    Ok(String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter(|l| !l.is_empty())
        .map(|l| l.to_string())
        .collect())
}

/// Get recent commits as oneline format
pub fn log_oneline(count: usize) -> Result<String> {
    let output = Command::new("git")
        .args(["log", "--oneline", &format!("-{}", count)])
        .output()
        .context("Failed to get recent commits")?;

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_github_url_ssh() {
        let url = "git@github.com:dustproject/dust.git";
        let (owner, repo) = parse_github_url(url).unwrap();
        assert_eq!(owner, "dustproject");
        assert_eq!(repo, "dust");
    }

    #[test]
    fn test_parse_github_url_https() {
        let url = "https://github.com/dustproject/dust.git";
        let (owner, repo) = parse_github_url(url).unwrap();
        assert_eq!(owner, "dustproject");
        assert_eq!(repo, "dust");
    }
}