oxi-cli 0.6.19

Terminal-based AI coding assistant — multi-provider, streaming-first, extensible
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
//! Git utilities for version control operations
//!
//! Provides utilities for interacting with git repositories,
//! including checkpoints, diffs, and log retrieval.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::SystemTime;

/// Git commit information
#[derive(Debug, Clone)]
pub struct GitCommit {
/// pub.
    pub sha: String,
/// pub.
    pub short_sha: String,
/// pub.
    pub message: String,
/// pub.
    pub author: String,
/// pub.
    pub timestamp: SystemTime,
}

/// Git log entry
#[derive(Debug, Clone)]
pub struct GitLogEntry {
/// pub.
    pub commit: GitCommit,
/// pub.
    pub branch: Option<String>,
}

/// Git diff result
#[derive(Debug, Clone)]
pub struct GitDiff {
/// pub.
    pub staged: String,
/// pub.
    pub unstaged: String,
/// pub.
    pub untracked: String,
}

/// Git status
#[derive(Debug, Clone)]
pub struct GitStatus {
/// pub.
    pub is_repo: bool,
/// pub.
    pub branch: Option<String>,
/// pub.
    pub is_dirty: bool,
/// pub.
    pub staged_files: Vec<String>,
/// pub.
    pub modified_files: Vec<String>,
/// pub.
    pub untracked_files: Vec<String>,
}

/// Check if a directory is a git repository
pub fn is_git_repo(dir: &Path) -> bool {
    find_git_root(dir).is_some()
}

/// Find the git root directory by walking up from a path
pub fn find_git_root(path: &Path) -> Option<PathBuf> {
    let mut current = path.to_path_buf();

    loop {
        let git_dir = current.join(".git");
        if git_dir.exists() {
            return Some(current);
        }

        if git_dir.is_file() {
            if let Ok(content) = std::fs::read_to_string(&git_dir) {
                if content.starts_with("gitdir: ") {
                    let gitdir_path = content.trim_start_matches("gitdir: ").trim();
                    if let Ok(main_git) = PathBuf::from(gitdir_path).canonicalize() {
                        if let Some(main_dir) = main_git.parent() {
                            return Some(main_dir.to_path_buf());
                        }
                    }
                }
            }
            return Some(current);
        }

        current = match current.parent() {
            Some(parent) => parent.to_path_buf(),
            None => return None,
        };

        if current.to_string_lossy() == "/" {
            return None;
        }
    }
}

/// Get the git root for a given directory
pub fn get_git_root(cwd: &Path) -> PathBuf {
    find_git_root(cwd).unwrap_or_else(|| cwd.to_path_buf())
}

/// Run a git command
fn run_git_command(repo_dir: &Path, args: &[&str]) -> Result<String, String> {
    let output = Command::new("git")
        .args(["-C", repo_dir.to_string_lossy().as_ref()])
        .args(args)
        .output()
        .map_err(|e| format!("Failed to run git: {}", e))?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(format!("Git command failed: {}", stderr))
    }
}

/// Get the current branch name
pub fn get_current_branch(repo_dir: &Path) -> Option<String> {
    run_git_command(repo_dir, &["symbolic-ref", "--quiet", "--short", "HEAD"])
        .ok()
        .filter(|b| !b.is_empty())
}

/// Check if the repository is in detached HEAD state
pub fn is_detached_head(repo_dir: &Path) -> bool {
    if let Ok(head) = run_git_command(repo_dir, &["rev-parse", "--abbrev-ref", "HEAD"]) {
        head == "HEAD"
    } else {
        false
    }
}

/// Create a checkpoint commit
pub fn git_checkpoint(repo_dir: &Path, message: Option<&str>) -> Result<String, String> {
    run_git_command(repo_dir, &["add", "-A"])?;

    let status = run_git_command(repo_dir, &["status", "--porcelain"])?;
    if status.trim().is_empty() {
        return Err("No changes to checkpoint".to_string());
    }

    let timestamp = chrono::Utc::now();
    let default_msg = format!("Checkpoint: {}", timestamp.format("%Y-%m-%d %H:%M:%S UTC"));
    let msg = message.unwrap_or(&default_msg);

    run_git_command(repo_dir, &["commit", "-m", msg])?;
    run_git_command(repo_dir, &["rev-parse", "--short", "HEAD"])
}

/// Get the git diff output
pub fn git_diff(repo_dir: &Path, diff_type: &str) -> Result<String, String> {
    match diff_type {
        "staged" => run_git_command(repo_dir, &["diff", "--cached"]),
        "unstaged" => run_git_command(repo_dir, &["diff"]),
        "untracked" => run_git_command(repo_dir, &["ls-files", "--others", "--exclude-standard"]),
        "all" => {
            let staged = run_git_command(repo_dir, &["diff", "--cached"]).unwrap_or_default();
            let unstaged = run_git_command(repo_dir, &["diff"]).unwrap_or_default();
            let untracked =
                run_git_command(repo_dir, &["ls-files", "--others", "--exclude-standard"])
                    .unwrap_or_default();
            Ok(format!(
                "=== STAGED ===\n{}\n\n=== UNSTAGED ===\n{}\n\n=== UNTRACKED ===\n{}",
                staged, unstaged, untracked
            ))
        }
        _ => Err(format!("Unknown diff type: {}", diff_type)),
    }
}

/// Get the git log
pub fn git_log(repo_dir: &Path, count: usize) -> Result<Vec<GitLogEntry>, String> {
    let format_str = "%H|%h|%s|%an|%ae|%at";
    let output = run_git_command(
        repo_dir,
        &[
            "log",
            &format!("-{}", count),
            &format!("--format={}", format_str),
            "--all",
        ],
    )?;

    let branch = get_current_branch(repo_dir);

    let entries: Vec<GitLogEntry> = output
        .lines()
        .filter_map(|line| {
            let parts: Vec<&str> = line.split('|').collect();
            if parts.len() < 6 {
                return None;
            }

            let timestamp = parts[5]
                .parse::<i64>()
                .ok()
                .and_then(|t| {
                    SystemTime::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(t as u64))
                })
                .unwrap_or(SystemTime::UNIX_EPOCH);

            Some(GitLogEntry {
                commit: GitCommit {
                    sha: parts[0].to_string(),
                    short_sha: parts[1].to_string(),
                    message: parts[2].to_string(),
                    author: parts[3].to_string(),
                    timestamp,
                },
                branch: branch.clone(),
            })
        })
        .collect();

    Ok(entries)
}

/// Restore a file or path to a specific commit
pub fn git_restore(repo_dir: &Path, sha: &str, path: Option<&str>) -> Result<(), String> {
    let target = if sha.starts_with("HEAD~") || sha.starts_with("HEAD^") || sha.contains('~') {
        sha.to_string()
    } else {
        run_git_command(repo_dir, &["rev-parse", "--verify", sha])?;
        sha.to_string()
    };

    let path_arg = path.unwrap_or(".");
    run_git_command(repo_dir, &["checkout", &target, "--", path_arg])?;
    Ok(())
}

/// Get git status
pub fn git_status(repo_dir: &Path) -> Result<GitStatus, String> {
    let is_repo = is_git_repo(repo_dir);
    if !is_repo {
        return Ok(GitStatus {
            is_repo: false,
            branch: None,
            is_dirty: false,
            staged_files: vec![],
            modified_files: vec![],
            untracked_files: vec![],
        });
    }

    let branch = get_current_branch(repo_dir);
    let status_output = run_git_command(repo_dir, &["status", "--porcelain"])?;

    let mut staged_files = Vec::new();
    let mut modified_files = Vec::new();
    let mut untracked_files = Vec::new();

    for line in status_output.lines() {
        if line.len() < 3 {
            continue;
        }
        let index_status = line.chars().next().unwrap_or(' ');
        let worktree_status = line.chars().nth(1).unwrap_or(' ');
        let filename = line[3..].to_string();

        if index_status == '?' && worktree_status == '?' {
            untracked_files.push(filename.clone());
        } else if index_status != ' ' && index_status != '?' {
            staged_files.push(filename.clone());
        }
        if worktree_status != ' ' && worktree_status != '?' {
            if !staged_files.contains(&filename) {
                modified_files.push(filename);
            }
        }
    }

    let is_dirty =
        !staged_files.is_empty() || !modified_files.is_empty() || !untracked_files.is_empty();

    Ok(GitStatus {
        is_repo: true,
        branch,
        is_dirty,
        staged_files,
        modified_files,
        untracked_files,
    })
}

/// Get the number of commits ahead/behind a remote branch
pub fn git_ahead_behind(repo_dir: &Path) -> Result<(usize, usize), String> {
    let current = get_current_branch(repo_dir).ok_or("Not on a branch")?;
    // Build upstream ref string: branch@ {u}
    let upstream_ref = format!("{}@{{u}}", current);
    let remote_branch =
        run_git_command(repo_dir, &["rev-parse", "--abbrev-ref", &upstream_ref]).ok();

    let remote_branch = match remote_branch {
        Some(rb) => rb,
        None => return Ok((0, 0)),
    };

    let base = run_git_command(repo_dir, &["merge-base", &current, &remote_branch])?;
    let ahead = run_git_command(
        repo_dir,
        &["log", &format!("{}..{}", base, current), "--oneline"],
    )
    .unwrap_or_default();
    let behind = run_git_command(
        repo_dir,
        &["log", &format!("{}..{}", current, base), "--oneline"],
    )
    .unwrap_or_default();

    Ok((ahead.lines().count(), behind.lines().count()))
}

/// Get the tags that contain a specific commit
pub fn git_tags_containing(repo_dir: &Path, sha: &str) -> Result<Vec<String>, String> {
    let output = run_git_command(repo_dir, &["tag", "--contains", sha])?;
    Ok(output.lines().map(|s| s.to_string()).collect())
}

/// Get the last modified date of a file in the repo
pub fn git_file_last_modified(repo_dir: &Path, file_path: &str) -> Result<SystemTime, String> {
    let output = run_git_command(repo_dir, &["log", "-1", "--format=%at", "--", file_path])?;

    let timestamp: i64 = output.trim().parse().map_err(|_| "Invalid timestamp")?;
    SystemTime::UNIX_EPOCH
        .checked_add(std::time::Duration::from_secs(timestamp as u64))
        .ok_or_else(|| "Invalid timestamp".to_string())
}

/// Check if a file has uncommitted changes
pub fn git_file_is_modified(repo_dir: &Path, file_path: &str) -> Result<bool, String> {
    let status = run_git_command(repo_dir, &["status", "--porcelain", "--", file_path])?;
    Ok(!status.trim().is_empty())
}

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

    fn test_repo_path() -> PathBuf {
        env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
    }

    #[test]
    fn test_is_git_repo() {
        let result = is_git_repo(&test_repo_path());
        assert!(result == true || result == false);
    }

    #[test]
    fn test_find_git_root() {
        let result = find_git_root(&test_repo_path());
        assert!(result.is_some());
    }

    #[test]
    fn test_get_git_root() {
        let root = get_git_root(&test_repo_path());
        assert!(root.exists());
    }

    #[test]
    fn test_git_status() {
        let status = git_status(&test_repo_path());
        assert!(status.is_ok());
        let status = status.unwrap();
        assert!(!status.is_repo || status.branch.is_some() || !status.branch.is_none());
    }

    #[test]
    fn test_git_log_returns_vec() {
        let result = git_log(&test_repo_path(), 5);
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_git_diff_invalid_type() {
        let result = git_diff(&test_repo_path(), "invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_git_checkpoint_no_changes() {
        let result = git_checkpoint(&test_repo_path(), None);
        assert!(result.is_ok() || result == Err("No changes to checkpoint".to_string()));
    }

    #[test]
    fn test_git_file_last_modified() {
        let result = git_file_last_modified(&test_repo_path(), "Cargo.toml");
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_git_file_is_modified() {
        let result = git_file_is_modified(&test_repo_path(), "Cargo.toml");
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn test_git_tags_containing() {
        let result = git_tags_containing(&test_repo_path(), "HEAD");
        assert!(result.is_ok());
    }
}