Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 14.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The hub commands of the `braid` binary where no hub answers: what is
5//! refused before anything goes over the network, what a linked repository
6//! does when its hub cannot be reached, and how `--local` and
7//! `BRAID_HUB=off` keep landing and updating local. Every test gets a
8//! configuration directory of its own, and a token is never printed.
9
10use std::fs;
11use std::net::TcpListener;
12use std::path::{Path, PathBuf};
13use std::process::{Command, Output};
14
15use serde_json::Value;
16
17/// A home, a configuration directory and a repository, in a temporary
18/// directory.
19struct Place {
20 _temp: tempfile::TempDir,
21 base: PathBuf,
22 root: PathBuf,
23}
24
25impl Place {
26 fn new() -> Place {
27 let temp = tempfile::tempdir().unwrap();
28 let base = fs::canonicalize(temp.path()).unwrap();
29 let root = base.join("repo");
30 let place = Place {
31 _temp: temp,
32 base,
33 root,
34 };
35 let out = place.braid(&place.base, &["init", "repo"], &[]);
36 assert!(out.status.success(), "{}", text(&out.stderr));
37 place
38 }
39
40 /// Runs braid in `dir`, with `env` on top of a clean environment.
41 fn braid(&self, dir: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
42 let mut command = Command::new(env!("CARGO_BIN_EXE_braid"));
43 command
44 .current_dir(dir)
45 .args(args)
46 .env("HOME", self.base.join("home"))
47 .env("XDG_CONFIG_HOME", self.base.join("config"))
48 .env("BRAID_AUTHOR", "Ada <ada@example.org>")
49 .env("BRAID_AGENT", "tester")
50 .env_remove("BRAID_TOKEN")
51 .env_remove("BRAID_HUB_URL")
52 .env_remove("BRAID_HUB");
53 for (key, value) in env {
54 command.env(key, value);
55 }
56 command.output().unwrap()
57 }
58
59 /// Links the repository to a hub on this machine where nothing
60 /// listens, and returns its URL.
61 fn link_to_nowhere(&self) -> String {
62 let port = TcpListener::bind("127.0.0.1:0")
63 .unwrap()
64 .local_addr()
65 .unwrap()
66 .port();
67 let url = format!("http://127.0.0.1:{port}");
68 fs::write(
69 self.root.join(".braid/hub"),
70 format!("{{\"url\": \"{url}\", \"repo\": \"ada/demo\"}}\n"),
71 )
72 .unwrap();
73 url
74 }
75
76 /// Makes a workspace and commits a file in it.
77 fn workspace_with_a_commit(&self, name: &str) -> PathBuf {
78 let out = self.braid(&self.root, &["workspace", "add", name], &[]);
79 assert!(out.status.success(), "{}", text(&out.stderr));
80 let dir = self.root.join(".braid/work").join(name);
81 self.commit(&dir, "a.txt", "one\n");
82 dir
83 }
84
85 fn commit(&self, dir: &Path, path: &str, content: &str) {
86 fs::write(dir.join(path), content).unwrap();
87 let out = self.braid(dir, &["commit", "-m", path], &[]);
88 assert!(out.status.success(), "{}", text(&out.stderr));
89 }
90}
91
92fn text(bytes: &[u8]) -> String {
93 String::from_utf8_lossy(bytes).into_owned()
94}
95
96/// Asserts that `out` failed with status 1, nothing on standard output,
97/// and an error that says `expected`.
98fn fails_with(out: &Output, expected: &str) {
99 let err = text(&out.stderr);
100 assert_eq!(out.status.code(), Some(1), "{err}");
101 assert!(out.stdout.is_empty(), "{}", text(&out.stdout));
102 assert!(err.starts_with("braid: error: "), "{err}");
103 assert!(err.contains(expected), "expected {expected:?} in {err}");
104}
105
106fn json(out: &Output) -> Value {
107 assert!(out.status.success(), "{}", text(&out.stderr));
108 serde_json::from_slice(&out.stdout).unwrap()
109}
110
111#[test]
112fn refused_before_any_request() {
113 let p = Place::new();
114 fails_with(
115 &p.braid(&p.root, &["hub", "status"], &[]),
116 "not linked to a hub",
117 );
118 fails_with(
119 &p.braid(&p.root, &["hub", "fetch"], &[]),
120 "not linked to a hub",
121 );
122 // Publishing needs a token, and nothing is linked without one.
123 fails_with(
124 &p.braid(&p.root, &["hub", "publish"], &[]),
125 "publishing needs signing in",
126 );
127 assert!(!p.root.join(".braid/hub").exists());
128 // A token is never sent in clear to another machine.
129 fails_with(
130 &p.braid(&p.base, &["login", "--hub", "http://hub.example.org"], &[]),
131 "would send the token in clear",
132 );
133 fails_with(
134 &p.braid(
135 &p.root,
136 &["hub", "publish"],
137 &[("BRAID_HUB_URL", "http://hub.example.org")],
138 ),
139 "would send the token in clear",
140 );
141 fails_with(
142 &p.braid(&p.base, &["hub", "clone", "nobody"], &[]),
143 "is not a repository",
144 );
145 fails_with(
146 &p.braid(
147 &p.base,
148 &["hub", "clone", "ada/demo", "--paths", "../etc"],
149 &[],
150 ),
151 "is not a path prefix",
152 );
153 // A malformed token is refused without being repeated.
154 let secret = "brd_aaaaaaaa_this-is-not-base32-and-must-not-show";
155 fails_with(
156 &p.braid(&p.root, &["hub", "publish"], &[("BRAID_TOKEN", secret)]),
157 "BRAID_TOKEN is not a braid hub token",
158 );
159 let out = p.braid(&p.root, &["hub", "publish"], &[("BRAID_TOKEN", secret)]);
160 assert!(!text(&out.stderr).contains("must-not-show"));
161 // Logging out of a hub never signed in to says so.
162 let out = p.braid(&p.base, &["logout", "--json"], &[]);
163 let value = json(&out);
164 assert_eq!(value["signed_in"], false);
165 assert_eq!(value["hub"], "https://braidhub.elffuss.com");
166 fails_with(
167 &p.braid(&p.base, &["hub", "whoami"], &[]),
168 "no one is signed in to https://braidhub.elffuss.com: run `braid login`, or set BRAID_TOKEN",
169 );
170 fails_with(
171 &p.braid(
172 &p.base,
173 &["hub", "whoami", "--hub", "http://localhost:1"],
174 &[],
175 ),
176 "run `braid login --hub http://localhost:1`",
177 );
178 fails_with(
179 &p.braid(
180 &p.root,
181 &["hub", "publish"],
182 &[
183 (
184 "BRAID_TOKEN",
185 "brd_aaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
186 ),
187 ("BRAID_HUB_MAX_BODY", "lots"),
188 ],
189 ),
190 "BRAID_HUB_MAX_BODY takes a number of bytes",
191 );
192}
193
194#[test]
195fn the_autopublish_answer_is_kept_for_every_project() {
196 let p = Place::new();
197 let ask = |args: &[&str]| -> String {
198 let out = p.braid(&p.base, args, &[]);
199 assert!(out.status.success(), "{}", text(&out.stderr));
200 text(&out.stdout)
201 };
202 assert_eq!(ask(&["hub", "autopublish"]), "unset\n");
203 let file = p.base.join("config/braid/hub.json");
204 assert!(!file.exists());
205 assert_eq!(ask(&["hub", "autopublish", "on"]), "on\n");
206 assert_eq!(ask(&["hub", "autopublish"]), "on\n");
207 let value = json(&p.braid(&p.root, &["hub", "autopublish", "--json"], &[]));
208 assert_eq!(value, serde_json::json!({ "autopublish": "on" }));
209 let value = json(&p.braid(&p.root, &["hub", "autopublish", "off", "--json"], &[]));
210 assert_eq!(value["autopublish"], "off");
211 let saved: Value = serde_json::from_slice(&fs::read(&file).unwrap()).unwrap();
212 assert_eq!(saved["autopublish"], false);
213 #[cfg(unix)]
214 {
215 use std::os::unix::fs::PermissionsExt;
216 let mode = fs::metadata(&file).unwrap().permissions().mode() & 0o777;
217 assert_eq!(mode, 0o600);
218 }
219 let out = p.braid(&p.base, &["hub", "autopublish", "maybe"], &[]);
220 assert_eq!(out.status.code(), Some(2), "{}", text(&out.stderr));
221 assert_eq!(ask(&["hub", "autopublish"]), "off\n");
222}
223
224/// The ```bash blocks and the code spans of a Markdown text: its lines that
225/// may hold commands.
226fn command_lines(text: &str) -> Vec<String> {
227 let mut lines = Vec::new();
228 let mut fenced = None;
229 let mut prose = Vec::new();
230 for line in text.lines() {
231 let trimmed = line.trim();
232 if trimmed.starts_with("```") {
233 fenced = match fenced {
234 None => Some(trimmed == "```bash"),
235 Some(_) => None,
236 };
237 continue;
238 }
239 match fenced {
240 Some(true) => lines.push(trimmed.to_owned()),
241 Some(false) => {}
242 None => prose.push(trimmed.to_owned()),
243 }
244 }
245 let prose = prose.join(" ");
246 lines.extend(prose.split('`').skip(1).step_by(2).map(str::to_owned));
247 lines
248}
249
250/// Whether the help `shown` lists `word` among its commands.
251fn lists_command(shown: &str, word: &str) -> bool {
252 shown
253 .lines()
254 .skip_while(|line| line.trim() != "Commands:")
255 .skip(1)
256 .take_while(|line| line.starts_with(" "))
257 .any(|line| line.split_whitespace().next() == Some(word))
258}
259
260/// Every braid command docs/hub-agents.md, the guide the hub serves at
261/// /agents.md, gives exists, with every flag it is given.
262#[test]
263fn every_braid_command_in_the_hub_guide_exists_with_its_flags() {
264 let guide =
265 fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/hub-agents.md"))
266 .unwrap();
267 let mut commands = Vec::new();
268 let mut flags = Vec::new();
269 for line in command_lines(&guide) {
270 let line = line.split(" #").next().unwrap();
271 for command in line.split(['|', '&', ';']).map(str::trim) {
272 if command.starts_with("braid ") {
273 commands.push(command.to_owned());
274 } else if command.starts_with("--") {
275 flags.push(command.split_whitespace().next().unwrap().to_owned());
276 }
277 }
278 }
279 assert!(commands.len() >= 12, "{commands:?}");
280 let help = |path: &[&str]| -> String {
281 let mut args = path.to_vec();
282 args.push("--help");
283 let out = Command::new(env!("CARGO_BIN_EXE_braid"))
284 .args(&args)
285 .output()
286 .unwrap();
287 assert!(
288 out.status.success(),
289 "braid {args:?}: {}",
290 text(&out.stderr)
291 );
292 text(&out.stdout)
293 };
294 let mut helps = String::new();
295 for command in &commands {
296 let words: Vec<&str> = command.split_whitespace().skip(1).collect();
297 if words == ["--version"] {
298 continue;
299 }
300 let mut path = vec![words[0]];
301 // Commands with subcommands of their own: the flags are those of
302 // the subcommand.
303 if ["hub", "change", "workspace", "git", "op", "agents"].contains(&words[0])
304 && words.get(1).is_some_and(|word| !word.starts_with('-'))
305 {
306 path.push(words[1]);
307 }
308 let mut shown = help(&path);
309 // A subcommand with commands of its own (`braid hub request
310 // create`): the flags are those of its command.
311 if path.len() == 2
312 && let Some(&word) = words.get(2)
313 && lists_command(&shown, word)
314 {
315 path.push(word);
316 shown = help(&path);
317 }
318 for word in &words[path.len()..] {
319 if word.starts_with('-') {
320 let flag = word.split('=').next().unwrap();
321 assert!(
322 shown.contains(flag),
323 "{command}: no {flag} in braid {path:?}"
324 );
325 }
326 }
327 helps.push_str(&shown);
328 }
329 // Flags the guide names on their own belong to the commands it gives.
330 assert!(flags.len() >= 3, "{flags:?}");
331 for flag in &flags {
332 assert!(
333 helps.contains(flag.as_str()),
334 "{flag} is no flag of the guide's commands"
335 );
336 }
337}
338
339#[test]
340fn a_linked_repository_goes_to_its_hub_unless_kept_local() {
341 let p = Place::new();
342 let url = p.link_to_nowhere();
343 let ws = p.workspace_with_a_commit("w1");
344
345 // Landing goes to the hub, which cannot be reached: nothing moves.
346 let out = p.braid(&ws, &["land", "--json"], &[]);
347 fails_with(&out, &format!("cannot reach the hub at {url}"));
348 let refs = json(&p.braid(&p.root, &["refs", "--json"], &[]));
349 assert_eq!(refs["refs"]["main"], Value::Null);
350
351 // BRAID_HUB=off and --local land here, as before.
352 let landed = json(&p.braid(&ws, &["land", "--json"], &[("BRAID_HUB", "off")]));
353 assert_eq!(landed["outcome"], "fast-forward");
354 for key in [
355 "branch",
356 "outcome",
357 "head_before",
358 "head",
359 "landed",
360 "merged_paths",
361 "operation",
362 "change",
363 "conflicts",
364 "next",
365 "base",
366 "updated_paths",
367 ] {
368 assert!(landed.get(key).is_some(), "{key}: {landed}");
369 }
370 p.commit(&ws, "b.txt", "two\n");
371 let landed = json(&p.braid(&ws, &["land", "--local", "--json"], &[]));
372 assert_eq!(landed["outcome"], "fast-forward");
373
374 // Updating fetches first, and says how to do without.
375 fails_with(&p.braid(&ws, &["update"], &[]), "--local");
376 let updated = json(&p.braid(&ws, &["update", "--local", "--json"], &[]));
377 assert_eq!(updated["outcome"], "up-to-date");
378 let out = p.braid(&ws, &["update"], &[("BRAID_HUB", "off")]);
379 assert!(out.status.success(), "{}", text(&out.stderr));
380
381 // change create --land too.
382 let file = p.base.join("c.txt");
383 fs::write(&file, "c\n").unwrap();
384 let set = format!("c.txt=@{}", file.display());
385 let create = [
386 "change", "create", "--base", "main", "--set", &set, "-m", "c", "--land", "main",
387 ];
388 fails_with(&p.braid(&p.root, &create, &[]), "cannot reach the hub");
389 let mut local = create.to_vec();
390 local.push("--local");
391 let made = json(&p.braid(&p.root, &local, &[]));
392 assert_eq!(made["land"]["outcome"], "fast-forward");
393
394 // A value of BRAID_HUB that means nothing is refused.
395 fails_with(
396 &p.braid(&ws, &["land"], &[("BRAID_HUB", "maybe")]),
397 "BRAID_HUB takes",
398 );
399
400 // The hub commands name the hub they cannot reach, and never the
401 // token they would have sent.
402 let token = "brd_aaaaaaaa_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
403 for args in [&["hub", "fetch"][..], &["hub", "status"]] {
404 let out = p.braid(&p.root, args, &[("BRAID_TOKEN", token)]);
405 fails_with(&out, &format!("cannot reach the hub at {url}"));
406 assert!(!text(&out.stderr).contains("bbbbbbbbbbbbbbbb"));
407 }
408}
409
410#[test]
411fn a_damaged_link_is_an_error_that_names_it() {
412 let p = Place::new();
413 fs::write(p.root.join(".braid/hub"), b"{\"url\": \"https://x\"}").unwrap();
414 let ws = p.workspace_with_a_commit("w1");
415 fails_with(&p.braid(&ws, &["land"], &[]), "is not a valid hub link");
416 // --local does not read it.
417 let out = p.braid(&ws, &["land", "--local"], &[]);
418 assert!(out.status.success(), "{}", text(&out.stderr));
419}