Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 13.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub show`, `ls` and `cat`: a repository on the hub, its
5//! directories and files, read without cloning it.
6//!
7//! Each takes the repository with `-R OWNER/NAME` (default: the one this
8//! repository is linked to) and the revision with `--ref` (default: the
9//! default branch): a branch, `tags/<name>`, a changeset's full id or its
10//! first 12 hex digits or more.
11
12use std::io::Write;
13use std::process::ExitCode;
14
15use anyhow::Result;
16use braid_hubproto::RepoPath;
17use braid_hubproto::api::RepoInfo;
18use braid_hubproto::browse::{Contents, DirEntry, Directory, Readme, encode_path};
19use clap::Args;
20use serde_json::{Value, json};
21
22use super::http::HttpHub;
23use super::remote::{HubError, shown};
24use super::social_common::{HubRepoArg, REFUSED, exit_for, hub_repo, print};
25use crate::{Cli, print_json};
26
27/// The most pages of one directory `ls` reads: a directory of a million
28/// entries, at the hub's default page.
29const MAX_PAGES: usize = 1_000;
30
31/// `hub show`.
32#[derive(Debug, Args)]
33pub(crate) struct ShowArgs {
34 #[command(flatten)]
35 pub(crate) repo: HubRepoArg,
36 /// The revision whose README to show: a branch, tags/NAME, or a
37 /// changeset's id or its start (default: the default branch).
38 #[arg(long = "ref", value_name = "REV")]
39 pub(crate) reference: Option<String>,
40}
41
42/// `hub ls`.
43#[derive(Debug, Args)]
44pub(crate) struct LsArgs {
45 /// The directory, from the repository's root (default: the root).
46 #[arg(value_name = "PATH")]
47 pub(crate) path: Option<String>,
48 #[command(flatten)]
49 pub(crate) repo: HubRepoArg,
50 /// The revision: a branch, tags/NAME, or a changeset's id or its start
51 /// (default: the default branch).
52 #[arg(long = "ref", value_name = "REV")]
53 pub(crate) reference: Option<String>,
54}
55
56/// `hub cat`.
57#[derive(Debug, Args)]
58pub(crate) struct CatArgs {
59 /// The file, from the repository's root.
60 #[arg(value_name = "PATH")]
61 pub(crate) path: String,
62 #[command(flatten)]
63 pub(crate) repo: HubRepoArg,
64 /// The revision: a branch, tags/NAME, or a changeset's id or its start
65 /// (default: the default branch).
66 #[arg(long = "ref", value_name = "REV")]
67 pub(crate) reference: Option<String>,
68}
69
70/// `value`, percent-encoded for a query string.
71fn query_value(value: &str) -> String {
72 let mut out = String::with_capacity(value.len());
73 for &byte in value.as_bytes() {
74 if byte.is_ascii_alphanumeric() || b"-._~/".contains(&byte) {
75 out.push(char::from(byte));
76 } else {
77 out.push_str(&format!("%{byte:02X}"));
78 }
79 }
80 out
81}
82
83/// The query of a revision and more `pairs`, each value encoded: empty
84/// when there is nothing to ask.
85fn query(reference: Option<&str>, pairs: &[(&str, &str)]) -> String {
86 let all: Vec<String> = reference
87 .map(|rev| ("ref", rev))
88 .into_iter()
89 .chain(pairs.iter().copied())
90 .map(|(name, value)| format!("{name}={}", query_value(value)))
91 .collect();
92 if all.is_empty() {
93 String::new()
94 } else {
95 format!("?{}", all.join("&"))
96 }
97}
98
99/// A path given on the command line, as a route's path takes it: `/` at
100/// either end dropped, the rest encoded as it is, `%` included.
101fn route_path(path: &str) -> String {
102 encode_path(path.trim_matches('/').as_bytes())
103}
104
105/// Runs `work`, which asks the hub: a refusal or a failure is said on
106/// standard error, with the exit status of [`exit_for`].
107fn asking(work: impl FnOnce() -> Result<(), HubError>) -> Result<ExitCode> {
108 match work() {
109 Ok(()) => Ok(ExitCode::SUCCESS),
110 // Standard output closed early: main says nothing of it.
111 Err(HubError::Io(err)) => Err(err.into()),
112 Err(err) => {
113 eprintln!("braid: error: {err}");
114 Ok(ExitCode::from(exit_for(&err)))
115 }
116 }
117}
118
119/// `GET …/contents/{path}`.
120fn contents(
121 hub: &HttpHub,
122 repo: &RepoPath,
123 path: &str,
124 reference: Option<&str>,
125 pairs: &[(&str, &str)],
126) -> Result<Contents, HubError> {
127 let route = if path.is_empty() {
128 format!("{}/contents", repo.api_path())
129 } else {
130 format!("{}/contents/{path}", repo.api_path())
131 };
132 hub.call_json(
133 "GET",
134 &format!("{route}{}", query(reference, pairs)),
135 &[],
136 None,
137 )
138}
139
140pub(crate) fn show(cli: &Cli, args: &ShowArgs) -> Result<ExitCode> {
141 let (hub, repo) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
142 let reference = args.reference.as_deref();
143 asking(|| {
144 let info: RepoInfo = hub.call_json("GET", &repo.api_path(), &[], None)?;
145 let route = format!("{}/readme{}", repo.api_path(), query(reference, &[]));
146 let readme = match hub.call_json::<Readme>("GET", &route, &[], None) {
147 Ok(readme) => Some(readme),
148 Err(HubError::Api { status: 404, .. }) => {
149 // No README, or no such revision: the root says which.
150 if reference.is_some() {
151 contents(&hub, &repo, "", reference, &[("text", "false")])?;
152 }
153 None
154 }
155 Err(err) => return Err(err),
156 };
157 let value = json!({ "repo": info, "readme": readme });
158 print(cli, &value, || show_text(&info, readme.as_ref())).map_err(io_error)
159 })
160}
161
162/// An error of printing, as the hub commands report it.
163fn io_error(err: anyhow::Error) -> HubError {
164 match err.downcast::<std::io::Error>() {
165 Ok(err) => HubError::Io(err),
166 Err(err) => HubError::Io(std::io::Error::other(err.to_string())),
167 }
168}
169
170/// Text of several lines from the hub, as braid shows it: each line as
171/// [`shown`] shows text, so that no control character reaches a terminal
172/// raw, but its line breaks and tabs kept.
173fn shown_lines(text: &str) -> String {
174 text.split('\n')
175 .map(|line| line.split('\t').map(shown).collect::<Vec<_>>().join("\t"))
176 .collect::<Vec<_>>()
177 .join("\n")
178}
179
180/// What `show` prints without `--json`. What the hub says goes through
181/// [`shown`]: a repository's names, description and README are anyone's
182/// text.
183fn show_text(info: &RepoInfo, readme: Option<&Readme>) -> String {
184 let mut out = format!(
185 "{}/{} ({})\n",
186 shown(&info.owner),
187 shown(&info.name),
188 if info.private { "private" } else { "public" }
189 );
190 if !info.description.is_empty() {
191 out.push_str(&format!("{}\n", shown(&info.description)));
192 }
193 out.push_str(&format!(
194 "Default branch: {}\n",
195 shown(&info.default_branch)
196 ));
197 if let Some(counts) = &info.counts {
198 out.push_str(&format!(
199 "Stars: {} · Forks: {} · Watchers: {} · Open issues: {} · Open requests: {}\n",
200 counts.stars, counts.forks, counts.watchers, counts.open_issues, counts.open_requests
201 ));
202 }
203 if !info.topics.is_empty() {
204 out.push_str(&format!("Topics: {}\n", shown(&info.topics.join(", "))));
205 }
206 if let Some(upstream) = &info.fork_of {
207 out.push_str(&format!(
208 "Forked from: {}/{}\n",
209 shown(&upstream.owner),
210 shown(&upstream.name)
211 ));
212 }
213 if let Some(mirror) = &info.mirror {
214 out.push_str(&format!(
215 "Mirror: {} ({})\n",
216 shown(&mirror.url),
217 shown(mirror.outcome.as_deref().unwrap_or("not synced yet"))
218 ));
219 }
220 out.push_str(&format!(
221 "Clone: braid hub clone {}/{}\n",
222 shown(&info.owner),
223 shown(&info.name)
224 ));
225 match readme {
226 Some(readme) => {
227 out.push_str(&format!(
228 "\n{}:\n\n{}",
229 shown(&readme.path),
230 shown_lines(&readme.markdown)
231 ));
232 if readme.truncated {
233 out.push_str("\n[The README goes on: the hub shows only its start.]");
234 }
235 }
236 None => out.push_str("\nNo README."),
237 }
238 out.trim_end().to_owned()
239}
240
241pub(crate) fn ls(cli: &Cli, args: &LsArgs) -> Result<ExitCode> {
242 let (hub, repo) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
243 let path = route_path(args.path.as_deref().unwrap_or(""));
244 let reference = args.reference.as_deref();
245 asking(|| {
246 let first = contents(&hub, &repo, &path, reference, &[("text", "false")])?;
247 let found = match first {
248 Contents::Dir(dir) => Contents::Dir(whole_dir(&hub, &repo, &path, dir)?),
249 file => file,
250 };
251 let value =
252 serde_json::to_value(&found).map_err(|err| HubError::Protocol(err.to_string()))?;
253 print(cli, &value, || ls_text(&found)).map_err(io_error)
254 })
255}
256
257/// `dir`, the first page of a directory, with the entries of every page
258/// after it.
259fn whole_dir(
260 hub: &HttpHub,
261 repo: &RepoPath,
262 path: &str,
263 mut dir: Directory,
264) -> Result<Directory, HubError> {
265 // The pages after the first ask for the changeset the first one read,
266 // so that a landing meanwhile does not mix two revisions.
267 let at = dir.changeset.to_hex();
268 for _ in 0..MAX_PAGES {
269 let Some(after) = dir.next.take() else {
270 return Ok(dir);
271 };
272 let page = contents(hub, repo, path, Some(&at), &[("after", &after)])?;
273 let Contents::Dir(page) = page else {
274 return Err(HubError::Protocol(
275 "a directory's next page is not a directory".to_owned(),
276 ));
277 };
278 dir.entries.extend(page.entries);
279 dir.next = page.next;
280 }
281 Err(HubError::Protocol(format!(
282 "the directory has more than {MAX_PAGES} pages: list a directory below it, or use braid hub api"
283 )))
284}
285
286/// One line of `ls`: kind, size and name, a directory's name ending in `/`.
287/// The name goes through [`shown`]: it may hold any byte but `/` and NUL,
288/// and a line break in it would print an entry the directory does not
289/// hold.
290fn entry_line(entry: &DirEntry) -> String {
291 let size = entry
292 .size
293 .map_or_else(|| "-".to_owned(), |size| size.to_string());
294 let slash = if entry.kind == "tree" { "/" } else { "" };
295 format!(
296 "{:<10} {:>10} {}{slash}",
297 shown(&entry.kind),
298 size,
299 shown(&entry.name)
300 )
301}
302
303/// What `ls` prints without `--json`.
304fn ls_text(found: &Contents) -> String {
305 match found {
306 Contents::Dir(dir) => dir
307 .entries
308 .iter()
309 .map(entry_line)
310 .collect::<Vec<_>>()
311 .join("\n"),
312 Contents::File(file) => entry_line(&DirEntry {
313 name: file.path.clone(),
314 raw_name: None,
315 kind: file.kind.clone(),
316 id: file.id.clone(),
317 size: file.size,
318 }),
319 }
320}
321
322pub(crate) fn cat(cli: &Cli, args: &CatArgs) -> Result<ExitCode> {
323 let (hub, repo) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
324 let path = route_path(&args.path);
325 if path.is_empty() {
326 anyhow::bail!("give the path of a file; braid hub ls lists a directory");
327 }
328 let reference = args.reference.as_deref();
329 if cli.json {
330 let found = match contents(&hub, &repo, &path, reference, &[]) {
331 Ok(Contents::Dir(_)) => return Ok(a_directory(&args.path)),
332 other => other,
333 };
334 return asking(|| {
335 let value: Value =
336 serde_json::to_value(found?).map_err(|err| HubError::Protocol(err.to_string()))?;
337 print_json(&value).map_err(io_error)
338 });
339 }
340 let route = format!("{}/raw/{path}{}", repo.api_path(), query(reference, &[]));
341 let mut out = std::io::stdout().lock();
342 let sent = hub.get_to(&route, &mut out);
343 // A directory has no bytes: say so, as ls would show it.
344 if let Err(HubError::Api { status: 404, .. }) = &sent
345 && let Ok(Contents::Dir(_)) = contents(&hub, &repo, &path, reference, &[("text", "false")])
346 {
347 return Ok(a_directory(&args.path));
348 }
349 asking(|| {
350 sent?;
351 out.flush().map_err(HubError::Io)
352 })
353}
354
355/// What `cat` says of a directory, and its exit status: refused.
356fn a_directory(path: &str) -> ExitCode {
357 eprintln!("braid: error: {path:?} is a directory: braid hub ls lists it");
358 ExitCode::from(REFUSED)
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 #[test]
366 fn routes_and_queries_are_encoded() {
367 assert_eq!(route_path("/src/main.rs/"), "src/main.rs");
368 assert_eq!(route_path("a b/100%.txt"), "a%20b/100%25.txt");
369 assert_eq!(query(None, &[]), "");
370 assert_eq!(query(Some("release/1.0"), &[]), "?ref=release/1.0");
371 assert_eq!(
372 query(Some("a&b c+d"), &[("text", "false")]),
373 "?ref=a%26b%20c%2Bd&text=false"
374 );
375 let line = entry_line(&DirEntry {
376 name: "src".into(),
377 raw_name: None,
378 kind: "tree".into(),
379 id: String::new(),
380 size: None,
381 });
382 assert_eq!(line, "tree - src/");
383 let odd = entry_line(&DirEntry {
384 name: "a\nfile 1 b\x1b[2J".into(),
385 raw_name: None,
386 kind: "file".into(),
387 id: String::new(),
388 size: Some(1),
389 });
390 assert_eq!(odd, r"file 1 a\nfile 1 b\u{1b}[2J");
391 assert_eq!(
392 shown_lines("\x1b[1m# T\r\n\tx\x07\n"),
393 "\\u{1b}[1m# T\\r\n\tx\\u{7}\n"
394 );
395 }
396}