gitorii 0.6.5

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
use git2::{Repository, Signature, IndexAddOption, StatusOptions};
use std::path::{Path, PathBuf};
use crate::error::{Result, ToriiError};

pub struct GitRepo {
    pub(crate) repo: Repository,
}

impl GitRepo {
    /// Initialize a new git repository.
    ///
    /// Sets the initial branch from `git.default_branch` in the global torii
    /// config (default `main`) instead of libgit2's hard-coded `master`.
    pub fn init<P: AsRef<Path>>(path: P) -> Result<Self> {
        let initial = crate::config::ToriiConfig::load_global()
            .map(|c| c.git.default_branch)
            .unwrap_or_else(|_| "main".to_string());
        let mut opts = git2::RepositoryInitOptions::new();
        opts.initial_head(&initial);
        let repo = Repository::init_opts(path, &opts)?;
        Ok(Self { repo })
    }

    /// Open an existing repository
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_ref = path.as_ref();
        let repo = Repository::discover(path_ref)
            .map_err(|_| ToriiError::RepositoryNotFound(
                path_ref.display().to_string()
            ))?;
        let git_repo = Self { repo };
        // Sync .toriignore on every open so all git operations respect it
        git_repo.sync_toriignore()?;
        Ok(git_repo)
    }

    /// Sync .toriignore (+ .toriignore.local) → .git/info/exclude so git
    /// itself respects the patterns. Always force-excludes `.toriignore.local`
    /// itself — local rules are machine-private and must never be committed.
    /// Called automatically on open and before staging.
    pub fn sync_toriignore(&self) -> Result<()> {
        let repo_path = self.repo.path().parent().unwrap().to_path_buf();
        let public_path = repo_path.join(".toriignore");
        let local_path = repo_path.join(".toriignore.local");
        let exclude_path = self.repo.path().join("info").join("exclude");

        let mut buf = String::from(
            "# Synced from .toriignore by torii — do not edit manually\n\
             # Local-only rules — never commit\n\
             .toriignore.local\n",
        );

        if public_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&public_path) {
                buf.push_str(&content);
                if !buf.ends_with('\n') { buf.push('\n'); }
            }
        }

        if local_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&local_path) {
                buf.push_str("# ─── from .toriignore.local ───\n");
                buf.push_str(&content);
            }
        }

        let _ = std::fs::write(&exclude_path, buf);
        Ok(())
    }

    /// Add all changes to staging, respecting .toriignore
    pub fn add_all(&self) -> Result<()> {
        self.sync_toriignore()?;

        let mut index = self.repo.index()?;
        index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)?;
        index.write()?;
        Ok(())
    }

    /// Add specific files to staging
    pub fn add<P: AsRef<Path>>(&self, paths: &[P]) -> Result<()> {
        let mut index = self.repo.index()?;
        for path in paths {
            index.add_path(path.as_ref())?;
        }
        index.write()?;
        Ok(())
    }

    /// Unstage paths — equivalent to `git reset HEAD -- <paths>` (or `git rm --cached`
    /// for files that were never committed). Keeps files on disk.
    pub fn unstage<P: AsRef<Path>>(&self, paths: &[P]) -> Result<()> {
        match self.repo.head() {
            Ok(head) => {
                let head_obj = head.peel(git2::ObjectType::Commit)?;
                let path_refs: Vec<&Path> = paths.iter().map(|p| p.as_ref()).collect();
                self.repo.reset_default(Some(&head_obj), path_refs.iter())?;
            }
            Err(_) => {
                // No HEAD yet (root commit not made) — drop entries from index directly
                let mut index = self.repo.index()?;
                for path in paths {
                    let _ = index.remove_path(path.as_ref());
                }
                index.write()?;
            }
        }
        Ok(())
    }

    /// Unstage all paths currently in the index.
    pub fn unstage_all(&self) -> Result<()> {
        let index = self.repo.index()?;
        let paths: Vec<PathBuf> = index
            .iter()
            .filter_map(|e| std::str::from_utf8(&e.path).ok().map(PathBuf::from))
            .collect();
        if paths.is_empty() {
            return Ok(());
        }
        self.unstage(&paths)
    }

    /// Commit changes
    pub fn commit(&self, message: &str) -> Result<()> {
        let sig = self.get_signature()?;
        let mut index = self.repo.index()?;
        let tree_id = index.write_tree()?;
        let tree = self.repo.find_tree(tree_id)?;

        // Root commit (empty repo) has no parent
        let parent_commit = match self.repo.head() {
            Ok(head) => Some(head.peel_to_commit()?),
            Err(_) => None,
        };

        let parents: Vec<&git2::Commit> = parent_commit.iter().collect();

        self.repo.commit(
            Some("HEAD"),
            &sig,
            &sig,
            message,
            &tree,
            &parents,
        )?;

        Ok(())
    }

    /// Amend the previous commit
    pub fn commit_amend(&self, message: &str) -> Result<()> {
        let sig = self.get_signature()?;
        let mut index = self.repo.index()?;
        let tree_id = index.write_tree()?;
        let tree = self.repo.find_tree(tree_id)?;

        // Resolve HEAD via the branch ref directly to dodge stale internal state
        // after operations like history rewrite.
        let head_ref = self.repo.head()?;
        let head_oid = head_ref.target()
            .ok_or_else(|| ToriiError::InvalidConfig("HEAD has no target".to_string()))?;
        let head_commit = self.repo.find_commit(head_oid)?;

        let parents: Vec<_> = head_commit.parents().collect();
        let parent_refs: Vec<_> = parents.iter().collect();

        let new_oid = self.repo.commit(
            None,
            &sig,
            &sig,
            message,
            &tree,
            &parent_refs,
        )?;

        // Move HEAD (or the underlying branch ref) to the new commit explicitly,
        // bypassing libgit2's "first parent" check that fails when HEAD was
        // rewritten just before this call.
        if head_ref.is_branch() {
            if let Some(refname) = head_ref.name() {
                self.repo.reference(refname, new_oid, true, "amend")?;
            }
        } else {
            self.repo.set_head_detached(new_oid)?;
        }

        Ok(())
    }
    
    /// Build auth callbacks for SSH and HTTPS token auth.
    /// Pass the remote URL so the correct token is selected per host.
    pub fn auth_callbacks_for<'a>(url: &str) -> git2::RemoteCallbacks<'a> {
        let cfg = crate::config::ToriiConfig::load_global().unwrap_or_default();
        let url_owned = url.to_string();
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.credentials(move |cb_url, username_from_url, allowed_types| {
            let effective_url = if url_owned.is_empty() { cb_url } else { &url_owned };
            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
                let username = username_from_url.unwrap_or("git");
                let home = dirs::home_dir().unwrap_or_default();
                let ed25519 = home.join(".ssh").join("id_ed25519");
                let rsa = home.join(".ssh").join("id_rsa");
                if ed25519.exists() {
                    return git2::Cred::ssh_key(username, None, &ed25519, None);
                } else if rsa.exists() {
                    return git2::Cred::ssh_key(username, None, &rsa, None);
                } else {
                    return git2::Cred::ssh_key_from_agent(username);
                }
            }
            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
                let token = if effective_url.contains("github.com") {
                    cfg.auth.github_token.clone()
                } else if effective_url.contains("gitlab.com") {
                    cfg.auth.gitlab_token.clone()
                } else if effective_url.contains("codeberg.org") {
                    cfg.auth.codeberg_token.clone()
                } else {
                    cfg.auth.gitea_token.clone()
                };
                if let Some(token) = token {
                    return git2::Cred::userpass_plaintext("oauth2", &token);
                }
            }
            git2::Cred::default()
        });
        callbacks
    }

    /// Attach progress reporters to an existing `RemoteCallbacks`. Covers:
    ///   - transfer_progress: pack receive + indexing + delta resolution
    ///   - sideband_progress: server messages like "Counting objects: …"
    /// Reused by clone / fetch / pull so every long-running op gives the
    /// same visual feedback. Throttled to ~10 fps.
    pub fn attach_fetch_progress<'a>(callbacks: &mut git2::RemoteCallbacks<'a>) {
        use std::cell::RefCell;
        use std::io::Write;
        use std::time::Instant;

        let last_print = RefCell::new(Instant::now());
        callbacks.transfer_progress(move |stats| {
            let mut last = last_print.borrow_mut();
            let total = stats.total_objects();
            let recv = stats.received_objects();
            let idx = stats.indexed_objects();
            let total_deltas = stats.total_deltas();
            let idx_deltas = stats.indexed_deltas();
            let receiving_done = total > 0 && recv == total && idx == total;
            let deltas_done = total_deltas == 0 || idx_deltas == total_deltas;
            let done = receiving_done && deltas_done;

            if !done && last.elapsed().as_millis() < 100 {
                return true;
            }
            *last = Instant::now();

            let mb = stats.received_bytes() as f64 / (1024.0 * 1024.0);
            // Two phases: receiving objects, then resolving deltas.
            // libgit2 reports both via the same callback, so emit whichever
            // is currently advancing.
            if total_deltas > 0 && recv == total {
                let pct = if total_deltas > 0 { idx_deltas * 100 / total_deltas } else { 100 };
                print!(
                    "\r🧩 Resolving deltas {pct}%  {idx_deltas}/{total_deltas}                       "
                );
            } else {
                let pct = if total > 0 { recv * 100 / total } else { 0 };
                print!(
                    "\r📥 {pct}%  {recv}/{total} objects  {idx} indexed  {mb:.1} MB       ",
                );
            }
            std::io::stdout().flush().ok();
            if done {
                println!();
            }
            true
        });
        callbacks.sideband_progress(|line| {
            std::io::stderr().write_all(line).ok();
            true
        });
    }

    /// Attach progress reporters for push (different libgit2 callback set).
    ///   - push_transfer_progress: pack upload
    ///   - sideband_progress: server messages
    /// Throttled to ~10 fps.
    pub fn attach_push_progress<'a>(callbacks: &mut git2::RemoteCallbacks<'a>) {
        use std::cell::RefCell;
        use std::io::Write;
        use std::time::Instant;

        let last_print = RefCell::new(Instant::now());
        callbacks.push_transfer_progress(move |current, total, bytes| {
            let mut last = last_print.borrow_mut();
            let done = total > 0 && current == total;
            if !done && last.elapsed().as_millis() < 100 {
                return;
            }
            *last = Instant::now();

            let pct = if total > 0 { current * 100 / total } else { 0 };
            let mb = bytes as f64 / (1024.0 * 1024.0);
            print!("\r📤 {pct}%  {current}/{total} objects  {mb:.1} MB       ");
            std::io::stdout().flush().ok();
            if done {
                println!();
            }
        });
        callbacks.sideband_progress(|line| {
            std::io::stderr().write_all(line).ok();
            true
        });
    }

    /// Pull from remote (fetch + fast-forward merge of current branch)
    pub fn pull(&self) -> Result<()> {
        let branch = self.get_current_branch()?;
        let mut remote = self.repo.find_remote("origin")?;

        let remote_url = remote.url().unwrap_or("").to_string();
        let mut callbacks = Self::auth_callbacks_for(&remote_url);
        Self::attach_fetch_progress(&mut callbacks);

        let mut fetch_options = git2::FetchOptions::new();
        fetch_options.remote_callbacks(callbacks);

        remote.fetch(&[&branch], Some(&mut fetch_options), None)?;

        // Empty / freshly-created remotes leave FETCH_HEAD as a 0-byte file
        // and libgit2 then refuses to parse it as a reference. Treat that
        // as "nothing to pull" — same outcome as up-to-date.
        let fetch_head_path = self.repo.path().join("FETCH_HEAD");
        if fetch_head_path.metadata().map(|m| m.len() == 0).unwrap_or(true) {
            return Ok(());
        }
        let fetch_head = self.repo.find_reference("FETCH_HEAD")?;
        let fetch_commit = self.repo.reference_to_annotated_commit(&fetch_head)?;

        let analysis = self.repo.merge_analysis(&[&fetch_commit])?;

        if analysis.0.is_up_to_date() {
            return Ok(());
        }
        if analysis.0.is_fast_forward() {
            let refname = format!("refs/heads/{}", branch);
            let mut reference = self.repo.find_reference(&refname)?;
            reference.set_target(fetch_commit.id(), "Fast-forward")?;
            self.repo.set_head(&refname)?;
            self.repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
            return Ok(());
        }

        Err(ToriiError::InvalidConfig(format!(
            "Pull not fast-forward on '{}'. Local and remote diverged. Use 'torii sync {} --merge' or 'torii sync {} --rebase' to integrate.",
            branch, branch, branch
        )))
    }

    /// Push to remote
    pub fn push(&self, force: bool) -> Result<()> {
        let mut remote = self.repo.find_remote("origin")?;
        let branch = self.get_current_branch()?;

        let refspec = if force {
            format!("+refs/heads/{}:refs/heads/{}", branch, branch)
        } else {
            format!("refs/heads/{}:refs/heads/{}", branch, branch)
        };

        let remote_url = remote.url().unwrap_or("").to_string();
        let mut callbacks = Self::auth_callbacks_for(&remote_url);

        // Capture per-ref rejections AND track that the callback was actually
        // fired. libgit2's `remote.push()` can return Ok in three failure
        // modes our previous fix didn't cover:
        //   1. Server-side rejection — caught by push_update_reference (msg)
        //   2. Connection dropped mid-pack on huge pushes — push_update_reference
        //      *never fires*, so we must also assert it was called at all
        //   3. SSH transport silently no-ops on auth fail — same: callback skip
        // We now treat "callback never fired" as failure too, since a real
        // accepted push always invokes the callback exactly once per refspec.
        let rejections: std::sync::Arc<std::sync::Mutex<Vec<(String, String)>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let acknowledged: std::sync::Arc<std::sync::Mutex<Vec<String>>> =
            std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let rejections_cb = rejections.clone();
        let acknowledged_cb = acknowledged.clone();
        callbacks.push_update_reference(move |refname, status| {
            acknowledged_cb.lock().unwrap().push(refname.to_string());
            if let Some(msg) = status {
                rejections_cb
                    .lock()
                    .unwrap()
                    .push((refname.to_string(), msg.to_string()));
            }
            Ok(())
        });

        // Live pack-upload progress + server sideband. Same look as fetch.
        Self::attach_push_progress(&mut callbacks);

        let mut push_options = git2::PushOptions::new();
        push_options.remote_callbacks(callbacks);

        // Push branch
        remote.push(&[&refspec], Some(&mut push_options))?;

        // Surface server-side rejections that libgit2 swallows silently.
        let rejected = rejections.lock().unwrap();
        if !rejected.is_empty() {
            let detail = rejected
                .iter()
                .map(|(r, m)| format!("{}{}", r, m))
                .collect::<Vec<_>>()
                .join("; ");
            return Err(ToriiError::Git(git2::Error::from_str(&format!(
                "push rejected by remote: {}",
                detail
            ))));
        }

        // No callback at all = transport silently dropped the push. Caught
        // in the wild pushing 3GB to GitLab over SSH where libgit2 returned
        // Ok with zero refs ever acknowledged by the server.
        let acks = acknowledged.lock().unwrap();
        if acks.is_empty() {
            return Err(ToriiError::Git(git2::Error::from_str(
                "push completed without server acknowledging any refs — \
                 transport may have failed silently. Check network / auth and retry. \
                 (Common with very large pushes over SSH; try HTTPS with a token.)"
            )));
        }

        // Push tags via git2 — enumerate local tags and push each one
        self.push_all_tags_via_git2("origin", force)?;

        Ok(())
    }

    /// Push all local tags to a remote using git2 (no subprocess needed)
    pub fn push_all_tags_via_git2(&self, remote_name: &str, force: bool) -> Result<()> {
        let tags = self.repo.tag_names(None)?;
        if tags.is_empty() {
            return Ok(());
        }
        let mut remote = self.repo.find_remote(remote_name)?;
        let remote_url = remote.url().unwrap_or("").to_string();
        let refspecs: Vec<String> = tags.iter()
            .flatten()
            .map(|t| {
                let r = format!("refs/tags/{}:refs/tags/{}", t, t);
                if force { format!("+{}", r) } else { r }
            })
            .collect();
        let refspec_refs: Vec<&str> = refspecs.iter().map(|s| s.as_str()).collect();
        if !refspec_refs.is_empty() {
            let callbacks = Self::auth_callbacks_for(&remote_url);
            let mut push_options = git2::PushOptions::new();
            push_options.remote_callbacks(callbacks);
            if let Err(e) = remote.push(&refspec_refs, Some(&mut push_options)) {
                eprintln!("⚠️  Tag push failed: {}", e);
            }
        }
        Ok(())
    }

    /// Get current branch name
    pub fn get_current_branch(&self) -> Result<String> {
        let head = self.repo.head()?;
        let branch_name = head.shorthand()
            .ok_or_else(|| ToriiError::Git(git2::Error::from_str("Could not get branch name")))?;
        Ok(branch_name.to_string())
    }

    /// Get the repository reference
    pub fn repository(&self) -> &Repository {
        &self.repo
    }

    /// Show repository status with context and suggestions
    pub fn status(&self) -> Result<()> {
        let mut opts = StatusOptions::new();
        opts.include_untracked(true);
        let statuses = self.repo.statuses(Some(&mut opts))?;

        // Header
        println!("📊 Repository Status\n");
        
        // Branch and commit info
        let branch = self.get_current_branch()?;
        println!("Branch: {}", branch);
        
        // Get latest commit info
        if let Ok(head) = self.repo.head() {
            if let Ok(commit) = head.peel_to_commit() {
                let msg = commit.message().unwrap_or("").lines().next().unwrap_or("");
                let time = commit.time();
                let timestamp = chrono::DateTime::from_timestamp(time.seconds(), 0)
                    .unwrap_or_default();
                let now = chrono::Utc::now();
                let duration = now.signed_duration_since(timestamp);
                
                let time_ago = if duration.num_days() > 0 {
                    format!("{} days ago", duration.num_days())
                } else if duration.num_hours() > 0 {
                    format!("{} hours ago", duration.num_hours())
                } else if duration.num_minutes() > 0 {
                    format!("{} minutes ago", duration.num_minutes())
                } else {
                    "just now".to_string()
                };
                
                let short_id = format!("{:.7}", commit.id());
                println!("Commit: {} - \"{}\" ({})", short_id, msg, time_ago);
            }
        }
        
        // Remote status
        if let Ok(remote) = self.repo.find_remote("origin") {
            if let Some(url) = remote.url() {
                let remote_name = url.split('/').last().unwrap_or("origin");
                print!("Remote: {}", remote_name.trim_end_matches(".git"));
                
                // Check if ahead/behind
                if let Ok(head) = self.repo.head() {
                    if let Ok(local_oid) = head.target().ok_or("No target") {
                        let remote_branch = format!("refs/remotes/origin/{}", branch);
                        if let Ok(remote_ref) = self.repo.find_reference(&remote_branch) {
                            if let Ok(remote_oid) = remote_ref.target().ok_or("No target") {
                                if let Ok((ahead, behind)) = self.repo.graph_ahead_behind(local_oid, remote_oid) {
                                    if ahead > 0 || behind > 0 {
                                        print!(" (");
                                        if ahead > 0 {
                                            print!("{} ahead", ahead);
                                        }
                                        if ahead > 0 && behind > 0 {
                                            print!(", ");
                                        }
                                        if behind > 0 {
                                            print!("{} behind", behind);
                                        }
                                        print!(")");
                                    } else {
                                        print!(" (up to date)");
                                    }
                                }
                            }
                        }
                    }
                }
                println!();
            }
        }
        
        println!();

        // Categorize changes
        let mut staged = Vec::new();
        let mut unstaged = Vec::new();
        let mut untracked = Vec::new();

        for entry in statuses.iter() {
            let status = entry.status();
            let path = entry.path().unwrap_or("unknown").to_string();

            if status.is_index_new() || status.is_index_modified() || status.is_index_deleted() {
                let prefix = if status.is_index_new() {
                    "A "
                } else if status.is_index_modified() {
                    "M "
                } else {
                    "D "
                };
                staged.push(format!("{} {}", prefix, path));
            }
            
            if status.is_wt_modified() || status.is_wt_deleted() {
                let prefix = if status.is_wt_modified() {
                    "M "
                } else {
                    "D "
                };
                unstaged.push(format!("{} {}", prefix, path));
            }
            
            if status.is_wt_new() {
                untracked.push(format!("?? {}", path));
            }
        }

        // Show status
        let is_clean = staged.is_empty() && unstaged.is_empty() && untracked.is_empty();

        if is_clean {
            println!("✨ Working tree clean");
        } else {
            if !staged.is_empty() {
                println!("✅ Changes staged for commit:");
                for file in &staged {
                    println!("  {}", file);
                }
                println!();
            }

            if !unstaged.is_empty() {
                println!("📝 Changes not staged:");
                for file in &unstaged {
                    println!("  {}", file);
                }
                println!();
            }

            if !untracked.is_empty() {
                println!("📦 Untracked files:");
                for file in &untracked {
                    println!("  {}", file);
                }
                println!();
            }
        }

        // Next steps suggestions
        println!("💡 Next steps:");
        if is_clean {
            println!("  • Start new work: torii branch feature-name -c");
            println!("  • Update from remote: torii sync");
            println!("  • Create snapshot: torii snapshot create");
        } else if !staged.is_empty() && unstaged.is_empty() && untracked.is_empty() {
            println!("  • Commit staged changes: torii save -m \"message\"");
            println!("  • See staged changes: torii diff --staged");
        } else if !unstaged.is_empty() || !untracked.is_empty() {
            println!("  • Save all changes: torii save -am \"message\"");
            println!("  • See changes: torii diff");
            if !staged.is_empty() {
                println!("  • Commit only staged: torii save -m \"message\"");
            }
        }

        Ok(())
    }

    /// Get git signature from config or use defaults
    fn get_signature(&self) -> Result<Signature<'_>> {
        let config = self.repo.config()?;
        
        let name = config
            .get_string("user.name")
            .unwrap_or_else(|_| "Torii User".to_string());
        
        let email = config
            .get_string("user.email")
            .unwrap_or_else(|_| "user@torii.local".to_string());

        Ok(Signature::now(&name, &email)?)
    }
}