gitfox_client/models/
content.rs1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use super::Commit;
5
6#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct Content {
14 #[serde(default, rename = "type")]
16 pub kind: String,
17 #[serde(default)]
18 pub sha: String,
19 #[serde(default)]
20 pub name: String,
21 #[serde(default)]
22 pub path: String,
23 #[serde(default)]
24 pub content: Value,
25 #[serde(default)]
26 pub latest_commit: Option<Commit>,
27}
28
29#[derive(Debug, Clone, Default, Serialize, Deserialize)]
31pub struct ContentEntry {
32 #[serde(default, rename = "type")]
33 pub kind: String,
34 #[serde(default)]
35 pub sha: String,
36 #[serde(default)]
37 pub name: String,
38 #[serde(default)]
39 pub path: String,
40}
41
42impl Content {
43 pub fn is_dir(&self) -> bool {
44 self.kind == "dir"
45 }
46
47 pub fn entries(&self) -> Vec<ContentEntry> {
49 self.content
50 .get("entries")
51 .cloned()
52 .and_then(|v| serde_json::from_value(v).ok())
53 .unwrap_or_default()
54 }
55
56 pub fn size(&self) -> Option<i64> {
58 self.content.get("size").and_then(Value::as_i64)
59 }
60
61 pub fn bytes(&self) -> Option<Vec<u8>> {
66 let data = self.content.get("data")?.as_str()?;
67 match self.content.get("encoding").and_then(Value::as_str) {
68 Some("base64") | None => decode_base64(data),
69 Some("utf8" | "utf-8" | "text") => Some(data.as_bytes().to_vec()),
70 Some(_) => None,
71 }
72 }
73}
74
75pub fn decode_base64(input: &str) -> Option<Vec<u8>> {
78 fn value(byte: u8) -> Option<u32> {
79 Some(match byte {
80 b'A'..=b'Z' => byte - b'A',
81 b'a'..=b'z' => byte - b'a' + 26,
82 b'0'..=b'9' => byte - b'0' + 52,
83 b'+' | b'-' => 62,
84 b'/' | b'_' => 63,
85 _ => return None,
86 } as u32)
87 }
88
89 let clean: Vec<u8> = input
90 .bytes()
91 .filter(|b| !b.is_ascii_whitespace() && *b != b'=')
92 .collect();
93 let mut out = Vec::with_capacity(clean.len() * 3 / 4);
94 for chunk in clean.chunks(4) {
95 let mut acc = 0u32;
96 for (i, byte) in chunk.iter().enumerate() {
97 acc |= value(*byte)? << (18 - 6 * i as u32);
98 }
99 let bytes = acc.to_be_bytes();
100 match chunk.len() {
101 4 => out.extend_from_slice(&bytes[1..4]),
102 3 => out.extend_from_slice(&bytes[1..3]),
103 2 => out.push(bytes[1]),
104 _ => return None,
105 }
106 }
107 Some(out)
108}
109
110pub fn encode_base64(input: &[u8]) -> String {
112 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
113 let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
114 for chunk in input.chunks(3) {
115 let n = match chunk.len() {
116 3 => (chunk[0] as u32) << 16 | (chunk[1] as u32) << 8 | chunk[2] as u32,
117 2 => (chunk[0] as u32) << 16 | (chunk[1] as u32) << 8,
118 _ => (chunk[0] as u32) << 16,
119 };
120 for i in 0..4 {
121 if i <= chunk.len() {
122 out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
123 } else {
124 out.push('=');
125 }
126 }
127 }
128 out
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134 use serde_json::json;
135
136 #[test]
137 fn base64_round_trips_every_padding_length() {
138 for text in ["", "a", "ab", "abc", "abcd", "# AgentNexus\n\n> δΈζ"] {
139 let encoded = encode_base64(text.as_bytes());
140 assert_eq!(decode_base64(&encoded).unwrap(), text.as_bytes(), "{text}");
141 }
142 assert_eq!(encode_base64(b"hello"), "aGVsbG8=");
143 assert_eq!(decode_base64("aGVs\nbG8=").unwrap(), b"hello");
145 assert!(decode_base64("not*base64").is_none());
146 }
147
148 #[test]
149 fn a_file_decodes_and_a_directory_lists() {
150 let file: Content = serde_json::from_value(json!({
151 "type": "file", "name": "README.md", "path": "README.md", "sha": "b72a",
152 "content": { "data": "IyBBZ2VudE5leHVz", "encoding": "base64", "size": 12 }
153 }))
154 .unwrap();
155 assert_eq!(file.bytes().unwrap(), b"# AgentNexus");
156 assert_eq!(file.size(), Some(12));
157 assert!(file.entries().is_empty());
158
159 let dir: Content = serde_json::from_value(json!({
160 "type": "dir", "path": "",
161 "content": { "entries": [
162 { "type": "file", "name": "Cargo.toml", "path": "Cargo.toml", "sha": "1" },
163 { "type": "dir", "name": "src", "path": "src", "sha": "2" }
164 ] }
165 }))
166 .unwrap();
167 assert!(dir.is_dir());
168 assert_eq!(dir.entries().len(), 2);
169 assert_eq!(dir.entries()[1].kind, "dir");
170 assert!(dir.bytes().is_none());
171 }
172}