Skip to main content

git_internal/internal/pack/encode/
output.rs

1//! Top-level convenience: encode entries directly to a `.pack` / `.idx` file pair.
2//!
3//! The pack is first written to a temporary file because its final name contains the checksum,
4//! which is not known until encoding completes. A background task drains the encoder's pack
5//! channel while the caller-facing task performs encoding. After the pack is finalized and
6//! renamed, a second writer drains the generated index bytes.
7
8use std::{future::Future, path::PathBuf};
9
10use chrono::Utc;
11use tokio::{fs::File, io::AsyncWriteExt as TokioAsyncWriteExt, sync::mpsc};
12
13use super::PackEncoder;
14use crate::{
15    errors::GitError,
16    hash::{HashKind, get_hash_kind},
17    internal::{
18        metadata::{EntryMeta, MetaAttached},
19        pack::entry::Entry,
20    },
21};
22
23/// Consume entries and write a matching `.pack`/`.idx` pair into `output_dir`.
24///
25/// The pack is first written to a temporary file because its final name contains the checksum,
26/// which is not known until encoding completes. A background task drains the encoder's pack
27/// channel while the caller-facing task performs encoding. After the pack is finalized and
28/// renamed, a second writer drains the generated index bytes.
29///
30/// `object_number` must equal the number of entries eventually received. A `window_size` of zero
31/// disables delta compression; any non-zero value selects the delta-search path. The default build
32/// uses Rabin fingerprinting; builds without `diff_rabin` use Myers or Patience.
33pub fn encode_and_output_to_files(
34    raw_entries_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
35    object_number: usize,
36    output_dir: PathBuf,
37    window_size: usize,
38) -> impl Future<Output = Result<(), GitError>> + Send {
39    // Capture the thread-local kind on the *calling* thread, before the future is first
40    // polled on some Tokio worker whose thread-local may belong to another repository.
41    let hash_kind = get_hash_kind();
42    encode_and_output_to_files_with_hash_kind(
43        hash_kind,
44        raw_entries_rx,
45        object_number,
46        output_dir,
47        window_size,
48    )
49}
50
51/// Like [`encode_and_output_to_files`], but for an explicit repository `hash_kind` (pack
52/// checksum, `pack-<checksum>` file names, ref-delta base IDs and idx object names all follow
53/// it). [`encode_and_output_to_files`] is the thread-local compatibility wrapper.
54pub async fn encode_and_output_to_files_with_hash_kind(
55    hash_kind: HashKind,
56    raw_entries_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
57    object_number: usize,
58    output_dir: PathBuf,
59    window_size: usize,
60) -> Result<(), GitError> {
61    let (pack_tx, mut pack_rx) = mpsc::channel(1024);
62    let (idx_tx, mut idx_rx) = mpsc::channel(1024);
63    let mut pack_encoder = PackEncoder::new_with_idx_and_hash_kind(
64        hash_kind,
65        object_number,
66        window_size,
67        pack_tx,
68        idx_tx,
69    );
70
71    // The checksum-based final filename is unknown until the complete pack has been hashed.
72    let now = Utc::now();
73    let timestamp = now.format("%Y%m%d%H%M%S%.3f").to_string();
74    let tmp_path = output_dir.join(format!("{}objects.pack.tmp", timestamp));
75    let mut pack_file = File::create(&tmp_path).await?;
76
77    // Drain pack chunks concurrently so a full channel does not stall the encoder behind file I/O.
78    let pack_writer = tokio::spawn(async move {
79        while let Some(chunk) = pack_rx.recv().await {
80            TokioAsyncWriteExt::write_all(&mut pack_file, &chunk).await?;
81        }
82        TokioAsyncWriteExt::flush(&mut pack_file).await?;
83        Ok::<(), GitError>(())
84    });
85
86    pack_encoder.encode(raw_entries_rx).await?;
87
88    // Closing PackEncoder's sender ends the writer loop; wait before renaming the file.
89    let pack_write_result = pack_writer
90        .await
91        .map_err(|e| GitError::PackEncodeError(format!("pack writer task join error: {e}")))?;
92    pack_write_result?;
93
94    let final_pack_name =
95        output_dir.join(format!("pack-{}.pack", pack_encoder.final_hash.unwrap()));
96    let final_idx_name = output_dir.join(format!("pack-{}.idx", pack_encoder.final_hash.unwrap()));
97    tokio::fs::rename(tmp_path, &final_pack_name).await?;
98
99    let mut idx_file = File::create(&final_idx_name).await?;
100    let idx_writer = tokio::spawn(async move {
101        while let Some(chunk) = idx_rx.recv().await {
102            TokioAsyncWriteExt::write_all(&mut idx_file, &chunk).await?;
103        }
104        TokioAsyncWriteExt::flush(&mut idx_file).await?;
105        Ok::<(), GitError>(())
106    });
107
108    // Index generation is deferred until pack offsets and the final pack checksum are known.
109    pack_encoder.encode_idx_file().await?;
110
111    let idx_write_result = idx_writer
112        .await
113        .map_err(|e| GitError::PackEncodeError(format!("idx writer task join error: {e}")))?;
114    idx_write_result?;
115
116    Ok(())
117}