Skip to main content

oak_core/
git.rs

1//! `Repository` implementation backed by a real `.git` directory.
2//!
3//! Like jj's git backend, the repository is *colocated*: commits, trees,
4//! blobs, branches, and HEAD are ordinary git objects and refs, so `git log`,
5//! `git status`, and any git host (GitHub, GitLab, ...) see Oak's work
6//! directly. Oak-only state (branch descriptions, parents, open/closed status)
7//! lives in a sidecar under `<git_dir>/oak/`. Whenever Oak moves HEAD it also
8//! resets git's index to HEAD's tree, so plain `git` commands agree with Oak
9//! about what is committed. Remote operations (push / fetch / pull) are
10//! implemented in the CLI by delegating to the system `git` binary.
11//!
12//! Hash semantics on this backend:
13//! - `Blob.hash` is the git blob OID.
14//! - `Manifest.hash` is the git tree OID.
15//! - `Commit.hash` is the git commit OID.
16//!
17//! That's a deliberate departure from the SQLite backend (which uses BLAKE3
18//! everywhere). Storing native git OIDs lets Oak commits round-trip through
19//! `git log` and other git tools without translation.
20
21use std::collections::BTreeMap;
22use std::path::{Path, PathBuf};
23use std::sync::Mutex;
24
25use crate::{
26    Blob, Branch, BranchStatus, ChunkInfo, CloseReason, Commit, FileChange, FileMode, Hash,
27    Manifest, ManifestEntry, MetadataKey, OakError, Result,
28};
29use gix::bstr::BString;
30use gix::ObjectId;
31
32use crate::traits::Repository;
33
34const BACKEND: &str = "git";
35
36/// Read-only `Repository` over an existing git directory.
37pub struct GitRepository {
38    /// Thread-safe handle; we re-derive a thread-local `gix::Repository` per call.
39    inner: gix::ThreadSafeRepository,
40    /// Sidecar directory for Oak-only state (workdir lock, branch metadata, etc.).
41    /// Lives at `<git_dir>/oak/` so it's hidden from normal git operations.
42    oak_sidecar_dir: PathBuf,
43    /// In-memory metadata fallback. Phase 1 doesn't persist these (writes are unsupported)
44    /// but `set_metadata` for `Head` / `CurrentBranch` is harmless to accept silently
45    /// because subsequent reads come from the live git refs anyway.
46    scratch_metadata: Mutex<std::collections::HashMap<String, String>>,
47}
48
49impl GitRepository {
50    /// Open an existing git repository at `git_dir` (the `.git` folder, or a bare repo).
51    /// `oak_sidecar_dir` is the directory where Oak-only state files live (created on demand).
52    pub fn open(git_dir: &Path, oak_sidecar_dir: &Path) -> Result<Self> {
53        // Inject a fallback identity so ref/reflog writes — e.g. moving a
54        // branch head after a commit (`set_branch_head`) or repointing HEAD —
55        // succeed even when the environment configures no `user.name` /
56        // `user.email`, as on CI runners. gix derives the reflog committer
57        // from config and errors with "The reflog could not be created or
58        // updated" when none is found. These `gitoxide.*Fallback` keys are
59        // consulted only when no real committer/author identity is present, so
60        // a developer's configured git identity still wins where it exists.
61        let options = gix::open::Options::default().config_overrides([
62            "gitoxide.committer.nameFallback=Oak",
63            "gitoxide.committer.emailFallback=oak@oak.space",
64            "gitoxide.author.nameFallback=Oak",
65            "gitoxide.author.emailFallback=oak@oak.space",
66        ]);
67        let inner = gix::ThreadSafeRepository::open_opts(git_dir, options).map_err(map_git_err)?;
68        Ok(Self {
69            inner,
70            oak_sidecar_dir: oak_sidecar_dir.to_path_buf(),
71            scratch_metadata: Mutex::new(Default::default()),
72        })
73    }
74
75    fn repo(&self) -> gix::Repository {
76        self.inner.to_thread_local()
77    }
78
79    /// Reset git's index to HEAD's tree (a `git reset --mixed` that never
80    /// touches the working tree). Oak writes commits and moves refs without
81    /// going through git's index, so without this `git status` would report
82    /// every freshly committed change as staged-and-reverted. Bare repos and
83    /// unborn HEADs have nothing to sync.
84    fn sync_index_to_head(&self) -> Result<()> {
85        let repo = self.repo();
86        if repo.workdir().is_none() {
87            return Ok(());
88        }
89        let tree_id = match repo.head_tree_id() {
90            Ok(id) => id.detach(),
91            Err(_) => return Ok(()),
92        };
93        let mut index = repo.index_from_tree(&tree_id).map_err(map_git_err)?;
94        index
95            .write(gix::index::write::Options::default())
96            .map_err(map_git_err)?;
97        Ok(())
98    }
99
100    /// The short name of the branch HEAD points at, if attached.
101    fn head_branch_name(&self) -> Result<Option<String>> {
102        let repo = self.repo();
103        let head = repo.head().map_err(map_git_err)?;
104        Ok(head.referent_name().map(|n| {
105            let full = n.as_bstr().to_string();
106            full.strip_prefix("refs/heads/")
107                .unwrap_or(&full)
108                .to_string()
109        }))
110    }
111
112    /// The commit identity: git's configured `user.name` / `user.email` when
113    /// present (so commits pushed to GitHub attribute to the right account),
114    /// otherwise Oak's author string.
115    fn commit_identity(&self, oak_author: &str) -> (String, String) {
116        // Read the identity explicitly rather than via `repo.author()`: gix
117        // lets the `gitoxide.author.*Fallback` overrides injected in `open`
118        // shadow the user's real `user.name` / `user.email`.
119        let repo = self.repo();
120        let config = repo.config_snapshot();
121        let pick = |env: &str, key: &str| {
122            std::env::var(env)
123                .ok()
124                .or_else(|| config.string(key).map(|v| v.to_string()))
125                .filter(|v| !v.trim().is_empty())
126        };
127        match (
128            pick("GIT_AUTHOR_NAME", "user.name"),
129            pick("GIT_AUTHOR_EMAIL", "user.email"),
130        ) {
131            (Some(name), Some(email)) => (name, email),
132            (None, Some(email)) => (split_author(oak_author).0, email),
133            _ => split_author(oak_author),
134        }
135    }
136
137    /// Build the git commit message for an Oak checkpoint on `branch`.
138    fn checkpoint_message(
139        &self,
140        branch: &str,
141        parent: Option<&Hash>,
142        files: &[FileChange],
143    ) -> Result<String> {
144        let meta = BranchSidecar::load(&self.oak_sidecar_dir)?
145            .branches
146            .get(branch)
147            .cloned();
148        let description = meta
149            .as_ref()
150            .and_then(|m| m.description.clone())
151            .filter(|d| !d.trim().is_empty());
152        let parent_branch = meta.and_then(|m| m.parent_branch);
153        let checkpoint = 1 + parent.map_or(0, |p| self.prior_checkpoints(branch, p));
154        let stats: Vec<FileStat> = files.iter().map(|f| self.file_stat(f)).collect();
155        Ok(format_checkpoint_message(&CheckpointInfo {
156            branch,
157            parent_branch: parent_branch.as_deref(),
158            checkpoint,
159            description: description.as_deref(),
160            files: &stats,
161        }))
162    }
163
164    /// How many consecutive first-parent ancestors (starting at `parent`) are
165    /// Oak checkpoints on `branch`, recognized by their `Oak-Branch` trailer.
166    /// Merge commits in between are skipped, not counted.
167    /// Bounded so a pathological history can't stall a commit.
168    fn prior_checkpoints(&self, branch: &str, parent: &Hash) -> usize {
169        const MAX_WALK: usize = 10_000;
170        let trailer = format!("{TRAILER_BRANCH}: {branch}");
171        let repo = self.repo();
172        let mut count = 0;
173        let mut steps = 0;
174        let mut current = Self::oid(parent).ok();
175        while let Some(oid) = current {
176            steps += 1;
177            if steps > MAX_WALK {
178                break;
179            }
180            let Ok(obj) = repo.find_object(oid) else {
181                break;
182            };
183            let Ok(commit) = obj.try_into_commit() else {
184                break;
185            };
186            let Ok(message) = commit.message_raw() else {
187                break;
188            };
189            let is_checkpoint = message.to_string().lines().any(|l| l.trim_end() == trailer);
190            // Merge commits from `oak pull` interrupt the run of checkpoints
191            // without ending it: step over them along the first parent.
192            let is_merge = commit.parent_ids().nth(1).is_some();
193            if is_checkpoint {
194                count += 1;
195            } else if !is_merge {
196                break;
197            }
198            current = commit.parent_ids().next().map(|p| p.detach());
199        }
200        count
201    }
202
203    /// Line counts for one changed file, read from the git objects.
204    fn file_stat(&self, change: &FileChange) -> FileStat {
205        let read = |hash: &Option<Hash>| -> Option<Vec<u8>> {
206            match hash {
207                None => Some(Vec::new()),
208                Some(h) => self.get_blob(h).ok().flatten().map(|b| b.content),
209            }
210        };
211        let lines = match (read(&change.old_blob_hash), read(&change.new_blob_hash)) {
212            (Some(old), Some(new)) => line_stat(&old, &new),
213            _ => LineStat::Unknown,
214        };
215        FileStat {
216            change_type: change.change_type,
217            path: change.path.clone(),
218            old_path: change.old_path.clone(),
219            // `oak commit` doesn't always carry modes through; a "modified"
220            // file whose content is unchanged can only have changed mode.
221            mode_changed: (change.old_mode.is_some()
222                && change.new_mode.is_some()
223                && change.old_mode != change.new_mode)
224                || (change.change_type == crate::ChangeType::Modified
225                    && change.old_blob_hash.is_some()
226                    && change.old_blob_hash == change.new_blob_hash),
227            lines,
228        }
229    }
230
231    fn oid(hash: &Hash) -> Result<ObjectId> {
232        ObjectId::from_hex(hash.as_str().as_bytes())
233            .map_err(|_| OakError::InvalidHash(hash.as_str().to_string()))
234    }
235
236    /// Load a commit by OID and convert it to an `crate::Commit`.
237    /// `files` is left empty — callers that need it should compute a tree diff lazily.
238    fn load_commit(&self, oid: ObjectId) -> Result<Commit> {
239        let repo = self.repo();
240        let obj = repo.find_object(oid).map_err(map_git_err)?;
241        let git_commit = obj
242            .try_into_commit()
243            .map_err(|e| OakError::Git(e.to_string()))?;
244
245        let tree_id = git_commit.tree_id().map_err(map_git_err)?.detach();
246        let parents: Vec<Hash> = git_commit
247            .parent_ids()
248            .map(|p| Hash(p.detach().to_string()))
249            .collect();
250
251        let author = git_commit
252            .author()
253            .map(|a| a.name.to_string())
254            .unwrap_or_else(|_| "unknown".to_string());
255
256        // Git always has a message string; treat empty/whitespace-only as
257        // "no message" to match the new oak model where messages are
258        // exclusively for main-branch squash-merges.
259        let message = git_commit
260            .message_raw()
261            .ok()
262            .map(|m| m.to_string())
263            .filter(|s| !s.trim().is_empty());
264
265        let timestamp = git_commit
266            .time()
267            .ok()
268            .and_then(|t| chrono::DateTime::from_timestamp(t.seconds, 0))
269            .unwrap_or_else(chrono::Utc::now);
270
271        // Git commits don't carry a branch name — the caller's context (which ref they
272        // walked) is the only signal. Leaving empty here; the `get_commits_for_branch`
273        // path stamps the branch name on commits it returns.
274        Ok(Commit {
275            hash: Hash(oid.to_string()),
276            branch_name: String::new(),
277            parent_hash: parents.first().cloned(),
278            merge_parent_hash: parents.get(1).cloned(),
279            manifest_hash: Hash(tree_id.to_string()),
280            author,
281            message,
282            timestamp,
283            files: Vec::<FileChange>::new(),
284        })
285    }
286}
287
288// --- Checkpoint commit messages ---------------------------------------------
289//
290// Oak commits have no message of their own, but on a git backend every commit
291// shows up in `git log` and on the host (GitHub's commit list, PR timeline,
292// blame). Rather than repeat the branch description on every checkpoint, the
293// message describes the checkpoint itself:
294//
295//     Add greet.txt, update README.md
296//
297//     Checkpoint 2 on feat (parent: main): 2 files changed, +12 -3
298//
299//       A  greet.txt  +1
300//       M  README.md  +11 -3
301//
302//     Branch description:
303//       Add greeting
304//
305//     Oak-Branch: feat
306//     Oak-Checkpoint: 2
307//
308// The trailers are machine-readable (`git interpret-trailers`) and let the
309// next checkpoint number itself by walking first parents.
310
311const TRAILER_BRANCH: &str = "Oak-Branch";
312const TRAILER_CHECKPOINT: &str = "Oak-Checkpoint";
313/// Longest subject line before it's shortened (git's conventional limit).
314const SUBJECT_MAX: usize = 72;
315/// At most this many per-file lines in the body.
316const MAX_LISTED_FILES: usize = 50;
317/// Files larger than this skip the line diff (reported as "large").
318const MAX_STAT_BYTES: usize = 2 * 1024 * 1024;
319
320#[derive(Debug, Clone, PartialEq, Eq)]
321enum LineStat {
322    Text { added: usize, removed: usize },
323    Binary,
324    Large,
325    Unknown,
326}
327
328#[derive(Debug, Clone)]
329struct FileStat {
330    change_type: crate::ChangeType,
331    path: String,
332    old_path: Option<String>,
333    mode_changed: bool,
334    lines: LineStat,
335}
336
337struct CheckpointInfo<'a> {
338    branch: &'a str,
339    parent_branch: Option<&'a str>,
340    checkpoint: usize,
341    description: Option<&'a str>,
342    files: &'a [FileStat],
343}
344
345fn line_stat(old: &[u8], new: &[u8]) -> LineStat {
346    if crate::diff::is_binary(old) || crate::diff::is_binary(new) {
347        return LineStat::Binary;
348    }
349    if old.len() > MAX_STAT_BYTES || new.len() > MAX_STAT_BYTES {
350        return LineStat::Large;
351    }
352    let old = String::from_utf8_lossy(old);
353    let new = String::from_utf8_lossy(new);
354    let (mut added, mut removed) = (0, 0);
355    for change in similar::TextDiff::from_lines(old.as_ref(), new.as_ref()).iter_all_changes() {
356        match change.tag() {
357            similar::ChangeTag::Insert => added += 1,
358            similar::ChangeTag::Delete => removed += 1,
359            similar::ChangeTag::Equal => {}
360        }
361    }
362    LineStat::Text { added, removed }
363}
364
365fn verb(change: &crate::ChangeType) -> &'static str {
366    match change {
367        crate::ChangeType::Added => "Add",
368        crate::ChangeType::Modified => "Update",
369        crate::ChangeType::Deleted => "Delete",
370        crate::ChangeType::Renamed => "Rename",
371    }
372}
373
374/// A path for a subject line: the file name alone when `short` (or when the
375/// full path is long), otherwise the full path.
376fn subject_path(path: &str, short: bool) -> &str {
377    if short || path.len() > 40 {
378        path.rsplit('/').next().unwrap_or(path)
379    } else {
380        path
381    }
382}
383
384fn subject_for_file(f: &FileStat, short: bool) -> String {
385    let path = subject_path(&f.path, short);
386    match (&f.change_type, &f.old_path) {
387        (crate::ChangeType::Renamed, Some(old)) => {
388            format!("Rename {} to {path}", subject_path(old, short))
389        }
390        (crate::ChangeType::Modified, _)
391            if f.mode_changed
392                && f.lines
393                    == (LineStat::Text {
394                        added: 0,
395                        removed: 0,
396                    }) =>
397        {
398            format!("Change mode of {path}")
399        }
400        (ct, _) => format!("{} {path}", verb(ct)),
401    }
402}
403
404/// The directory containing every path ("" when they share none).
405fn common_dir(paths: &[&str]) -> String {
406    let mut common: Option<Vec<&str>> = None;
407    for path in paths {
408        let mut parts: Vec<&str> = path.split('/').collect();
409        parts.pop(); // the file name
410        common = Some(match common {
411            None => parts,
412            Some(prev) => prev
413                .iter()
414                .zip(parts.iter())
415                .take_while(|(a, b)| a == b)
416                .map(|(a, _)| *a)
417                .collect(),
418        });
419    }
420    common.unwrap_or_default().join("/")
421}
422
423/// "2 added, 3 modified" — omitted kinds are skipped.
424fn change_breakdown(files: &[FileStat]) -> String {
425    let count = |ct: crate::ChangeType| files.iter().filter(|f| f.change_type == ct).count();
426    [
427        (count(crate::ChangeType::Added), "added"),
428        (count(crate::ChangeType::Modified), "modified"),
429        (count(crate::ChangeType::Deleted), "deleted"),
430        (count(crate::ChangeType::Renamed), "renamed"),
431    ]
432    .iter()
433    .filter(|(n, _)| *n > 0)
434    .map(|(n, label)| format!("{n} {label}"))
435    .collect::<Vec<_>>()
436    .join(", ")
437}
438
439fn truncate_subject(subject: String) -> String {
440    if subject.chars().count() <= SUBJECT_MAX {
441        return subject;
442    }
443    let mut cut: String = subject.chars().take(SUBJECT_MAX - 1).collect();
444    cut.push('…');
445    cut
446}
447
448/// One-line summary of a checkpoint's changes, e.g. `Add a.rs, update b.rs`
449/// or `Update 7 files in cli/src (2 added, 5 modified)`.
450fn checkpoint_subject(files: &[FileStat], branch: &str) -> String {
451    if files.is_empty() {
452        return format!("Checkpoint on {branch}");
453    }
454    // Same kind of change to a few files: say the verb (and directory) once,
455    // e.g. `Add m1.rs, m2.rs and m3.rs in src/cmd`.
456    let same_kind = files.iter().all(|f| {
457        f.change_type == files[0].change_type
458            && f.change_type != crate::ChangeType::Renamed
459            && !f.mode_changed
460    });
461    if files.len() > 1 && files.len() <= 3 && same_kind {
462        let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
463        let dir = common_dir(&paths);
464        let names: Vec<&str> = paths
465            .iter()
466            .map(|p| {
467                if dir.is_empty() {
468                    *p
469                } else {
470                    &p[dir.len() + 1..]
471                }
472            })
473            .collect();
474        let (last, rest) = names.split_last().expect("more than one file");
475        let mut subject = format!(
476            "{} {} and {last}",
477            verb(&files[0].change_type),
478            rest.join(", ")
479        );
480        if !dir.is_empty() {
481            subject.push_str(&format!(" in {dir}"));
482        }
483        if subject.chars().count() <= SUBJECT_MAX {
484            return subject;
485        }
486    }
487    if files.len() <= 3 {
488        // Full paths first; if that's too long, bare file names.
489        for short in [false, true] {
490            let parts: Vec<String> = files
491                .iter()
492                .enumerate()
493                .map(|(i, f)| {
494                    let s = subject_for_file(f, short);
495                    if i == 0 {
496                        s
497                    } else {
498                        let mut chars = s.chars();
499                        chars
500                            .next()
501                            .map(|c| c.to_lowercase().chain(chars).collect())
502                            .unwrap_or_default()
503                    }
504                })
505                .collect();
506            let joined = parts.join(", ");
507            if joined.chars().count() <= SUBJECT_MAX {
508                return joined;
509            }
510        }
511    }
512
513    let first = &files[0].change_type;
514    let mixed = files.iter().any(|f| &f.change_type != first);
515    let verb = if mixed { "Update" } else { verb(first) };
516    let n = files.len();
517    let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
518    let dir = common_dir(&paths);
519    let mut subject = if !dir.is_empty() {
520        format!("{verb} {n} files in {dir}")
521    } else {
522        let mut tops: Vec<&str> = paths
523            .iter()
524            .map(|p| match p.split_once('/') {
525                Some((top, _)) => top,
526                None => ".",
527            })
528            .collect();
529        tops.sort_unstable();
530        tops.dedup();
531        if tops.len() <= 3 {
532            // Directories first, then files at the top level.
533            let mut listed: Vec<String> = tops
534                .iter()
535                .filter(|t| **t != ".")
536                .map(|t| format!("{t}/"))
537                .collect();
538            if tops.contains(&".") {
539                listed.push("the top level".to_string());
540            }
541            let listed = match listed.split_last() {
542                Some((last, rest)) if !rest.is_empty() => {
543                    format!("{} and {last}", rest.join(", "))
544                }
545                _ => listed.join(""),
546            };
547            format!("{verb} {n} files in {listed}")
548        } else {
549            format!("{verb} {n} files across {} directories", tops.len())
550        }
551    };
552    if mixed {
553        let with_breakdown = format!("{subject} ({})", change_breakdown(files));
554        if with_breakdown.chars().count() <= SUBJECT_MAX {
555            subject = with_breakdown;
556        }
557    }
558    truncate_subject(subject)
559}
560
561fn format_line_stat(f: &FileStat) -> String {
562    let mut out = match &f.lines {
563        LineStat::Text { added, removed } => match (added, removed) {
564            (0, 0) => String::new(),
565            (a, 0) => format!("+{a}"),
566            (0, r) => format!("-{r}"),
567            (a, r) => format!("+{a} -{r}"),
568        },
569        LineStat::Binary => "binary".to_string(),
570        LineStat::Large => "large".to_string(),
571        LineStat::Unknown => String::new(),
572    };
573    if f.mode_changed {
574        if !out.is_empty() {
575            out.push_str(", ");
576        }
577        out.push_str("mode changed");
578    }
579    out
580}
581
582fn format_checkpoint_message(info: &CheckpointInfo<'_>) -> String {
583    let files = info.files;
584    let mut msg = checkpoint_subject(files, info.branch);
585    msg.push_str("\n\n");
586
587    // Summary line: where this checkpoint sits, and how big it is.
588    msg.push_str(&format!(
589        "Checkpoint {} on {}",
590        info.checkpoint, info.branch
591    ));
592    if let Some(parent) = info.parent_branch.filter(|p| *p != info.branch) {
593        msg.push_str(&format!(" (parent: {parent})"));
594    }
595    if !files.is_empty() {
596        let (added, removed) = files.iter().fold((0, 0), |(a, r), f| match f.lines {
597            LineStat::Text { added, removed } => (a + added, r + removed),
598            _ => (a, r),
599        });
600        let binary = files
601            .iter()
602            .filter(|f| matches!(f.lines, LineStat::Binary | LineStat::Large))
603            .count();
604        msg.push_str(&format!(
605            ": {} file{} changed, +{added} -{removed}",
606            files.len(),
607            if files.len() == 1 { "" } else { "s" },
608        ));
609        if binary > 0 {
610            msg.push_str(&format!(", {binary} binary"));
611        }
612    }
613    msg.push('\n');
614
615    // Per-file listing, aligned like `git diff --stat`.
616    if !files.is_empty() {
617        msg.push('\n');
618        let display: Vec<String> = files
619            .iter()
620            .take(MAX_LISTED_FILES)
621            .map(|f| match (&f.change_type, &f.old_path) {
622                (crate::ChangeType::Renamed, Some(old)) => format!("{old} → {}", f.path),
623                _ => f.path.clone(),
624            })
625            .collect();
626        let width = display
627            .iter()
628            .map(|d| d.chars().count())
629            .max()
630            .unwrap_or(0)
631            .min(48);
632        for (f, path) in files.iter().zip(&display) {
633            let stat = format_line_stat(f);
634            let line = format!("  {}  {path:<width$}  {stat}", f.change_type);
635            msg.push_str(line.trim_end());
636            msg.push('\n');
637        }
638        if files.len() > MAX_LISTED_FILES {
639            msg.push_str(&format!(
640                "  … and {} more files\n",
641                files.len() - MAX_LISTED_FILES
642            ));
643        }
644    }
645
646    // The branch narrative, for context when reading one commit in isolation.
647    if let Some(description) = info.description.map(str::trim).filter(|d| !d.is_empty()) {
648        msg.push_str("\nBranch description:\n");
649        for line in description.lines() {
650            if line.trim().is_empty() {
651                msg.push('\n');
652            } else {
653                msg.push_str("  ");
654                msg.push_str(line);
655                msg.push('\n');
656            }
657        }
658    }
659
660    msg.push_str(&format!(
661        "\n{TRAILER_BRANCH}: {}\n{TRAILER_CHECKPOINT}: {}\n",
662        info.branch, info.checkpoint
663    ));
664    msg
665}
666
667fn map_git_err<E: std::fmt::Display>(e: E) -> OakError {
668    OakError::Git(e.to_string())
669}
670
671fn unsupported(op: &'static str) -> OakError {
672    OakError::Unsupported {
673        backend: BACKEND,
674        op,
675    }
676}
677
678// --- Branch metadata sidecar ------------------------------------------------
679//
680// Git refs only carry a name and a commit OID. Oak's `Branch` struct also has a
681// description, parent_branch, status (open/closed), and created_at. Rather than
682// silently drop those on the git backend, we persist them in a TOML file at
683// `<git_dir>/oak/branches.toml` — outside the git object/ref store, but inside
684// `.git/` so it lives with the repo. The sidecar is read lazily and written on
685// any branch metadata change.
686
687#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
688struct BranchSidecar {
689    /// Map of branch name → metadata. Branches without a sidecar entry default
690    /// to `(description=None, parent_branch=None, status=Open, created_at=now)`.
691    #[serde(default)]
692    branches: std::collections::BTreeMap<String, BranchMeta>,
693}
694
695#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
696struct BranchMeta {
697    #[serde(default, skip_serializing_if = "Option::is_none")]
698    description: Option<String>,
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    parent_branch: Option<String>,
701    /// "open" or "closed" — serialized as a string for forward-compat.
702    #[serde(default = "default_status")]
703    status: String,
704    #[serde(default, skip_serializing_if = "Option::is_none")]
705    close_reason: Option<String>,
706    /// RFC3339 timestamp; omitted means "unknown" and we fall back to now-ish on read.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    created_at: Option<String>,
709}
710
711fn default_status() -> String {
712    "open".to_string()
713}
714
715impl BranchSidecar {
716    fn path(sidecar_dir: &Path) -> PathBuf {
717        sidecar_dir.join("branches.toml")
718    }
719
720    fn load(sidecar_dir: &Path) -> Result<Self> {
721        let path = Self::path(sidecar_dir);
722        if !path.exists() {
723            return Ok(Self::default());
724        }
725        let raw = std::fs::read_to_string(&path)?;
726        toml::from_str(&raw).map_err(|e| OakError::Config(format!("branches.toml: {e}")))
727    }
728
729    fn save(&self, sidecar_dir: &Path) -> Result<()> {
730        std::fs::create_dir_all(sidecar_dir)?;
731        let raw = toml::to_string_pretty(self)
732            .map_err(|e| OakError::Config(format!("serialize branches.toml: {e}")))?;
733        std::fs::write(Self::path(sidecar_dir), raw)?;
734        Ok(())
735    }
736}
737
738fn meta_to_branch(name: &str, meta: &BranchMeta) -> Branch {
739    let status = BranchStatus::from_db_str(&meta.status);
740    let close_reason = meta
741        .close_reason
742        .as_deref()
743        .map(CloseReason::parse)
744        .transpose()
745        .unwrap_or(None);
746    let created_at = meta
747        .created_at
748        .as_deref()
749        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
750        .map(|dt| dt.with_timezone(&chrono::Utc))
751        .unwrap_or_else(chrono::Utc::now);
752    Branch {
753        name: name.to_string(),
754        description: meta.description.clone(),
755        parent_branch: meta.parent_branch.clone(),
756        status,
757        close_reason,
758        created_at,
759    }
760}
761
762fn branch_to_meta(branch: &Branch) -> BranchMeta {
763    BranchMeta {
764        description: branch.description.clone(),
765        parent_branch: branch.parent_branch.clone(),
766        status: branch.status.as_str().to_string(),
767        close_reason: branch.close_reason.as_ref().map(|r| r.as_str().to_string()),
768        created_at: Some(branch.created_at.to_rfc3339()),
769    }
770}
771
772// --- Write-path helpers -----------------------------------------------------
773
774/// Convert an Oak `FileMode` to the matching git tree entry mode.
775fn oak_mode_to_git(mode: FileMode) -> gix::objs::tree::EntryMode {
776    match mode {
777        FileMode::Regular => gix::objs::tree::EntryKind::Blob.into(),
778        FileMode::Executable => gix::objs::tree::EntryKind::BlobExecutable.into(),
779        FileMode::Symlink => gix::objs::tree::EntryKind::Link.into(),
780    }
781}
782
783/// Intermediate node used to build a nested git tree from Oak's flat manifest.
784enum TreeNode {
785    Blob {
786        oid: ObjectId,
787        mode: FileMode,
788    },
789    Dir {
790        children: BTreeMap<String, TreeNode>,
791    },
792}
793
794impl TreeNode {
795    fn new_dir() -> Self {
796        TreeNode::Dir {
797            children: BTreeMap::new(),
798        }
799    }
800
801    /// Insert a flat path (e.g. `"src/foo.rs"`) into the nested tree.
802    fn insert(&mut self, path: &str, oid: ObjectId, mode: FileMode) {
803        let TreeNode::Dir { children } = self else {
804            return; // Shouldn't happen — root is always a Dir.
805        };
806        let mut parts = path.splitn(2, '/');
807        let head = parts.next().unwrap_or("").to_string();
808        match parts.next() {
809            None => {
810                children.insert(head, TreeNode::Blob { oid, mode });
811            }
812            Some(rest) => {
813                let entry = children.entry(head).or_insert_with(TreeNode::new_dir);
814                entry.insert(rest, oid, mode);
815            }
816        }
817    }
818}
819
820/// Build the byte key git uses to order a tree entry: the name, with a
821/// trailing `/` appended for directories. Sorting entries by this key yields
822/// git's canonical (directory-aware) tree order — the order gix's tree writer
823/// asserts but does not enforce.
824fn git_tree_sort_key(name: &str, is_dir: bool) -> Vec<u8> {
825    let mut key = name.as_bytes().to_vec();
826    if is_dir {
827        key.push(b'/');
828    }
829    key
830}
831
832fn validate_git_tree_entries(entries: &[ManifestEntry]) -> Result<()> {
833    for entry in entries {
834        crate::validate_tree_path(&entry.path)?;
835    }
836    Ok(())
837}
838
839/// Recursively write nested `TreeNode`s as git trees, returning the root tree OID.
840fn write_tree_recursive(repo: &gix::Repository, node: &TreeNode) -> Result<ObjectId> {
841    let TreeNode::Dir { children } = node else {
842        return Err(OakError::Git(
843            "internal error: tried to write a Blob node as a tree".into(),
844        ));
845    };
846
847    // Git's canonical tree order is directory-aware: an entry sorts as if a
848    // tree's name had a trailing '/'. `children` is a `BTreeMap`, so iterating
849    // it yields plain lexicographic order — which differs whenever a file and a
850    // directory straddle the '/' (0x2f) boundary (classic case: a file `foo`
851    // next to a directory `foo`). gix does NOT re-sort: `Tree::write_to` only
852    // `debug_assert!`s the entries are already ordered, so the wrong order
853    // panics in debug builds and writes a `git fsck`-rejected tree in release.
854    // Sort the names ourselves with the trailing-'/' rule before building.
855    let mut names: Vec<&String> = children.keys().collect();
856    names.sort_by(|a, b| {
857        git_tree_sort_key(a, matches!(children[*a], TreeNode::Dir { .. })).cmp(&git_tree_sort_key(
858            b,
859            matches!(children[*b], TreeNode::Dir { .. }),
860        ))
861    });
862
863    let mut entries = Vec::with_capacity(children.len());
864    for name in names {
865        match &children[name] {
866            TreeNode::Blob { oid, mode } => {
867                entries.push(gix::objs::tree::Entry {
868                    mode: oak_mode_to_git(*mode),
869                    filename: name.as_str().into(),
870                    oid: *oid,
871                });
872            }
873            child @ TreeNode::Dir { .. } => {
874                let subtree = write_tree_recursive(repo, child)?;
875                entries.push(gix::objs::tree::Entry {
876                    mode: gix::objs::tree::EntryKind::Tree.into(),
877                    filename: name.as_str().into(),
878                    oid: subtree,
879                });
880            }
881        }
882    }
883
884    let tree = gix::objs::Tree { entries };
885    let id = repo.write_object(&tree).map_err(map_git_err)?;
886    Ok(id.detach())
887}
888
889/// Parse an `author` string of the form `"Name <email>"` into separate name/email parts.
890/// Falls back to a synthesized email if the input doesn't carry one.
891fn split_author(author: &str) -> (String, String) {
892    if let Some(start) = author.find('<') {
893        if let Some(end) = author[start + 1..].find('>') {
894            let name = author[..start].trim().to_string();
895            let email = author[start + 1..start + 1 + end].trim().to_string();
896            return (name, email);
897        }
898    }
899    (author.to_string(), "oak@oak.space".to_string())
900}
901
902/// Walk a git tree recursively into a flat `Vec<ManifestEntry>`.
903/// Submodules and other non-blob entries are skipped.
904fn read_tree_recursive(
905    repo: &gix::Repository,
906    tree_id: ObjectId,
907    prefix: &str,
908    out: &mut Vec<ManifestEntry>,
909) -> Result<()> {
910    let obj = repo.find_object(tree_id).map_err(map_git_err)?;
911    let tree = obj
912        .try_into_tree()
913        .map_err(|e| OakError::Git(e.to_string()))?;
914
915    for entry in tree.iter() {
916        let entry = entry.map_err(map_git_err)?;
917        let name = entry.filename().to_string();
918        let path = if prefix.is_empty() {
919            name
920        } else {
921            format!("{prefix}/{name}")
922        };
923
924        let mode = entry.mode();
925        if mode.is_tree() {
926            read_tree_recursive(repo, entry.id().detach(), &path, out)?;
927        } else if mode.is_blob() || mode.is_executable() || mode.is_link() {
928            let oak_mode = if mode.is_executable() {
929                FileMode::Executable
930            } else if mode.is_link() {
931                FileMode::Symlink
932            } else {
933                FileMode::Regular
934            };
935            out.push(ManifestEntry {
936                path,
937                blob_hash: Hash(entry.id().detach().to_string()),
938                mode: oak_mode,
939            });
940        }
941        // Submodules (gitlinks) and other entry kinds are intentionally dropped.
942    }
943    Ok(())
944}
945
946impl Repository for GitRepository {
947    // --- Blobs ---
948
949    /// `store_blob` is unsupported because Oak's `Blob` carries a precomputed BLAKE3
950    /// hash, and writing it as a git blob would assign a different OID. Callers must
951    /// use [`Repository::put_blob`] instead, which returns the canonical git OID.
952    fn store_blob(&self, _blob: &Blob) -> Result<()> {
953        Err(unsupported("store_blob (use put_blob)"))
954    }
955
956    fn hash_blob_content(&self, content: &[u8]) -> Hash {
957        let oid = gix::objs::compute_hash(gix::hash::Kind::Sha1, gix::object::Kind::Blob, content)
958            .expect("sha1 hashing of an in-memory buffer cannot fail");
959        Hash(oid.to_string())
960    }
961
962    fn put_blob(&self, content: Vec<u8>) -> Result<Hash> {
963        let repo = self.repo();
964        let id = repo.write_blob(content).map_err(map_git_err)?;
965        Ok(Hash(id.detach().to_string()))
966    }
967
968    fn get_blob(&self, hash: &Hash) -> Result<Option<Blob>> {
969        let oid = Self::oid(hash)?;
970        let repo = self.repo();
971        let obj = repo.try_find_object(oid).map_err(map_git_err)?;
972        match obj {
973            Some(obj) => {
974                let content = obj.data.to_vec();
975                let size = content.len() as u64;
976                Ok(Some(Blob {
977                    hash: hash.clone(),
978                    content,
979                    size,
980                }))
981            }
982            None => Ok(None),
983        }
984    }
985
986    fn has_blob(&self, hash: &Hash) -> Result<bool> {
987        let oid = Self::oid(hash)?;
988        Ok(self
989            .repo()
990            .try_find_object(oid)
991            .map_err(map_git_err)?
992            .is_some())
993    }
994
995    // --- Manifests (git trees) ---
996
997    /// Unsupported for the same reason as `store_blob` — Oak's manifest hash is
998    /// BLAKE3 over a flat encoding, but git trees are nested with their own OID
999    /// derivation. Callers must use [`Repository::put_manifest`].
1000    fn store_manifest(&self, _manifest: &Manifest) -> Result<()> {
1001        Err(unsupported("store_manifest (use put_manifest)"))
1002    }
1003
1004    fn put_manifest(&self, entries: Vec<ManifestEntry>) -> Result<Hash> {
1005        validate_git_tree_entries(&entries)?;
1006        let repo = self.repo();
1007        let mut root = TreeNode::new_dir();
1008        for entry in entries {
1009            let oid = ObjectId::from_hex(entry.blob_hash.as_str().as_bytes())
1010                .map_err(|_| OakError::InvalidHash(entry.blob_hash.as_str().to_string()))?;
1011            root.insert(&entry.path, oid, entry.mode);
1012        }
1013        let tree_oid = write_tree_recursive(&repo, &root)?;
1014        Ok(Hash(tree_oid.to_string()))
1015    }
1016
1017    fn get_manifest(&self, hash: &Hash) -> Result<Option<Manifest>> {
1018        let oid = Self::oid(hash)?;
1019        let repo = self.repo();
1020        let obj = repo.try_find_object(oid).map_err(map_git_err)?;
1021        let is_tree = matches!(&obj, Some(o) if o.kind == gix::object::Kind::Tree);
1022        drop(obj);
1023        if !is_tree {
1024            return Ok(None);
1025        }
1026        let mut entries = Vec::new();
1027        read_tree_recursive(&repo, oid, "", &mut entries)?;
1028        Ok(Some(Manifest {
1029            hash: hash.clone(),
1030            entries,
1031        }))
1032    }
1033
1034    // --- Trees (git's native tree objects) ---
1035
1036    /// Read the direct children of one git tree as an Oak `Tree`.
1037    /// Submodules are skipped (matching `read_tree_recursive`).
1038    fn get_tree(&self, hash: &Hash) -> Result<Option<crate::Tree>> {
1039        let oid = Self::oid(hash)?;
1040        let repo = self.repo();
1041        let obj = match repo.try_find_object(oid).map_err(map_git_err)? {
1042            Some(o) if o.kind == gix::object::Kind::Tree => o,
1043            _ => return Ok(None),
1044        };
1045        let tree = obj
1046            .try_into_tree()
1047            .map_err(|e| OakError::Git(e.to_string()))?;
1048
1049        let mut entries = Vec::new();
1050        for entry in tree.iter() {
1051            let entry = entry.map_err(map_git_err)?;
1052            let mode = entry.mode();
1053            if mode.is_tree() {
1054                entries.push(crate::TreeEntry {
1055                    name: entry.filename().to_string(),
1056                    kind: crate::TreeEntryKind::Tree,
1057                    hash: Hash(entry.id().detach().to_string()),
1058                    mode: FileMode::Regular,
1059                });
1060            } else if mode.is_blob() || mode.is_executable() || mode.is_link() {
1061                let oak_mode = if mode.is_executable() {
1062                    FileMode::Executable
1063                } else if mode.is_link() {
1064                    FileMode::Symlink
1065                } else {
1066                    FileMode::Regular
1067                };
1068                entries.push(crate::TreeEntry {
1069                    name: entry.filename().to_string(),
1070                    kind: crate::TreeEntryKind::Blob,
1071                    hash: Hash(entry.id().detach().to_string()),
1072                    mode: oak_mode,
1073                });
1074            }
1075        }
1076        Ok(Some(crate::Tree {
1077            hash: hash.clone(),
1078            entries,
1079        }))
1080    }
1081
1082    /// Unsupported for the same reason as `store_blob`: the Tree's hash is Oak's
1083    /// BLAKE3, but a git tree object would assign its own OID. Use [`put_tree`]
1084    /// instead, which returns the git OID.
1085    fn store_tree(&self, _tree: &crate::Tree) -> Result<()> {
1086        Err(unsupported("store_tree (use put_tree)"))
1087    }
1088
1089    fn put_tree(&self, entries: Vec<ManifestEntry>) -> Result<Hash> {
1090        // Same algorithm as `put_manifest`: build a nested TreeNode and write
1091        // it as git trees. Returns the root tree OID.
1092        validate_git_tree_entries(&entries)?;
1093        let repo = self.repo();
1094        let mut root = TreeNode::new_dir();
1095        for entry in entries {
1096            let oid = ObjectId::from_hex(entry.blob_hash.as_str().as_bytes())
1097                .map_err(|_| OakError::InvalidHash(entry.blob_hash.as_str().to_string()))?;
1098            root.insert(&entry.path, oid, entry.mode);
1099        }
1100        let tree_oid = write_tree_recursive(&repo, &root)?;
1101        Ok(Hash(tree_oid.to_string()))
1102    }
1103
1104    fn walk_tree(&self, root: &Hash) -> Result<Vec<ManifestEntry>> {
1105        let oid = Self::oid(root)?;
1106        let repo = self.repo();
1107        let mut entries = Vec::new();
1108        read_tree_recursive(&repo, oid, "", &mut entries)?;
1109        Ok(entries)
1110    }
1111
1112    // --- Branches (git refs) ---
1113
1114    /// Create the git ref for a new branch, pointing at the current HEAD, and
1115    /// record Oak's branch metadata (description / parent_branch / status / created_at)
1116    /// in the sidecar TOML at `<git_dir>/oak/branches.toml`.
1117    ///
1118    /// The git ref is what actually makes the branch usable; the sidecar just
1119    /// preserves Oak-only fields so `oak branch show` / `branch list` aren't lossy.
1120    fn store_branch(&self, branch: &Branch) -> Result<()> {
1121        let repo = self.repo();
1122        let refname = format!("refs/heads/{}", branch.name);
1123
1124        // Create the ref if missing (don't move it if it already exists).
1125        if repo
1126            .try_find_reference(&refname)
1127            .map_err(map_git_err)?
1128            .is_none()
1129        {
1130            let head = repo.head().map_err(map_git_err)?;
1131            let head_oid = match head.try_into_peeled_id() {
1132                Ok(Some(id)) => id.detach(),
1133                Ok(None) => {
1134                    return Err(OakError::Git(format!(
1135                        "cannot create branch '{}': repository has no commits yet",
1136                        branch.name
1137                    )));
1138                }
1139                Err(e) => return Err(map_git_err(e)),
1140            };
1141
1142            repo.reference(
1143                refname.as_str(),
1144                head_oid,
1145                gix::refs::transaction::PreviousValue::MustNotExist,
1146                BString::from(format!("oak: create branch {}", branch.name)),
1147            )
1148            .map_err(map_git_err)?;
1149        }
1150
1151        // Persist Oak-only metadata in the sidecar.
1152        let mut sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1153        sidecar
1154            .branches
1155            .insert(branch.name.clone(), branch_to_meta(branch));
1156        sidecar.save(&self.oak_sidecar_dir)?;
1157        Ok(())
1158    }
1159
1160    fn get_branch(&self, name: &str) -> Result<Option<Branch>> {
1161        let repo = self.repo();
1162        let refname = format!("refs/heads/{name}");
1163        // HEAD's branch in a fresh repo is "unborn": HEAD names it but the ref
1164        // doesn't exist until the first commit. It's still the branch the user
1165        // is on (and the one `oak commit` creates), so report it.
1166        if repo
1167            .try_find_reference(&refname)
1168            .map_err(map_git_err)?
1169            .is_none()
1170            && self.head_branch_name()?.as_deref() != Some(name)
1171        {
1172            return Ok(None);
1173        }
1174        let sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1175        let branch = match sidecar.branches.get(name) {
1176            Some(meta) => meta_to_branch(name, meta),
1177            None => Branch {
1178                name: name.to_string(),
1179                description: None,
1180                parent_branch: None,
1181                status: BranchStatus::Open,
1182                close_reason: None,
1183                created_at: chrono::Utc::now(),
1184            },
1185        };
1186        Ok(Some(branch))
1187    }
1188
1189    fn list_branches(&self) -> Result<Vec<Branch>> {
1190        let repo = self.repo();
1191        let platform = repo.references().map_err(map_git_err)?;
1192        let iter = platform.local_branches().map_err(map_git_err)?;
1193        let sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1194        let mut out = Vec::new();
1195        for r in iter {
1196            let r = r.map_err(map_git_err)?;
1197            let full = r.name().as_bstr().to_string();
1198            let name = full
1199                .strip_prefix("refs/heads/")
1200                .unwrap_or(&full)
1201                .to_string();
1202            let branch = match sidecar.branches.get(&name) {
1203                Some(meta) => meta_to_branch(&name, meta),
1204                None => Branch {
1205                    name,
1206                    description: None,
1207                    parent_branch: None,
1208                    status: BranchStatus::Open,
1209                    close_reason: None,
1210                    created_at: chrono::Utc::now(),
1211                },
1212            };
1213            out.push(branch);
1214        }
1215        Ok(out)
1216    }
1217
1218    fn update_branch_status(&self, name: &str, status: BranchStatus) -> Result<()> {
1219        let mut sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1220        let entry = sidecar.branches.entry(name.to_string()).or_default();
1221        entry.status = status.as_str().to_string();
1222        sidecar.save(&self.oak_sidecar_dir)?;
1223        Ok(())
1224    }
1225
1226    fn close_branch(&self, name: &str, close_reason: Option<CloseReason>) -> Result<()> {
1227        let mut sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1228        let entry = sidecar.branches.entry(name.to_string()).or_default();
1229        entry.status = BranchStatus::Closed.as_str().to_string();
1230        entry.close_reason = close_reason.map(|r| r.as_str().to_string());
1231        sidecar.save(&self.oak_sidecar_dir)?;
1232        Ok(())
1233    }
1234
1235    fn update_branch_close_reason(&self, name: &str, close_reason: CloseReason) -> Result<()> {
1236        let mut sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1237        let entry = sidecar.branches.entry(name.to_string()).or_default();
1238        entry.close_reason = Some(close_reason.as_str().to_string());
1239        sidecar.save(&self.oak_sidecar_dir)?;
1240        Ok(())
1241    }
1242
1243    fn update_branch_description(&self, name: &str, description: &str) -> Result<()> {
1244        let mut sidecar = BranchSidecar::load(&self.oak_sidecar_dir)?;
1245        let entry = sidecar.branches.entry(name.to_string()).or_default();
1246        entry.description = if description.is_empty() {
1247            None
1248        } else {
1249            Some(description.to_string())
1250        };
1251        sidecar.save(&self.oak_sidecar_dir)?;
1252        Ok(())
1253    }
1254
1255    fn get_branch_head(&self, name: &str) -> Result<Option<Hash>> {
1256        let repo = self.repo();
1257        let refname = format!("refs/heads/{name}");
1258        let r = repo.try_find_reference(&refname).map_err(map_git_err)?;
1259        match r {
1260            Some(mut r) => {
1261                let id = r.peel_to_id().map_err(map_git_err)?;
1262                Ok(Some(Hash(id.detach().to_string())))
1263            }
1264            None => Ok(None),
1265        }
1266    }
1267
1268    fn set_branch_head(&self, name: &str, hash: &Hash) -> Result<()> {
1269        let repo = self.repo();
1270        let oid = ObjectId::from_hex(hash.as_str().as_bytes())
1271            .map_err(|_| OakError::InvalidHash(hash.as_str().to_string()))?;
1272        let refname = format!("refs/heads/{name}");
1273        repo.reference(
1274            refname.as_str(),
1275            oid,
1276            gix::refs::transaction::PreviousValue::Any,
1277            BString::from(format!("oak: set head of {name}")),
1278        )
1279        .map_err(map_git_err)?;
1280        if self.head_branch_name()?.as_deref() == Some(name) {
1281            self.sync_index_to_head()?;
1282        }
1283        Ok(())
1284    }
1285
1286    // --- Commits ---
1287
1288    fn store_commit(&self, _commit: &Commit) -> Result<()> {
1289        Err(unsupported("store_commit (use put_commit)"))
1290    }
1291
1292    fn put_commit(
1293        &self,
1294        branch_name: String,
1295        parent_hash: Option<Hash>,
1296        merge_parent_hash: Option<Hash>,
1297        manifest_hash: Hash,
1298        author: String,
1299        message: Option<String>,
1300        timestamp: chrono::DateTime<chrono::Utc>,
1301        files: Vec<FileChange>,
1302    ) -> Result<Hash> {
1303        // Oak checkpoints carry no message; the branch description is the
1304        // narrative. Git (and every git host) shows one per commit, so
1305        // generate it from what this checkpoint actually changed — see
1306        // `format_checkpoint_message`.
1307        let message = match message {
1308            Some(m) => m,
1309            None => self.checkpoint_message(&branch_name, parent_hash.as_ref(), &files)?,
1310        };
1311        let repo = self.repo();
1312        let tree = ObjectId::from_hex(manifest_hash.as_str().as_bytes())
1313            .map_err(|_| OakError::InvalidHash(manifest_hash.as_str().to_string()))?;
1314
1315        let mut parents: Vec<ObjectId> = Vec::new();
1316        if let Some(p) = parent_hash {
1317            parents.push(
1318                ObjectId::from_hex(p.as_str().as_bytes())
1319                    .map_err(|_| OakError::InvalidHash(p.as_str().to_string()))?,
1320            );
1321        }
1322        if let Some(p) = merge_parent_hash {
1323            parents.push(
1324                ObjectId::from_hex(p.as_str().as_bytes())
1325                    .map_err(|_| OakError::InvalidHash(p.as_str().to_string()))?,
1326            );
1327        }
1328
1329        let (name, email) = self.commit_identity(&author);
1330        let sig = gix::actor::Signature {
1331            name: name.into(),
1332            email: email.into(),
1333            time: gix::date::Time::new(timestamp.timestamp(), 0),
1334        };
1335
1336        let commit = gix::objs::Commit {
1337            tree,
1338            parents: parents.into(),
1339            author: sig.clone(),
1340            committer: sig,
1341            encoding: None,
1342            message: message.into(),
1343            extra_headers: vec![],
1344        };
1345
1346        let id = repo.write_object(&commit).map_err(map_git_err)?;
1347        Ok(Hash(id.detach().to_string()))
1348    }
1349
1350    fn get_commit(&self, hash: &Hash) -> Result<Option<Commit>> {
1351        let oid = Self::oid(hash)?;
1352        let repo = self.repo();
1353        let obj = repo.try_find_object(oid).map_err(map_git_err)?;
1354        let is_commit = matches!(&obj, Some(o) if o.kind == gix::object::Kind::Commit);
1355        drop(obj);
1356        drop(repo);
1357        if !is_commit {
1358            return Ok(None);
1359        }
1360        Ok(Some(self.load_commit(oid)?))
1361    }
1362
1363    fn has_commit(&self, hash: &Hash) -> Result<bool> {
1364        let oid = Self::oid(hash)?;
1365        Ok(self
1366            .repo()
1367            .try_find_object(oid)
1368            .map_err(map_git_err)?
1369            .is_some())
1370    }
1371
1372    fn get_commits_for_branch(&self, branch_name: &str) -> Result<Vec<Commit>> {
1373        let head = match self.get_branch_head(branch_name)? {
1374            Some(h) => h,
1375            None => return Ok(Vec::new()),
1376        };
1377        let mut out = Vec::new();
1378        let mut current = Some(Self::oid(&head)?);
1379        while let Some(oid) = current {
1380            let mut commit = self.load_commit(oid)?;
1381            // Branch name isn't stored on git commits — stamp it from the caller's context.
1382            commit.branch_name = branch_name.to_string();
1383            current = commit.parent_hash.as_ref().and_then(|p| Self::oid(p).ok());
1384            out.push(commit);
1385        }
1386        Ok(out)
1387    }
1388
1389    fn get_commits_since(&self, branch_name: &str, since: Option<&Hash>) -> Result<Vec<Commit>> {
1390        let all = self.get_commits_for_branch(branch_name)?;
1391        match since {
1392            None => Ok(all),
1393            Some(stop) => Ok(all.into_iter().take_while(|c| &c.hash != stop).collect()),
1394        }
1395    }
1396
1397    fn get_all_commits(&self) -> Result<Vec<Commit>> {
1398        // Walk every local branch tip; dedupe by hash. For huge repos this is expensive
1399        // but matches the SQLite backend's semantics ("everything reachable").
1400        let mut seen = std::collections::HashSet::new();
1401        let mut out = Vec::new();
1402        for branch in self.list_branches()? {
1403            for commit in self.get_commits_for_branch(&branch.name)? {
1404                if seen.insert(commit.hash.clone()) {
1405                    out.push(commit);
1406                }
1407            }
1408        }
1409        Ok(out)
1410    }
1411
1412    // --- Metadata ---
1413
1414    fn get_metadata(&self, key: MetadataKey) -> Result<Option<String>> {
1415        match key {
1416            MetadataKey::Head => {
1417                // Resolve HEAD to a commit OID (works for both attached and detached HEAD).
1418                let repo = self.repo();
1419                match repo.head().map_err(map_git_err)?.try_into_peeled_id() {
1420                    Ok(Some(id)) => Ok(Some(id.detach().to_string())),
1421                    Ok(None) => Ok(None),
1422                    Err(e) => Err(map_git_err(e)),
1423                }
1424            }
1425            MetadataKey::CurrentBranch => {
1426                // Symbolic HEAD → return the branch short name.
1427                let repo = self.repo();
1428                let head = repo.head().map_err(map_git_err)?;
1429                Ok(head.referent_name().map(|n| {
1430                    let full = n.as_bstr().to_string();
1431                    full.strip_prefix("refs/heads/")
1432                        .unwrap_or(&full)
1433                        .to_string()
1434                }))
1435            }
1436            _ => Ok(self
1437                .scratch_metadata
1438                .lock()
1439                .unwrap()
1440                .get(key.as_str())
1441                .cloned()),
1442        }
1443    }
1444
1445    fn set_metadata(&self, key: MetadataKey, value: &str) -> Result<()> {
1446        match key {
1447            MetadataKey::Head => {
1448                // Oak's `set_head` is called after every commit to record the new tip.
1449                // For attached HEAD, gix updates the underlying branch ref automatically
1450                // when `set_branch_head` is called, so this is usually redundant. We only
1451                // need to act when HEAD is detached — write the OID directly.
1452                let repo = self.repo();
1453                let oid = ObjectId::from_hex(value.as_bytes())
1454                    .map_err(|_| OakError::InvalidHash(value.to_string()))?;
1455                let head = repo.head().map_err(map_git_err)?;
1456                if head.referent_name().is_none() {
1457                    // Detached HEAD — point HEAD directly at the OID.
1458                    repo.reference(
1459                        "HEAD",
1460                        oid,
1461                        gix::refs::transaction::PreviousValue::Any,
1462                        BString::from("oak: set detached HEAD"),
1463                    )
1464                    .map_err(map_git_err)?;
1465                    self.sync_index_to_head()?;
1466                }
1467                Ok(())
1468            }
1469            MetadataKey::CurrentBranch => {
1470                // Update HEAD to be a symbolic ref pointing at refs/heads/<value>.
1471                // gix doesn't expose a one-line "make HEAD symbolic" — open the ref
1472                // file directly via the loose store.
1473                let repo = self.repo();
1474                let target = format!("refs/heads/{value}");
1475                let target_name: gix::refs::FullName =
1476                    target.as_str().try_into().map_err(map_git_err)?;
1477                let edit = gix::refs::transaction::RefEdit {
1478                    change: gix::refs::transaction::Change::Update {
1479                        log: gix::refs::transaction::LogChange {
1480                            mode: gix::refs::transaction::RefLog::AndReference,
1481                            force_create_reflog: false,
1482                            message: BString::from(format!("oak: switch HEAD to {value}")),
1483                        },
1484                        expected: gix::refs::transaction::PreviousValue::Any,
1485                        new: gix::refs::Target::Symbolic(target_name),
1486                    },
1487                    name: "HEAD".try_into().map_err(map_git_err)?,
1488                    deref: false,
1489                };
1490                repo.edit_reference(edit).map_err(map_git_err)?;
1491                drop(repo);
1492                self.sync_index_to_head()?;
1493                Ok(())
1494            }
1495            _ => {
1496                self.scratch_metadata
1497                    .lock()
1498                    .unwrap()
1499                    .insert(key.as_str().to_string(), value.to_string());
1500                Ok(())
1501            }
1502        }
1503    }
1504
1505    // --- Chunks ---
1506
1507    fn store_chunk(&self, _hash: &Hash, _content: &[u8]) -> Result<()> {
1508        Err(unsupported("store_chunk"))
1509    }
1510    fn get_chunk(&self, _hash: &Hash) -> Result<Option<Vec<u8>>> {
1511        Err(unsupported("get_chunk"))
1512    }
1513    fn has_chunk(&self, _hash: &Hash) -> Result<bool> {
1514        Err(unsupported("has_chunk"))
1515    }
1516    fn store_blob_chunks(&self, _blob_hash: &Hash, _chunks: &[ChunkInfo]) -> Result<()> {
1517        Err(unsupported("store_blob_chunks"))
1518    }
1519    fn get_blob_chunks(&self, _blob_hash: &Hash) -> Result<Option<Vec<ChunkInfo>>> {
1520        Err(unsupported("get_blob_chunks"))
1521    }
1522}
1523
1524#[cfg(test)]
1525mod tests {
1526    use super::*;
1527
1528    /// A file `foo.txt` next to a directory `foo` is the canonical case where
1529    /// plain lexicographic order (`foo` < `foo.txt`) diverges from git's
1530    /// directory-aware order (`foo.txt` < `foo/`, because '.' 0x2e < '/' 0x2f).
1531    /// Getting this wrong panics gix's tree writer in debug and produces a
1532    /// `git fsck`-rejected tree in release.
1533    #[test]
1534    fn dir_and_file_straddling_slash_sort_in_git_order() {
1535        // Start in the "wrong" (BTreeMap) order to prove the sort reorders.
1536        let mut names = [("foo", true), ("foo.txt", false)];
1537        names.sort_by(|(a, ad), (b, bd)| git_tree_sort_key(a, *ad).cmp(&git_tree_sort_key(b, *bd)));
1538        assert_eq!(
1539            names.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
1540            vec!["foo.txt", "foo"],
1541            "git orders the file before the same-stem directory"
1542        );
1543    }
1544
1545    #[test]
1546    fn two_dirs_and_two_files_sort_stably() {
1547        let mut names = [("b", true), ("a.txt", false), ("a", true), ("b.txt", false)];
1548        names.sort_by(|(a, ad), (b, bd)| git_tree_sort_key(a, *ad).cmp(&git_tree_sort_key(b, *bd)));
1549        // a/, then a.txt? No: "a/" (0x2f) vs "a.txt" (0x2e) → "a.txt" < "a/".
1550        assert_eq!(
1551            names.iter().map(|(n, _)| *n).collect::<Vec<_>>(),
1552            vec!["a.txt", "a", "b.txt", "b"],
1553        );
1554    }
1555
1556    fn stat(ct: crate::ChangeType, path: &str, added: usize, removed: usize) -> FileStat {
1557        FileStat {
1558            change_type: ct,
1559            path: path.to_string(),
1560            old_path: None,
1561            mode_changed: false,
1562            lines: LineStat::Text { added, removed },
1563        }
1564    }
1565
1566    #[test]
1567    fn subject_lists_up_to_three_files_with_lowercased_verbs() {
1568        let files = [
1569            stat(crate::ChangeType::Modified, "README.md", 2, 1),
1570            stat(crate::ChangeType::Added, "greet.txt", 1, 0),
1571        ];
1572        assert_eq!(
1573            checkpoint_subject(&files, "feat"),
1574            "Update README.md, add greet.txt"
1575        );
1576    }
1577
1578    #[test]
1579    fn subject_falls_back_to_file_names_then_directory_summary() {
1580        let long = |name: &str| format!("some/deeply/nested/directory/tree/{name}");
1581        let files = [
1582            stat(crate::ChangeType::Modified, &long("alpha_module.rs"), 1, 1),
1583            stat(crate::ChangeType::Modified, &long("beta_module.rs"), 1, 1),
1584        ];
1585        assert_eq!(
1586            checkpoint_subject(&files, "feat"),
1587            "Update alpha_module.rs, update beta_module.rs"
1588        );
1589
1590        let many: Vec<FileStat> = (0..5)
1591            .map(|i| stat(crate::ChangeType::Added, &format!("src/cmd/m{i}.rs"), 1, 0))
1592            .collect();
1593        assert_eq!(checkpoint_subject(&many, "feat"), "Add 5 files in src/cmd");
1594
1595        let mut mixed = many.clone();
1596        mixed.push(stat(crate::ChangeType::Deleted, "README.md", 0, 3));
1597        assert_eq!(
1598            checkpoint_subject(&mixed, "feat"),
1599            "Update 6 files in src/ and the top level (5 added, 1 deleted)"
1600        );
1601    }
1602
1603    #[test]
1604    fn subject_states_a_shared_verb_and_directory_once() {
1605        let files: Vec<FileStat> = (1..=3)
1606            .map(|i| stat(crate::ChangeType::Added, &format!("src/cmd/m{i}.rs"), 1, 0))
1607            .collect();
1608        assert_eq!(
1609            checkpoint_subject(&files, "feat"),
1610            "Add m1.rs, m2.rs and m3.rs in src/cmd"
1611        );
1612        let top = [
1613            stat(crate::ChangeType::Deleted, "a.txt", 0, 1),
1614            stat(crate::ChangeType::Deleted, "b.txt", 0, 1),
1615        ];
1616        assert_eq!(checkpoint_subject(&top, "feat"), "Delete a.txt and b.txt");
1617    }
1618
1619    #[test]
1620    fn subject_names_renames_and_mode_changes() {
1621        let mut rename = stat(crate::ChangeType::Renamed, "b.txt", 0, 0);
1622        rename.old_path = Some("a.txt".to_string());
1623        let mut chmod = stat(crate::ChangeType::Modified, "run.sh", 0, 0);
1624        chmod.mode_changed = true;
1625        assert_eq!(
1626            checkpoint_subject(&[rename, chmod], "feat"),
1627            "Rename a.txt to b.txt, change mode of run.sh"
1628        );
1629        assert_eq!(checkpoint_subject(&[], "feat"), "Checkpoint on feat");
1630    }
1631
1632    #[test]
1633    fn long_subjects_are_truncated_to_the_git_limit() {
1634        let subject = truncate_subject("x".repeat(100));
1635        assert_eq!(subject.chars().count(), SUBJECT_MAX);
1636        assert!(subject.ends_with('…'));
1637    }
1638
1639    #[test]
1640    fn line_stat_counts_lines_and_flags_binary() {
1641        assert_eq!(
1642            line_stat(b"a\nb\n", b"a\nc\nd\n"),
1643            LineStat::Text {
1644                added: 2,
1645                removed: 1
1646            }
1647        );
1648        assert_eq!(line_stat(b"", b"\0\x01"), LineStat::Binary);
1649    }
1650
1651    #[test]
1652    fn message_has_summary_file_table_description_and_trailers() {
1653        let files = [
1654            stat(crate::ChangeType::Modified, "README.md", 2, 1),
1655            stat(crate::ChangeType::Added, "greet.txt", 1, 0),
1656        ];
1657        let msg = format_checkpoint_message(&CheckpointInfo {
1658            branch: "feat",
1659            parent_branch: Some("main"),
1660            checkpoint: 2,
1661            description: Some("Add greeting\n\nDetails here."),
1662            files: &files,
1663        });
1664        assert_eq!(
1665            msg,
1666            "Update README.md, add greet.txt\n\
1667             \n\
1668             Checkpoint 2 on feat (parent: main): 2 files changed, +3 -1\n\
1669             \n\
1670             \x20 M  README.md  +2 -1\n\
1671             \x20 A  greet.txt  +1\n\
1672             \n\
1673             Branch description:\n\
1674             \x20 Add greeting\n\
1675             \n\
1676             \x20 Details here.\n\
1677             \n\
1678             Oak-Branch: feat\n\
1679             Oak-Checkpoint: 2\n"
1680        );
1681    }
1682
1683    fn entry(path: &str) -> ManifestEntry {
1684        ManifestEntry {
1685            path: path.to_string(),
1686            blob_hash: Hash::from_hex(&"a".repeat(40)).unwrap(),
1687            mode: FileMode::Regular,
1688        }
1689    }
1690
1691    #[test]
1692    fn validate_git_tree_entries_accepts_normal_paths() {
1693        validate_git_tree_entries(&[entry("src/main.rs"), entry("README.md")]).unwrap();
1694    }
1695
1696    #[test]
1697    fn validate_git_tree_entries_rejects_invalid_components() {
1698        for path in ["../escape.txt", "src/../escape.txt", "bad\nname.txt"] {
1699            let err = validate_git_tree_entries(&[entry(path)]).unwrap_err();
1700            assert!(
1701                matches!(err, OakError::InvalidPath(_)),
1702                "{path:?} should be InvalidPath, got {err:?}"
1703            );
1704        }
1705    }
1706}