git-internal 0.7.4

High-performance Rust library for Git internal objects, Pack files, and AI-assisted development objects (Intent, Plan, Task, Run, Evidence, Decision) with delta compression, streaming I/O, and smart protocol support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Transport-agnostic pack generator that reuses repository storage traits to walk commits, expand
//! trees/blobs, and either stream packs to clients or unpack uploads for server-side ingestion.

use std::{
    collections::{HashSet, VecDeque},
    io::Cursor,
};

use bytes::Bytes;
use tokio::{self, sync::mpsc};
use tokio_stream::wrappers::ReceiverStream;

use super::{core::RepositoryAccess, types::ProtocolError};
use crate::{
    hash::ObjectHash,
    internal::{
        metadata::{EntryMeta, MetaAttached},
        object::{ObjectTrait, blob::Blob, commit::Commit, tree::Tree, types::ObjectType},
        pack::{Pack, encode::PackEncoder, entry::Entry},
    },
};

/// Pack generation service for Git protocol operations
///
/// This handles the core Git pack generation logic internally within git-internal,
/// using the RepositoryAccess trait only for data access.
pub struct PackGenerator<'a, R>
where
    R: RepositoryAccess,
{
    repo_access: &'a R,
}

impl<'a, R> PackGenerator<'a, R>
where
    R: RepositoryAccess,
{
    pub fn new(repo_access: &'a R) -> Self {
        Self { repo_access }
    }

    /// Generate a full pack containing all requested objects
    pub async fn generate_full_pack(
        &self,
        want: Vec<String>,
    ) -> Result<ReceiverStream<Vec<u8>>, ProtocolError> {
        let (tx, rx) = mpsc::channel(1024);

        // Collect all objects needed for the wanted commits
        let all_objects = self.collect_all_objects(want).await?;

        // Generate pack data
        tokio::spawn(async move {
            if let Err(e) = Self::generate_pack_stream(all_objects, tx).await {
                tracing::error!("Failed to generate pack stream: {}", e);
            }
        });

        Ok(ReceiverStream::new(rx))
    }

    /// Generate an incremental pack containing only objects not in 'have'
    pub async fn generate_incremental_pack(
        &self,
        want: Vec<String>,
        have: Vec<String>,
    ) -> Result<ReceiverStream<Vec<u8>>, ProtocolError> {
        let (tx, rx) = mpsc::channel(1024);

        // Collect objects for wanted commits
        let wanted_objects = self.collect_all_objects(want).await?;

        // Collect objects for have commits (to exclude)
        let have_objects = self.collect_all_objects(have).await?;

        // Filter out objects that are already in 'have'
        let incremental_objects = Self::filter_objects(wanted_objects, have_objects);

        // Generate pack data
        tokio::spawn(async move {
            if let Err(e) = Self::generate_pack_stream(incremental_objects, tx).await {
                tracing::error!("Failed to generate incremental pack stream: {}", e);
            }
        });

        Ok(ReceiverStream::new(rx))
    }

    /// Unpack incoming pack stream and extract objects
    pub async fn unpack_stream(
        &self,
        pack_data: Bytes,
    ) -> Result<(Vec<Commit>, Vec<Tree>, Vec<Blob>), ProtocolError> {
        use std::sync::{Arc, Mutex};

        let commits = Arc::new(Mutex::new(Vec::new()));
        let trees = Arc::new(Mutex::new(Vec::new()));
        let blobs = Arc::new(Mutex::new(Vec::new()));

        let commits_clone = commits.clone();
        let trees_clone = trees.clone();
        let blobs_clone = blobs.clone();

        // Create a Pack instance for decoding
        let mut pack = Pack::new(None, None, None, true);
        let mut cursor = Cursor::new(pack_data.to_vec());

        // Decode the pack and collect entries
        pack.decode(
            &mut cursor,
            move |entry: MetaAttached<Entry, EntryMeta>| match entry.inner.obj_type {
                ObjectType::Commit => {
                    if let Ok(commit) = Commit::from_bytes(&entry.inner.data, entry.inner.hash) {
                        commits_clone.lock().unwrap().push(commit);
                    } else {
                        tracing::warn!("Failed to parse commit from pack entry");
                    }
                }
                ObjectType::Tree => {
                    if let Ok(tree) = Tree::from_bytes(&entry.inner.data, entry.inner.hash) {
                        trees_clone.lock().unwrap().push(tree);
                    } else {
                        tracing::warn!("Failed to parse tree from pack entry");
                    }
                }
                ObjectType::Blob => {
                    if let Ok(blob) = Blob::from_bytes(&entry.inner.data, entry.inner.hash) {
                        blobs_clone.lock().unwrap().push(blob);
                    } else {
                        tracing::warn!("Failed to parse blob from pack entry");
                    }
                }
                _ => {
                    tracing::warn!("Unknown object type in pack: {:?}", entry.inner.obj_type);
                }
            },
            None::<fn(ObjectHash)>,
        )
        .map_err(|e| ProtocolError::invalid_request(&format!("Failed to decode pack: {e}")))?;

        // Extract the results
        let commits_result = Arc::try_unwrap(commits).unwrap().into_inner().unwrap();
        let trees_result = Arc::try_unwrap(trees).unwrap().into_inner().unwrap();
        let blobs_result = Arc::try_unwrap(blobs).unwrap().into_inner().unwrap();

        Ok((commits_result, trees_result, blobs_result))
    }

    /// Collect all objects reachable from the given commit hashes
    async fn collect_all_objects(
        &self,
        commit_hashes: Vec<String>,
    ) -> Result<(Vec<Commit>, Vec<Tree>, Vec<Blob>), ProtocolError> {
        let mut commits = Vec::new();
        let mut trees = Vec::new();
        let mut blobs = Vec::new();

        let mut visited_commits = HashSet::new();
        let mut visited_trees = HashSet::new();
        let mut visited_blobs = HashSet::new();

        let mut commit_queue = VecDeque::from(commit_hashes);

        // BFS traversal of commit graph
        while let Some(commit_hash) = commit_queue.pop_front() {
            if visited_commits.contains(&commit_hash) {
                continue;
            }
            visited_commits.insert(commit_hash.clone());

            // Get commit object
            let commit = self
                .repo_access
                .get_commit(&commit_hash)
                .await
                .map_err(|e| {
                    ProtocolError::repository_error(format!(
                        "Failed to get commit {commit_hash}: {e}"
                    ))
                })?;

            // Add parent commits to queue
            for parent in &commit.parent_commit_ids {
                let parent_str = parent.to_string();
                if !visited_commits.contains(&parent_str) {
                    commit_queue.push_back(parent_str);
                }
            }

            // Collect tree objects
            Box::pin(self.collect_tree_objects(
                &commit.tree_id.to_string(),
                &mut trees,
                &mut blobs,
                &mut visited_trees,
                &mut visited_blobs,
            ))
            .await?;

            commits.push(commit);
        }

        Ok((commits, trees, blobs))
    }

    /// Recursively collect tree and blob objects
    async fn collect_tree_objects(
        &self,
        tree_hash: &str,
        trees: &mut Vec<Tree>,
        blobs: &mut Vec<Blob>,
        visited_trees: &mut HashSet<String>,
        visited_blobs: &mut HashSet<String>,
    ) -> Result<(), ProtocolError> {
        if visited_trees.contains(tree_hash) {
            return Ok(());
        }
        visited_trees.insert(tree_hash.to_string());

        let tree = self.repo_access.get_tree(tree_hash).await.map_err(|e| {
            ProtocolError::repository_error(format!("Failed to get tree {tree_hash}: {e}"))
        })?;

        for entry in &tree.tree_items {
            let entry_hash = entry.id.to_string();
            match entry.mode {
                crate::internal::object::tree::TreeItemMode::Tree => {
                    Box::pin(self.collect_tree_objects(
                        &entry_hash,
                        trees,
                        blobs,
                        visited_trees,
                        visited_blobs,
                    ))
                    .await?;
                }
                crate::internal::object::tree::TreeItemMode::Blob
                | crate::internal::object::tree::TreeItemMode::BlobExecutable => {
                    if !visited_blobs.contains(&entry_hash) {
                        visited_blobs.insert(entry_hash.clone());
                        let blob = self.repo_access.get_blob(&entry_hash).await.map_err(|e| {
                            ProtocolError::repository_error(format!(
                                "Failed to get blob {entry_hash}: {e}"
                            ))
                        })?;
                        blobs.push(blob);
                    }
                }
                _ => {}
            }
        }

        trees.push(tree);
        Ok(())
    }

    /// Filter objects to exclude those already in 'have'
    fn filter_objects(
        wanted: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
        have: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
    ) -> (Vec<Commit>, Vec<Tree>, Vec<Blob>) {
        let (wanted_commits, wanted_trees, wanted_blobs) = wanted;
        let (have_commits, have_trees, have_blobs) = have;

        // Create hash sets for efficient lookup
        let have_commit_hashes: HashSet<String> =
            have_commits.iter().map(|c| c.id.to_string()).collect();
        let have_tree_hashes: HashSet<String> =
            have_trees.iter().map(|t| t.id.to_string()).collect();
        let have_blob_hashes: HashSet<String> =
            have_blobs.iter().map(|b| b.id.to_string()).collect();

        // Filter out objects that are in 'have'
        let filtered_commits: Vec<Commit> = wanted_commits
            .into_iter()
            .filter(|c| !have_commit_hashes.contains(&c.id.to_string()))
            .collect();

        let filtered_trees: Vec<Tree> = wanted_trees
            .into_iter()
            .filter(|t| !have_tree_hashes.contains(&t.id.to_string()))
            .collect();

        let filtered_blobs: Vec<Blob> = wanted_blobs
            .into_iter()
            .filter(|b| !have_blob_hashes.contains(&b.id.to_string()))
            .collect();

        (filtered_commits, filtered_trees, filtered_blobs)
    }

    /// Generate pack stream from objects
    async fn generate_pack_stream(
        objects: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
        tx: mpsc::Sender<Vec<u8>>,
    ) -> Result<(), ProtocolError> {
        let (commits, trees, blobs) = objects;

        // Convert objects to entries
        let mut entries = Vec::new();

        for commit in commits {
            entries.push(Entry::from(commit));
        }

        for tree in trees {
            entries.push(Entry::from(tree));
        }

        for blob in blobs {
            entries.push(Entry::from(blob));
        }

        // Create PackEncoder and encode entries
        let (pack_tx, mut pack_rx) = mpsc::channel(1024);
        let (entry_tx, entry_rx) = mpsc::channel(1024);
        let mut encoder = PackEncoder::new(entries.len(), 10, pack_tx); // window_size = 10

        // Spawn encoding task
        tokio::spawn(async move {
            if let Err(e) = encoder.encode(entry_rx).await {
                tracing::error!("Failed to encode pack: {}", e);
            }
        });

        // Send entries to encoder
        tokio::spawn(async move {
            for entry in entries {
                if entry_tx
                    .send(MetaAttached {
                        inner: entry,
                        meta: EntryMeta::new(),
                    })
                    .await
                    .is_err()
                {
                    break; // Receiver dropped
                }
            }
            // Drop sender to signal end of entries
        });

        // Forward pack data to output channel
        while let Some(chunk) = pack_rx.recv().await {
            if tx.send(chunk).await.is_err() {
                break; // Receiver dropped
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use async_trait::async_trait;
    use bytes::Bytes;

    use super::*;
    use crate::{
        hash::{HashKind, set_hash_kind_for_test},
        internal::object::{
            blob::Blob,
            commit::Commit,
            signature::{Signature, SignatureType},
            tree::{Tree, TreeItem, TreeItemMode},
        },
    };
    /// Dummy repository access for testing
    #[derive(Clone)]
    struct DummyRepoAccess;

    #[async_trait]
    impl RepositoryAccess for DummyRepoAccess {
        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
            Ok(vec![])
        }
        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
            Ok(false)
        }
        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
            Err(ProtocolError::repository_error(
                "not implemented".to_string(),
            ))
        }
        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
            Ok(())
        }
        async fn update_reference(
            &self,
            _ref_name: &str,
            _old_hash: Option<&str>,
            _new_hash: &str,
        ) -> Result<(), ProtocolError> {
            Ok(())
        }
        async fn get_objects_for_pack(
            &self,
            _wants: &[String],
            _haves: &[String],
        ) -> Result<Vec<String>, ProtocolError> {
            Ok(vec![])
        }
        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
            Ok(false)
        }
        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
            Ok(())
        }
    }

    /// Encode and decode a pack, asserting that all object IDs survive the roundtrip.
    async fn run_pack_roundtrip(kind: HashKind) {
        let _guard = set_hash_kind_for_test(kind);
        let blob1 = Blob::from_content("hello");
        let blob2 = Blob::from_content("world");

        let item1 = TreeItem::new(TreeItemMode::Blob, blob1.id, "hello.txt".to_string());
        let item2 = TreeItem::new(TreeItemMode::Blob, blob2.id, "world.txt".to_string());
        let tree = Tree::from_tree_items(vec![item1, item2]).unwrap();

        let author = Signature::new(
            SignatureType::Author,
            "tester".to_string(),
            "tester@example.com".to_string(),
        );
        let committer = Signature::new(
            SignatureType::Committer,
            "tester".to_string(),
            "tester@example.com".to_string(),
        );
        let commit = Commit::new(author, committer, tree.id, vec![], "init commit");

        let (tx, mut rx) = mpsc::channel::<Vec<u8>>(64);
        PackGenerator::<DummyRepoAccess>::generate_pack_stream(
            (
                vec![commit.clone()],
                vec![tree.clone()],
                vec![blob1.clone(), blob2.clone()],
            ),
            tx,
        )
        .await
        .unwrap();

        let mut pack_bytes: Vec<u8> = Vec::new();
        while let Some(chunk) = rx.recv().await {
            pack_bytes.extend_from_slice(&chunk);
        }

        let dummy = DummyRepoAccess;
        let generator = PackGenerator::new(&dummy);
        let (decoded_commits, decoded_trees, decoded_blobs) = generator
            .unpack_stream(Bytes::from(pack_bytes))
            .await
            .unwrap();

        assert_eq!(decoded_commits.len(), 1);
        assert_eq!(decoded_trees.len(), 1);
        assert_eq!(decoded_blobs.len(), 2);

        assert_eq!(decoded_commits[0].id, commit.id);
        assert_eq!(decoded_trees[0].id, tree.id);

        let mut orig_blob_ids = vec![blob1.id.to_string(), blob2.id.to_string()];
        orig_blob_ids.sort_unstable();
        let mut decoded_blob_ids = decoded_blobs
            .iter()
            .map(|b| b.id.to_string())
            .collect::<Vec<_>>();
        decoded_blob_ids.sort_unstable();
        assert_eq!(orig_blob_ids, decoded_blob_ids);
    }

    /// Pack encode/decode roundtrip using SHA-1 and SHA-256
    #[tokio::test]
    async fn test_pack_roundtrip_encode_decode() {
        run_pack_roundtrip(HashKind::Sha1).await;
        run_pack_roundtrip(HashKind::Sha256).await;
    }
}