git-meta-lib 0.1.10

Library for attaching and exchanging structured metadata in Git repositories (serialize/materialize, SQLite store, merge).
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
/// High-level sync operations: promisor entry insertion, commit change parsing,
/// and tree key extraction for blobless clone support.
use gix::bstr::ByteSlice;
use gix::prelude::ObjectIdExt;

use crate::db::Store;
use crate::error::{Error, Result};
use crate::tree::format::parse_path_parts;
use crate::types::{
    Target, TargetType, ValueType, LIST_VALUE_DIR, SET_VALUE_DIR, STRING_VALUE_BLOB, TOMBSTONE_ROOT,
};

/// A parsed change from a `git-meta` serialize commit message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitChange {
    /// The operation character: 'A' (add), 'M' (modify), 'D' (delete).
    pub op: char,
    /// The target type string (e.g. "commit", "project").
    pub target_type: String,
    /// The target value (e.g. commit SHA, branch name). Empty for project targets.
    pub target_value: String,
    /// The metadata key.
    pub key: String,
}

/// Parse the change list from a `git-meta` serialize commit message.
///
/// Returns `None` if the message is not a serialize commit or if changes were
/// omitted (too many to inline).
///
/// Accepts the current `git-meta: serialize` prefix and the legacy `gmeta: serialize`
/// prefix so historical metadata histories remain readable.
///
/// Each entry describes an operation (add/modify/delete), the target, and key.
pub fn parse_commit_changes(message: &str) -> Option<Vec<CommitChange>> {
    if !is_serialize_commit_message(message) {
        return None;
    }

    if commit_changes_omitted(message) {
        return None;
    }

    let body_start = message.find("\n\n")?;
    let body = &message[body_start + 2..];

    let mut changes = Vec::new();
    for line in body.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() != 3 {
            continue;
        }
        let op = parts[0].chars().next()?;
        let target_label = parts[1];
        let key = parts[2].to_string();

        let (target_type, target_value) = if target_label == "project" {
            ("project".to_string(), String::new())
        } else if let Some((t, v)) = target_label.split_once(':') {
            (t.to_string(), v.to_string())
        } else {
            continue;
        };

        changes.push(CommitChange {
            op,
            target_type,
            target_value,
            key,
        });
    }

    Some(changes)
}

/// Return whether a serialize commit omitted its inline change list.
///
/// Large serialize commits include `changes-omitted: true` instead of one
/// line per changed key. Callers can still discover keys by walking the
/// commit's tree, because the tree layout records target/key paths without
/// requiring blob content.
#[must_use]
pub fn commit_changes_omitted(message: &str) -> bool {
    if !is_serialize_commit_message(message) {
        return false;
    }

    let Some(body_start) = message.find("\n\n") else {
        return false;
    };
    let body = &message[body_start + 2..];
    body.contains("changes-omitted: true")
}

fn is_serialize_commit_message(message: &str) -> bool {
    message.starts_with("git-meta: serialize") || message.starts_with("gmeta: serialize")
}

/// Walk non-tip commits and insert promisor entries for keys mentioned
/// in their commit messages.
///
/// Used after a blobless fetch to build an index of all metadata keys
/// in the history without downloading blob content. Returns the number
/// of new promisor entries inserted.
///
/// # Parameters
/// - `repo`: the git repository
/// - `store`: the metadata store (promisor entries are inserted here)
/// - `tip_oid`: the tip commit (already materialized, will be skipped)
/// - `old_tip`: optional boundary — stop walking when this commit is reached
pub fn insert_promisor_entries(
    repo: &gix::Repository,
    store: &Store,
    tip_oid: gix::ObjectId,
    old_tip: Option<gix::ObjectId>,
) -> Result<usize> {
    let mut walk = repo.rev_walk(Some(tip_oid));
    if let Some(old) = old_tip {
        walk = walk.with_boundary(Some(old));
    }
    let iter = walk
        .all()
        .map_err(|e| Error::Other(format!("rev_walk failed: {e}")))?;

    let mut count = 0;
    let mut is_tip = true;

    for info_result in iter {
        let info = info_result.map_err(|e| Error::Other(format!("rev_walk iter: {e}")))?;
        let oid = info.id;

        // Skip the tip commit — it was already fully materialized
        if is_tip {
            is_tip = false;
            continue;
        }

        // If we're using boundary, stop at the boundary commit
        if old_tip.is_some() && Some(oid) == old_tip {
            break;
        }

        let commit_obj = oid
            .attach(repo)
            .object()
            .map_err(|e| Error::Other(format!("{e}")))?;
        let commit = commit_obj.into_commit();
        let message = commit.message_raw_sloppy().to_str_lossy().to_string();

        match parse_commit_changes(&message) {
            Some(changes) => {
                for change in &changes {
                    if change.op == 'D' {
                        continue;
                    }
                    let target_type = change.target_type.parse::<TargetType>()?;
                    let target = if target_type == TargetType::Project {
                        Target::project()
                    } else {
                        Target::from_parts(target_type, Some(change.target_value.clone()))
                    };
                    if store.insert_promised(&target, &change.key, &ValueType::String)? {
                        count += 1;
                    }
                }
            }
            None => {
                let decoded = commit.decode().map_err(|e| Error::Other(format!("{e}")))?;
                if decoded.parents().count() == 0 || commit_changes_omitted(&message) {
                    // Root commits and omitted-change commits need tree walking
                    // because they do not carry an inline per-key change list.
                    let tree_id = commit
                        .tree_id()
                        .map_err(|e| Error::Other(format!("{e}")))?
                        .detach();
                    count += insert_promised_tree_keys(repo, store, tree_id)?;
                }
            }
        }
    }

    Ok(count)
}

fn insert_promised_tree_keys(
    repo: &gix::Repository,
    store: &Store,
    tree_id: gix::ObjectId,
) -> Result<usize> {
    let keys = extract_keys_from_tree(repo, tree_id)?;
    let mut count = 0;

    for (target_type_str, target_value, key) in &keys {
        let target_type = target_type_str.parse::<TargetType>()?;
        let target = if target_type == TargetType::Project {
            Target::project()
        } else {
            Target::from_parts(target_type, Some(target_value.clone()))
        };
        if store.insert_promised(&target, key, &ValueType::String)? {
            count += 1;
        }
    }

    Ok(count)
}

/// Extract `(target_type, target_value, key)` tuples from a git tree by walking
/// all paths and parsing the tree structure.
///
/// Only looks at path names — does not read blob content, so works on trees
/// with missing blobs (blobless clones).
pub fn extract_keys_from_tree(
    repo: &gix::Repository,
    tree_id: gix::ObjectId,
) -> Result<Vec<(String, String, String)>> {
    let mut keys = Vec::new();
    let mut paths = Vec::new();

    collect_blob_paths(repo, tree_id, String::new(), &mut paths)?;

    for path in &paths {
        if let Some(parsed) = parse_tree_path(path) {
            keys.push(parsed);
        }
    }

    keys.sort();
    keys.dedup();
    Ok(keys)
}

/// Recursively collect all blob paths in a tree.
fn collect_blob_paths(
    repo: &gix::Repository,
    tree_id: gix::ObjectId,
    prefix: String,
    paths: &mut Vec<String>,
) -> Result<()> {
    let tree = tree_id
        .attach(repo)
        .object()
        .map_err(|e| Error::Other(format!("{e}")))?
        .into_tree();
    for entry_result in tree.iter() {
        let entry = entry_result.map_err(|e| Error::Other(format!("{e}")))?;
        let name = entry.filename().to_str_lossy().to_string();
        let full_path = if prefix.is_empty() {
            name.clone()
        } else {
            format!("{prefix}{name}")
        };
        if entry.mode().is_blob() {
            paths.push(full_path);
        } else if entry.mode().is_tree() {
            collect_blob_paths(repo, entry.object_id(), format!("{full_path}/"), paths)?;
        }
    }
    Ok(())
}

/// Parse a tree path into `(target_type, target_value, key)`.
///
/// Handles all target type layouts: project, commit (sharded), path (with separator),
/// and branch/change-id (hash-sharded). Returns `None` for tombstone paths or
/// unparseable paths.
fn parse_tree_path(path: &str) -> Option<(String, String, String)> {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() < 2 {
        return None;
    }

    if parts.contains(&TOMBSTONE_ROOT) {
        return None;
    }

    let value_type_marker = if parts.contains(&STRING_VALUE_BLOB) {
        STRING_VALUE_BLOB
    } else if parts.contains(&LIST_VALUE_DIR) {
        LIST_VALUE_DIR
    } else if parts.contains(&SET_VALUE_DIR) {
        SET_VALUE_DIR
    } else {
        return None;
    };

    let (target_type, target_value, key_parts) = parse_path_parts(&parts).ok()?;
    let marker_pos = key_parts.iter().position(|&p| p == value_type_marker)?;
    if marker_pos == 0 {
        return None;
    }
    let key = key_parts[..marker_pos].join(":");
    Some((target_type.as_str().to_string(), target_value, key))
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_commit_changes_normal() {
        let msg = "git-meta: serialize (3 changes)\n\n\
                   A\tcommit:abc123\tagent:model\n\
                   M\tproject\tmeta:prune:since\n\
                   D\tbranch:main\treview:status";
        let changes = parse_commit_changes(msg).unwrap();
        assert_eq!(changes.len(), 3);
        assert_eq!(changes[0].op, 'A');
        assert_eq!(changes[0].target_type, "commit");
        assert_eq!(changes[0].target_value, "abc123");
        assert_eq!(changes[0].key, "agent:model");
        assert_eq!(changes[2].op, 'D');
    }

    #[test]
    fn test_parse_commit_changes_legacy_gmeta_prefix() {
        let msg = "gmeta: serialize (1 changes)\n\nA\tproject\told_key";
        let changes = parse_commit_changes(msg).unwrap();
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].key, "old_key");
    }

    #[test]
    fn test_parse_commit_changes_non_git_meta() {
        assert_eq!(parse_commit_changes("fix: some bug"), None);
    }

    #[test]
    fn test_parse_commit_changes_omitted() {
        let msg = "git-meta: serialize (5000 changes)\n\nchanges-omitted: true\ncount: 5000";
        assert_eq!(parse_commit_changes(msg), None);
    }

    #[test]
    fn test_parse_commit_changes_no_body() {
        let msg = "git-meta: serialize (0 changes)";
        assert_eq!(parse_commit_changes(msg), None);
    }

    #[test]
    fn test_parse_tree_path_commit() {
        let path = "commit/ab/abc123def456/agent/model/__value";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(
            result,
            ("commit".into(), "abc123def456".into(), "agent:model".into())
        );
    }

    #[test]
    fn test_parse_tree_path_project() {
        let path = "project/testing/__value";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(result, ("project".into(), String::new(), "testing".into()));
    }

    #[test]
    fn test_parse_tree_path_tombstone_ignored() {
        let path = "commit/ab/abc123/__tombstones/key/__deleted";
        assert_eq!(parse_tree_path(path), None);
    }

    #[test]
    fn test_parse_tree_path_list() {
        let path = "commit/ab/abc123/tags/__list/12345-abcde";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(result, ("commit".into(), "abc123".into(), "tags".into()));
    }

    #[test]
    fn test_parse_tree_path_branch() {
        let path = "branch/ab/feature-x/review/status/__value";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(
            result,
            ("branch".into(), "feature-x".into(), "review:status".into())
        );
    }

    #[test]
    fn test_parse_tree_path_branch_with_slash() {
        let path = "branch/a6/alex/trails-multi-pr-a57e52c3/review/status/__value";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(
            result,
            (
                "branch".into(),
                "alex/trails-multi-pr-a57e52c3".into(),
                "review:status".into()
            )
        );
    }

    #[test]
    fn test_parse_tree_path_project_nested_key() {
        let path = "project/meta/prune/since/__value";
        let result = parse_tree_path(path).unwrap();
        assert_eq!(
            result,
            ("project".into(), String::new(), "meta:prune:since".into())
        );
    }
}