Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 8.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Browsing a repository without cloning it: directories, files, READMEs (section 15).
5//!
6//! A revision (`ref`) is a branch, a tag (`tags/<name>`), a changeset's
7//! full id, or the first 12 to 63 hex digits of the id of a changeset the
8//! repository holds; the default branch when none is given.
9//!
10//! Names and paths come as UTF-8, with what is not UTF-8 replaced. One that
11//! is not UTF-8 also comes in `raw_name` or `raw_path`, percent-encoded as
12//! a route's path takes it ([`encode_path`]), so that a client can ask for
13//! it again.
14
15use braid_format::ObjectId;
16use serde::{Deserialize, Serialize};
17
18use crate::hex;
19
20/// One entry of a directory.
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
22pub struct DirEntry {
23 /// Its name.
24 pub name: String,
25 /// Its name percent-encoded, when it is not UTF-8.
26 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub raw_name: Option<String>,
28 /// `file`, `executable`, `symlink`, `tree` or `gitlink`.
29 pub kind: String,
30 /// Its blob or tree, or a gitlink's git commit, in hex.
31 pub id: String,
32 /// Its size in bytes, for a file, an executable or a symlink.
33 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub size: Option<u64>,
35}
36
37/// A page of a directory, in `GET …/contents/{path}`: directories first,
38/// then the rest, each in order of their names' bytes.
39#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Directory {
41 /// The branch or tag the revision named; `None` for an id.
42 #[serde(rename = "ref")]
43 pub reference: Option<String>,
44 /// The changeset read.
45 #[serde(with = "hex::id")]
46 pub changeset: ObjectId,
47 /// The directory, from the root, which is the empty path.
48 pub path: String,
49 /// The path percent-encoded, when it is not UTF-8.
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub raw_path: Option<String>,
52 /// The entries of this page.
53 pub entries: Vec<DirEntry>,
54 /// The cursor of the next page (`?after=`), or `None` on the last one.
55 #[serde(default)]
56 pub next: Option<String>,
57}
58
59/// A file, a symlink or a gitlink, in `GET …/contents/{path}`.
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61pub struct File {
62 /// The branch or tag the revision named; `None` for an id.
63 #[serde(rename = "ref")]
64 pub reference: Option<String>,
65 /// The changeset read.
66 #[serde(with = "hex::id")]
67 pub changeset: ObjectId,
68 /// Its path, from the root.
69 pub path: String,
70 /// Its path percent-encoded, when it is not UTF-8.
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub raw_path: Option<String>,
73 /// `file`, `executable`, `symlink` or `gitlink`.
74 pub kind: String,
75 /// Its blob, or a gitlink's git commit, in hex.
76 pub id: String,
77 /// Its size in bytes; `None` for a gitlink.
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub size: Option<u64>,
80 /// Whether its content is binary: a NUL among its first 8,000 bytes.
81 pub binary: bool,
82 /// Its content, for a file or an executable that is not binary, is
83 /// UTF-8, and is no larger than the hub shows as text (`text_view` of
84 /// `limits.social`); `None` otherwise, or when `text=false` was asked.
85 pub text: Option<String>,
86 /// A symlink's target, which the hub never follows.
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub target: Option<String>,
89 /// A gitlink's git commit, in hex.
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub commit: Option<String>,
92}
93
94/// `GET …/contents` and `GET …/contents/{path}`: what is at a path.
95#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(tag = "type", rename_all = "lowercase")]
97pub enum Contents {
98 /// A directory: `"type": "dir"`.
99 Dir(Directory),
100 /// Anything else: `"type": "file"`.
101 File(File),
102}
103
104/// `GET …/readme`: the README of a directory.
105#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106pub struct Readme {
107 /// Its path, from the root.
108 pub path: String,
109 /// Its path percent-encoded, when it is not UTF-8.
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub raw_path: Option<String>,
112 /// Its blob.
113 #[serde(with = "hex::id")]
114 pub blob: ObjectId,
115 /// Its size in bytes.
116 pub size: u64,
117 /// Its text, as UTF-8, cut at the largest README the hub renders.
118 pub markdown: String,
119 /// Its text rendered as HTML, safe to show: Markdown for a `.md` or
120 /// `.markdown` file, preformatted text otherwise.
121 pub html: String,
122 /// Whether `markdown` was cut.
123 pub truncated: bool,
124}
125
126/// `path`, percent-encoded as a route's path takes it: `/` and most of the
127/// characters a path may hold as they are (letters, digits, `-._~` and
128/// `!$()*+,;=:@`), every other byte as `%XX`. `&` and `'` are encoded too,
129/// so that the result reads the same inside an HTML attribute, where `&`
130/// would start a character reference.
131pub fn encode_path(path: &[u8]) -> String {
132 const HEX: &[u8; 16] = b"0123456789ABCDEF";
133 let mut out = String::with_capacity(path.len());
134 for &byte in path {
135 let plain = byte.is_ascii_alphanumeric() || b"/-._~!$()*+,;=:@".contains(&byte);
136 if plain {
137 out.push(char::from(byte));
138 } else {
139 out.push('%');
140 out.push(char::from(HEX[usize::from(byte >> 4)]));
141 out.push(char::from(HEX[usize::from(byte & 0x0f)]));
142 }
143 }
144 out
145}
146
147/// The text of `bytes`, and their percent-encoded form when they are not
148/// UTF-8: a name or a path, as the answers of this section give it.
149pub fn text_and_raw(bytes: &[u8]) -> (String, Option<String>) {
150 match std::str::from_utf8(bytes) {
151 Ok(text) => (text.to_owned(), None),
152 Err(_) => (
153 String::from_utf8_lossy(bytes).into_owned(),
154 Some(encode_path(bytes)),
155 ),
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use braid_format::Kind;
163
164 fn id(text: &str) -> ObjectId {
165 ObjectId::hash(Kind::Changeset, text.as_bytes())
166 }
167
168 #[test]
169 fn contents_on_the_wire() {
170 let dir = Contents::Dir(Directory {
171 reference: Some("main".into()),
172 changeset: id("head"),
173 path: String::new(),
174 raw_path: None,
175 entries: vec![DirEntry {
176 name: "src".into(),
177 raw_name: None,
178 kind: "tree".into(),
179 id: id("tree").to_hex(),
180 size: None,
181 }],
182 next: Some("cursor".into()),
183 });
184 let text = serde_json::to_string(&dir).unwrap();
185 assert!(text.starts_with(r#"{"type":"dir","ref":"main""#), "{text}");
186 assert!(!text.contains("raw_") && !text.contains("size"), "{text}");
187 assert_eq!(serde_json::from_str::<Contents>(&text).unwrap(), dir);
188
189 let file = Contents::File(File {
190 reference: None,
191 changeset: id("head"),
192 path: "a.txt".into(),
193 raw_path: None,
194 kind: "file".into(),
195 id: id("blob").to_hex(),
196 size: Some(2),
197 binary: false,
198 text: Some("a\n".into()),
199 target: None,
200 commit: None,
201 });
202 let text = serde_json::to_string(&file).unwrap();
203 assert!(text.contains(r#""type":"file""#), "{text}");
204 assert!(text.contains(r#""ref":null"#), "{text}");
205 assert!(
206 !text.contains("target") && !text.contains("commit"),
207 "{text}"
208 );
209 assert_eq!(serde_json::from_str::<Contents>(&text).unwrap(), file);
210
211 let readme = Readme {
212 path: "README.md".into(),
213 raw_path: None,
214 blob: id("readme"),
215 size: 7,
216 markdown: "# Hello".into(),
217 html: "<h1>Hello</h1>".into(),
218 truncated: false,
219 };
220 let text = serde_json::to_string(&readme).unwrap();
221 assert_eq!(serde_json::from_str::<Readme>(&text).unwrap(), readme);
222 }
223
224 #[test]
225 fn paths_are_encoded_as_routes_take_them() {
226 assert_eq!(encode_path(b"src/main.rs"), "src/main.rs");
227 assert_eq!(encode_path(b"a b/c#d?e%f"), "a%20b/c%23d%3Fe%25f");
228 assert_eq!(encode_path(b"f\xff"), "f%FF");
229 assert_eq!(encode_path("ñ".as_bytes()), "%C3%B1");
230 assert_eq!(encode_path(b"(1)+x=y;@:~"), "(1)+x=y;@:~");
231 assert_eq!(encode_path(b"<\"'>"), "%3C%22%27%3E");
232 assert_eq!(encode_path(b"R&amp;D/a&lt;b"), "R%26amp;D/a%26lt;b");
233 assert_eq!(text_and_raw(b"plain"), ("plain".to_owned(), None));
234 let (text, raw) = text_and_raw(b"bad\xfe");
235 assert_eq!(text, "bad\u{fffd}");
236 assert_eq!(raw.as_deref(), Some("bad%FE"));
237 }
238}