use serde::{Deserialize, Serialize};
use gitpoulpi_core::domain::FileDiff;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiFileDiff {
pub diff: FileDiff,
pub previous_path: Option<String>,
pub additions: u32,
pub deletions: u32,
pub omitted: Option<String>,
}
pub const NOT_SHOWN_BY_THE_HOST: &str = "not shown by the host";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiCommit {
pub sha: String,
pub parents: Vec<String>,
pub author: String,
pub date: String,
pub summary: String,
}
#[cfg_attr(
not(any(feature = "github", feature = "gitlab", feature = "gitea")),
allow(dead_code)
)]
pub(crate) fn summary_of(message: &str) -> String {
message
.lines()
.next()
.unwrap_or_default()
.trim()
.to_string()
}
#[cfg_attr(not(feature = "gitea"), allow(dead_code))]
pub(crate) fn hunk_counts(diff: &FileDiff) -> (u32, u32) {
use gitpoulpi_core::domain::LineOrigin;
let count = |origin: LineOrigin| {
diff.hunks
.iter()
.flat_map(|h| h.lines.iter())
.filter(|l| l.origin == origin)
.count() as u32
};
(count(LineOrigin::Add), count(LineOrigin::Delete))
}
#[cfg_attr(
not(any(feature = "gitlab", feature = "gitea", feature = "gerrit")),
allow(dead_code)
)]
pub(crate) fn base64_decode(text: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(text.len() / 4 * 3);
let (mut acc, mut bits) = (0u32, 0u32);
let mut padding = 0usize;
for c in text.bytes() {
let value = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
b'=' => {
padding += 1;
continue;
}
b'\n' | b'\r' | b' ' => continue,
_ => return None,
};
if padding > 0 {
return None;
}
acc = (acc << 6) | u32::from(value);
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
(padding <= 2).then_some(out)
}
#[cfg(any(feature = "github", feature = "gitea"))]
pub(crate) fn encode_path(path: &str) -> String {
path.trim_start_matches('/')
.split('/')
.map(crate::client::encode_component)
.collect::<Vec<_>>()
.join("/")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_decodes_rfc_vectors_with_and_without_line_breaks() {
for (plain, encoded) in [
("", ""),
("f", "Zg=="),
("fo", "Zm8="),
("foo", "Zm9v"),
("foobar", "Zm9vYmFy"),
] {
assert_eq!(base64_decode(encoded).unwrap(), plain.as_bytes());
}
assert_eq!(base64_decode("Zm9v\nYmFy\n").unwrap(), b"foobar");
assert_eq!(base64_decode("AP8=").unwrap(), vec![0u8, 255]);
assert!(base64_decode("Zm9v!").is_none());
assert!(base64_decode("Zg==Zg").is_none());
}
#[test]
fn a_summary_is_the_first_line() {
assert_eq!(summary_of("fix: x\n\nlong body"), "fix: x");
assert_eq!(summary_of(""), "");
}
}