git_internal/internal/pack/encode/
output.rs1use 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
23pub 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 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
51pub 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 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 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 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 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}