gitorii 0.1.4

A human-first Git client with simplified commands, snapshots, multi-platform mirrors and built-in secret scanning
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
// Extended Git operations for Torii
use git2::{Repository, BranchType};
use crate::error::Result;
use crate::core::GitRepo;
use std::process::Command;
use chrono::{DateTime, NaiveDateTime};

impl GitRepo {
    /// Show commit history
    pub fn log(
        &self,
        count: Option<usize>,
        oneline: bool,
        _graph: bool,
        author: Option<&str>,
        since: Option<&str>,
        until: Option<&str>,
        grep: Option<&str>,
        stat: bool,
    ) -> Result<()> {
        let mut revwalk = self.repository().revwalk()?;
        revwalk.push_head()?;

        let max_count = count.unwrap_or(10);
        let mut shown = 0;

        // Parse date filters
        let since_ts: Option<i64> = since.and_then(|s| {
            NaiveDateTime::parse_from_str(&format!("{} 00:00:00", s), "%Y-%m-%d %H:%M:%S")
                .ok()
                .map(|dt| dt.and_utc().timestamp())
        });
        let until_ts: Option<i64> = until.and_then(|s| {
            NaiveDateTime::parse_from_str(&format!("{} 23:59:59", s), "%Y-%m-%d %H:%M:%S")
                .ok()
                .map(|dt| dt.and_utc().timestamp())
        });

        println!("📜 Commit History:");
        println!();

        for oid in revwalk {
            if shown >= max_count {
                break;
            }

            let oid = oid?;
            let commit = self.repository().find_commit(oid)?;
            let ts = commit.time().seconds();

            // Author filter
            if let Some(filter) = author {
                let name = commit.author().name().unwrap_or("").to_lowercase();
                let email = commit.author().email().unwrap_or("").to_lowercase();
                let f = filter.to_lowercase();
                if !name.contains(&f) && !email.contains(&f) {
                    continue;
                }
            }

            // Date filters
            if let Some(s) = since_ts {
                if ts < s { continue; }
            }
            if let Some(u) = until_ts {
                if ts > u { continue; }
            }

            // Grep filter
            if let Some(pattern) = grep {
                let msg = commit.message().unwrap_or("");
                if !msg.to_lowercase().contains(&pattern.to_lowercase()) {
                    continue;
                }
            }

            if oneline {
                let short_id = &oid.to_string()[..7];
                let message = commit.message().unwrap_or("<no message>").lines().next().unwrap_or("");
                println!("  {} {}", short_id, message);
            } else {
                println!("  commit {}", oid);
                if let Some(author_name) = commit.author().name() {
                    println!("  Author: {}", author_name);
                }
                println!("  Date:   {}", chrono::DateTime::from_timestamp(ts, 0)
                    .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
                    .unwrap_or_else(|| "<unknown>".to_string()));
                println!();
                if let Some(msg) = commit.message() {
                    for line in msg.lines() {
                        println!("      {}", line);
                    }
                }
                println!();

                // Stat: show changed files count
                if stat {
                    if let Ok(parent) = commit.parent(0) {
                        let old_tree = parent.tree().ok();
                        let new_tree = commit.tree().ok();
                        if let (Some(old), Some(new)) = (old_tree, new_tree) {
                            let diff = self.repository().diff_tree_to_tree(Some(&old), Some(&new), None);
                            if let Ok(diff) = diff {
                                let stats = diff.stats()?;
                                println!("  {} files changed, {} insertions(+), {} deletions(-)",
                                    stats.files_changed(),
                                    stats.insertions(),
                                    stats.deletions()
                                );
                                println!();
                            }
                        }
                    }
                }
            }

            shown += 1;
        }

        Ok(())
    }

    /// Show reflog (HEAD movement history)
    pub fn show_reflog(&self, count: usize) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        let output = Command::new("git")
            .args(["reflog", "--format=%gd %gs %H %ci", &format!("-{}", count)])
            .current_dir(&repo_path)
            .output()?;

        if !output.status.success() {
            let err = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to read reflog: {}", err)
            ));
        }

        println!("📋 Reflog (HEAD movements):");
        println!();

        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            println!("  {}", line);
        }

        println!();
        println!("💡 Restore a state: torii save --reset <commit-hash> --reset-mode soft");

        Ok(())
    }

    /// Rebase with a pre-written todo file (no editor required)
    pub fn rebase_with_todo(&self, base: &str, todo_file: &std::path::Path) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();

        let todo_abs = todo_file.canonicalize().map_err(|_| {
            crate::error::ToriiError::InvalidConfig(
                format!("Todo file not found: {}", todo_file.display())
            )
        })?;

        println!("🔄 Rebasing from {} using todo file: {}", base, todo_abs.display());

        let editor = format!("cp {}", todo_abs.display());
        let status = std::process::Command::new("git")
            .args(["rebase", "-i", base])
            .env("GIT_SEQUENCE_EDITOR", &editor)
            .current_dir(&repo_path)
            .status()?;

        if !status.success() {
            eprintln!("⚠️  Rebase ended with conflicts or was aborted.");
            eprintln!("   Resolve conflicts then: torii rebase --continue");
            eprintln!("   Or abort with:          torii rebase --abort");
        } else {
            println!("✅ Rebase complete");
        }

        Ok(())
    }

    /// Interactive rebase
    pub fn rebase_interactive(&self, base: &str) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        println!("🔄 Starting interactive rebase onto {}...", base);

        let status = std::process::Command::new("git")
            .args(["rebase", "-i", base])
            .current_dir(&repo_path)
            .status()?;

        if !status.success() {
            eprintln!("⚠️  Interactive rebase ended with conflicts or was aborted.");
            eprintln!("   Resolve conflicts then: torii rebase --continue");
            eprintln!("   Or abort with:          torii rebase --abort");
        } else {
            println!("✅ Interactive rebase complete");
        }

        Ok(())
    }

    /// Continue an in-progress rebase
    pub fn rebase_continue(&self) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        let output = Command::new("git")
            .args(["rebase", "--continue"])
            .current_dir(&repo_path)
            .status()?;
        if output.success() {
            println!("✅ Rebase continued");
        }
        Ok(())
    }

    /// Abort the current rebase
    pub fn rebase_abort(&self) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        Command::new("git")
            .args(["rebase", "--abort"])
            .current_dir(&repo_path)
            .status()?;
        println!("✅ Rebase aborted");
        Ok(())
    }

    /// Skip current patch in rebase
    pub fn rebase_skip(&self) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        Command::new("git")
            .args(["rebase", "--skip"])
            .current_dir(&repo_path)
            .status()?;
        println!("✅ Patch skipped");
        Ok(())
    }

    /// Show changes
    pub fn diff(&self, staged: bool, last: bool) -> Result<()> {
        if last {
            // Show diff of last commit
            let head = self.repository().head()?.peel_to_commit()?;
            let tree = head.tree()?;
            
            let parent_tree = if head.parent_count() > 0 {
                Some(head.parent(0)?.tree()?)
            } else {
                None
            };
            
            let diff = self.repository().diff_tree_to_tree(
                parent_tree.as_ref(),
                Some(&tree),
                None,
            )?;
            
            self.print_diff(&diff)?;
        } else if staged {
            // Show staged changes
            let head = self.repository().head()?.peel_to_tree()?;
            let diff = self.repository().diff_tree_to_index(Some(&head), None, None)?;
            self.print_diff(&diff)?;
        } else {
            // Show unstaged changes
            let diff = self.repository().diff_index_to_workdir(None, None)?;
            self.print_diff(&diff)?;
        }
        
        Ok(())
    }

    fn print_diff(&self, diff: &git2::Diff) -> Result<()> {
        diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
            let origin = line.origin();
            let content = std::str::from_utf8(line.content()).unwrap_or("<binary>");
            
            match origin {
                '+' => print!("\x1b[32m+{}\x1b[0m", content),
                '-' => print!("\x1b[31m-{}\x1b[0m", content),
                _ => print!(" {}", content),
            }
            true
        })?;
        
        Ok(())
    }

    /// List local branches
    pub fn list_branches(&self) -> Result<Vec<String>> {
        let branches = self.repository().branches(Some(BranchType::Local))?;
        let mut branch_names = Vec::new();

        for branch in branches {
            let (branch, _) = branch?;
            if let Some(name) = branch.name()? {
                branch_names.push(name.to_string());
            }
        }

        Ok(branch_names)
    }

    /// List remote branches
    pub fn list_remote_branches(&self) -> Result<Vec<String>> {
        let branches = self.repository().branches(Some(BranchType::Remote))?;
        let mut branch_names = Vec::new();

        for branch in branches {
            let (branch, _) = branch?;
            if let Some(name) = branch.name()? {
                // Skip HEAD symrefs (e.g. origin/HEAD)
                if !name.ends_with("/HEAD") {
                    branch_names.push(name.to_string());
                }
            }
        }

        Ok(branch_names)
    }

    /// Create a new branch
    pub fn create_branch(&self, name: &str) -> Result<()> {
        let head = self.repository().head()?.peel_to_commit()?;
        self.repository().branch(name, &head, false)?;
        Ok(())
    }

    /// Delete a branch
    pub fn delete_branch(&self, name: &str) -> Result<()> {
        let mut branch = self.repository().find_branch(name, BranchType::Local)?;
        branch.delete()?;
        Ok(())
    }

    /// Switch to a branch
    pub fn switch_branch(&self, name: &str) -> Result<()> {
        let obj = self.repository().revparse_single(&format!("refs/heads/{}", name))?;
        self.repository().checkout_tree(&obj, None)?;
        self.repository().set_head(&format!("refs/heads/{}", name))?;
        Ok(())
    }

    /// Clone a repository
    pub fn clone_repo(url: &str, directory: Option<&str>) -> Result<()> {
        let target = if let Some(dir) = directory {
            dir.to_string()
        } else {
            // Extract repo name from URL
            url.split('/')
                .last()
                .unwrap_or("repo")
                .trim_end_matches(".git")
                .to_string()
        };
        
        Repository::clone(url, &target)?;
        Ok(())
    }

    /// Rename a branch
    pub fn rename_branch(&self, old_name: &str, new_name: &str) -> Result<()> {
        // Use git command for renaming as git2 doesn't have a direct rename
        let output = Command::new("git")
            .args(&["branch", "-m", old_name, new_name])
            .current_dir(self.repo.path().parent().unwrap())
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to rename branch: {}", error)
            ));
        }

        Ok(())
    }

    /// Rewrite commit history with new dates
    pub fn rewrite_history(&self, start_date: &str, end_date: &str) -> Result<()> {
        println!("🔄 Rewriting commit history...");
        
        // Parse dates
        let start = NaiveDateTime::parse_from_str(&format!("{} +0200", start_date), "%Y-%m-%d %H:%M %z")
            .map_err(|e| crate::error::ToriiError::InvalidConfig(format!("Invalid start date: {}", e)))?;
        let end = NaiveDateTime::parse_from_str(&format!("{} +0200", end_date), "%Y-%m-%d %H:%M %z")
            .map_err(|e| crate::error::ToriiError::InvalidConfig(format!("Invalid end date: {}", e)))?;

        // Get all commits
        let output = Command::new("git")
            .args(&["log", "--reverse", "--format=%H"])
            .current_dir(self.repo.path().parent().unwrap())
            .output()?;

        let commits: Vec<String> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(|s| s.to_string())
            .collect();

        let total_commits = commits.len();
        if total_commits == 0 {
            return Ok(());
        }

        // Create filter script
        let mut filter_script = String::new();
        let interval_seconds = (end.and_utc().timestamp() - start.and_utc().timestamp()) / (total_commits as i64 - 1).max(1);

        for (i, commit_hash) in commits.iter().enumerate() {
            let new_timestamp = start.and_utc().timestamp() + (i as i64 * interval_seconds);
            let new_date = DateTime::from_timestamp(new_timestamp, 0)
                .unwrap()
                .format("%Y-%m-%d %H:%M:%S +0200");
            
            filter_script.push_str(&format!(
                "if [ \"$GIT_COMMIT\" = \"{}\" ]; then\n    export GIT_AUTHOR_DATE=\"{}\"\n    export GIT_COMMITTER_DATE=\"{}\"\nfi\n",
                commit_hash, new_date, new_date
            ));
        }

        // Write filter script to temp file
        std::fs::write("/tmp/torii_filter.sh", &filter_script)?;

        // Run filter-branch
        let output = Command::new("bash")
            .args(&["-c", "FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --env-filter \"$(cat /tmp/torii_filter.sh)\" -- --all"])
            .current_dir(self.repo.path().parent().unwrap())
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to rewrite history: {}", error)
            ));
        }

        println!("✅ Rewrote {} commits", total_commits);
        Ok(())
    }

    /// Remove a file from the entire git history
    pub fn remove_file_from_history(&self, file_path: &str) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap();

        println!("🗑️  Removing '{}' from entire history...", file_path);

        let cmd = format!(
            "FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --index-filter \
            'git rm -r --cached --ignore-unmatch {}' --tag-name-filter cat -- --all",
            file_path
        );

        let output = Command::new("bash")
            .args(["-c", &cmd])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to remove file from history: {}", error)
            ));
        }

        println!("✅ '{}' removed from all commits", file_path);
        println!("💡 Run 'torii history clean' then 'torii sync --force' to update remote");
        Ok(())
    }

    /// Clean up repository (gc, reflog expire)
    pub fn clean_history(&self) -> Result<()> {
        println!("🧹 Cleaning repository...");
        
        let repo_path = self.repo.path().parent().unwrap();

        // Remove filter-branch refs
        let _ = Command::new("rm")
            .args(&["-rf", ".git/refs/original/"])
            .current_dir(repo_path)
            .output();

        // Expire reflog
        let output = Command::new("git")
            .args(&["reflog", "expire", "--expire=now", "--all"])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to expire reflog: {}", error)
            ));
        }

        // Run gc
        let output = Command::new("git")
            .args(&["gc", "--prune=now"])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to run gc: {}", error)
            ));
        }

        Ok(())
    }

    /// Verify remote repository status
    pub fn verify_remote(&self) -> Result<()> {
        println!("🔍 Verifying remote status...\n");
        
        let repo_path = self.repo.path().parent().unwrap();

        // Get local HEAD
        let local_output = Command::new("git")
            .args(&["rev-parse", "HEAD"])
            .current_dir(repo_path)
            .output()?;

        let local_hash = String::from_utf8_lossy(&local_output.stdout).trim().to_string();

        // Get remote HEAD
        let remote_output = Command::new("git")
            .args(&["ls-remote", "origin", "main"])
            .current_dir(repo_path)
            .output()?;

        if !remote_output.status.success() {
            println!("❌ Failed to connect to remote");
            return Ok(());
        }

        let remote_line = String::from_utf8_lossy(&remote_output.stdout);
        let remote_hash = remote_line.split_whitespace().next().unwrap_or("");

        println!("Local HEAD:  {}", &local_hash[..7.min(local_hash.len())]);
        println!("Remote HEAD: {}", &remote_hash[..7.min(remote_hash.len())]);

        if local_hash.starts_with(remote_hash) || remote_hash.starts_with(&local_hash) {
            println!("\n✅ Local and remote are in sync");
        } else {
            println!("\n⚠️  Local and remote have diverged");
            println!("💡 Use 'torii sync --force' to push local changes");
        }

        Ok(())
    }

    /// Fetch from remote without merging
    pub fn fetch(&self) -> Result<()> {
        println!("🔄 Fetching from remote...");
        
        let repo_path = self.repo.path().parent().unwrap();

        let output = Command::new("git")
            .args(&["fetch", "origin"])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to fetch: {}", error)
            ));
        }

        Ok(())
    }

    /// Revert a specific commit
    pub fn revert_commit(&self, commit_hash: &str) -> Result<()> {
        println!("🔄 Reverting commit {}...", commit_hash);
        
        let repo_path = self.repo.path().parent().unwrap();

        let output = Command::new("git")
            .args(&["revert", "--no-edit", commit_hash])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to revert commit: {}", error)
            ));
        }

        Ok(())
    }

    /// Reset to a specific commit
    pub fn reset_commit(&self, commit_hash: &str, mode: &str) -> Result<()> {
        println!("🔄 Resetting to commit {} (mode: {})...", commit_hash, mode);
        
        let repo_path = self.repo.path().parent().unwrap();

        let reset_flag = match mode {
            "soft" => "--soft",
            "hard" => "--hard",
            _ => "--mixed", // default
        };

        let output = Command::new("git")
            .args(&["reset", reset_flag, commit_hash])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to reset: {}", error)
            ));
        }

        Ok(())
    }

    /// Merge a branch into current branch
    pub fn merge_branch(&self, branch_name: &str) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap();

        let output = Command::new("git")
            .args(&["merge", branch_name])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to merge branch: {}", error)
            ));
        }

        Ok(())
    }

    /// Rebase current branch onto another branch
    pub fn rebase_branch(&self, branch_name: &str) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap();

        let output = Command::new("git")
            .args(&["rebase", branch_name])
            .current_dir(repo_path)
            .output()?;

        if !output.status.success() {
            let error = String::from_utf8_lossy(&output.stderr);
            return Err(crate::error::ToriiError::InvalidConfig(
                format!("Failed to rebase: {}", error)
            ));
        }

        Ok(())
    }

    /// List all tracked files in the index
    pub fn ls(&self, path_filter: Option<&str>) -> Result<()> {
        let mut index = self.repo.index()?;
        index.read(true)?;

        let entries: Vec<_> = index.iter()
            .filter(|e| {
                let path = String::from_utf8_lossy(&e.path).to_string();
                match path_filter {
                    Some(filter) => path.starts_with(filter),
                    None => true,
                }
            })
            .collect();

        if entries.is_empty() {
            println!("No tracked files.");
            return Ok(());
        }

        for entry in &entries {
            let path = String::from_utf8_lossy(&entry.path);
            println!("{}", path);
        }

        println!();
        println!("{} tracked file(s)", entries.len());

        Ok(())
    }

    /// Show details of a commit, tag, or file at a given ref
    pub fn show(&self, object: Option<&str>) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap();

        // Use the ref or default to HEAD
        let target = object.unwrap_or("HEAD");

        // Try to resolve as commit first
        let resolved = self.repo.revparse_single(target);

        match resolved {
            Ok(obj) => {
                match obj.kind() {
                    Some(git2::ObjectType::Commit) => {
                        let commit = obj.peel_to_commit()?;
                        let sig = commit.author();
                        let time = commit.time();
                        let timestamp = chrono::DateTime::from_timestamp(time.seconds(), 0)
                            .unwrap_or_default();

                        println!("commit {}", commit.id());
                        println!("Author: {} <{}>", sig.name().unwrap_or(""), sig.email().unwrap_or(""));
                        println!("Date:   {}", timestamp.format("%Y-%m-%d %H:%M:%S"));
                        println!();
                        println!("    {}", commit.message().unwrap_or("").trim());
                        println!();

                        // Show diff vs parent
                        let output = Command::new("git")
                            .args(["show", "--stat", "--patch", target])
                            .current_dir(repo_path)
                            .output()?;

                        if output.status.success() {
                            let diff = String::from_utf8_lossy(&output.stdout);
                            // Skip the header lines already printed above
                            let lines: Vec<&str> = diff.lines().collect();
                            let skip = lines.iter().position(|l| l.starts_with("diff --git") || l.starts_with("---")).unwrap_or(0);
                            for line in &lines[skip..] {
                                println!("{}", line);
                            }
                        }
                    }
                    Some(git2::ObjectType::Tag) => {
                        let tag = obj.peel_to_tag()?;
                        println!("tag {}", tag.name().unwrap_or(""));
                        if let Some(tagger) = tag.tagger() {
                            println!("Tagger: {} <{}>", tagger.name().unwrap_or(""), tagger.email().unwrap_or(""));
                        }
                        println!();
                        println!("{}", tag.message().unwrap_or("").trim());
                    }
                    Some(git2::ObjectType::Blob) => {
                        let blob = obj.peel_to_blob()?;
                        let content = std::str::from_utf8(blob.content())
                            .unwrap_or("<binary>");
                        print!("{}", content);
                    }
                    _ => {
                        println!("{}", obj.id());
                    }
                }
            }
            Err(_) => {
                return Err(crate::error::ToriiError::InvalidConfig(
                    format!("Unknown ref or object: '{}'", target)
                ).into());
            }
        }

        Ok(())
    }
}