gitorii 0.7.2

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
use std::path::{Path, PathBuf};
use std::fs;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::error::{Result, ToriiError};
use crate::core::GitRepo;

#[derive(Debug, Serialize, Deserialize)]
pub struct SnapshotMetadata {
    pub id: String,
    pub timestamp: DateTime<Utc>,
    pub name: Option<String>,
    pub branch: String,
    pub commit_hash: Option<String>,
}

pub struct SnapshotManager {
    repo_path: PathBuf,
    snapshots_dir: PathBuf,
}

impl SnapshotManager {
    pub fn new<P: AsRef<Path>>(repo_path: P) -> Result<Self> {
        let repo_path = repo_path.as_ref().to_path_buf();
        let snapshots_dir = repo_path.join(".torii").join("snapshots");
        
        fs::create_dir_all(&snapshots_dir)?;

        Ok(Self {
            repo_path,
            snapshots_dir,
        })
    }

    /// Create a new snapshot
    pub fn create_snapshot(&self, name: Option<&str>) -> Result<String> {
        let repo = GitRepo::open(&self.repo_path)?;
        let timestamp = Utc::now();
        // Include millis so back-to-back snapshots in the same second don't
        // collide and silently overwrite each other (the original `_HMS`
        // format made `stash` lose data when invoked twice quickly).
        let mut id = timestamp.format("%Y%m%d_%H%M%S_%3f").to_string();

        // Defensive: if even the millis collide (highly unlikely), append
        // an integer suffix until the dir is fresh.
        let mut snapshot_dir = self.snapshots_dir.join(&id);
        let mut suffix = 0;
        while snapshot_dir.exists() {
            suffix += 1;
            id = format!("{}_{}", timestamp.format("%Y%m%d_%H%M%S_%3f"), suffix);
            snapshot_dir = self.snapshots_dir.join(&id);
        }
        fs::create_dir_all(&snapshot_dir)?;

        let branch = repo.get_current_branch()?;
        
        let metadata = SnapshotMetadata {
            id: id.clone(),
            timestamp,
            name: name.map(String::from),
            branch,
            commit_hash: None,
        };

        let metadata_path = snapshot_dir.join("metadata.json");
        let metadata_json = serde_json::to_string_pretty(&metadata)?;
        fs::write(metadata_path, metadata_json)?;

        self.create_bundle(&snapshot_dir, &repo)?;

        Ok(id)
    }

    /// Create a git bundle for the snapshot
    fn create_bundle(&self, snapshot_dir: &Path, repo: &GitRepo) -> Result<()> {
        // Create bundle with all refs
        let mut revwalk = repo.repository().revwalk()?;
        revwalk.push_head()?;

        let git_path = self.repo_path.join(".git");
        let snapshot_git = snapshot_dir.join("git_backup");

        // .git is normally a directory (regular checkout). In linked
        // worktrees and submodules it's a regular file whose first line is
        // "gitdir: <path-to-real-gitdir>" pointing at the metadata that
        // actually lives elsewhere — shared with the main repo. In that
        // case copying the file alone preserves the link; the worktree's
        // working-tree content gets copied below alongside it. We do NOT
        // duplicate the linked gitdir because (a) it's shared and (b) the
        // worktree's unique state lives in the working tree.
        match fs::symlink_metadata(&git_path) {
            Ok(meta) if meta.is_dir() => {
                self.copy_dir_recursive(&git_path, &snapshot_git)?;
            }
            Ok(_) => {
                // .git is a file (worktree / submodule gitlink). Copy the
                // single file so we know which gitdir this was tied to,
                // then leave the rest alone.
                fs::create_dir_all(&snapshot_git)?;
                fs::copy(&git_path, snapshot_git.join("gitdir-link"))?;
                // Also dump the resolved gitdir path so restoration knows
                // where the real metadata lived.
                if let Ok(content) = fs::read_to_string(&git_path) {
                    let pointer = content.trim();
                    fs::write(snapshot_git.join("RESOLVED-GITDIR"), pointer)?;
                }
            }
            Err(e) => {
                return Err(ToriiError::Io(e));
            }
        }

        Ok(())
    }

    /// Recursively copy directory
    fn copy_dir_recursive(&self, src: &Path, dst: &Path) -> Result<()> {
        fs::create_dir_all(dst)?;
        
        for entry in fs::read_dir(src)? {
            let entry = entry?;
            let file_type = entry.file_type()?;
            let src_path = entry.path();
            let dst_path = dst.join(entry.file_name());

            if file_type.is_dir() {
                self.copy_dir_recursive(&src_path, &dst_path)?;
            } else {
                fs::copy(&src_path, &dst_path)?;
            }
        }

        Ok(())
    }

    /// List all snapshots
    pub fn list_snapshots(&self) -> Result<()> {
        let entries = fs::read_dir(&self.snapshots_dir)?;
        
        println!("📸 Snapshots:");
        println!();

        for entry in entries {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                let metadata_path = entry.path().join("metadata.json");
                if metadata_path.exists() {
                    let metadata_json = fs::read_to_string(metadata_path)?;
                    let metadata: SnapshotMetadata = serde_json::from_str(&metadata_json)?;
                    
                    let name_str = metadata.name
                        .as_ref()
                        .map(|n| format!(" ({})", n))
                        .unwrap_or_default();
                    
                    println!("  {} - {}{}", 
                        metadata.id,
                        metadata.timestamp.format("%Y-%m-%d %H:%M:%S"),
                        name_str
                    );
                    println!("    Branch: {}", metadata.branch);
                }
            }
        }

        Ok(())
    }

    /// Restore from a snapshot
    pub fn restore_snapshot(&self, id: &str) -> Result<()> {
        let snapshot_dir = self.snapshots_dir.join(id);
        
        if !snapshot_dir.exists() {
            return Err(ToriiError::Snapshot(format!("Snapshot not found: {}", id)));
        }

        let snapshot_git = snapshot_dir.join("git_backup");
        let git_dir = self.repo_path.join(".git");

        fs::remove_dir_all(&git_dir)?;
        self.copy_dir_recursive(&snapshot_git, &git_dir)?;

        // Reset working directory to match restored git state via git2
        {
            let repo = git2::Repository::discover(&self.repo_path)
                .map_err(|e| ToriiError::Git(e))?;
            let head = repo.head()
                .map_err(|e| ToriiError::Git(e))?
                .peel_to_commit()
                .map_err(|e| ToriiError::Git(e))?;
            repo.reset(
                head.as_object(),
                git2::ResetType::Hard,
                Some(git2::build::CheckoutBuilder::default().force()),
            ).map_err(|e| ToriiError::Git(e))?;
        }

        Ok(())
    }

    /// Delete a snapshot
    pub fn delete_snapshot(&self, id: &str) -> Result<()> {
        let snapshot_dir = self.snapshots_dir.join(id);

        if !snapshot_dir.exists() {
            return Err(ToriiError::Snapshot(format!("Snapshot not found: {}", id)));
        }

        fs::remove_dir_all(snapshot_dir)?;
        Ok(())
    }

    /// Delete every snapshot in this repo. Returns the count deleted so
    /// the CLI can report it. Idempotent — empty dir returns 0.
    pub fn clear_all(&self) -> Result<usize> {
        if !self.snapshots_dir.exists() {
            return Ok(0);
        }
        let mut count = 0;
        for entry in fs::read_dir(&self.snapshots_dir)? {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                fs::remove_dir_all(entry.path())?;
                count += 1;
            }
        }
        Ok(count)
    }

    /// Print everything we have on one snapshot: metadata + bundle layout.
    /// Doesn't try to list every file under git_backup (could be huge);
    /// shows the top-level entries so the user knows it's a real backup.
    pub fn show(&self, id: &str) -> Result<()> {
        let snapshot_dir = self.snapshots_dir.join(id);
        if !snapshot_dir.exists() {
            return Err(ToriiError::Snapshot(format!("Snapshot not found: {}", id)));
        }
        let metadata_path = snapshot_dir.join("metadata.json");
        if metadata_path.exists() {
            let metadata_json = fs::read_to_string(&metadata_path)?;
            let metadata: SnapshotMetadata = serde_json::from_str(&metadata_json)?;
            println!("📸 Snapshot {}", metadata.id);
            println!("   timestamp: {}", metadata.timestamp.format("%Y-%m-%d %H:%M:%S"));
            if let Some(name) = &metadata.name {
                println!("   name:      {}", name);
            }
            println!("   branch:    {}", metadata.branch);
            if let Some(commit) = &metadata.commit_hash {
                println!("   commit:    {}", commit);
            }
        } else {
            println!("📸 Snapshot {} (no metadata.json — likely partial)", id);
        }
        // Show what's captured inside.
        println!("   contents:");
        for entry in fs::read_dir(&snapshot_dir)? {
            let entry = entry?;
            let kind = if entry.file_type()?.is_dir() { "dir" } else { "file" };
            println!("     {kind}: {}", entry.file_name().to_string_lossy());
        }
        Ok(())
    }


    /// Configure auto-snapshot settings
    pub fn configure_auto_snapshot(&self, enable: bool, interval: Option<u32>) -> Result<()> {
        let config_path = self.repo_path.join(".torii").join("config.json");
        
        #[derive(Serialize, Deserialize)]
        struct Config {
            auto_snapshot_enabled: bool,
            auto_snapshot_interval_minutes: u32,
        }

        let config = Config {
            auto_snapshot_enabled: enable,
            auto_snapshot_interval_minutes: interval.unwrap_or(30),
        };

        let config_json = serde_json::to_string_pretty(&config)?;
        fs::write(config_path, config_json)?;

        Ok(())
    }

    /// Save work temporarily (like git stash).
    ///
    /// Uses libgit2's native stash API rather than the snapshot bundle path.
    /// The previous implementation copied `.git/` and reset HEAD, which
    /// silently dropped working-tree changes — `git_backup` only contains
    /// committed history, so any uncommitted edits were unrecoverable.
    pub fn stash(&self, name: Option<&str>, include_untracked: bool) -> Result<()> {
        let stash_name = name.unwrap_or("WIP");
        let mut repo = git2::Repository::discover(&self.repo_path)
            .map_err(ToriiError::Git)?;

        // Detect whether there is anything to stash; libgit2 errors with
        // "no changes selected" otherwise and the message is unhelpful.
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(include_untracked)
            .recurse_untracked_dirs(include_untracked);
        let is_empty = {
            let statuses = repo.statuses(Some(&mut opts)).map_err(ToriiError::Git)?;
            statuses.is_empty()
        };
        if is_empty {
            return Err(ToriiError::Snapshot(
                "Nothing to stash — working tree is clean.".to_string(),
            ));
        }

        // Build signature; if user.name/email aren't configured fall back to
        // a generic identity so stash never fails purely on a missing config.
        let signature = repo.signature().or_else(|_| {
            git2::Signature::now("torii", "torii@local")
        }).map_err(ToriiError::Git)?;

        let mut flags = git2::StashFlags::DEFAULT;
        if include_untracked {
            flags |= git2::StashFlags::INCLUDE_UNTRACKED;
        }
        let oid = repo.stash_save2(&signature, Some(stash_name), Some(flags))
            .map_err(ToriiError::Git)?;

        println!("📦 Stashed changes");
        println!("   stash@{{0}}: {}", &oid.to_string()[..7]);
        println!("   Name: {}", stash_name);
        if include_untracked {
            println!("   Untracked files included");
        }
        println!();
        println!("💡 To restore: torii snapshot unstash");

        Ok(())
    }

    /// Restore stashed work via libgit2's native stash API.
    /// `id` selects which stash entry: `"0"` (default) is the most recent,
    /// `"1"` the one before, etc. `keep` retains the stash entry after apply.
    pub fn unstash(&self, id: Option<&str>, keep: bool) -> Result<()> {
        let mut repo = git2::Repository::discover(&self.repo_path)
            .map_err(ToriiError::Git)?;

        let index: usize = match id {
            Some(s) => s.trim_start_matches("stash@{").trim_end_matches('}')
                .parse()
                .map_err(|_| ToriiError::Snapshot(
                    format!("invalid stash index `{}` (use a number: 0, 1, …)", s)
                ))?,
            None => 0,
        };

        // Confirm the entry exists for a friendlier error than libgit2's.
        let mut count = 0;
        repo.stash_foreach(|_, _, _| { count += 1; true }).map_err(ToriiError::Git)?;
        if count == 0 {
            return Err(ToriiError::Snapshot("No stash found".to_string()));
        }
        if index >= count {
            return Err(ToriiError::Snapshot(format!(
                "stash@{{{}}} doesn't exist (have {} stash{})", index, count,
                if count == 1 { "" } else { "es" }
            )));
        }

        println!("🔄 Restoring stash@{{{}}}", index);
        if keep {
            let mut opts = git2::StashApplyOptions::new();
            opts.reinstantiate_index();
            repo.stash_apply(index, Some(&mut opts)).map_err(ToriiError::Git)?;
            println!("   Stash kept (use `torii snapshot unstash {} --no-keep` to drop)", index);
        } else {
            repo.stash_pop(index, None).map_err(ToriiError::Git)?;
            println!("   Stash popped");
        }
        println!("✅ Stash restored");

        Ok(())
    }

    /// Undo last operation
    pub fn undo(&self) -> Result<()> {
        // Find most recent auto snapshot
        let mut snapshots: Vec<_> = fs::read_dir(&self.snapshots_dir)?
            .filter_map(|e| e.ok())
            .filter(|e| {
                let name = e.file_name().to_string_lossy().to_string();
                name.starts_with("before-") || name.contains("auto-")
            })
            .collect();
        
        snapshots.sort_by_key(|e| e.metadata().ok().and_then(|m| m.modified().ok()));
        
        let latest = snapshots.last()
            .ok_or_else(|| ToriiError::Snapshot("No operation to undo".to_string()))?;
        
        let snapshot_id = latest.file_name().to_string_lossy().to_string();
        
        println!("🔄 Undoing last operation...");
        println!("   Restoring snapshot: {}", snapshot_id);
        
        self.restore_snapshot(&snapshot_id)?;
        
        println!("✅ Operation undone");
        
        Ok(())
    }
}