git-cloak 0.0.1

The Invisible Layer for Your Repositories - Manage private, untracked files across Git clones.
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
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

use cap_std::ambient_authority;
use cap_std::fs::Dir;

use crate::git_utils::{self, GitUtilError};
use crate::pid::{self, Pid, PidError};
use crate::store::{self, FileEntry, Store, StoreError, Strategy};

#[derive(Debug, Error)]
pub enum CloakError {
    #[error("{0}")]
    Pid(#[from] PidError),
    #[error("{0}")]
    Store(#[from] StoreError),
    #[error("{0}")]
    GitUtil(#[from] GitUtilError),
    #[error("file not found: {0}")]
    FileNotFound(PathBuf),
    #[error("target occupied by non-cloak file: {0}")]
    TargetOccupied(PathBuf),
    #[error("file not tracked: {0}")]
    NotTracked(PathBuf),
    #[error("file {file} is outside repository root {root}")]
    OutsideRepo { file: PathBuf, root: PathBuf },
    #[error("invalid target path (contains \"..\"): {0}")]
    InvalidTargetPath(PathBuf),
    #[error("invalid repository root (no .git found): {0}")]
    InvalidRepoRoot(PathBuf),
    #[error("I/O error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

fn io_err(path: &Path, source: std::io::Error) -> CloakError {
    CloakError::Io {
        path: path.to_owned(),
        source,
    }
}

// ---------------------------------------------------------------------------
// Context helpers
// ---------------------------------------------------------------------------

struct Context {
    cwd: PathBuf,
    cwd_canonical: PathBuf,
    repo_root: Option<PathBuf>, // canonical when Some
    repo_dir: Option<Dir>,
    pid: Pid,
    store: Store,
}

impl Context {
    fn resolve() -> Result<Self, CloakError> {
        let cwd = std::env::current_dir().map_err(|e| io_err(Path::new("."), e))?;
        let cwd_canonical = std::fs::canonicalize(&cwd).map_err(|e| io_err(&cwd, e))?;
        let repo_root = git_utils::repo_root(&cwd)
            .ok()
            .map(|r| std::fs::canonicalize(&r).unwrap_or(r));
        let pid_dir = repo_root.as_deref().unwrap_or(&cwd_canonical);
        let pid = pid::compute(pid_dir)?;
        let store = Store::open()?;
        store.ensure_dirs()?;
        store.ensure_project_sandbox(&pid)?;

        let dir_path = repo_root.as_deref().unwrap_or(&cwd_canonical);
        let repo_dir = Dir::open_ambient_dir(dir_path, ambient_authority())
            .map_err(|e| io_err(dir_path, e))?;

        // Defense-in-depth: verify the opened directory is actually a git repo root.
        // If gix::discover returned a wrong path, fail early rather than operating
        // on an unrelated directory.
        if repo_root.is_some() && !repo_dir.symlink_metadata(".git").is_ok() {
            return Err(CloakError::InvalidRepoRoot(dir_path.to_owned())); // TODO situ seems not working when pid type is not git...
        }

        Ok(Context {
            cwd,
            cwd_canonical,
            repo_root,
            repo_dir: Some(repo_dir),
            pid,
            store,
        })
    }
}

// ---------------------------------------------------------------------------
// Path helpers
// ---------------------------------------------------------------------------

/// Pure-function path normalization: resolve `.` and `..` without filesystem access.
fn normalize_path(path: &Path) -> PathBuf {
    let mut out = Vec::new();
    for c in path.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other),
        }
    }
    out.iter().collect()
}

/// Resolve the repo-relative target path for a tracked file.
///
/// `repo_root_canonical` must already be canonicalized (done once at bootstrap).
fn resolve_target_path(
    file: &Path,
    explicit_target: Option<&Path>,
    repo_root_canonical: Option<&Path>,
) -> Result<PathBuf, CloakError> {
    if let Some(target) = explicit_target {
        validate_target_path(target)?;
        return Ok(target.to_owned());
    }

    let normalized = normalize_path(file);
    let root = repo_root_canonical.unwrap_or_else(|| Path::new("."));

    normalized
        .strip_prefix(root)
        .map(|p| p.to_owned())
        .map_err(|_| CloakError::OutsideRepo {
            file: normalized,
            root: root.to_owned(),
        })
}

fn validate_target_path(target: &Path) -> Result<(), CloakError> {
    for component in target.components() {
        if let std::path::Component::ParentDir = component {
            return Err(CloakError::InvalidTargetPath(target.to_owned()));
        }
    }
    if target.is_absolute() {
        return Err(CloakError::InvalidTargetPath(target.to_owned()));
    }
    Ok(())
}

/// Check if `rel_path` (relative to `dir`) is a symlink pointing into the store library.
fn is_cloak_symlink(dir: &Dir, rel_path: &Path, library_abs: &Path) -> bool {
    // Use read_link_contents to get the raw symlink target without sandboxing
    // the result. The target is an absolute path into the store.
    dir.read_link_contents(rel_path)
        .map(|target| target.starts_with(library_abs))
        .unwrap_or(false)
}

/// Resolved exclude file location: either a relative path within repo_dir,
/// or a separately-opened Dir handle (worktree fallback).
enum ExcludeHandle {
    /// Exclude file is inside repo_dir (normal case: `.git/info/exclude`).
    InRepo(PathBuf),
    /// Exclude file is outside repo_dir (worktree case); holds an owned Dir
    /// opened at the common_dir, plus the relative path within it.
    External(Dir, PathBuf),
}

/// Resolve the exclude file location relative to a Dir handle.
///
/// For normal repos, `.git/info/exclude` is relative to repo_root → returns InRepo.
/// For worktrees where common_dir differs, opens a new ambient Dir → returns External.
fn resolve_exclude(repo_root: &Path) -> Option<(ExcludeHandle, PathBuf)> {
    let exclude_abs = git_utils::exclude_path(repo_root).ok()?;
    let rel_to_repo = exclude_abs.strip_prefix(repo_root).ok();

    if let Some(rel) = rel_to_repo {
        // Normal case: .git/info/exclude is within the repo directory.
        Some((ExcludeHandle::InRepo(rel.to_owned()), exclude_abs))
    } else {
        // Worktree fallback: exclude file is in the shared common_dir.
        // Open a new ambient Dir at the parent of the exclude file.
        let parent = exclude_abs.parent()?;
        let file_name = exclude_abs.file_name()?;
        let dir = Dir::open_ambient_dir(parent, ambient_authority()).ok()?;
        Some((
            ExcludeHandle::External(dir, PathBuf::from(file_name)),
            exclude_abs,
        ))
    }
}

/// Run an exclude operation (ensure/remove) through the resolved handle.
fn with_exclude_dir<F>(handle: &ExcludeHandle, repo_dir: &Dir, abs_context: &Path, f: F)
where
    F: FnOnce(&Dir, &Path, &Path),
{
    match handle {
        ExcludeHandle::InRepo(rel) => f(repo_dir, rel, abs_context),
        ExcludeHandle::External(dir, rel) => f(dir, rel, abs_context),
    }
}

// ---------------------------------------------------------------------------
// Safe remove (trash instead of hard delete)
// ---------------------------------------------------------------------------

/// Remove a file safely via its containing Dir handle.
///
/// Fallback chain:
/// 1. Rename into `~/.git-cloak/trash/<name>.<timestamp_nanos>` (fast, same-device)
/// 2. Throw error
fn safe_remove_in_dir(
    store: &Store,
    source_dir: &Dir,
    rel_path: &Path,
    abs_context: &Path, // for error messages and macOS trash
) -> Result<(), CloakError> {
    let trash_rel = Path::new("trash");
    store
        .dir()
        .create_dir_all(trash_rel)
        .map_err(|e| io_err(&store.base_path().join("trash"), e))?;

    let name = rel_path.file_name().unwrap_or_default().to_string_lossy();
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let trash_dest = trash_rel.join(format!("{name}.{ts}"));

    // 1. Rename from source_dir into store's trash
    if source_dir
        .rename(rel_path, store.dir(), &trash_dest)
        .is_ok()
    {
        return Ok(());
    }

    Err(CloakError::Io {
        path: abs_context.join(rel_path),
        source: std::io::Error::new(std::io::ErrorKind::Other, "Failed to rename file"),
    })
}

// ---------------------------------------------------------------------------
// File-level ops
// ---------------------------------------------------------------------------

fn inject_single_file(
    store: &Store,
    pid: &Pid,
    target_path: &Path,
    repo_dir: &Dir,
    repo_root: &Path, // for git_utils calls and error messages
) -> Result<(), CloakError> {
    let library_abs = store.base_path().join("library");

    if is_cloak_symlink(repo_dir, target_path, &library_abs) {
        // Already injected
        return Ok(());
    }

    if repo_dir.symlink_metadata(target_path).is_ok() {
        return Err(CloakError::TargetOccupied(repo_root.join(target_path)));
    }

    // Create parent directories for the symlink
    if let Some(parent) = target_path.parent() {
        if !parent.as_os_str().is_empty() {
            repo_dir
                .create_dir_all(parent)
                .map_err(|e| io_err(&repo_root.join(parent), e))?;
        }
    }

    // Symlink target is an absolute path to the stored file.
    let stored_abs = store.stored_file_abs(pid, target_path);

    #[cfg(unix)]
    repo_dir
        .symlink_contents(&stored_abs, target_path)
        .map_err(|e| io_err(&repo_root.join(target_path), e))?;

    #[cfg(not(unix))]
    std::os::windows::fs::symlink_file(&stored_abs, &repo_root.join(target_path))
        .map_err(|e| io_err(&repo_root.join(target_path), e))?;

    // Add to git exclude
    if let Some((handle, abs)) = resolve_exclude(repo_root) {
        let entry = target_path.to_string_lossy();
        with_exclude_dir(&handle, repo_dir, &abs, |dir, rel, abs_ctx| {
            let _ = git_utils::ensure_excluded(dir, rel, abs_ctx, &[&entry]);
        });
    }

    Ok(())
}

fn eject_single_file(
    store: &Store,
    target_path: &Path,
    repo_dir: &Dir,
    repo_root: &Path,
    library_abs: &Path,
) -> Result<(), CloakError> {
    if is_cloak_symlink(repo_dir, target_path, library_abs) {
        safe_remove_in_dir(store, repo_dir, target_path, repo_root)?;
    }

    // Remove from git exclude
    if let Some((handle, abs)) = resolve_exclude(repo_root) {
        let entry = target_path.to_string_lossy();
        with_exclude_dir(&handle, repo_dir, &abs, |dir, rel, abs_ctx| {
            let _ = git_utils::remove_excluded(dir, rel, abs_ctx, &[&entry]);
        });
    }

    Ok(())
}

/// Move a file between two Dir-sandboxed scopes, with cross-device fallback.
fn rename_or_copy(
    src_dir: &Dir,
    src_rel: &Path,
    dst_dir: &Dir,
    dst_rel: &Path,
    abs_src_base: &Path, // for error messages
    abs_dst_base: &Path, // for error messages
) -> Result<(), CloakError> {
    // Ensure parent directory of destination exists
    if let Some(parent) = dst_rel.parent() {
        if !parent.as_os_str().is_empty() {
            dst_dir
                .create_dir_all(parent)
                .map_err(|e| io_err(&abs_dst_base.join(parent), e))?;
        }
    }

    match src_dir.rename(src_rel, dst_dir, dst_rel) {
        Ok(()) => Ok(()),
        Err(e) => {
            #[cfg(unix)]
            let is_xdev = e.raw_os_error() == Some(libc::EXDEV);
            #[cfg(not(unix))]
            let is_xdev = true; // always fallback on non-unix

            if is_xdev {
                src_dir
                    .copy(src_rel, dst_dir, dst_rel)
                    .map_err(|e| io_err(&abs_dst_base.join(dst_rel), e))?;
                src_dir
                    .remove_file(src_rel)
                    .map_err(|e| io_err(&abs_src_base.join(src_rel), e))?;
                Ok(())
            } else {
                Err(io_err(&abs_dst_base.join(dst_rel), e))
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Public commands
// ---------------------------------------------------------------------------

pub fn track(file: &Path, target_path: Option<&Path>) -> Result<(), CloakError> {
    let ctx = Context::resolve()?;
    let cwd = &ctx.cwd;

    let file_abs = if file.is_absolute() {
        file.to_owned()
    } else {
        cwd.join(file)
    };

    let root = ctx.repo_root.as_deref().unwrap_or(&ctx.cwd_canonical);
    let repo_dir = ctx.repo_dir.as_ref().unwrap();
    let library_abs = ctx.store.base_path().join("library");

    // Compute a repo-relative path for Dir-based existence check.
    let file_normalized = normalize_path(&file_abs);
    let file_repo_rel = file_normalized
        .strip_prefix(root)
        .map(|p| p.to_owned())
        .map_err(|_| CloakError::OutsideRepo {
            file: file_normalized.clone(),
            root: root.to_owned(),
        })?;

    // Check existence via Dir handle (no ambient authority).
    if repo_dir.symlink_metadata(&file_repo_rel).is_err() {
        return Err(CloakError::FileNotFound(file_abs));
    }

    // Early return: if the file is already a cloak symlink, it's already tracked.
    if is_cloak_symlink(repo_dir, &file_repo_rel, &library_abs) {
        println!("Already tracked: {}", file_repo_rel.display());
        return Ok(());
    }

    let target = resolve_target_path(&file_abs, target_path, Some(root))?;

    let stored_rel = ctx.store.stored_file_rel(&ctx.pid, &target);

    // Already tracked: stored file exists and symlink in place
    if ctx.store.dir().exists(&stored_rel) && is_cloak_symlink(repo_dir, &target, &library_abs) {
        println!("Already tracked: {}", target.display());
        return Ok(());
    }

    // Move file from repo to store
    rename_or_copy(
        repo_dir,
        &file_repo_rel,
        ctx.store.dir(),
        &stored_rel,
        root,
        ctx.store.base_path(),
    )?;

    // Update manifest
    let mut manifest = ctx
        .store
        .load_manifest(&ctx.pid)?
        .unwrap_or_else(|| store::new_manifest(ctx.pid.clone()));
    manifest.upsert_file(FileEntry {
        target_path: target.clone(),
        strategy: Strategy::Symlink,
        theirs_hash: None,
    });
    ctx.store.save_manifest(&manifest)?;

    // Update global index
    let mut index = ctx.store.load_index()?;
    let project_name = root
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| ctx.pid.to_string());
    store::upsert_project(&mut index, &ctx.pid, project_name, root.to_owned());
    ctx.store.save_index(&index)?;

    // Create symlink + exclude entry
    inject_single_file(&ctx.store, &ctx.pid, &target, repo_dir, root)?;

    println!("Tracked: {}", target.display());
    Ok(())
}

pub fn untrack(file_in_project: &Path) -> Result<(), CloakError> {
    let ctx = Context::resolve()?;
    let root = ctx.repo_root.as_deref().unwrap_or(&ctx.cwd_canonical);
    let repo_dir = ctx.repo_dir.as_ref().unwrap();

    // Compute target_path from input using pre-canonicalized root and cwd
    let target = if file_in_project.is_absolute() {
        file_in_project
            .strip_prefix(root)
            .map(|p| p.to_owned())
            .map_err(|_| CloakError::OutsideRepo {
                file: file_in_project.to_owned(),
                root: root.to_owned(),
            })?
    } else {
        // Relative path: might be relative to cwd, need to make it relative to repo root
        let abs = normalize_path(&ctx.cwd_canonical.join(file_in_project));
        abs.strip_prefix(root)
            .map(|p| p.to_owned())
            .unwrap_or_else(|_| file_in_project.to_owned())
    };

    // Load manifest, verify file is tracked
    let mut manifest = ctx
        .store
        .load_manifest(&ctx.pid)?
        .ok_or_else(|| CloakError::NotTracked(target.clone()))?;

    if manifest.find_file(&target).is_none() {
        return Err(CloakError::NotTracked(target));
    }

    let library_abs = ctx.store.base_path().join("library");

    // Eject: remove symlink + exclude
    eject_single_file(&ctx.store, &target, repo_dir, root, &library_abs)?;

    // Move stored file back to workspace
    let stored_rel = ctx.store.stored_file_rel(&ctx.pid, &target);
    if ctx.store.dir().exists(&stored_rel) {
        rename_or_copy(
            ctx.store.dir(),
            &stored_rel,
            repo_dir,
            &target,
            ctx.store.base_path(),
            root,
        )?;
    }

    // Remove from manifest
    manifest.remove_file(&target);
    ctx.store.save_manifest(&manifest)?;

    // If manifest is now empty, remove project from index
    if manifest.files.is_empty() {
        let mut index = ctx.store.load_index()?;
        store::remove_project(&mut index, &ctx.pid);
        ctx.store.save_index(&index)?;
    }

    println!("Untracked: {}", target.display());
    Ok(())
}

pub fn inject() -> Result<(), CloakError> {
    let ctx = Context::resolve()?;
    let root = ctx.repo_root.as_deref().unwrap_or(&ctx.cwd_canonical);
    let repo_dir = ctx.repo_dir.as_ref().unwrap();

    let manifest = match ctx.store.load_manifest(&ctx.pid)? {
        Some(m) => m,
        None => {
            println!("No tracked files for this project.");
            return Ok(());
        }
    };

    for entry in &manifest.files {
        if entry.strategy == Strategy::Symlink {
            inject_single_file(&ctx.store, &ctx.pid, &entry.target_path, repo_dir, root)?;
        }
    }

    // Update last_known_path in global index
    let mut index = ctx.store.load_index()?;
    if let Some(project) = index.projects.get_mut(ctx.pid.as_str()) {
        project.last_known_path = root.to_owned();
    }
    ctx.store.save_index(&index)?;

    println!(
        "Injected {} file(s).",
        manifest
            .files
            .iter()
            .filter(|f| f.strategy == Strategy::Symlink)
            .count()
    );
    Ok(())
}

pub fn eject() -> Result<(), CloakError> {
    let ctx = Context::resolve()?;
    let root = ctx.repo_root.as_deref().unwrap_or(&ctx.cwd_canonical);
    let repo_dir = ctx.repo_dir.as_ref().unwrap();

    let manifest = match ctx.store.load_manifest(&ctx.pid)? {
        Some(m) => m,
        None => {
            println!("No tracked files for this project.");
            return Ok(());
        }
    };

    let library_abs = ctx.store.base_path().join("library");

    // Collect all target paths for batch exclude removal
    let target_strs: Vec<String> = manifest
        .files
        .iter()
        .map(|f| f.target_path.to_string_lossy().into_owned())
        .collect();

    for entry in &manifest.files {
        if is_cloak_symlink(repo_dir, &entry.target_path, &library_abs) {
            safe_remove_in_dir(&ctx.store, repo_dir, &entry.target_path, root)?;
        }
    }

    // Batch remove exclude entries
    if let Some((handle, abs)) = resolve_exclude(root) {
        let refs: Vec<&str> = target_strs.iter().map(|s| s.as_str()).collect();
        with_exclude_dir(&handle, repo_dir, &abs, |dir, rel, abs_ctx| {
            let _ = git_utils::remove_excluded(dir, rel, abs_ctx, &refs);
        });
    }

    println!("Ejected {} file(s).", manifest.files.len());
    Ok(())
}

pub fn status() -> Result<(), CloakError> {
    let ctx = Context::resolve()?;
    let repo_dir = ctx.repo_dir.as_ref().unwrap();
    let library_abs = ctx.store.base_path().join("library");

    let manifest = match ctx.store.load_manifest(&ctx.pid)? {
        Some(m) => m,
        None => {
            println!("No tracked files.");
            return Ok(());
        }
    };

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

    for entry in &manifest.files {
        let stored_rel = ctx.store.stored_file_rel(&ctx.pid, &entry.target_path);
        let stored_exists = ctx.store.dir().exists(&stored_rel);

        // TODO situ extract to enum, and notes it is not the final definition. should TBD
        let state = if !stored_exists {
            "Orphaned"
        } else if is_cloak_symlink(repo_dir, &entry.target_path, &library_abs) {
            "Linked"
        } else {
            "Ejected"
        };

        let strategy = match entry.strategy {
            Strategy::Symlink => "symlink",
            Strategy::Merge => "merge",
        };

        println!(
            "{}  {}  {}",
            entry.target_path.display(),
            strategy,
            state,
        );
    }

    Ok(())
}

pub fn projects() -> Result<(), CloakError> {
    let store = Store::open()?;
    let index = store.load_index()?;

    if index.projects.is_empty() {
        println!("No managed projects.");
        return Ok(());
    }

    for (_pid, entry) in &index.projects {
        println!(
            "{}  {}  {}",
            entry.name,
            entry.project_type,
            entry.last_known_path.display(),
        );
    }

    Ok(())
}