git-ledger 0.1.0-alpha.4

Git-native record storage: each record is a ref with typed fields.
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
//! Git-native record storage.
//!
//! Each record is its own ref. The ref points to a commit whose tree holds the
//! record's fields as blobs. Updates create new commits, providing full history.

use git2::{Error, Oid, Repository};

/// A single record in the ledger.
#[derive(Debug, Clone)]
pub struct LedgerEntry {
    /// The record's identifier (e.g. `1`, `abc123`).
    pub id: String,
    /// The full ref name (e.g. `refs/issues/1`).
    pub ref_: String,
    /// The commit OID backing this version of the record.
    pub commit: Oid,
    /// The record's fields as `(name, value)` pairs.
    pub fields: Vec<(String, Vec<u8>)>,
}

/// Strategy for generating record IDs.
pub enum IdStrategy<'a> {
    /// Scan existing refs and use max + 1.
    Sequential,
    /// Hash caller-supplied bytes using git's object hash.
    ContentAddressed(&'a [u8]),
    /// Use the caller's string directly.
    CallerProvided(&'a str),
    /// Name the record's ref after the OID of the commit that `create` writes.
    CommitOid,
}

/// The file mode for a pinned tree entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileMode {
    /// Regular file (0o100644).
    Blob,
    /// Executable file (0o100755).
    Executable,
    /// Subtree (0o040000).
    Tree,
    /// Gitlink / submodule commit (0o160000).
    Commit,
}

impl FileMode {
    fn as_raw(self) -> i32 {
        match self {
            FileMode::Blob => 0o100644,
            FileMode::Executable => 0o100755,
            FileMode::Tree => 0o040000,
            FileMode::Commit => 0o160000,
        }
    }
}

/// A mutation to apply to a record's fields.
pub enum Mutation<'a> {
    /// Upsert a field.
    Set(&'a str, &'a [u8]),
    /// Delete a field.
    Delete(&'a str),
    /// Insert a tree entry pointing at an existing git object with the given file mode.
    Pin(&'a str, Oid, FileMode),
}

/// Core ledger operations.
pub trait Ledger {
    /// Create a new record under `ref_prefix`.
    ///
    /// `author` overrides the commit author; when `None`, `self.signature()` is
    /// used for both author and committer.
    fn create(
        &self,
        ref_prefix: &str,
        strategy: &IdStrategy<'_>,
        mutations: &[Mutation<'_>],
        message: &str,
        author: Option<&git2::Signature<'_>>,
    ) -> Result<LedgerEntry, Error>;

    /// Read an existing record by its full ref name.
    fn read(&self, ref_name: &str) -> Result<LedgerEntry, Error>;

    /// Update an existing record by applying mutations.
    fn update(
        &self,
        ref_name: &str,
        mutations: &[Mutation<'_>],
        message: &str,
    ) -> Result<LedgerEntry, Error>;

    /// List all record IDs under a ref prefix.
    fn list(&self, ref_prefix: &str) -> Result<Vec<String>, Error>;

    /// Return the commit history for a record.
    fn history(&self, ref_name: &str) -> Result<Vec<Oid>, Error>;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Recursively insert a tree entry at an arbitrary depth inside a tree builder.
fn insert_nested(
    repo: &Repository,
    builder: &mut git2::TreeBuilder<'_>,
    components: &[&str],
    oid: Oid,
    mode: i32,
) -> Result<(), Error> {
    match components {
        [leaf] => {
            builder.insert(leaf, oid, mode)?;
        }
        [head, rest @ ..] => {
            let mut sub_builder = if let Some(existing) = builder.get(head)? {
                let existing_tree = repo.find_tree(existing.id())?;
                repo.treebuilder(Some(&existing_tree))?
            } else {
                repo.treebuilder(None)?
            };
            insert_nested(repo, &mut sub_builder, rest, oid, mode)?;
            let sub_tree = sub_builder.write()?;
            builder.insert(head, sub_tree, 0o040000)?;
        }
        [] => {}
    }
    Ok(())
}

/// Recursively remove a blob at an arbitrary depth inside a tree builder.
/// Returns `true` if the subtree at this level is now empty and should be pruned.
fn remove_nested(
    repo: &Repository,
    builder: &mut git2::TreeBuilder<'_>,
    components: &[&str],
) -> Result<bool, Error> {
    match components {
        [leaf] => {
            let _ = builder.remove(leaf);
        }
        [head, rest @ ..] => {
            let existing_tree_id = builder
                .get(head)?
                .filter(|e| e.kind() == Some(git2::ObjectType::Tree))
                .map(|e| e.id());
            if let Some(tree_id) = existing_tree_id {
                let et = repo.find_tree(tree_id)?;
                let mut sub_builder = repo.treebuilder(Some(&et))?;
                let empty = remove_nested(repo, &mut sub_builder, rest)?;
                if empty {
                    let _ = builder.remove(head);
                } else {
                    let sub_tree = sub_builder.write()?;
                    builder.insert(head, sub_tree, 0o040000)?;
                }
            }
        }
        [] => {}
    }
    Ok(builder.is_empty())
}

/// Build a tree from a list of mutations (Set and Pin only; Delete is a no-op at create time).
fn build_mutation_tree(repo: &Repository, mutations: &[Mutation<'_>]) -> Result<Oid, Error> {
    let mut builder = repo.treebuilder(None)?;
    for mutation in mutations {
        match mutation {
            Mutation::Set(name, value) => {
                let blob_oid = repo.blob(value)?;
                let components: Vec<&str> = name.split('/').collect();
                insert_nested(repo, &mut builder, &components, blob_oid, 0o100644)?;
            }
            Mutation::Pin(name, oid, mode) => {
                let components: Vec<&str> = name.split('/').collect();
                insert_nested(repo, &mut builder, &components, *oid, mode.as_raw())?;
            }
            Mutation::Delete(_) => {}
        }
    }
    builder.write()
}

/// Read all fields from a tree (recursively for subdirectories).
fn read_fields(
    repo: &Repository,
    tree: &git2::Tree<'_>,
    prefix: &str,
) -> Result<Vec<(String, Vec<u8>)>, Error> {
    let mut fields = Vec::new();
    for entry in tree.iter() {
        let name = entry.name().unwrap_or("").to_string();
        let path = if prefix.is_empty() {
            name.clone()
        } else {
            format!("{}/{}", prefix, name)
        };
        match entry.kind() {
            Some(git2::ObjectType::Blob) => {
                let blob = repo.find_blob(entry.id())?;
                fields.push((path, blob.content().to_vec()));
            }
            Some(git2::ObjectType::Tree) => {
                let subtree = repo.find_tree(entry.id())?;
                fields.extend(read_fields(repo, &subtree, &path)?);
            }
            _ => {}
        }
    }
    Ok(fields)
}

/// Extract the ID portion from a full ref name given a prefix.
fn id_from_ref(ref_name: &str, ref_prefix: &str) -> String {
    let prefix = if ref_prefix.ends_with('/') {
        ref_prefix.to_string()
    } else {
        format!("{}/", ref_prefix)
    };
    ref_name
        .strip_prefix(&prefix)
        .unwrap_or(ref_name)
        .to_string()
}

/// Generate the next sequential ID by scanning existing refs.
fn next_sequential_id(repo: &Repository, ref_prefix: &str) -> Result<u64, Error> {
    let pattern = if ref_prefix.ends_with('/') {
        format!("{}*", ref_prefix)
    } else {
        format!("{}/*", ref_prefix)
    };
    let refs = repo.references_glob(&pattern)?;
    let mut max_id: u64 = 0;
    for reference in refs {
        let reference = reference?;
        if let Some(name) = reference.name() {
            let id_str = id_from_ref(name, ref_prefix);
            if let Ok(n) = id_str.parse::<u64>() {
                max_id = max_id.max(n);
            }
        }
    }
    Ok(max_id + 1)
}

// ---------------------------------------------------------------------------
// Implementation
// ---------------------------------------------------------------------------

impl Ledger for Repository {
    fn create(
        &self,
        ref_prefix: &str,
        strategy: &IdStrategy<'_>,
        mutations: &[Mutation<'_>],
        message: &str,
        author: Option<&git2::Signature<'_>>,
    ) -> Result<LedgerEntry, Error> {
        let tree_oid = build_mutation_tree(self, mutations)?;
        let tree = self.find_tree(tree_oid)?;
        let committer = self.signature()?;
        let owned_author;
        let author = match author {
            Some(a) => a,
            None => {
                owned_author = self.signature()?;
                &owned_author
            }
        };

        if let IdStrategy::CommitOid = strategy {
            let commit_oid = self.commit(None, author, &committer, message, &tree, &[])?;
            let ref_name = if ref_prefix.ends_with('/') {
                format!("{}{}", ref_prefix, commit_oid)
            } else {
                format!("{}/{}", ref_prefix, commit_oid)
            };
            self.reference(&ref_name, commit_oid, false, message)?;
            let fields = read_fields(self, &tree, "")?;
            return Ok(LedgerEntry {
                id: commit_oid.to_string(),
                ref_: ref_name,
                commit: commit_oid,
                fields,
            });
        }

        let id = match strategy {
            IdStrategy::Sequential => {
                let next = next_sequential_id(self, ref_prefix)?;
                next.to_string()
            }
            IdStrategy::ContentAddressed(bytes) => {
                let oid = self.blob(bytes)?;
                oid.to_string()
            }
            IdStrategy::CallerProvided(s) => s.to_string(),
            IdStrategy::CommitOid => unreachable!(),
        };

        let ref_name = if ref_prefix.ends_with('/') {
            format!("{}{}", ref_prefix, id)
        } else {
            format!("{}/{}", ref_prefix, id)
        };

        if self.find_reference(&ref_name).is_ok() {
            return Err(Error::from_str(&format!(
                "record already exists: {}",
                ref_name
            )));
        }

        let commit_oid = self.commit(Some(&ref_name), author, &committer, message, &tree, &[])?;

        let fields = read_fields(self, &tree, "")?;
        let id = ref_name.rsplit('/').next().unwrap_or(&ref_name).to_string();

        Ok(LedgerEntry {
            id,
            ref_: ref_name,
            commit: commit_oid,
            fields,
        })
    }

    fn read(&self, ref_name: &str) -> Result<LedgerEntry, Error> {
        let reference = self.find_reference(ref_name)?;
        let commit = reference.peel_to_commit()?;
        let tree = commit.tree()?;
        let fields = read_fields(self, &tree, "")?;

        // Extract ID from ref name — take the last component
        let id = ref_name.rsplit('/').next().unwrap_or(ref_name).to_string();

        Ok(LedgerEntry {
            id,
            ref_: ref_name.to_string(),
            commit: commit.id(),
            fields,
        })
    }

    fn update(
        &self,
        ref_name: &str,
        mutations: &[Mutation<'_>],
        message: &str,
    ) -> Result<LedgerEntry, Error> {
        let reference = self.find_reference(ref_name)?;
        let parent_commit = reference.peel_to_commit()?;
        let existing_tree = parent_commit.tree()?;

        let mut builder = self.treebuilder(Some(&existing_tree))?;

        for mutation in mutations {
            match mutation {
                Mutation::Set(name, value) => {
                    let blob_oid = self.blob(value)?;
                    let components: Vec<&str> = name.split('/').collect();
                    insert_nested(self, &mut builder, &components, blob_oid, 0o100644)?;
                }
                Mutation::Delete(name) => {
                    let components: Vec<&str> = name.split('/').collect();
                    remove_nested(self, &mut builder, &components)?;
                }
                Mutation::Pin(name, oid, mode) => {
                    let components: Vec<&str> = name.split('/').collect();
                    insert_nested(self, &mut builder, &components, *oid, mode.as_raw())?;
                }
            }
        }

        let tree_oid = builder.write()?;
        let tree = self.find_tree(tree_oid)?;
        let sig = self.signature()?;

        let commit_oid = self.commit(
            Some(ref_name),
            &sig,
            &sig,
            message,
            &tree,
            &[&parent_commit],
        )?;

        let fields = read_fields(self, &tree, "")?;
        let id = ref_name.rsplit('/').next().unwrap_or(ref_name).to_string();

        Ok(LedgerEntry {
            id,
            ref_: ref_name.to_string(),
            commit: commit_oid,
            fields,
        })
    }

    fn list(&self, ref_prefix: &str) -> Result<Vec<String>, Error> {
        let pattern = if ref_prefix.ends_with('/') {
            format!("{}*", ref_prefix)
        } else {
            format!("{}/*", ref_prefix)
        };
        let refs = self.references_glob(&pattern)?;
        let mut ids = Vec::new();
        for reference in refs {
            let reference = reference?;
            if let Some(name) = reference.name() {
                ids.push(id_from_ref(name, ref_prefix));
            }
        }
        ids.sort();
        Ok(ids)
    }

    fn history(&self, ref_name: &str) -> Result<Vec<Oid>, Error> {
        let reference = self.find_reference(ref_name)?;
        let commit = reference.peel_to_commit()?;

        let mut oids = Vec::new();
        let mut current = Some(commit);
        while let Some(c) = current {
            oids.push(c.id());
            current = c.parent(0).ok();
        }
        Ok(oids)
    }
}

#[cfg(test)]
mod tests;