|
| 1 | +//! An example demonstrating how to encode Git objects into a pack file using git-internal crate. |
| 2 | +//! This example creates several Blob objects from string data, encodes them into a pack file, |
| 3 | +//! and writes the resulting pack file to disk. |
| 4 | +//! |
| 5 | +//! Make sure to check the output directory for the generated pack file after running this example. |
| 6 | +//! The example assumes SHA-1 hashing for simplicity. |
| 7 | +
|
| 8 | +use git_internal::internal::metadata::{EntryMeta, MetaAttached}; |
| 9 | +use git_internal::internal::object::blob::Blob; |
| 10 | +use git_internal::internal::pack::encode::encode_and_output_to_files; |
| 11 | +use git_internal::internal::pack::entry::Entry; |
| 12 | +use std::fs; |
| 13 | +use std::path::PathBuf; |
| 14 | +use tokio::sync::mpsc; |
| 15 | + |
| 16 | +#[tokio::main] |
| 17 | +async fn main() { |
| 18 | + // 1. prepare data to encode |
| 19 | + let contents = vec!["Hello World", "Rust is awesome", "Git internals are fun"]; |
| 20 | + |
| 21 | + let object_number = contents.len(); |
| 22 | + let window_size = 10; // Delta compression window size, 0 means no Delta compression |
| 23 | + let output_dir = PathBuf::from("examples/output_packs"); |
| 24 | + |
| 25 | + if !output_dir.exists() { |
| 26 | + fs::create_dir(&output_dir).expect("Failed to create output directory"); |
| 27 | + } |
| 28 | + |
| 29 | + println!("Preparing to encode {} objects...", object_number); |
| 30 | + |
| 31 | + // 2. Create a channel to send Entry |
| 32 | + // Buffer size can be adjusted based on memory conditions |
| 33 | + let (entry_tx, entry_rx) = mpsc::channel(100); |
| 34 | + |
| 35 | + // 3. Start encoding task |
| 36 | + // encode_and_output_to_files will process received Entry in the background and write to files |
| 37 | + let encode_handle = tokio::spawn(async move { |
| 38 | + encode_and_output_to_files(entry_rx, object_number, output_dir, window_size).await |
| 39 | + }); |
| 40 | + |
| 41 | + // 4. Send data |
| 42 | + for content in contents { |
| 43 | + // Convert string to Blob, then to Entry |
| 44 | + let blob = Blob::from_content(content); |
| 45 | + let entry: Entry = blob.into(); |
| 46 | + |
| 47 | + // Wrap metadata |
| 48 | + let meta_entry = MetaAttached { |
| 49 | + inner: entry, |
| 50 | + meta: EntryMeta::new(), |
| 51 | + }; |
| 52 | + |
| 53 | + entry_tx |
| 54 | + .send(meta_entry) |
| 55 | + .await |
| 56 | + .expect("Failed to send entry"); |
| 57 | + } |
| 58 | + |
| 59 | + // 5. Close the sender to notify the encoder that data sending is complete |
| 60 | + drop(entry_tx); |
| 61 | + |
| 62 | + // 6. wait for encoding to complete |
| 63 | + match encode_handle.await.unwrap() { |
| 64 | + Ok(_) => println!("Pack encoding successful! Check 'output_packs' directory."), |
| 65 | + Err(e) => eprintln!("Pack encoding failed: {}", e), |
| 66 | + } |
| 67 | +} |
0 commit comments