use std::borrow::Cow;
use std::cell::Cell;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use super::{b64, ImageInfo, LfsPointer, Oid};
thread_local! {
static FALLBACK_ENCODING: Cell<Option<&'static encoding_rs::Encoding>> =
const { Cell::new(None) };
}
pub fn with_fallback_encoding<R>(label: Option<&str>, f: impl FnOnce() -> R) -> R {
let encoding = label
.map(str::trim)
.and_then(|l| encoding_rs::Encoding::for_label(l.as_bytes()))
.filter(|e| *e != encoding_rs::UTF_8);
let previous = FALLBACK_ENCODING.with(|c| c.replace(encoding));
struct Restore(Option<&'static encoding_rs::Encoding>);
impl Drop for Restore {
fn drop(&mut self) {
FALLBACK_ENCODING.with(|c| c.set(self.0));
}
}
let _restore = Restore(previous);
f()
}
fn fallback_encoding() -> Option<&'static encoding_rs::Encoding> {
FALLBACK_ENCODING.with(Cell::get)
}
pub fn fallback_encoding_name() -> Option<&'static str> {
fallback_encoding().map(|e| e.name())
}
pub fn decode_text(raw: &[u8]) -> Option<Cow<'_, str>> {
if let Ok(text) = std::str::from_utf8(raw) {
return Some(Cow::Borrowed(text));
}
fallback_encoding()?.decode_without_bom_handling_and_without_replacement(raw)
}
pub fn decode_text_lossy(raw: &[u8]) -> Cow<'_, str> {
decode_text(raw).unwrap_or_else(|| String::from_utf8_lossy(raw))
}
pub fn decode_commit_text<'a>(raw: &'a [u8], header_encoding: Option<&str>) -> Cow<'a, str> {
let declared = header_encoding
.map(str::trim)
.and_then(|l| encoding_rs::Encoding::for_label(l.as_bytes()))
.filter(|e| *e != encoding_rs::UTF_8);
match declared {
Some(encoding) => encoding.decode_without_bom_handling(raw).0,
None => decode_text_lossy(raw),
}
}
pub fn commit_summary(message: &str) -> String {
let message = message.trim_start_matches('\n');
let first = message.split("\n\n").next().unwrap_or_default();
first
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
pub const MAX_TEXT_BLOB_BYTES: u64 = 8 * 1024 * 1024;
const BINARY_SNIFF_BYTES: usize = 8000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlobSource {
Commit(Oid),
Index,
WorkingTree,
Stage(u8),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Blob {
pub path: PathBuf,
pub source: BlobSource,
pub size: u64,
pub content: BlobContent,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image: Option<ImageInfo>,
}
impl Blob {
pub fn image_of(content: &BlobContent, raw: &[u8]) -> Option<ImageInfo> {
match content {
BlobContent::Binary => super::image_info::sniff(raw),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlobBytes {
pub path: PathBuf,
pub source: BlobSource,
pub size: u64,
pub body: BlobBody,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlobBody {
Bytes(#[serde(with = "b64")] Vec<u8>),
TooLarge,
Lfs {
pointer: LfsPointer,
#[serde(with = "b64::option", default)]
object: Option<Vec<u8>>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlobContent {
Text {
lines: Vec<String>,
crlf: bool,
final_newline: bool,
},
Binary,
TooLarge,
LfsPointer(LfsPointer),
}
impl BlobContent {
pub fn from_bytes(raw: &[u8]) -> Self {
if let Some(pointer) = LfsPointer::parse(raw) {
return BlobContent::LfsPointer(pointer);
}
let sniff = &raw[..raw.len().min(BINARY_SNIFF_BYTES)];
let utf16 = fallback_encoding()
.is_some_and(|e| e == encoding_rs::UTF_16LE || e == encoding_rs::UTF_16BE);
if sniff.contains(&0) && !utf16 {
return BlobContent::Binary;
}
let decoded = if utf16 && sniff.contains(&0) {
fallback_encoding()
.and_then(|e| e.decode_without_bom_handling_and_without_replacement(raw))
} else {
decode_text(raw)
};
let Some(text) = decoded else {
return BlobContent::Binary;
};
Self::text_of(text.as_ref())
}
pub fn from_bytes_as_text(raw: &[u8]) -> Self {
Self::text_of(decode_text_lossy(raw).as_ref())
}
fn text_of(text: &str) -> Self {
let final_newline = text.is_empty() || text.ends_with('\n');
let mut crlf = false;
let mut lines: Vec<String> = Vec::new();
for line in text.split('\n') {
if let Some(stripped) = line.strip_suffix('\r') {
crlf = true;
lines.push(stripped.to_string());
} else {
lines.push(line.to_string());
}
}
if final_newline {
lines.pop();
}
BlobContent::Text {
lines,
crlf,
final_newline,
}
}
pub fn lines(&self) -> &[String] {
match self {
BlobContent::Text { lines, .. } => lines,
_ => &[],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Blame {
pub path: PathBuf,
pub at: Oid,
pub size: u64,
pub content: BlameContent,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlameContent {
Lines(Vec<BlameLine>),
Binary,
TooLarge,
LfsPointer(LfsPointer),
}
impl BlameContent {
pub fn lines(&self) -> &[BlameLine] {
match self {
BlameContent::Lines(lines) => lines,
_ => &[],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlameLine {
pub commit: Oid,
pub author_name: String,
pub author_email: String,
pub timestamp: i64,
pub committer_time: i64,
pub summary: String,
pub final_line: u32,
pub orig_line: u32,
pub orig_path: PathBuf,
pub previous: Option<(Oid, PathBuf)>,
pub content: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bytes_forced_to_text_keep_their_lines_even_with_a_nul() {
let raw = b"alpha\nbe\0ta\ngamma\n";
assert_eq!(BlobContent::from_bytes(raw), BlobContent::Binary);
let forced = BlobContent::from_bytes_as_text(raw);
assert_eq!(forced.lines(), ["alpha", "be\0ta", "gamma"]);
}
#[test]
fn crlf_and_lf_content_produce_the_same_lines() {
let lf = BlobContent::from_bytes(b"one\ntwo\n");
let crlf = BlobContent::from_bytes(b"one\r\ntwo\r\n");
assert_eq!(lf.lines(), ["one", "two"]);
assert_eq!(crlf.lines(), ["one", "two"]);
assert!(matches!(crlf, BlobContent::Text { crlf: true, .. }));
assert!(matches!(lf, BlobContent::Text { crlf: false, .. }));
}
#[test]
fn a_fallback_encoding_decodes_what_is_not_utf8_and_only_in_its_scope() {
let raw = b"caf\xe9\n";
assert_eq!(BlobContent::from_bytes(raw), BlobContent::Binary);
with_fallback_encoding(Some("windows-1252"), || {
assert_eq!(BlobContent::from_bytes(raw).lines(), ["caf\u{e9}"]);
assert_eq!(
BlobContent::from_bytes("caf\u{e9}\n".as_bytes()).lines(),
["caf\u{e9}"]
);
assert_eq!(BlobContent::from_bytes(b"a\0b\xe9"), BlobContent::Binary);
});
with_fallback_encoding(Some("utf-16le"), || {
assert_eq!(BlobContent::from_bytes(b"h\0i\0").lines(), ["hi"]);
});
for label in [Some("utf-8"), Some("klingon"), None] {
with_fallback_encoding(label, || {
assert_eq!(BlobContent::from_bytes(raw), BlobContent::Binary);
});
}
assert_eq!(decode_text_lossy(raw), "caf\u{fffd}\n");
}
#[test]
fn a_final_newline_does_not_add_a_phantom_line() {
assert_eq!(BlobContent::from_bytes(b"one\n").lines().len(), 1);
assert_eq!(BlobContent::from_bytes(b"one").lines().len(), 1);
assert_eq!(BlobContent::from_bytes(b"").lines().len(), 0);
assert_eq!(BlobContent::from_bytes(b"\n").lines(), [""]);
}
#[test]
fn a_missing_final_newline_is_recorded() {
assert!(matches!(
BlobContent::from_bytes(b"one"),
BlobContent::Text {
final_newline: false,
..
}
));
assert!(matches!(
BlobContent::from_bytes(b"one\n"),
BlobContent::Text {
final_newline: true,
..
}
));
}
#[test]
fn a_nul_byte_makes_it_binary() {
assert_eq!(
BlobContent::from_bytes(b"png\0\x01\x02"),
BlobContent::Binary
);
assert_eq!(
BlobContent::from_bytes(&[0xff, 0xfe, 0x41]),
BlobContent::Binary
);
}
#[test]
fn a_nul_past_the_sniff_window_is_still_text() {
let mut raw = vec![b'a'; BINARY_SNIFF_BYTES + 10];
raw[BINARY_SNIFF_BYTES + 5] = 0;
assert!(matches!(
BlobContent::from_bytes(&raw),
BlobContent::Text { .. }
));
}
#[test]
fn a_pointer_blob_is_an_lfs_pointer_not_text() {
let raw = b"version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 12345\n";
match BlobContent::from_bytes(raw) {
BlobContent::LfsPointer(p) => assert_eq!(p.size, 12345),
other => panic!("expected a pointer, got {other:?}"),
}
assert!(matches!(
BlobContent::from_bytes(b"version 2\nsize 3\n"),
BlobContent::Text { .. }
));
}
}