Skip to main content

gitpoulpi_hosting/review/
api_code.rs

1//! The code of a request read through the host's API instead of a clone:
2//! the diff per file, the commits, the diff of one commit and a file at a
3//! revision. The shapes live here, the per-host calls in [`super::github`]
4//! and [`super::gitlab`], behind `HostingClient` methods whose default is
5//! `Unsupported`.
6//!
7//! A host's per-file `patch` has hunks but no `diff --git` header, so it is
8//! parsed with [`gitpoulpi_core::diff_text::parse_hunks`], the parser the
9//! system-git backend uses too.
10
11use serde::{Deserialize, Serialize};
12
13use gitpoulpi_core::domain::FileDiff;
14
15/// One changed file with its hunks.
16///
17/// `omitted` says why a file that did change carries no hunks (the host
18/// did not send its patch: too big, too many files). A binary file, a
19/// rename without edits or a mode change has no hunks either and is *not*
20/// omitted.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct ApiFileDiff {
23    pub diff: FileDiff,
24    /// The path at the merge base, for a rename.
25    pub previous_path: Option<String>,
26    pub additions: u32,
27    pub deletions: u32,
28    pub omitted: Option<String>,
29}
30
31/// The reason shown for a file whose patch the host left out.
32pub const NOT_SHOWN_BY_THE_HOST: &str = "not shown by the host";
33
34/// One commit of a request, oldest first in a list.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct ApiCommit {
37    pub sha: String,
38    pub parents: Vec<String>,
39    pub author: String,
40    pub date: String,
41    pub summary: String,
42}
43
44/// The first line of a commit message.
45#[cfg_attr(
46    not(any(feature = "github", feature = "gitlab", feature = "gitea")),
47    allow(dead_code)
48)]
49pub(crate) fn summary_of(message: &str) -> String {
50    message
51        .lines()
52        .next()
53        .unwrap_or_default()
54        .trim()
55        .to_string()
56}
57
58/// The added and deleted lines of `diff`'s hunks.
59#[cfg_attr(not(feature = "gitea"), allow(dead_code))]
60pub(crate) fn hunk_counts(diff: &FileDiff) -> (u32, u32) {
61    use gitpoulpi_core::domain::LineOrigin;
62    let count = |origin: LineOrigin| {
63        diff.hunks
64            .iter()
65            .flat_map(|h| h.lines.iter())
66            .filter(|l| l.origin == origin)
67            .count() as u32
68    };
69    (count(LineOrigin::Add), count(LineOrigin::Delete))
70}
71
72/// Decodes RFC 4648 base64 (standard alphabet), ignoring the line breaks
73/// both hosts put in the `content` of a file. `None` for any other
74/// character or a bad length.
75#[cfg_attr(
76    not(any(feature = "gitlab", feature = "gitea", feature = "gerrit")),
77    allow(dead_code)
78)]
79pub(crate) fn base64_decode(text: &str) -> Option<Vec<u8>> {
80    let mut out = Vec::with_capacity(text.len() / 4 * 3);
81    let (mut acc, mut bits) = (0u32, 0u32);
82    let mut padding = 0usize;
83    for c in text.bytes() {
84        let value = match c {
85            b'A'..=b'Z' => c - b'A',
86            b'a'..=b'z' => c - b'a' + 26,
87            b'0'..=b'9' => c - b'0' + 52,
88            b'+' => 62,
89            b'/' => 63,
90            b'=' => {
91                padding += 1;
92                continue;
93            }
94            b'\n' | b'\r' | b' ' => continue,
95            _ => return None,
96        };
97        if padding > 0 {
98            return None;
99        }
100        acc = (acc << 6) | u32::from(value);
101        bits += 6;
102        if bits >= 8 {
103            bits -= 8;
104            out.push((acc >> bits) as u8);
105            acc &= (1 << bits) - 1;
106        }
107    }
108    (padding <= 2).then_some(out)
109}
110
111/// `a/b c/d.rs` as `a/b%20c/d.rs`: each segment percent-encoded, the
112/// slashes kept (GitHub's and Gitea's `contents` route).
113#[cfg(any(feature = "github", feature = "gitea"))]
114pub(crate) fn encode_path(path: &str) -> String {
115    path.trim_start_matches('/')
116        .split('/')
117        .map(crate::client::encode_component)
118        .collect::<Vec<_>>()
119        .join("/")
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn base64_decodes_rfc_vectors_with_and_without_line_breaks() {
128        for (plain, encoded) in [
129            ("", ""),
130            ("f", "Zg=="),
131            ("fo", "Zm8="),
132            ("foo", "Zm9v"),
133            ("foobar", "Zm9vYmFy"),
134        ] {
135            assert_eq!(base64_decode(encoded).unwrap(), plain.as_bytes());
136        }
137        assert_eq!(base64_decode("Zm9v\nYmFy\n").unwrap(), b"foobar");
138        assert_eq!(base64_decode("AP8=").unwrap(), vec![0u8, 255]);
139        assert!(base64_decode("Zm9v!").is_none());
140        assert!(base64_decode("Zg==Zg").is_none());
141    }
142
143    #[test]
144    fn a_summary_is_the_first_line() {
145        assert_eq!(summary_of("fix: x\n\nlong body"), "fix: x");
146        assert_eq!(summary_of(""), "");
147    }
148}