repotoire 0.7.1

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use dashmap::DashMap;

use super::commit::RawCommit;
use super::error::GitError;
use super::object::{self, ObjectType};
use super::oid::Oid;
use super::pack::Packfile;
use super::pack_index::PackIndex;
use super::tree::{self, TreeEntry};

const MAX_SYMREF_DEPTH: usize = 10;

/// Soft upper bound on total bytes held in the object cache.
///
/// Once we cross this threshold we stop caching new objects for the
/// rest of the `RawRepo`'s lifetime. This is a deliberately simple
/// bound — no per-entry eviction — because under parallel blame
/// workloads an LRU behind a `Mutex` serialized every cache hit (see
/// the prior `Arc<RawRepo>` sharing attempt: a single global mutex
/// dwarfed the per-worker `discover()` savings by ~5x on an ARM64
/// bench). At the limit the cache degrades to "no caching" for new
/// Oids while still serving hits on everything cached before the cap.
///
/// 64MB mirrors the prior LRU ceiling and empirically covers the
/// commit+tree working set for repos in the ~100k-LOC range.
const CACHE_SOFT_CAP_BYTES: usize = 64 * 1024 * 1024;

/// A pure-Rust read-only git repository handle.
///
/// Supports loose objects, packfiles, packed-refs, worktrees,
/// alternates, and shallow clones.
///
/// Thread-safety: all internal state is read-only after construction
/// except `cache`, which is a lock-free sharded `DashMap`. A single
/// `RawRepo` can be shared across rayon workers via `Arc` without
/// serialization bottlenecks.
pub struct RawRepo {
    git_dir: PathBuf,
    common_dir: PathBuf,
    workdir: PathBuf,
    pack_stores: Vec<(PackIndex, Packfile)>,
    packed_refs: Vec<(String, Oid)>,
    shallow_oids: HashSet<Oid>,
    cache: ObjectCache,
}

/// Concurrent object cache for commit and tree payloads.
///
/// Backed by `DashMap<Oid, CachedObject>` with per-shard locking, so
/// `find_object` calls from parallel rayon workers don't serialize on
/// a single mutex the way the prior `Mutex<LruCache>` did.
///
/// No LRU eviction: once `total_bytes` exceeds `CACHE_SOFT_CAP_BYTES`
/// we stop admitting new entries. This keeps the hot path branch-free
/// and avoids the write contention an LRU's recency-update would
/// introduce. Objects are only inserted for Commit/Tree (small,
/// frequently re-read) — blob/tag admission policy is unchanged from
/// the prior implementation.
struct ObjectCache {
    entries: DashMap<Oid, CachedObject>,
    total_bytes: AtomicUsize,
}

#[derive(Clone)]
struct CachedObject {
    obj_type: ObjectType,
    data: std::sync::Arc<[u8]>,
}

impl ObjectCache {
    fn new() -> Self {
        Self {
            entries: DashMap::new(),
            total_bytes: AtomicUsize::new(0),
        }
    }

    fn get(&self, oid: &Oid) -> Option<(ObjectType, Vec<u8>)> {
        let entry = self.entries.get(oid)?;
        // Consumers receive an owned `Vec<u8>` — matches the prior
        // `LruCache::get` signature so call sites don't need updating.
        // The per-get allocation is the price of a shared cache with
        // owned outputs; if it shows up in profiles we can switch
        // callers to `Arc<[u8]>` directly.
        Some((entry.obj_type, entry.data.as_ref().to_vec()))
    }

    fn insert(&self, oid: Oid, obj_type: ObjectType, data: &[u8]) {
        // Admission check: if we've crossed the soft cap, don't grow.
        // Load is Relaxed because this is an advisory bound — a few
        // extra inserts racing past the cap are harmless.
        if self.total_bytes.load(Ordering::Relaxed) >= CACHE_SOFT_CAP_BYTES {
            return;
        }
        let size = data.len();
        let cached = CachedObject {
            obj_type,
            data: std::sync::Arc::from(data),
        };
        // `insert` returns the prior value if the key was already
        // present. Only bump the byte counter on a fresh insertion so
        // we don't double-count when two workers race on the same Oid.
        if self.entries.insert(oid, cached).is_none() {
            self.total_bytes.fetch_add(size, Ordering::Relaxed);
        }
    }
}

impl RawRepo {
    /// Discover a git repository by walking up from the given path.
    pub fn discover(start: &Path) -> Result<Self, GitError> {
        let start = start
            .canonicalize()
            .map_err(|e| GitError::NotAGitRepo(format!("{}: {e}", start.display())))?;
        let mut dir = start.as_path();

        loop {
            let git_path = dir.join(".git");
            if git_path.is_dir() {
                return Self::open_git_dir(git_path, dir.to_path_buf());
            }
            if git_path.is_file() {
                // Worktree: .git file contains "gitdir: <path>"
                let content = std::fs::read_to_string(&git_path).map_err(GitError::Io)?;
                let gitdir = content
                    .strip_prefix("gitdir: ")
                    .ok_or_else(|| {
                        GitError::NotAGitRepo(format!("invalid .git file: {}", git_path.display()))
                    })?
                    .trim();
                let git_dir = if Path::new(gitdir).is_absolute() {
                    PathBuf::from(gitdir)
                } else {
                    dir.join(gitdir)
                };
                return Self::open_git_dir(git_dir, dir.to_path_buf());
            }
            if let Some(parent) = dir.parent() {
                dir = parent;
            } else {
                return Err(GitError::NotAGitRepo(format!(
                    "no .git found from {}",
                    start.display()
                )));
            }
        }
    }

    fn open_git_dir(git_dir: PathBuf, workdir: PathBuf) -> Result<Self, GitError> {
        // Resolve common dir (for worktrees)
        let common_dir = {
            let commondir_file = git_dir.join("commondir");
            if commondir_file.exists() {
                let content = std::fs::read_to_string(&commondir_file).map_err(GitError::Io)?;
                let path = content.trim();
                if Path::new(path).is_absolute() {
                    PathBuf::from(path)
                } else {
                    git_dir.join(path)
                }
            } else {
                git_dir.clone()
            }
        };

        // Check for SHA-256 extension
        let config_path = common_dir.join("config");
        if config_path.exists() {
            let config = std::fs::read_to_string(&config_path).unwrap_or_default();
            if config.contains("objectFormat = sha256") || config.contains("objectformat = sha256")
            {
                return Err(GitError::NotAGitRepo(
                    "SHA-256 repositories are not supported".into(),
                ));
            }
        }

        // Load pack stores
        let pack_dir = common_dir.join("objects/pack");
        let mut pack_stores = Vec::new();
        if pack_dir.is_dir() {
            for entry in std::fs::read_dir(&pack_dir)
                .map_err(GitError::Io)?
                .flatten()
            {
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) == Some("idx") {
                    let pack_path = path.with_extension("pack");
                    if pack_path.exists() {
                        let idx = PackIndex::open(&path)?;
                        let pack = Packfile::open(&pack_path)?;
                        pack_stores.push((idx, pack));
                    }
                }
            }
        }

        // Load alternates
        let alternates_path = common_dir.join("objects/info/alternates");
        if alternates_path.exists() {
            let content = std::fs::read_to_string(&alternates_path).unwrap_or_default();
            for line in content.lines() {
                let alt_dir = if Path::new(line).is_absolute() {
                    PathBuf::from(line)
                } else {
                    common_dir.join("objects").join(line)
                };
                let alt_pack_dir = alt_dir.join("pack");
                if alt_pack_dir.is_dir() {
                    for entry in std::fs::read_dir(&alt_pack_dir)
                        .map_err(GitError::Io)?
                        .flatten()
                    {
                        let path = entry.path();
                        if path.extension().and_then(|e| e.to_str()) == Some("idx") {
                            let pack_path = path.with_extension("pack");
                            if pack_path.exists() {
                                let idx = PackIndex::open(&path)?;
                                let pack = Packfile::open(&pack_path)?;
                                pack_stores.push((idx, pack));
                            }
                        }
                    }
                }
            }
        }

        // Parse packed-refs
        let mut packed_refs = Vec::new();
        let packed_refs_path = common_dir.join("packed-refs");
        if packed_refs_path.exists() {
            let content = std::fs::read_to_string(&packed_refs_path).unwrap_or_default();
            for line in content.lines() {
                if line.starts_with('#') || line.starts_with('^') {
                    continue;
                }
                if let Some((hex, refname)) = line.split_once(' ') {
                    if hex.len() == 40 {
                        if let Ok(oid) = Oid::from_hex(hex) {
                            packed_refs.push((refname.to_string(), oid));
                        }
                    }
                }
            }
        }

        // Parse shallow commits
        let mut shallow_oids = HashSet::new();
        let shallow_path = common_dir.join("shallow");
        if shallow_path.exists() {
            let content = std::fs::read_to_string(&shallow_path).unwrap_or_default();
            for line in content.lines() {
                if let Ok(oid) = Oid::from_hex(line.trim()) {
                    shallow_oids.insert(oid);
                }
            }
        }

        Ok(Self {
            git_dir,
            common_dir,
            workdir,
            pack_stores,
            packed_refs,
            shallow_oids,
            cache: ObjectCache::new(),
        })
    }

    pub fn workdir(&self) -> &Path {
        &self.workdir
    }

    pub fn git_dir(&self) -> &Path {
        &self.git_dir
    }

    pub fn common_dir(&self) -> &Path {
        &self.common_dir
    }

    /// Resolve HEAD to an OID.
    pub fn resolve_head(&self) -> Result<Oid, GitError> {
        let head_path = self.git_dir.join("HEAD");
        let content = std::fs::read_to_string(&head_path).map_err(GitError::Io)?;
        let content = content.trim();

        if let Some(refname) = content.strip_prefix("ref: ") {
            self.resolve_ref(refname)
        } else {
            Oid::from_hex(content)
        }
    }

    /// Resolve a ref name (e.g., "refs/heads/main") to an OID.
    pub fn resolve_ref(&self, refname: &str) -> Result<Oid, GitError> {
        self.resolve_ref_recursive(refname, 0)
    }

    fn resolve_ref_recursive(&self, refname: &str, depth: usize) -> Result<Oid, GitError> {
        if depth > MAX_SYMREF_DEPTH {
            return Err(GitError::RefNotFound(format!("symref loop: {refname}")));
        }

        // Check loose ref
        let ref_path = self.common_dir.join(refname);
        if ref_path.exists() {
            let content = std::fs::read_to_string(&ref_path).map_err(GitError::Io)?;
            let content = content.trim();
            if let Some(target) = content.strip_prefix("ref: ") {
                return self.resolve_ref_recursive(target, depth + 1);
            }
            return Oid::from_hex(content);
        }

        // Check packed-refs
        for (name, oid) in &self.packed_refs {
            if name == refname {
                return Ok(*oid);
            }
        }

        Err(GitError::RefNotFound(refname.to_string()))
    }

    /// Read a raw git object by OID.
    pub fn find_object(&self, oid: &Oid) -> Result<(ObjectType, Vec<u8>), GitError> {
        // Fast path: cache hit. DashMap shards the read so parallel
        // workers don't serialize on a single lock.
        if let Some(result) = self.cache.get(oid) {
            return Ok(result);
        }

        // Try loose objects
        let objects_dir = self.common_dir.join("objects");
        match object::read_loose_object(&objects_dir, oid) {
            Ok(result) => {
                self.cache_object(oid, &result);
                return Ok(result);
            }
            Err(GitError::ObjectNotFound(_)) => {}
            Err(e) => return Err(e),
        }

        // Try pack stores
        for (idx, pack) in &self.pack_stores {
            if let Some(offset) = idx.find(oid) {
                let result = pack.read_object_at(offset, idx)?;
                self.cache_object(oid, &result);
                return Ok(result);
            }
        }

        Err(GitError::ObjectNotFound(*oid))
    }

    fn cache_object(&self, oid: &Oid, result: &(ObjectType, Vec<u8>)) {
        // Only cache commits and trees (small, frequently accessed).
        // Blobs and tags are read once and discarded.
        if matches!(result.0, ObjectType::Commit | ObjectType::Tree) {
            self.cache.insert(*oid, result.0, &result.1);
        }
    }

    /// Parse a commit object by OID.
    pub fn find_commit(&self, oid: &Oid) -> Result<RawCommit, GitError> {
        let (obj_type, data) = self.find_object(oid)?;
        match obj_type {
            ObjectType::Commit => RawCommit::parse(&data),
            ObjectType::Tag => {
                // Peel tag to commit
                let text = std::str::from_utf8(&data).map_err(|_| GitError::CorruptObject {
                    path: String::new(),
                    detail: "non-UTF8 tag".into(),
                })?;
                for line in text.lines() {
                    if let Some(hex) = line.strip_prefix("object ") {
                        let target = Oid::from_hex(hex.trim())?;
                        return self.find_commit(&target);
                    }
                }
                Err(GitError::CorruptObject {
                    path: String::new(),
                    detail: "tag without object field".into(),
                })
            }
            _ => Err(GitError::CorruptObject {
                path: String::new(),
                detail: format!("expected commit, got {obj_type:?}"),
            }),
        }
    }

    /// Parse a tree object by OID.
    pub fn find_tree(&self, oid: &Oid) -> Result<Vec<TreeEntry>, GitError> {
        let (obj_type, data) = self.find_object(oid)?;
        if obj_type != ObjectType::Tree {
            return Err(GitError::CorruptObject {
                path: String::new(),
                detail: format!("expected tree, got {obj_type:?}"),
            });
        }
        tree::parse_tree(&data)
    }

    /// Read a blob object by OID.
    pub fn find_blob(&self, oid: &Oid) -> Result<Vec<u8>, GitError> {
        let (obj_type, data) = self.find_object(oid)?;
        if obj_type != ObjectType::Blob {
            return Err(GitError::CorruptObject {
                path: String::new(),
                detail: format!("expected blob, got {obj_type:?}"),
            });
        }
        Ok(data)
    }

    /// Resolve HEAD and return its tree entries.
    pub fn head_tree(&self) -> Result<(Oid, Vec<TreeEntry>), GitError> {
        let head = self.resolve_head()?;
        let commit = self.find_commit(&head)?;
        let entries = self.find_tree(&commit.tree_oid)?;
        Ok((commit.tree_oid, entries))
    }

    /// Walk first-parent chain from HEAD to find the root commit.
    pub fn find_root_commit(&self) -> Result<Oid, GitError> {
        let mut current = self.resolve_head()?;
        loop {
            let commit = self.find_commit(&current)?;
            if commit.parents.is_empty() || self.shallow_oids.contains(&current) {
                return Ok(current);
            }
            current = commit.parents[0];
        }
    }

    /// Check if a commit is a shallow boundary.
    pub fn is_shallow(&self, oid: &Oid) -> bool {
        self.shallow_oids.contains(oid)
    }
}

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

    #[test]
    fn test_discover_repo() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        assert!(repo.workdir().exists());
    }

    #[test]
    fn test_resolve_head() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let head_oid = repo.resolve_head().unwrap();
        assert_ne!(head_oid, Oid::ZERO);
    }

    #[test]
    fn test_find_commit() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let head_oid = repo.resolve_head().unwrap();
        let commit = repo.find_commit(&head_oid).unwrap();
        assert_ne!(commit.tree_oid, Oid::ZERO);
        assert!(!commit.author_name.is_empty());
    }

    #[test]
    fn test_find_tree() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let head_oid = repo.resolve_head().unwrap();
        let commit = repo.find_commit(&head_oid).unwrap();
        let entries = repo.find_tree(&commit.tree_oid).unwrap();
        assert!(!entries.is_empty());
    }

    #[test]
    fn test_head_tree() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let (_oid, entries) = repo.head_tree().unwrap();
        assert!(!entries.is_empty());
    }

    #[test]
    fn test_not_a_repo() {
        let result = RawRepo::discover(Path::new("/tmp"));
        assert!(result.is_err());
    }

    #[test]
    fn test_find_root_commit() {
        let repo = RawRepo::discover(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let root = repo.find_root_commit().unwrap();
        let commit = repo.find_commit(&root).unwrap();
        assert!(commit.parents.is_empty());
    }

    #[test]
    fn test_detached_head() {
        let dir = tempfile::tempdir().unwrap();
        let run = |args: &[&str]| {
            std::process::Command::new("git")
                .args(args)
                .current_dir(dir.path())
                .env("GIT_AUTHOR_NAME", "Test")
                .env("GIT_AUTHOR_EMAIL", "t@t.com")
                .env("GIT_COMMITTER_NAME", "Test")
                .env("GIT_COMMITTER_EMAIL", "t@t.com")
                .output()
                .expect("git command failed")
        };
        run(&["init"]);
        run(&["config", "user.name", "Test"]);
        run(&["config", "user.email", "t@t.com"]);
        std::fs::write(dir.path().join("f.txt"), "x").unwrap();
        run(&["add", "."]);
        run(&["commit", "-m", "init"]);
        run(&["checkout", "--detach", "HEAD"]);

        let repo = RawRepo::discover(dir.path()).unwrap();
        let head = repo.resolve_head().unwrap();
        assert_ne!(head, Oid::ZERO);
    }

    #[test]
    fn test_empty_repo() {
        let dir = tempfile::tempdir().unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        let repo = RawRepo::discover(dir.path()).unwrap();
        assert!(repo.resolve_head().is_err());
    }

    #[test]
    fn test_sha256_detection() {
        let dir = tempfile::tempdir().unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        let config_path = dir.path().join(".git/config");
        let mut config = std::fs::read_to_string(&config_path).unwrap();
        config.push_str("\n[extensions]\n\tobjectFormat = sha256\n");
        std::fs::write(&config_path, config).unwrap();
        let result = RawRepo::discover(dir.path());
        assert!(result.is_err(), "should reject SHA-256 repos");
    }
}