1use crate::error::ObjectError;
4use std::borrow::Cow;
5use std::collections::HashMap;
6use std::io::Write;
7use std::sync::Arc;
8
9use super::structured::{StructuredFileDiff, StructuredLine, StructuredLineKind};
10use crate::attributes::load_gitattributes_for_check_attr_source;
11use crate::commit_pretty::{abbrev_hex, resolve_core_abbrev_len};
12use crate::config::ConfigSet;
13use crate::diff::options::DiffOptions;
14use crate::error::Result;
15use crate::index::Index;
16use crate::merge_file;
17use crate::objects::CommitData;
18use crate::objects::FileMode;
19use crate::objects::{parse_commit, ObjectId, ObjectKind};
20use crate::odb::Odb;
21use crate::oid_abbrev_cache::OidAbbrevCache;
22use crate::pack_store::PackReadContextGuard;
23use crate::parallel::{run_ordered_batches, ParallelOp};
24use crate::quote_path::format_diff_path_with_prefix;
25use crate::repo::Repository;
26use crate::repo::RepositoryError;
27use crate::userdiff::{matcher_for_path_parsed, FuncnameMatcher};
28use crate::worktree_rules::WorktreeRules;
29
30use super::merge_commit::commit_first_parent_diff_entries;
31use super::merge_commit::DiffMerges;
32use super::tree_content::load_odb_blob_side_for_diff;
33use super::{empty_blob_oid, load_worktree_side_for_diff, zero_oid, DiffEntry, DiffStatus};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum LogPatchCommitHeader {
38 #[default]
40 Full,
41 FormatPercentH,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum LogPatchBinaryFormat {
48 #[default]
50 LogShortMessage,
51 GitApplyBinaryPatch,
53}
54
55#[derive(Debug, Clone)]
57pub struct LogPatchOptions {
58 pub diff: DiffOptions,
60 pub abbrev_len: usize,
62 pub commit_header: LogPatchCommitHeader,
64 pub binary_format: LogPatchBinaryFormat,
66 pub pathspec: crate::pathspec::Pathspec,
68 pub diff_merges: DiffMerges,
70}
71
72impl LogPatchOptions {
73 #[must_use]
75 pub fn git_default(config: &ConfigSet) -> Self {
76 Self {
77 diff: DiffOptions::from_config(config),
78 abbrev_len: 7,
79 commit_header: LogPatchCommitHeader::Full,
80 binary_format: LogPatchBinaryFormat::default(),
81 pathspec: crate::pathspec::Pathspec::entire_tree(
82 crate::pathspec::PathspecGlobalFlags::default(),
83 ),
84 diff_merges: DiffMerges::Combined,
85 }
86 }
87}
88
89#[derive(Debug, Clone)]
91pub struct PatchTextOptions {
92 pub diff: DiffOptions,
94 pub abbrev_len: usize,
96}
97
98impl PatchTextOptions {
99 pub fn from_repo(repo: &Repository, diff: DiffOptions) -> Result<Self> {
105 let config = repo.config().snapshot()?.clone();
106 Ok(Self {
107 diff,
108 abbrev_len: resolve_core_abbrev_len(&config, repo.odb())?,
109 })
110 }
111}
112
113pub fn write_patch<W: Write>(
121 repo: &Repository,
122 entries: &[DiffEntry],
123 opts: &PatchTextOptions,
124 out: &mut W,
125) -> Result<()> {
126 if entries.is_empty() {
127 return Ok(());
128 }
129 let odb = repo.odb();
130 super::tree_content::prefetch_tree_diff_blobs(odb, entries)?;
131 let config = repo.config().snapshot()?.clone();
132 let thread_policy = repo.thread_policy();
133 let log_opts = LogPatchOptions {
134 diff: opts.diff.clone(),
135 abbrev_len: opts.abbrev_len,
136 commit_header: LogPatchCommitHeader::FormatPercentH,
137 binary_format: LogPatchBinaryFormat::GitApplyBinaryPatch,
138 pathspec: crate::pathspec::Pathspec::entire_tree(
139 crate::pathspec::PathspecGlobalFlags::default(),
140 ),
141 diff_merges: DiffMerges::FirstParent,
142 };
143 let abbrev_len = opts.abbrev_len;
144 let mut abbrev_cache = OidAbbrevCache::new(abbrev_len);
145 let oids = entries.iter().flat_map(|e| [e.old_oid, e.new_oid]);
146 abbrev_cache.warm_for_patch_batch(repo, oids, &thread_policy, &config)?;
147 let mut par_opts = thread_policy.resolve(ParallelOp::DiffContent, &config);
148 par_opts.min_items = 0;
149 par_opts.min_total_bytes = None;
150 let n_workers = par_opts.threads.get();
151 if n_workers <= 1 || entries.len() < 2 {
152 for entry in entries {
153 write_diff_entry_patch(
154 out,
155 repo,
156 odb,
157 entry,
158 &log_opts,
159 &mut abbrev_cache,
160 None,
161 LogPatchBinaryFormat::GitApplyBinaryPatch,
162 &config,
163 )?;
164 }
165 return Ok(());
166 }
167 let store = odb.pack_store_for(odb.objects_dir());
168 let warmed_cache = abbrev_cache;
169 struct PatchWriteWorker {
170 _read: PackReadContextGuard,
171 abbrev: OidAbbrevCache,
172 }
173 run_ordered_batches(
174 entries,
175 1,
176 n_workers,
177 || PatchWriteWorker {
178 _read: PackReadContextGuard::install(Arc::clone(&store)),
179 abbrev: warmed_cache.clone(),
180 },
181 |worker, entry| {
182 let mut buf = Vec::new();
183 write_diff_entry_patch(
184 &mut buf,
185 repo,
186 odb,
187 entry,
188 &log_opts,
189 &mut worker.abbrev,
190 None,
191 LogPatchBinaryFormat::GitApplyBinaryPatch,
192 &config,
193 )?;
194 Ok(buf)
195 },
196 |_batch, chunks: Vec<Vec<u8>>| {
197 for chunk in chunks {
198 out.write_all(&chunk)?;
199 }
200 Ok(())
201 },
202 )
203}
204
205pub fn write_patch_structured<W: Write>(
214 repo: &Repository,
215 items: &[super::tree_content::TreeDiffStructured],
216 opts: &PatchTextOptions,
217 out: &mut W,
218) -> Result<()> {
219 if items.is_empty() {
220 return Ok(());
221 }
222 let odb = repo.odb();
223 let config = repo.config().snapshot()?.clone();
224 let thread_policy = repo.thread_policy();
225 let log_opts = LogPatchOptions {
226 diff: opts.diff.clone(),
227 abbrev_len: opts.abbrev_len,
228 commit_header: LogPatchCommitHeader::FormatPercentH,
229 binary_format: LogPatchBinaryFormat::GitApplyBinaryPatch,
230 pathspec: crate::pathspec::Pathspec::entire_tree(
231 crate::pathspec::PathspecGlobalFlags::default(),
232 ),
233 diff_merges: DiffMerges::FirstParent,
234 };
235 let mut abbrev_cache = OidAbbrevCache::new(opts.abbrev_len);
236 let oids = items
237 .iter()
238 .flat_map(|item| [item.entry.old_oid, item.entry.new_oid]);
239 abbrev_cache.warm_for_patch_batch(repo, oids, &thread_policy, &config)?;
240 for item in items {
241 write_diff_entry_patch_from_structured(
242 out,
243 repo,
244 odb,
245 &item.entry,
246 &log_opts,
247 &mut abbrev_cache,
248 item.binary,
249 &item.structured,
250 )?;
251 }
252 Ok(())
253}
254
255fn write_structured_line<W: Write>(out: &mut W, prefix: char, line: &StructuredLine) -> Result<()> {
256 write!(out, "{prefix}")?;
257 for segment in &line.segments {
258 write!(out, "{}", segment.text)?;
259 }
260 Ok(())
261}
262
263fn format_git_diff_hunk_side(start_1based: usize, line_count: usize) -> String {
264 if line_count == 1 {
265 format!("{start_1based}")
266 } else {
267 format!("{start_1based},{line_count}")
268 }
269}
270
271fn write_structured_unified_body<W: Write>(
272 out: &mut W,
273 git_old: &str,
274 git_new: &str,
275 old_mode: u32,
276 new_mode: u32,
277 structured: &StructuredFileDiff,
278) -> Result<()> {
279 const QUOTE_FULLY: bool = true;
280 let old_path = if old_mode == 0 {
281 "/dev/null".to_owned()
282 } else {
283 format_diff_path_with_prefix("a/", git_old, QUOTE_FULLY)
284 };
285 let new_path = if new_mode == 0 {
286 "/dev/null".to_owned()
287 } else {
288 format_diff_path_with_prefix("b/", git_new, QUOTE_FULLY)
289 };
290 writeln!(out, "--- {old_path}")?;
291 writeln!(out, "+++ {new_path}")?;
292 for hunk in &structured.hunks {
293 writeln!(
294 out,
295 "@@ -{} +{} @@",
296 format_git_diff_hunk_side(hunk.old_start, hunk.old_lines),
297 format_git_diff_hunk_side(hunk.new_start, hunk.new_lines),
298 )?;
299 for line in &hunk.lines {
300 let prefix = match line.kind {
301 StructuredLineKind::Context => ' ',
302 StructuredLineKind::Add => '+',
303 StructuredLineKind::Del => '-',
304 };
305 if line.no_newline_at_eof {
306 write_structured_line(out, prefix, line)?;
307 writeln!(out)?;
308 writeln!(out, "\\ No newline at end of file")?;
309 } else {
310 write_structured_line(out, prefix, line)?;
311 writeln!(out)?;
312 }
313 }
314 }
315 Ok(())
316}
317
318#[allow(clippy::too_many_arguments)]
319fn write_diff_entry_patch_from_structured<W: Write>(
320 out: &mut W,
321 repo: &Repository,
322 odb: &Odb,
323 entry: &DiffEntry,
324 opts: &LogPatchOptions,
325 abbrev_cache: &mut OidAbbrevCache,
326 is_binary: bool,
327 structured: &StructuredFileDiff,
328) -> Result<()> {
329 write_diff_entry_patch_headers(out, repo, entry, opts, abbrev_cache, is_binary)?;
330 let old_mode = entry.old_mode.bits();
331 let new_mode = entry.new_mode.bits();
332 let git_old = entry
333 .old_path
334 .as_deref()
335 .or(entry.new_path.as_deref())
336 .unwrap_or("dev/null");
337 let git_new = entry
338 .new_path
339 .as_deref()
340 .or(entry.old_path.as_deref())
341 .unwrap_or("dev/null");
342 if entry.old_oid == entry.new_oid {
343 return Ok(());
344 }
345 let use_structured = !is_binary
346 && !structured.hunks.is_empty()
347 && !structured.old_encoding_lossy
348 && !structured.new_encoding_lossy;
349 if use_structured {
350 write_structured_unified_body(out, git_old, git_new, old_mode, new_mode, structured)?;
351 return Ok(());
352 }
353 let path = entry.new_path.as_deref().or(entry.old_path.as_deref());
354 let force_read = is_binary;
355 let old_bytes = read_blob_side(odb, entry.old_oid, old_mode == 0, path, force_read)?;
356 let new_bytes = read_blob_side(odb, entry.new_oid, new_mode == 0, path, force_read)?;
357 if old_bytes == new_bytes {
358 return Ok(());
359 }
360 if is_binary {
361 crate::apply::write_git_binary_patch_sections(out, &old_bytes, &new_bytes)?;
362 return Ok(());
363 }
364 write_patch_unified_body_from_bytes(
365 out, &old_bytes, &new_bytes, git_old, git_new, old_mode, new_mode, opts,
366 )
367}
368
369#[allow(clippy::too_many_arguments)]
371fn write_patch_unified_body_from_bytes<W: Write>(
372 out: &mut W,
373 old_bytes: &[u8],
374 new_bytes: &[u8],
375 git_old: &str,
376 git_new: &str,
377 old_mode: u32,
378 new_mode: u32,
379 opts: &LogPatchOptions,
380) -> Result<()> {
381 const QUOTE_FULLY: bool = true;
382 let byte_oriented = !crate::commit_encoding::is_strict_utf8(old_bytes)
383 || !crate::commit_encoding::is_strict_utf8(new_bytes);
384 let (old_text, new_text) = if byte_oriented {
385 (
386 crate::commit_encoding::decode_latin1(old_bytes),
387 crate::commit_encoding::decode_latin1(new_bytes),
388 )
389 } else {
390 let old_s = std::str::from_utf8(old_bytes).map_err(|_| {
391 crate::error::Error::Object(ObjectError::Corrupt {
392 detail: "blob is not valid UTF-8".into(),
393 })
394 })?;
395 let new_s = std::str::from_utf8(new_bytes).map_err(|_| {
396 crate::error::Error::Object(ObjectError::Corrupt {
397 detail: "blob is not valid UTF-8".into(),
398 })
399 })?;
400 (old_s.to_owned(), new_s.to_owned())
401 };
402 let old_path = if old_mode == 0 {
403 "/dev/null".to_owned()
404 } else {
405 git_old.to_owned()
406 };
407 let new_path = if new_mode == 0 {
408 "/dev/null".to_owned()
409 } else {
410 git_new.to_owned()
411 };
412 let d = &opts.diff;
413 if byte_oriented {
414 let mut patch_buf = Vec::new();
415 super::write_unified_diff_from_diff_options(
416 &mut patch_buf,
417 &old_text,
418 &new_text,
419 &old_path,
420 &new_path,
421 "a/",
422 "b/",
423 None,
424 d,
425 QUOTE_FULLY,
426 )?;
427 let patch_str = std::str::from_utf8(&patch_buf).map_err(|_| {
428 crate::error::Error::Object(ObjectError::Corrupt {
429 detail: "patch re-encoding failed".into(),
430 })
431 })?;
432 out.write_all(&crate::commit_encoding::encode_latin1_lossy(patch_str))?;
433 } else {
434 super::write_unified_diff_from_diff_options(
435 out,
436 &old_text,
437 &new_text,
438 &old_path,
439 &new_path,
440 "a/",
441 "b/",
442 None,
443 d,
444 QUOTE_FULLY,
445 )?;
446 }
447 Ok(())
448}
449
450fn effective_log_patch_options(
451 repo: &Repository,
452 opts: &LogPatchOptions,
453) -> Result<LogPatchOptions> {
454 let config = repo.config().snapshot()?.clone();
455 let mut out = opts.clone();
456 out.abbrev_len = resolve_core_abbrev_len(&config, repo.odb())?;
457 Ok(out)
458}
459
460fn log_patch_funcname_matcher(
461 repo: &Repository,
462 config: &ConfigSet,
463 tree_oid: &ObjectId,
464 rel_path: &str,
465) -> Result<Option<FuncnameMatcher>> {
466 let parsed = load_gitattributes_for_check_attr_source(repo, tree_oid)?;
467 Ok(matcher_for_path_parsed(
468 config,
469 &parsed.rules,
470 &parsed.macros,
471 rel_path,
472 false,
473 )?)
474}
475
476pub fn write_commit_log_patch<W: Write>(
482 repo: &Repository,
483 out: &mut W,
484 oid: &ObjectId,
485 opts: &LogPatchOptions,
486) -> Result<()> {
487 let odb = repo.odb();
488 let raw = odb.read(oid)?;
489 let commit = parse_commit(&raw.data)?;
490 let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
491 let parent_tree = parent_tree_for_commit(repo, &parent_ctx, oid, &commit, None)?;
492 let opts = effective_log_patch_options(repo, opts)?;
493 let mut abbrev_cache = OidAbbrevCache::new(opts.abbrev_len);
494 write_parsed_commit_log_patch(
495 out,
496 repo,
497 odb,
498 oid,
499 &commit,
500 parent_tree,
501 &parent_ctx,
502 &opts,
503 &mut abbrev_cache,
504 )
505}
506
507pub fn write_commits_log_patch<W: Write>(
517 repo: &Repository,
518 out: &mut W,
519 oids: &[ObjectId],
520 opts: &LogPatchOptions,
521) -> Result<()> {
522 if oids.is_empty() {
523 return Ok(());
524 }
525 let odb = repo.odb();
526 let mut trees_by_commit: HashMap<ObjectId, ObjectId> = HashMap::with_capacity(oids.len());
527 let mut parsed: Vec<(ObjectId, CommitData)> = Vec::with_capacity(oids.len());
528 for oid in oids {
529 let raw = odb.read(oid)?;
530 let commit = parse_commit(&raw.data)?;
531 trees_by_commit.insert(*oid, commit.tree);
532 parsed.push((*oid, commit));
533 }
534 let opts = effective_log_patch_options(repo, opts)?;
535 let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
536 let mut abbrev_cache = OidAbbrevCache::new(opts.abbrev_len);
537 for (i, (oid, commit)) in parsed.iter().enumerate() {
538 if i > 0 && opts.commit_header == LogPatchCommitHeader::Full {
539 writeln!(out)?;
540 }
541 let parent_tree =
542 parent_tree_for_commit(repo, &parent_ctx, oid, commit, Some(&trees_by_commit))?;
543 write_parsed_commit_log_patch(
544 out,
545 repo,
546 odb,
547 oid,
548 commit,
549 parent_tree,
550 &parent_ctx,
551 &opts,
552 &mut abbrev_cache,
553 )?;
554 }
555 Ok(())
556}
557
558fn parent_tree_for_commit(
559 repo: &Repository,
560 parent_ctx: &crate::shallow::EffectiveCommitParents,
561 commit_oid: &ObjectId,
562 commit: &CommitData,
563 trees_by_commit: Option<&HashMap<ObjectId, ObjectId>>,
564) -> Result<Option<ObjectId>> {
565 let effective_parents = parent_ctx.for_commit(*commit_oid, &commit.parents);
566 if effective_parents.is_empty() {
567 return Ok(None);
568 }
569 let parent = effective_parents[0];
570 let odb = repo.odb();
571 if let Some(map) = trees_by_commit {
572 if let Some(tree) = map.get(&parent) {
573 return Ok(Some(*tree));
574 }
575 }
576 let parent_raw = odb.read(&parent)?;
577 Ok(Some(parse_commit(&parent_raw.data)?.tree))
578}
579
580fn abbrev_for_index_line(
581 cache: &mut OidAbbrevCache,
582 repo: &Repository,
583 oid: &ObjectId,
584 min_len: usize,
585) -> Result<String> {
586 if *oid == zero_oid() {
587 return Ok(abbrev_hex(oid, min_len));
588 }
589 cache.abbrev(repo, oid)
590}
591
592fn abbrev_index_pair(
593 cache: &mut OidAbbrevCache,
594 repo: &Repository,
595 old_oid: &ObjectId,
596 new_oid: &ObjectId,
597 min_len: usize,
598) -> Result<(String, String)> {
599 let old = abbrev_for_index_line(cache, repo, old_oid, min_len)?;
600 let new = abbrev_for_index_line(cache, repo, new_oid, min_len)?;
601 let len = old.len().max(new.len());
602 let pad = |oid: &ObjectId, abbrev: String| {
603 if abbrev.len() >= len {
604 return abbrev;
605 }
606 let hex = oid.to_hex();
607 hex[..len.min(hex.len())].to_string()
608 };
609 Ok((pad(old_oid, old), pad(new_oid, new)))
610}
611
612#[allow(clippy::too_many_arguments)]
613fn write_parsed_commit_log_patch<W: Write>(
614 out: &mut W,
615 repo: &Repository,
616 odb: &Odb,
617 oid: &ObjectId,
618 commit: &CommitData,
619 _parent_tree: Option<ObjectId>,
620 parent_ctx: &crate::shallow::EffectiveCommitParents,
621 opts: &LogPatchOptions,
622 abbrev_cache: &mut OidAbbrevCache,
623) -> Result<()> {
624 let effective_parents = parent_ctx.for_commit(*oid, &commit.parents);
625 let is_merge = effective_parents.len() > 1;
626 let omit_merge_patch = is_merge && opts.diff_merges == DiffMerges::Combined;
627 match opts.commit_header {
628 LogPatchCommitHeader::Full => {
629 writeln!(out, "commit {oid}")?;
630 if is_merge {
631 let mut parts = Vec::with_capacity(effective_parents.len());
632 for parent in &effective_parents {
633 parts.push(abbrev_for_index_line(
634 abbrev_cache,
635 repo,
636 parent,
637 opts.abbrev_len,
638 )?);
639 }
640 writeln!(out, "Merge: {}", parts.join(" "))?;
641 }
642 write_commit_header_and_message(out, &commit.author, &commit.message)?;
643 if omit_merge_patch {
644 return Ok(());
645 }
646 writeln!(out)?;
647 }
648 LogPatchCommitHeader::FormatPercentH => {
649 writeln!(out, "{oid}")?;
650 if omit_merge_patch {
651 return Ok(());
652 }
653 writeln!(out)?;
654 }
655 }
656 let config = repo.config().snapshot()?.clone();
657 let thread_policy = repo.thread_policy();
658 let entries = commit_first_parent_diff_entries(
659 repo,
660 oid,
661 commit,
662 opts.pathspec.specs(),
663 &config,
664 &thread_policy,
665 )?;
666 for entry in entries {
667 write_diff_entry_patch(
668 out,
669 repo,
670 odb,
671 &entry,
672 opts,
673 abbrev_cache,
674 Some(&commit.tree),
675 opts.binary_format,
676 &config,
677 )?;
678 }
679 Ok(())
680}
681
682pub fn write_commit_header_and_message<W: Write>(
684 out: &mut W,
685 author_ident: &str,
686 message: &str,
687) -> Result<()> {
688 writeln!(out, "Author: {}", format_ident_display(author_ident))?;
689 writeln!(out, "Date: {}", format_log_date(author_ident))?;
690 writeln!(out)?;
691 for line in message.lines() {
692 writeln!(out, " {line}")?;
693 }
694 Ok(())
695}
696
697fn format_ident_display(ident: &str) -> String {
698 let name = ident.find('<').map_or(ident.trim(), |i| ident[..i].trim());
699 let email = ident
700 .find('<')
701 .and_then(|start| ident.find('>').map(|end| &ident[start..=end]))
702 .unwrap_or("");
703 format!("{name} {email}")
704}
705
706fn format_log_date(ident: &str) -> String {
707 let parts: Vec<&str> = ident.rsplitn(3, ' ').collect();
708 if parts.len() < 2 {
709 return String::new();
710 }
711 let ts_str = parts[1];
712 let offset_str = parts[0];
713 let Ok(ts) = ts_str.parse::<i64>() else {
714 return format!("{ts_str} {offset_str}");
715 };
716 let tz_bytes = offset_str.as_bytes();
717 let tz_secs: i64 = if tz_bytes.len() >= 5 {
718 let sign = if tz_bytes[0] == b'-' { -1 } else { 1 };
719 let h: i64 = offset_str[1..3].parse().unwrap_or(0);
720 let m: i64 = offset_str[3..5].parse().unwrap_or(0);
721 sign * (h * 3600 + m * 60)
722 } else {
723 0
724 };
725 let adjusted = ts + tz_secs;
726 let dt = time::OffsetDateTime::from_unix_timestamp(adjusted)
727 .unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
728 let weekday = match dt.weekday() {
729 time::Weekday::Monday => "Mon",
730 time::Weekday::Tuesday => "Tue",
731 time::Weekday::Wednesday => "Wed",
732 time::Weekday::Thursday => "Thu",
733 time::Weekday::Friday => "Fri",
734 time::Weekday::Saturday => "Sat",
735 time::Weekday::Sunday => "Sun",
736 };
737 let month = match dt.month() {
738 time::Month::January => "Jan",
739 time::Month::February => "Feb",
740 time::Month::March => "Mar",
741 time::Month::April => "Apr",
742 time::Month::May => "May",
743 time::Month::June => "Jun",
744 time::Month::July => "Jul",
745 time::Month::August => "Aug",
746 time::Month::September => "Sep",
747 time::Month::October => "Oct",
748 time::Month::November => "Nov",
749 time::Month::December => "Dec",
750 };
751 format!(
752 "{weekday} {month} {} {:02}:{:02}:{:02} {} {offset_str}",
753 dt.day(),
754 dt.hour(),
755 dt.minute(),
756 dt.second(),
757 dt.year()
758 )
759}
760
761pub fn write_diff_entry_log_patch<W: Write>(
767 out: &mut W,
768 repo: &Repository,
769 odb: &Odb,
770 entry: &DiffEntry,
771 opts: &LogPatchOptions,
772) -> Result<()> {
773 let config = repo.config().snapshot()?.clone();
774 let mut abbrev_cache = OidAbbrevCache::new(opts.abbrev_len);
775 write_diff_entry_patch(
776 out,
777 repo,
778 odb,
779 entry,
780 opts,
781 &mut abbrev_cache,
782 None,
783 opts.binary_format,
784 &config,
785 )
786}
787
788fn index_oid_full(oid: &ObjectId) -> String {
789 oid.to_hex()
790}
791
792#[allow(clippy::too_many_arguments)]
793fn write_diff_entry_patch_headers<W: Write>(
794 out: &mut W,
795 repo: &Repository,
796 entry: &DiffEntry,
797 opts: &LogPatchOptions,
798 abbrev_cache: &mut OidAbbrevCache,
799 index_full_oid: bool,
800) -> Result<()> {
801 let git_old = entry
802 .old_path
803 .as_deref()
804 .or(entry.new_path.as_deref())
805 .unwrap_or("dev/null");
806 let git_new = entry
807 .new_path
808 .as_deref()
809 .or(entry.old_path.as_deref())
810 .unwrap_or("dev/null");
811 const QUOTE_FULLY: bool = true;
812 writeln!(
813 out,
814 "diff --git {} {}",
815 format_diff_path_with_prefix("a/", git_old, QUOTE_FULLY),
816 format_diff_path_with_prefix("b/", git_new, QUOTE_FULLY)
817 )?;
818
819 let old_mode = entry.old_mode.bits();
820 let new_mode = entry.new_mode.bits();
821
822 if old_mode == 0 {
823 writeln!(out, "new file mode {}", entry.new_mode)?;
824 } else if new_mode == 0 {
825 writeln!(out, "deleted file mode {}", entry.old_mode)?;
826 }
827
828 match entry.status {
829 DiffStatus::Renamed => {
830 writeln!(out, "similarity index {}%", entry.score.unwrap_or(100))?;
831 if let Some(path) = &entry.old_path {
832 writeln!(out, "rename from {path}")?;
833 }
834 if let Some(path) = &entry.new_path {
835 writeln!(out, "rename to {path}")?;
836 }
837 }
838 DiffStatus::Copied => {
839 writeln!(out, "similarity index {}%", entry.score.unwrap_or(100))?;
840 if let Some(path) = &entry.old_path {
841 writeln!(out, "copy from {path}")?;
842 }
843 if let Some(path) = &entry.new_path {
844 writeln!(out, "copy to {path}")?;
845 }
846 }
847 _ if old_mode != 0 && new_mode != 0 && old_mode != new_mode => {
848 writeln!(out, "old mode {}", entry.old_mode)?;
849 writeln!(out, "new mode {}", entry.new_mode)?;
850 }
851 _ => {}
852 }
853
854 if entry.old_oid != entry.new_oid {
855 let index_mode = if new_mode != 0 {
856 entry.new_mode
857 } else {
858 entry.old_mode
859 };
860 let mut index_pair = |old: &ObjectId, new: &ObjectId| -> Result<(String, String)> {
861 if index_full_oid {
862 Ok((index_oid_full(old), index_oid_full(new)))
863 } else {
864 abbrev_index_pair(abbrev_cache, repo, old, new, opts.abbrev_len)
865 }
866 };
867 match entry.status {
868 DiffStatus::Added => {
869 let (old_a, new_a) = index_pair(&zero_oid(), &entry.new_oid)?;
870 writeln!(out, "index {old_a}..{new_a}")?;
871 }
872 DiffStatus::Deleted => {
873 let (old_a, new_a) = index_pair(&entry.old_oid, &zero_oid())?;
874 writeln!(out, "index {old_a}..{new_a}")?;
875 }
876 DiffStatus::Renamed | DiffStatus::Copied => {
877 let (old_a, new_a) = index_pair(&entry.old_oid, &entry.new_oid)?;
878 writeln!(out, "index {old_a}..{new_a}")?;
879 }
880 _ => {
881 let (old_a, new_a) = index_pair(&entry.old_oid, &entry.new_oid)?;
882 writeln!(out, "index {old_a}..{new_a} {index_mode}")?;
883 }
884 }
885 }
886 Ok(())
887}
888
889#[allow(clippy::too_many_arguments)]
890fn write_diff_entry_patch<W: Write>(
891 out: &mut W,
892 repo: &Repository,
893 odb: &Odb,
894 entry: &DiffEntry,
895 opts: &LogPatchOptions,
896 abbrev_cache: &mut OidAbbrevCache,
897 new_tree: Option<&ObjectId>,
898 binary_format: LogPatchBinaryFormat,
899 config: &ConfigSet,
900) -> Result<()> {
901 let old_mode = entry.old_mode.bits();
902 let new_mode = entry.new_mode.bits();
903 let path = entry.new_path.as_deref().or(entry.old_path.as_deref());
904 let force_read = binary_format == LogPatchBinaryFormat::GitApplyBinaryPatch;
905 let (old_bytes, old_bin) =
906 load_patch_blob_side(odb, entry.old_oid, old_mode == 0, path, force_read)?;
907 let (new_bytes, new_bin) =
908 load_patch_blob_side(odb, entry.new_oid, new_mode == 0, path, force_read)?;
909 write_diff_entry_patch_with_resolved_bytes(
910 out,
911 repo,
912 entry,
913 opts,
914 abbrev_cache,
915 binary_format,
916 config,
917 old_bin || new_bin,
918 &old_bytes,
919 &new_bytes,
920 new_tree,
921 )
922}
923
924#[allow(clippy::too_many_arguments)]
925fn write_diff_entry_patch_with_resolved_bytes<W: Write>(
926 out: &mut W,
927 repo: &Repository,
928 entry: &DiffEntry,
929 opts: &LogPatchOptions,
930 abbrev_cache: &mut OidAbbrevCache,
931 binary_format: LogPatchBinaryFormat,
932 config: &ConfigSet,
933 side_known_binary: bool,
934 old_bytes: &[u8],
935 new_bytes: &[u8],
936 new_tree: Option<&ObjectId>,
937) -> Result<()> {
938 const QUOTE_FULLY: bool = true;
939 let git_old = entry
940 .old_path
941 .as_deref()
942 .or(entry.new_path.as_deref())
943 .unwrap_or("dev/null");
944 let git_new = entry
945 .new_path
946 .as_deref()
947 .or(entry.old_path.as_deref())
948 .unwrap_or("dev/null");
949 let old_mode = entry.old_mode.bits();
950 let new_mode = entry.new_mode.bits();
951 let is_binary =
952 side_known_binary || merge_file::is_binary(old_bytes) || merge_file::is_binary(new_bytes);
953 let index_full_oid = is_binary && binary_format == LogPatchBinaryFormat::GitApplyBinaryPatch;
954 write_diff_entry_patch_headers(out, repo, entry, opts, abbrev_cache, index_full_oid)?;
955
956 if old_bytes == new_bytes && entry.old_oid == entry.new_oid {
957 return Ok(());
958 }
959
960 if is_binary {
961 match binary_format {
962 LogPatchBinaryFormat::LogShortMessage => {
963 let old_side = if old_mode == 0 {
964 "/dev/null".to_owned()
965 } else {
966 format_diff_path_with_prefix("a/", git_old, QUOTE_FULLY)
967 };
968 let new_side = if new_mode == 0 {
969 "/dev/null".to_owned()
970 } else {
971 format_diff_path_with_prefix("b/", git_new, QUOTE_FULLY)
972 };
973 writeln!(out, "Binary files {old_side} and {new_side} differ")?;
974 }
975 LogPatchBinaryFormat::GitApplyBinaryPatch => {
976 crate::apply::write_git_binary_patch_sections(out, old_bytes, new_bytes)?;
977 }
978 }
979 return Ok(());
980 }
981
982 if binary_format == LogPatchBinaryFormat::GitApplyBinaryPatch && new_tree.is_none() {
983 return write_patch_unified_body_from_bytes(
984 out, old_bytes, new_bytes, git_old, git_new, old_mode, new_mode, opts,
985 );
986 }
987 let byte_oriented = !crate::commit_encoding::is_strict_utf8(old_bytes)
988 || !crate::commit_encoding::is_strict_utf8(new_bytes);
989 let (old_text, new_text) = if byte_oriented {
990 (
991 crate::commit_encoding::decode_latin1(old_bytes),
992 crate::commit_encoding::decode_latin1(new_bytes),
993 )
994 } else {
995 let old_s = std::str::from_utf8(old_bytes).map_err(|_| {
996 crate::error::Error::Object(ObjectError::Corrupt {
997 detail: "blob is not valid UTF-8".into(),
998 })
999 })?;
1000 let new_s = std::str::from_utf8(new_bytes).map_err(|_| {
1001 crate::error::Error::Object(ObjectError::Corrupt {
1002 detail: "blob is not valid UTF-8".into(),
1003 })
1004 })?;
1005 (old_s.to_owned(), new_s.to_owned())
1006 };
1007 let old_path = if old_mode == 0 {
1008 "/dev/null".to_owned()
1009 } else {
1010 git_old.to_owned()
1011 };
1012 let new_path = if new_mode == 0 {
1013 "/dev/null".to_owned()
1014 } else {
1015 git_new.to_owned()
1016 };
1017 let d = &opts.diff;
1018 let funcname_matcher = if let Some(tree) = new_tree {
1019 log_patch_funcname_matcher(repo, config, tree, git_new)?
1020 } else {
1021 None
1022 };
1023 let funcname_ref = funcname_matcher.as_ref();
1024 if byte_oriented {
1025 let mut patch_buf = Vec::new();
1026 super::write_unified_diff_from_diff_options(
1027 &mut patch_buf,
1028 &old_text,
1029 &new_text,
1030 &old_path,
1031 &new_path,
1032 "a/",
1033 "b/",
1034 funcname_ref,
1035 d,
1036 QUOTE_FULLY,
1037 )?;
1038 let patch_str = std::str::from_utf8(&patch_buf).map_err(|_| {
1039 crate::error::Error::Object(ObjectError::Corrupt {
1040 detail: "patch re-encoding failed".into(),
1041 })
1042 })?;
1043 out.write_all(&crate::commit_encoding::encode_latin1_lossy(patch_str))?;
1044 } else {
1045 super::write_unified_diff_from_diff_options(
1046 out,
1047 &old_text,
1048 &new_text,
1049 &old_path,
1050 &new_path,
1051 "a/",
1052 "b/",
1053 funcname_ref,
1054 d,
1055 QUOTE_FULLY,
1056 )?;
1057 }
1058 Ok(())
1059}
1060
1061#[derive(Debug, Clone, PartialEq, Eq)]
1069pub enum PatchSide {
1070 Bytes(Vec<u8>),
1072 Blob,
1075 Worktree,
1078}
1079
1080#[derive(Debug, Clone)]
1082pub struct PatchResolvedSide {
1083 pub entry: DiffEntry,
1085 pub old: PatchSide,
1087 pub new: PatchSide,
1089}
1090
1091pub fn write_patch_resolved<W: Write>(
1114 repo: &Repository,
1115 files: &[PatchResolvedSide],
1116 opts: &PatchTextOptions,
1117 out: &mut W,
1118) -> Result<()> {
1119 if files.is_empty() {
1120 return Ok(());
1121 }
1122 let config = repo.config().snapshot()?.clone();
1123 let thread_policy = repo.thread_policy();
1124 let log_opts = LogPatchOptions {
1125 diff: opts.diff.clone(),
1126 abbrev_len: opts.abbrev_len,
1127 commit_header: LogPatchCommitHeader::FormatPercentH,
1128 binary_format: LogPatchBinaryFormat::GitApplyBinaryPatch,
1129 pathspec: crate::pathspec::Pathspec::entire_tree(
1130 crate::pathspec::PathspecGlobalFlags::default(),
1131 ),
1132 diff_merges: DiffMerges::FirstParent,
1133 };
1134 let mut abbrev_cache = OidAbbrevCache::new(opts.abbrev_len);
1135 let mut worktree = None;
1136 for file in files {
1137 let old = resolve_patch_side(repo, file, EntrySide::Old, &mut worktree)?;
1138 let new = resolve_patch_side(repo, file, EntrySide::New, &mut worktree)?;
1139 let entry = entry_with_content_ids(repo, file, &old, &new)?;
1140 abbrev_cache.warm_for_patch_batch(
1141 repo,
1142 [entry.old_oid, entry.new_oid],
1143 &thread_policy,
1144 &config,
1145 )?;
1146 write_diff_entry_patch_with_resolved_bytes(
1147 out,
1148 repo,
1149 &entry,
1150 &log_opts,
1151 &mut abbrev_cache,
1152 LogPatchBinaryFormat::GitApplyBinaryPatch,
1153 &config,
1154 false,
1155 &old,
1156 &new,
1157 None,
1158 )?;
1159 }
1160 Ok(())
1161}
1162
1163#[derive(Clone, Copy)]
1164enum EntrySide {
1165 Old,
1166 New,
1167}
1168
1169impl EntrySide {
1170 fn of(self, file: &PatchResolvedSide) -> (&PatchSide, FileMode, ObjectId) {
1171 let e = &file.entry;
1172 match self {
1173 Self::Old => (&file.old, e.old_mode, e.old_oid),
1174 Self::New => (&file.new, e.new_mode, e.new_oid),
1175 }
1176 }
1177
1178 fn path(self, entry: &DiffEntry) -> &str {
1179 match self {
1180 Self::Old => entry.old_path.as_deref().unwrap_or_else(|| entry.path()),
1181 Self::New => entry.path(),
1182 }
1183 }
1184}
1185
1186struct WorktreeSideReader<'r> {
1188 work_tree: &'r std::path::Path,
1189 index: Index,
1190 rules: WorktreeRules,
1191}
1192
1193impl<'r> WorktreeSideReader<'r> {
1194 fn open(repo: &'r Repository) -> Result<Self> {
1195 let work_tree = repo.work_tree().ok_or(RepositoryError::RequiresWorkTree)?;
1196 let index = repo.load_index()?;
1197 let rules = WorktreeRules::from_repository(repo, &index)?;
1198 Ok(Self {
1199 work_tree,
1200 index,
1201 rules,
1202 })
1203 }
1204
1205 fn read(&self, odb: &Odb, path: &str, mode: u32) -> Result<Vec<u8>> {
1206 let index_entry = self.index.get(&crate::repo_relpath::storage_bytes(path), 0);
1207 Ok(load_worktree_side_for_diff(
1208 odb,
1209 self.work_tree,
1210 path,
1211 mode,
1212 self.rules.config(),
1213 index_entry,
1214 Some(&self.rules),
1215 true,
1216 )?
1217 .0
1218 .data)
1219 }
1220}
1221
1222fn resolve_patch_side<'f, 'r>(
1223 repo: &'r Repository,
1224 file: &'f PatchResolvedSide,
1225 side: EntrySide,
1226 worktree: &mut Option<WorktreeSideReader<'r>>,
1227) -> Result<Cow<'f, [u8]>> {
1228 let (source, mode, oid) = side.of(file);
1229 let mode = mode.bits();
1230 if mode == 0 {
1231 return Ok(Cow::Borrowed(&[]));
1232 }
1233 match source {
1234 PatchSide::Bytes(bytes) => Ok(Cow::Borrowed(bytes)),
1235 PatchSide::Blob => Ok(Cow::Owned(read_blob_side(
1236 repo.odb(),
1237 oid,
1238 false,
1239 Some(side.path(&file.entry)),
1240 true,
1241 )?)),
1242 PatchSide::Worktree => {
1243 let reader = match worktree {
1244 Some(reader) => reader,
1245 None => worktree.insert(WorktreeSideReader::open(repo)?),
1246 };
1247 Ok(Cow::Owned(reader.read(
1248 repo.odb(),
1249 side.path(&file.entry),
1250 mode,
1251 )?))
1252 }
1253 }
1254}
1255
1256fn entry_with_content_ids(
1258 repo: &Repository,
1259 file: &PatchResolvedSide,
1260 old: &[u8],
1261 new: &[u8],
1262) -> Result<DiffEntry> {
1263 let content_id = |side: EntrySide, bytes: &[u8]| -> Result<ObjectId> {
1264 let (source, mode, oid) = side.of(file);
1265 if mode.is_absent() {
1266 return Ok(zero_oid());
1267 }
1268 if mode.is_gitlink() {
1269 return Ok(oid);
1270 }
1271 match source {
1272 PatchSide::Blob => Ok(oid),
1273 PatchSide::Bytes(_) | PatchSide::Worktree => {
1274 repo.odb().hash_algo().hash_object(ObjectKind::Blob, bytes)
1275 }
1276 }
1277 };
1278 let mut entry = file.entry.clone();
1279 entry.old_oid = content_id(EntrySide::Old, old)?;
1280 entry.new_oid = content_id(EntrySide::New, new)?;
1281 Ok(entry)
1282}
1283
1284fn load_patch_blob_side(
1285 odb: &Odb,
1286 oid: ObjectId,
1287 is_missing: bool,
1288 path: Option<&str>,
1289 force_read_content: bool,
1290) -> Result<(Vec<u8>, bool)> {
1291 if is_missing || oid == zero_oid() || oid == empty_blob_oid() {
1292 return Ok((Vec::new(), false));
1293 }
1294 let (side, binary) = load_odb_blob_side_for_diff(odb, &oid, path, force_read_content)?;
1295 Ok((side.data, binary))
1296}
1297
1298fn read_blob_side(
1299 odb: &Odb,
1300 oid: ObjectId,
1301 is_missing: bool,
1302 path: Option<&str>,
1303 force_read_content: bool,
1304) -> Result<Vec<u8>> {
1305 Ok(load_patch_blob_side(odb, oid, is_missing, path, force_read_content)?.0)
1306}
1307
1308#[cfg(test)]
1309mod tests {
1310 use super::*;
1311 use std::io::Cursor;
1312
1313 use crate::hash::hash_object;
1314 use crate::objects::HashAlgo;
1315
1316 #[test]
1317 fn log_short_message_skips_big_blob_reads() -> Result<()> {
1318 let dir = tempfile::tempdir().expect("tempdir");
1319 let (repo, _) = Repository::init(dir.path(), &crate::repo::InitOptions::default())?;
1320 std::fs::write(
1321 repo.git_dir().join("config"),
1322 "[core]\n\tbigFileThreshold = 4k\n",
1323 )?;
1324 let odb = repo.odb();
1325 let old = odb.write(ObjectKind::Blob, &vec![b'o'; 5000])?;
1326 let new = odb.write(ObjectKind::Blob, &vec![b'n'; 5001])?;
1327 let entry = DiffEntry {
1328 status: DiffStatus::Modified,
1329 old_path: Some("asset.bin".into()),
1330 new_path: Some("asset.bin".into()),
1331 old_oid: old,
1332 new_oid: new,
1333 old_mode: FileMode::REGULAR,
1334 new_mode: FileMode::REGULAR,
1335 score: None,
1336 };
1337 let metrics = odb.hot_path_metrics();
1338 metrics.reset_blob_content_reads();
1339 metrics.set_blob_counting(true);
1340 let mut out = Cursor::new(Vec::new());
1341 let mut opts = LogPatchOptions::git_default(&ConfigSet::default());
1342 opts.binary_format = LogPatchBinaryFormat::LogShortMessage;
1343 write_diff_entry_log_patch(&mut out, &repo, odb, &entry, &opts)?;
1344 metrics.set_blob_counting(false);
1345 let text = String::from_utf8(out.into_inner()).expect("utf-8");
1346 assert!(text.contains("Binary files"));
1347 assert_eq!(metrics.blob_content_reads(), 0);
1348 Ok(())
1349 }
1350
1351 #[test]
1352 fn copied_diff_emits_copy_headers() -> Result<()> {
1353 let blob_oid = hash_object(HashAlgo::Sha1, ObjectKind::Blob, b"x").expect("hash");
1354 let entry = DiffEntry {
1355 status: DiffStatus::Copied,
1356 old_path: Some("src/a.txt".into()),
1357 new_path: Some("dst/b.txt".into()),
1358 old_oid: blob_oid,
1359 new_oid: blob_oid,
1360 old_mode: FileMode::REGULAR,
1361 new_mode: FileMode::REGULAR,
1362 score: Some(100),
1363 };
1364 let dir = tempfile::tempdir().expect("tempdir");
1365 let (repo, _) = Repository::init(dir.path(), &crate::repo::InitOptions::default())?;
1366 repo.odb().write(ObjectKind::Blob, b"x")?;
1367 let mut out = Cursor::new(Vec::new());
1368 let opts = LogPatchOptions::git_default(&ConfigSet::default());
1369 write_diff_entry_log_patch(&mut out, &repo, repo.odb(), &entry, &opts)?;
1370 let text = String::from_utf8(out.into_inner()).expect("utf-8");
1371 assert!(text.contains("copy from src/a.txt"));
1372 assert!(text.contains("copy to dst/b.txt"));
1373 assert!(!text.contains("rename from"));
1374 Ok(())
1375 }
1376
1377 #[test]
1378 fn write_patch_resolved_index_line_hashes_text_bytes_when_new_oid_zero() -> Result<()> {
1379 let dir = tempfile::tempdir().expect("tempdir");
1380 let (repo, _) = Repository::init(dir.path(), &crate::repo::InitOptions::default())?;
1381 let old_oid = repo.odb().write(ObjectKind::Blob, b"one\n")?;
1382 let new_bytes = b"one\ntwo\n".to_vec();
1383 let new_oid = repo
1384 .odb()
1385 .hash_algo()
1386 .hash_object(ObjectKind::Blob, &new_bytes)?;
1387 let files = [PatchResolvedSide {
1388 entry: DiffEntry {
1389 status: DiffStatus::Modified,
1390 old_path: Some("t.txt".into()),
1391 new_path: Some("t.txt".into()),
1392 old_oid,
1393 new_oid: zero_oid(),
1394 old_mode: FileMode::REGULAR,
1395 new_mode: FileMode::REGULAR,
1396 score: None,
1397 },
1398 old: PatchSide::Bytes(b"one\n".to_vec()),
1399 new: PatchSide::Bytes(new_bytes),
1400 }];
1401 let opts = PatchTextOptions::from_repo(&repo, DiffOptions::default())?;
1402 let mut out = Cursor::new(Vec::new());
1403 write_patch_resolved(&repo, &files, &opts, &mut out)?;
1404 let text = String::from_utf8(out.into_inner()).expect("utf-8");
1405 assert!(
1406 !text.contains("..0000000 100644"),
1407 "must not emit placeholder new oid:\n{text}"
1408 );
1409 assert!(
1410 text.contains(&format!("..{} 100644", &new_oid.to_hex()[..7])),
1411 "index line must abbreviate hashed postimage:\n{text}"
1412 );
1413 Ok(())
1414 }
1415
1416 #[test]
1417 fn write_patch_resolved_gitlink_index_line_keeps_commit_ids() -> Result<()> {
1418 let dir = tempfile::tempdir().expect("tempdir");
1419 let (repo, _) = Repository::init(dir.path(), &crate::repo::InitOptions::default())?;
1420 let old_commit =
1421 ObjectId::from_hex("1111111111111111111111111111111111111111").expect("oid");
1422 let new_commit =
1423 ObjectId::from_hex("2222222222222222222222222222222222222222").expect("oid");
1424 let files = [PatchResolvedSide {
1425 entry: DiffEntry {
1426 status: DiffStatus::Modified,
1427 old_path: Some("sub".into()),
1428 new_path: Some("sub".into()),
1429 old_oid: old_commit,
1430 new_oid: new_commit,
1431 old_mode: FileMode::GITLINK,
1432 new_mode: FileMode::GITLINK,
1433 score: None,
1434 },
1435 old: PatchSide::Bytes(format!("Subproject commit {}\n", old_commit.to_hex()).into()),
1436 new: PatchSide::Bytes(format!("Subproject commit {}\n", new_commit.to_hex()).into()),
1437 }];
1438 let opts = PatchTextOptions::from_repo(&repo, DiffOptions::default())?;
1439 let mut out = Cursor::new(Vec::new());
1440 write_patch_resolved(&repo, &files, &opts, &mut out)?;
1441 let text = String::from_utf8(out.into_inner()).expect("utf-8");
1442 assert!(
1443 text.contains(&format!(
1444 "index {}..{} 160000",
1445 &old_commit.to_hex()[..7],
1446 &new_commit.to_hex()[..7]
1447 )),
1448 "gitlink index line must keep commit oids:\n{text}"
1449 );
1450 Ok(())
1451 }
1452}