puregit 0.0.1

A pure-Rust implementation of git, in the spirit of libgit2, built on purecrypto. Object model, packfiles, refs, and the smart transport over HTTP and SSH — client and server.
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
//! References — branches, tags, `HEAD`, and the ref store.
//!
//! A reference is a named pointer. It is either *direct* (it holds an
//! [`ObjectId`]) or *symbolic* (it holds the name of another ref, like `HEAD →
//! refs/heads/main`). On disk a ref is either a "loose" file under
//! `refs/…` (or a top-level pseudo-ref like `HEAD`) containing one line, or an
//! entry in the consolidated `packed-refs` file.
//!
//! This module owns:
//! - [`is_valid_ref_name`] — git's reference-name rules (`git-check-ref-format`).
//! - [`Reference`] — the direct/symbolic value, with [`Reference::parse`] for a
//!   loose ref file's contents.
//! - [`parse_packed_refs`] — the `packed-refs` file format (incl. peeled tags).
//! - [`RefStore`] — a [`crate::vfs::Vfs`]-backed store that resolves and updates refs.

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::error::{Error, ObjectKindHint, Result};
use crate::oid::{HashAlgo, ObjectId};
use crate::vfs::Vfs;

/// The value of a reference: a direct object id or a pointer to another ref.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reference {
    /// Points directly at an object.
    Direct(ObjectId),
    /// Points at another reference by name (`ref: refs/heads/main`).
    Symbolic(String),
}

impl Reference {
    /// Parses the contents of a loose ref file.
    ///
    /// A symbolic ref is `ref: <target>\n`; otherwise the file holds a single
    /// hex object id. Trailing whitespace is tolerated.
    pub fn parse(algo: HashAlgo, contents: &[u8]) -> Result<Self> {
        let text = core::str::from_utf8(contents)
            .map_err(|_| Error::Reference("non-utf8 ref contents".to_string()))?
            .trim();
        if let Some(target) = text.strip_prefix("ref:") {
            let target = target.trim();
            if !is_valid_ref_name(target) {
                return Err(Error::Reference(format!(
                    "symbolic ref target is not a valid name: {target:?}"
                )));
            }
            Ok(Reference::Symbolic(target.to_string()))
        } else {
            Ok(Reference::Direct(ObjectId::from_hex(algo, text)?))
        }
    }

    /// Serializes the ref to its loose-file contents (with trailing newline).
    pub fn to_file_contents(&self) -> Vec<u8> {
        let mut s = match self {
            Reference::Direct(id) => id.to_hex(),
            Reference::Symbolic(target) => format!("ref: {target}"),
        };
        s.push('\n');
        s.into_bytes()
    }
}

/// Validates a reference name against git's rules (a subset of
/// `git-check-ref-format`): no `..`, no leading/trailing or doubled `/`, no
/// control or special characters (` `, `~`, `^`, `:`, `?`, `*`, `[`, `\`), no
/// component starting with `.` or ending in `.lock`, and not the single
/// character `@`.
pub fn is_valid_ref_name(name: &str) -> bool {
    if name.is_empty() || name == "@" {
        return false;
    }
    if name.starts_with('/') || name.ends_with('/') || name.contains("//") {
        return false;
    }
    if name.contains("..") || name.contains("@{") {
        return false;
    }
    if name.ends_with('.') || name.ends_with(".lock") {
        return false;
    }
    for component in name.split('/') {
        if component.is_empty() || component.starts_with('.') || component.ends_with(".lock") {
            return false;
        }
    }
    for &b in name.as_bytes() {
        match b {
            0..=0x20 | 0x7f => return false, // control chars and space
            b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\' => return false,
            _ => {}
        }
    }
    true
}

/// One parsed entry from a `packed-refs` file: the ref name, its object id, and
/// (for annotated tags) the peeled commit id from the following `^…` line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackedRef {
    /// The full ref name (e.g. `refs/tags/v1.0`).
    pub name: String,
    /// The object the ref points at.
    pub id: ObjectId,
    /// For an annotated tag, the underlying commit (the `^<oid>` peel line).
    pub peeled: Option<ObjectId>,
}

/// Serializes `packed-refs` entries back to the file format: the standard
/// header line, then one `"<oid> <name>"` line per ref with a `"^<oid>"` peel
/// line for annotated tags. Used to rewrite the file when a packed ref is
/// deleted.
fn serialize_packed_refs<'a>(entries: impl Iterator<Item = &'a PackedRef>) -> Vec<u8> {
    let mut out = String::from("# pack-refs with: peeled fully-peeled sorted \n");
    for e in entries {
        out.push_str(&format!("{} {}\n", e.id.to_hex(), e.name));
        if let Some(peeled) = e.peeled {
            out.push_str(&format!("^{}\n", peeled.to_hex()));
        }
    }
    out.into_bytes()
}

/// Parses a `packed-refs` file into its entries.
///
/// The format is a `# pack-refs with: …` header line, then `"<oid> <name>"`
/// lines, each optionally followed by a `"^<oid>"` line giving the peeled
/// target of an annotated tag.
pub fn parse_packed_refs(algo: HashAlgo, contents: &[u8]) -> Result<Vec<PackedRef>> {
    let text = core::str::from_utf8(contents)
        .map_err(|_| Error::Reference("non-utf8 packed-refs".to_string()))?;
    let mut out: Vec<PackedRef> = Vec::new();
    // Tracks whether the most recent ref line was skipped for an invalid name,
    // so a following `^<oid>` peel line is dropped with it rather than being
    // mis-attached to an earlier, valid ref.
    let mut last_skipped = false;
    for line in text.lines() {
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(peel) = line.strip_prefix('^') {
            let id = ObjectId::from_hex(algo, peel.trim())?;
            if last_skipped {
                // The ref this peel belongs to was rejected; ignore the peel.
                continue;
            }
            let last = out
                .last_mut()
                .ok_or_else(|| Error::Reference("packed-refs: peel line without ref".into()))?;
            last.peeled = Some(id);
            continue;
        }
        let (oid, name) = line
            .split_once(' ')
            .ok_or_else(|| Error::Reference("packed-refs: malformed line".into()))?;
        let name = name.trim();
        // A `packed-refs` file can come from an untrusted remote (it is written
        // during fetch/clone). Unlike the loose-ref write path, names here were
        // stored unchecked (D5); a malformed name (`..`, control chars, an
        // absolute-looking path) must not become a resolvable ref. Match git and
        // skip such lines rather than aborting the whole parse.
        if !is_valid_ref_name(name) {
            last_skipped = true;
            continue;
        }
        last_skipped = false;
        out.push(PackedRef {
            name: name.to_string(),
            id: ObjectId::from_hex(algo, oid.trim())?,
            peeled: None,
        });
    }
    Ok(out)
}

/// A [`crate::vfs::Vfs`]-backed reference store rooted at the git directory.
///
/// Resolves loose refs first, then falls back to `packed-refs`, and follows
/// symbolic refs (with a depth limit) to a final object id.
#[derive(Debug, Clone)]
pub struct RefStore<V: Vfs> {
    vfs: V,
    algo: HashAlgo,
}

const MAX_SYMREF_DEPTH: usize = 5;

impl<V: Vfs> RefStore<V> {
    /// Creates a ref store over a VFS rooted at the git directory (so it reads
    /// `HEAD`, `refs/…`, and `packed-refs` directly).
    pub fn new(vfs: V, algo: HashAlgo) -> Self {
        RefStore { vfs, algo }
    }

    /// Reads a single ref's value without following symrefs. Consults the loose
    /// file first, then `packed-refs`. Returns [`Error::NotFound`] if neither
    /// has it.
    pub fn lookup(&self, name: &str) -> Result<Reference> {
        if self.vfs.exists(name) {
            let contents = self.vfs.read(name)?;
            return Reference::parse(self.algo, &contents);
        }
        for entry in self.packed()? {
            if entry.name == name {
                return Ok(Reference::Direct(entry.id));
            }
        }
        Err(Error::NotFound(ObjectKindHint::Reference(name.to_string())))
    }

    /// Resolves a ref all the way to an object id, following symbolic refs.
    pub fn resolve(&self, name: &str) -> Result<ObjectId> {
        let mut current = name.to_string();
        for _ in 0..MAX_SYMREF_DEPTH {
            match self.lookup(&current)? {
                Reference::Direct(id) => return Ok(id),
                Reference::Symbolic(target) => current = target,
            }
        }
        Err(Error::Reference(format!(
            "symref chain too deep starting at {name}"
        )))
    }

    /// Writes a ref's value as a loose ref file (creating parent dirs). This
    /// does not update `packed-refs`; a loose ref shadows any packed entry of
    /// the same name, which is exactly git's precedence.
    pub fn update(&self, name: &str, value: &Reference) -> Result<()> {
        if !is_valid_ref_name(name) && name != "HEAD" {
            return Err(Error::Reference(format!("invalid ref name {name:?}")));
        }
        let contents = value.to_file_contents();
        // Lockfile update (git's `*.lock` protocol): create `<name>.lock`
        // exclusively so a concurrent writer of the same ref is detected and
        // rejected, write the new value into it, then atomically rename it into
        // place. A ref name can never end in `.lock` (see `is_valid_ref_name`),
        // so the lock path never collides with a real ref.
        let lock = format!("{name}.lock");
        self.vfs.create_new(&lock, &contents).map_err(|_| {
            Error::Reference(format!(
                "cannot lock ref {name:?}: it is already locked (another update in progress?)"
            ))
        })?;
        match self.vfs.rename(&lock, name) {
            Ok(()) => Ok(()),
            Err(e) => {
                let _ = self.vfs.remove_file(&lock);
                Err(e)
            }
        }
    }

    /// Deletes a loose ref. A packed entry of the same name is left in
    /// `packed-refs` (rewriting that file is a separate maintenance step), which
    /// matches git's loose-first deletion for the common case. Deleting a
    /// nonexistent loose ref is a no-op.
    pub fn delete(&self, name: &str) -> Result<()> {
        // Remove the loose ref file if present.
        if self.vfs.exists(name) {
            self.vfs.remove_file(name)?;
        }
        // A ref can also live only in `packed-refs`; drop it there too, rewriting
        // the file without it (otherwise a "deleted" packed ref would reappear).
        if self.vfs.exists("packed-refs") {
            let contents = self.vfs.read("packed-refs")?;
            let entries = parse_packed_refs(self.algo, &contents)?;
            if entries.iter().any(|e| e.name == name) {
                let rewritten = serialize_packed_refs(entries.iter().filter(|e| e.name != name));
                self.vfs.write("packed-refs", &rewritten)?;
            }
        }
        Ok(())
    }

    /// Reads and parses `packed-refs` (empty if the file is absent).
    pub fn packed(&self) -> Result<Vec<PackedRef>> {
        if !self.vfs.exists("packed-refs") {
            return Ok(Vec::new());
        }
        let contents = self.vfs.read("packed-refs")?;
        parse_packed_refs(self.algo, &contents)
    }

    /// Lists all refs (loose and packed) under `refs/`, resolved to ids,
    /// as a name→id map. Loose refs win over packed on conflict.
    pub fn list(&self) -> Result<BTreeMap<String, ObjectId>> {
        let mut map = BTreeMap::new();
        for entry in self.packed()? {
            map.insert(entry.name, entry.id);
        }
        self.collect_loose("refs", &mut map)?;
        Ok(map)
    }

    fn collect_loose(&self, dir: &str, map: &mut BTreeMap<String, ObjectId>) -> Result<()> {
        if !self.vfs.exists(dir) {
            return Ok(());
        }
        for entry in self.vfs.read_dir(dir)? {
            let child = format!("{dir}/{}", entry.name);
            match entry.file_type {
                crate::vfs::FileType::Dir => self.collect_loose(&child, map)?,
                _ => {
                    if let Ok(id) = self.resolve(&child) {
                        map.insert(child, id);
                    }
                }
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn valid_names() {
        assert!(is_valid_ref_name("refs/heads/main"));
        assert!(is_valid_ref_name("refs/tags/v1.0.0"));
        assert!(!is_valid_ref_name("refs/heads/"));
        assert!(!is_valid_ref_name("refs//heads"));
        assert!(!is_valid_ref_name("refs/heads/..hidden"));
        assert!(!is_valid_ref_name("refs/heads/foo.lock"));
        assert!(!is_valid_ref_name("refs/heads/a b"));
        assert!(!is_valid_ref_name("@"));
    }

    #[test]
    fn parse_symbolic_head() {
        let r = Reference::parse(HashAlgo::Sha1, b"ref: refs/heads/main\n").unwrap();
        assert_eq!(r, Reference::Symbolic("refs/heads/main".to_string()));
        assert_eq!(r.to_file_contents(), b"ref: refs/heads/main\n");
    }

    #[test]
    fn parse_direct() {
        let hex = "ce013625030ba8dba906f756967f9e9ca394464a";
        let r = Reference::parse(HashAlgo::Sha1, format!("{hex}\n").as_bytes()).unwrap();
        match r {
            Reference::Direct(id) => assert_eq!(id.to_hex(), hex),
            _ => panic!("expected direct"),
        }
    }

    #[test]
    fn serialize_packed_refs_roundtrips_and_filters() {
        let oid =
            |b: u8| ObjectId::from_hex(HashAlgo::Sha1, &format!("{:02x}", b).repeat(20)).unwrap();
        let entries = alloc::vec![
            PackedRef {
                name: "refs/heads/main".into(),
                id: oid(0x11),
                peeled: None,
            },
            PackedRef {
                name: "refs/tags/v1".into(),
                id: oid(0x22),
                peeled: Some(oid(0x33)),
            },
        ];
        // Round-trip: serialize then re-parse yields the same entries.
        let back =
            parse_packed_refs(HashAlgo::Sha1, &serialize_packed_refs(entries.iter())).unwrap();
        assert_eq!(back, entries);
        // Filtering one out (what delete does) drops exactly that ref.
        let filtered =
            serialize_packed_refs(entries.iter().filter(|e| e.name != "refs/heads/main"));
        let kept = parse_packed_refs(HashAlgo::Sha1, &filtered).unwrap();
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].name, "refs/tags/v1");
        assert_eq!(kept[0].peeled, Some(oid(0x33)));
    }

    #[test]
    fn packed_refs_skips_invalid_names() {
        let good = "1111111111111111111111111111111111111111";
        let bad = "2222222222222222222222222222222222222222";
        let evil_peel = "3333333333333333333333333333333333333333";
        // A valid ref, then an invalid one (`..` component) with a dangling
        // peel line that must be dropped with it — not attached to the good ref.
        let contents = format!(
            "# pack-refs with: peeled\n\
             {good} refs/heads/main\n\
             {bad} refs/heads/../../etc/evil\n\
             ^{evil_peel}\n"
        );
        let parsed = parse_packed_refs(HashAlgo::Sha1, contents.as_bytes()).unwrap();
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].name, "refs/heads/main");
        // The dropped peel was not mis-attached to the surviving ref.
        assert!(parsed[0].peeled.is_none());
    }

    #[test]
    fn packed_refs_with_peel() {
        let hex_tag = "1111111111111111111111111111111111111111";
        let hex_commit = "2222222222222222222222222222222222222222";
        let contents = format!(
            "# pack-refs with: peeled fully-peeled sorted\n{hex_tag} refs/tags/v1\n^{hex_commit}\n"
        );
        let parsed = parse_packed_refs(HashAlgo::Sha1, contents.as_bytes()).unwrap();
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].name, "refs/tags/v1");
        assert_eq!(parsed[0].peeled.as_ref().unwrap().to_hex(), hex_commit);
    }
}