Elffuss BraidHub

utopia-ia/elffuss-braid public

52e22f93c9da · 47.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! BraidHub from the client's side (`docs/hub.md`, section 13): `braid
5//! login` and `logout`, `braid hub publish`, `clone`, `fetch`, `status`,
6//! `whoami` and `autopublish`, and what `land`, `update` and `change create
7//! --land` do in a repository linked to a hub.
8//!
9//! - [`creds`]: hub URLs and tokens, from `hub.json` and the environment.
10//! - [`link`]: `.braid/hub`, which links a repository to its hub.
11//! - [`remote`]: the trait the transfer logic talks to, and its errors;
12//! [`http`] speaks it over HTTP.
13//! - [`transfer`], [`fetch`], [`publish`](mod@publish), [`land`]: moving
14//! history.
15//! - [`device`]: waiting for a device-flow sign-in; [`status`]: how
16//! branches compare.
17//! - [`browse`], [`history`], [`explore`], [`social`], [`issue`],
18//! [`inbox`], [`fork`], [`request`], [`github`] and [`settings`]: reading
19//! a repository without cloning it, finding repositories, stars,
20//! watching and following, issues, the inbox, forks, change requests,
21//! GitHub sync and settings; [`social_common`]: what they share; [`api`]:
22//! any route of the API.
23
24pub(crate) mod api;
25pub(crate) mod browse;
26pub(crate) mod creds;
27pub(crate) mod device;
28pub(crate) mod explore;
29pub(crate) mod fetch;
30pub(crate) mod fork;
31pub(crate) mod github;
32pub(crate) mod history;
33pub(crate) mod http;
34pub(crate) mod inbox;
35pub(crate) mod issue;
36pub(crate) mod land;
37pub(crate) mod link;
38pub(crate) mod publish;
39pub(crate) mod remote;
40pub(crate) mod request;
41#[cfg(test)]
42mod resilience_tests;
43pub(crate) mod settings;
44pub(crate) mod social;
45pub(crate) mod social_common;
46pub(crate) mod status;
47#[cfg(test)]
48pub(crate) mod testing;
49pub(crate) mod transfer;
50
51use std::fs;
52use std::io;
53use std::path::{Path, PathBuf};
54use std::process::ExitCode;
55
56use anyhow::{Context, Result, bail};
57use braid_hubproto::api::RepoCreate;
58use braid_hubproto::names::is_repo_name;
59use braid_hubproto::{RepoPath, Token};
60use braid_repo::{Repo, WorkspaceLink};
61use braid_wc::Workspace;
62use clap::{Args, Subcommand};
63use serde_json::{Value, json};
64
65use crate::work::{branches, count, hex, short};
66use crate::{Cli, open_repo, print_json};
67use creds::{Credentials, HubEnv, Saved, TokenSource};
68use fetch::{Fetched, Outcome, RefFetched, is_tag};
69use http::HttpHub;
70use link::Link;
71use remote::{HubError, Remote};
72
73/// The long help of `login`.
74pub(crate) const LOGIN_HELP: &str =
75 "Sign in to a hub with GitHub's device flow, run through the hub, so that
76no browser is needed on this machine: braid prints a web address and a code
77on standard error; open the address anywhere, enter the code and approve.
78braid polls the hub until then, at the interval it asks for, and saves the
79token it gets.
80
81The token is saved in hub.json in braid's configuration directory
82($XDG_CONFIG_HOME/braid, or ~/.config/braid), which only you can read, and
83that hub becomes the one `braid hub publish` and `braid hub clone` use. The
84token reads, writes and lands on every repository the account can, for 90
85days. BRAID_TOKEN and BRAID_HUB_URL take precedence over the file: an agent
86or CI job can set them instead of signing in.
87
88The hub is --hub, else BRAID_HUB_URL, else the hub signed in to last, else
89https://braidhub.elffuss.com. Only https:// is taken, and http:// to this
90machine.
91
92With --json it prints hub, login and expires.";
93
94/// The long help of `logout`.
95pub(crate) const LOGOUT_HELP: &str =
96 "Revoke the token saved for a hub, on the hub when it can be reached, and
97delete it here. BRAID_TOKEN is left alone: unset it yourself.
98
99With --json it prints hub, signed_in (whether a token was saved), revoked
100(whether the hub revoked it) and detail (why it could not, or null).";
101
102/// The long help of `hub publish`.
103pub(crate) const PUBLISH_HELP: &str =
104 "Create the repository on the hub signed in to, upload every branch and
105tag, and link the repository to it: .braid/hub names the hub and the
106repository, and from then on `braid land`, `braid update` and `braid change
107create --land` go through the hub.
108
109NAME defaults to the name of the repository's directory, made valid: 1 to
110100 ASCII letters, digits, '.', '_' and '-'. The repository is private
111unless --public. --mirror names a git repository the hub publishes the
112default branch to after each landing, with the account's GitHub access.
113
114What the branches and tags reach is uploaded, less what the hub has, in
115requests no larger than the hub takes (it says so, at most 256 MiB), or
116than BRAID_HUB_MAX_BODY bytes, for a proxy in front of the hub that takes
117less; and each ref is created on the hub at its head.
118A ref that names no changeset, such as an annotated tag imported from git,
119cannot be created through the hub protocol: it is reported and skipped. If
120an upload fails, run the command again: in a linked repository it uploads
121what the hub lacks and creates the refs it misses.
122
123With --json it prints hub, repo, url (the repository's address on the hub,
124<hub>/<owner>/<name>), created (whether the repository was made now),
125objects and bytes (what was uploaded), refs (each with name, id, outcome,
126head_before and head) and skipped (each with name and reason).";
127
128/// The long help of `hub clone`.
129pub(crate) const CLONE_HELP: &str =
130 "Make a repository in DIR (default: NAME, in the current directory) from
131OWNER/NAME on the hub, linked to it, with every branch and tag, and a
132first workspace in .braid/work/<name> on the hub's default branch, named by
133--workspace, or else after the branch.
134
135--paths takes path prefixes: only the trees under them come, with the
136directories on the way to them. Such a sparse repository serves `braid
137cat-object`, `braid log` and `braid change create --land`, but holds no
138workspace, since a workspace is a whole checkout. Give DIR before --paths.
139
140The hub is BRAID_HUB_URL, else the hub signed in to last, else
141https://braidhub.elffuss.com. A public repository needs no sign-in.
142
143With --json it prints hub, repo, root, paths, objects, refs (as `braid hub
144fetch` prints them) and workspace (name, path, branch, base and files, or
145null).";
146
147/// The long help of `hub fetch`.
148pub(crate) const FETCH_HELP: &str =
149 "Bring the hub's branches and tags into the linked repository. A local
150branch moves to the hub's head when it does not exist yet, or when its head
151is on the first-parent chain of the hub's; a branch with changesets the hub
152does not have stays where it is, and is reported as ahead or diverged. A
153tag is created, and never moved. remote/hub/<ref> records where each of the
154hub's refs was seen, so `braid log remote/hub/main` shows the hub's main
155even when the local one was kept back. Tags that name no changeset are
156skipped: the hub protocol carries changesets only.
157
158`braid land` and `braid update` fetch by themselves in a linked repository.
159
160With --json it prints hub, repo, seq (the hub's op log sequence number),
161objects (how many came), operation (the local op log operation that moved
162refs, or null) and refs, each with name, hub, before, after and outcome:
163created, moved, same, ahead, diverged, or skipped with a reason.";
164
165/// The long help of `hub status`.
166pub(crate) const STATUS_HELP: &str =
167 "Show the hub and the repository this one is linked to, who is signed in,
168and how each branch compares with the hub's: same; behind, when the hub's
169has changesets on top of this one (`braid hub fetch` brings them in);
170ahead, when this one has changesets the hub lacks (`braid land` from a
171workspace on the branch sends them); or diverged. A branch only the hub has
172is behind, and one only this repository has is ahead.
173
174A repository with a mirror shows where the hub publishes its default
175branch, and how the last sync ended: diverged means someone pushed to the
176mirror directly, and the hub's owner takes those commits in on the hub.
177
178With --json it prints hub, repo, paths, login (null when not signed in),
179token (environment, file or null), mirror (url, last_sync, outcome and
180detail, or null), seq (the hub's op log sequence number) and branches, each
181with name, local, hub and state.";
182
183/// The long help of `hub whoami`.
184pub(crate) const WHOAMI_HELP: &str =
185 "Say who is signed in to the hub, as the hub sees the token: the account's
186login and when the token expires (GET /v1/me). The exit status is 1 when no
187token is saved for the hub and BRAID_TOKEN is not set for it, or when the
188hub refuses the token because it expired or was revoked: then `braid login`
189is needed. It is 3 when braid cannot tell, because the hub cannot be reached
190or failed, or its answer is not one: then signing in again would not help.
191
192The hub is the one `braid login` signs in to: --hub, else BRAID_HUB_URL,
193else the hub signed in to last, else https://braidhub.elffuss.com.
194
195With --json it prints hub, login, name (or null), expires and token (where
196the token came from: environment or file).";
197
198/// The long help of `hub autopublish`.
199pub(crate) const AUTOPUBLISH_HELP: &str =
200 "Say, or record, whether coding agents publish the new projects they start
201for you to the hub, privately, so that agents on your other machines can
202work on them too. With no argument it prints on, off or unset; on or off
203records the answer, and prints it. The answer holds for every project and
204every hub, and is kept in hub.json, next to the tokens.
205
206braid never publishes by itself: an agent reads the answer, and runs `braid
207hub publish` when it is on (the hub's guide for agents, /agents.md, says
208when).
209
210With --json it prints autopublish: on, off or unset.";
211
212/// `login` and `logout`.
213#[derive(Debug, Args)]
214pub(crate) struct LoginArgs {
215 /// The hub (default: BRAID_HUB_URL, else the hub signed in to last,
216 /// else the public hub).
217 #[arg(long, value_name = "URL")]
218 pub(crate) hub: Option<String>,
219}
220
221/// `braid hub`.
222#[derive(Debug, Subcommand)]
223pub(crate) enum HubAction {
224 /// Create the repository on the hub, upload every branch and tag, and
225 /// link this repository to it.
226 #[command(long_about = PUBLISH_HELP)]
227 Publish(PublishArgs),
228 /// Make a repository from one on the hub, linked to it.
229 #[command(long_about = CLONE_HELP)]
230 Clone(CloneArgs),
231 /// Bring the hub's branches and tags in, moving local branches forward.
232 #[command(long_about = FETCH_HELP)]
233 Fetch,
234 /// Show the link, who is signed in, and how each branch compares.
235 #[command(long_about = STATUS_HELP)]
236 Status,
237 /// Say who is signed in to the hub (exit status 1 when no one is).
238 #[command(long_about = WHOAMI_HELP)]
239 Whoami(LoginArgs),
240 /// Say, or record, whether agents publish the new projects they start.
241 #[command(long_about = AUTOPUBLISH_HELP)]
242 Autopublish(AutopublishArgs),
243 /// Show a repository on the hub: its description, default branch,
244 /// counts and README.
245 Show(browse::ShowArgs),
246 /// List a directory of a repository on the hub, without cloning it.
247 Ls(browse::LsArgs),
248 /// Print a file of a repository on the hub, without cloning it.
249 Cat(browse::CatArgs),
250 /// Show the changesets of a branch on the hub, newest first.
251 Log(history::LogArgs),
252 /// Show what a changeset on the hub changed.
253 Diff(history::DiffArgs),
254 /// Find public repositories on the hub.
255 Explore(explore::ExploreArgs),
256 /// Show an account on the hub: its repositories, stars and follows.
257 User(explore::UserArgs),
258 /// Star a repository.
259 Star(social::StarArgs),
260 /// Take back a star.
261 Unstar(social::UnstarArgs),
262 /// List the repositories you, or an account, starred.
263 Stars(social::StarsArgs),
264 /// Watch a repository: all of it, what you take part in, or nothing.
265 Watch(social::WatchArgs),
266 /// Stop watching a repository: back to what you take part in.
267 Unwatch(social::UnwatchArgs),
268 /// Follow an account.
269 Follow(social::FollowArgs),
270 /// Stop following an account.
271 Unfollow(social::UnfollowArgs),
272 /// List, show, open, comment on and close a repository's issues.
273 Issue(issue::IssueArgs),
274 /// List, create and delete a repository's labels.
275 Label(issue::LabelArgs),
276 /// Show your notifications; mark them read or done; mute a thread.
277 Inbox(inbox::InboxArgs),
278 /// Fork a repository into your account.
279 Fork(fork::ForkArgs),
280 /// Bring what the upstream of a fork landed into the fork.
281 SyncFork(fork::SyncForkArgs),
282 /// Show your jobs, such as forks being made, or wait for one.
283 Jobs(fork::JobsArgs),
284 /// Open, review, update and land change requests.
285 #[command(long_about = request::REQUEST_HELP)]
286 Request(request::RequestArgs),
287 /// Grant the hub GitHub access, and sync your GitHub repositories to
288 /// it.
289 Github(github::GithubArgs),
290 /// Show or change a repository's settings.
291 Settings(settings::SettingsArgs),
292 /// Block an account from your repositories, or from one of them.
293 Block(settings::BlockArgs),
294 /// Lift a block.
295 Unblock(settings::UnblockArgs),
296 /// Show or change your account's settings.
297 Account(settings::AccountArgs),
298 /// Send a request to the hub's API and print its answer.
299 #[command(long_about = api::API_HELP)]
300 Api(api::ApiArgs),
301}
302
303/// `hub autopublish`.
304#[derive(Debug, Args)]
305pub(crate) struct AutopublishArgs {
306 /// Record the answer (default: print it).
307 #[arg(value_enum)]
308 pub(crate) answer: Option<Switch>,
309}
310
311/// An answer to `hub autopublish`.
312#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
313pub(crate) enum Switch {
314 /// Agents publish the new projects they start, privately.
315 On,
316 /// Agents publish only when asked.
317 Off,
318}
319
320/// `hub publish`.
321#[derive(Debug, Args)]
322pub(crate) struct PublishArgs {
323 /// The repository's name on the hub (default: the directory's name,
324 /// made valid).
325 pub(crate) name: Option<String>,
326 /// Let anyone read it.
327 #[arg(long)]
328 pub(crate) public: bool,
329 /// A description, for people.
330 #[arg(long, value_name = "TEXT")]
331 pub(crate) description: Option<String>,
332 /// A git repository the hub publishes the default branch to after each
333 /// landing.
334 #[arg(long, value_name = "URL")]
335 pub(crate) mirror: Option<String>,
336}
337
338/// `hub clone`.
339#[derive(Debug, Args)]
340pub(crate) struct CloneArgs {
341 // Not named `repo`: that is the id of the global --repo.
342 /// The repository: OWNER/NAME.
343 #[arg(value_name = "OWNER/NAME")]
344 pub(crate) source: String,
345 /// The directory to make it in, which must not exist or be empty
346 /// (default: NAME).
347 pub(crate) dir: Option<PathBuf>,
348 /// Take only the trees under these path prefixes.
349 #[arg(long, value_name = "PREFIX", num_args = 1..)]
350 pub(crate) paths: Vec<String>,
351}
352
353pub(crate) fn hub(cli: &Cli, action: &HubAction) -> Result<ExitCode> {
354 match action {
355 HubAction::Publish(args) => publish(cli, args),
356 HubAction::Clone(args) => clone(cli, args),
357 HubAction::Fetch => fetch_command(cli),
358 HubAction::Status => status_command(cli),
359 HubAction::Whoami(args) => whoami(cli, args),
360 HubAction::Autopublish(args) => autopublish(cli, args),
361 HubAction::Show(args) => browse::show(cli, args),
362 HubAction::Ls(args) => browse::ls(cli, args),
363 HubAction::Cat(args) => browse::cat(cli, args),
364 HubAction::Log(args) => history::log(cli, args),
365 HubAction::Diff(args) => history::diff(cli, args),
366 HubAction::Explore(args) => explore::explore(cli, args),
367 HubAction::User(args) => explore::user(cli, args),
368 HubAction::Star(args) => social::star(cli, args),
369 HubAction::Unstar(args) => social::unstar(cli, args),
370 HubAction::Stars(args) => social::stars(cli, args),
371 HubAction::Watch(args) => social::watch(cli, args),
372 HubAction::Unwatch(args) => social::unwatch(cli, args),
373 HubAction::Follow(args) => social::follow(cli, args),
374 HubAction::Unfollow(args) => social::unfollow(cli, args),
375 HubAction::Issue(args) => issue::issue(cli, args),
376 HubAction::Label(args) => issue::label(cli, args),
377 HubAction::Inbox(args) => inbox::inbox(cli, args),
378 HubAction::Fork(args) => fork::fork(cli, args),
379 HubAction::SyncFork(args) => fork::sync_fork(cli, args),
380 HubAction::Jobs(args) => fork::jobs(cli, args),
381 HubAction::Request(args) => request::request(cli, args),
382 HubAction::Github(args) => github::github(cli, args),
383 HubAction::Settings(args) => settings::settings(cli, args),
384 HubAction::Block(args) => settings::block(cli, args),
385 HubAction::Unblock(args) => settings::unblock(cli, args),
386 HubAction::Account(args) => settings::account(cli, args),
387 HubAction::Api(args) => api::api(cli, args),
388 }
389}
390
391/// A client for the hub at `url`, with the token the environment or the
392/// credentials file give for it, if any.
393fn client(env: &HubEnv, url: &str) -> Result<(HttpHub, TokenSource)> {
394 let creds = env.credentials()?;
395 let (token, source) = creds::token_for(env, &creds, url)?;
396 let hub = HttpHub::new(url, token)?
397 .with_max_body(env.max_body()?)
398 .with_source(source)
399 .with_withheld(creds::withheld_for(env, &creds, url));
400 Ok((hub, source))
401}
402
403/// A client for the hub a repository is linked to.
404pub(crate) fn connect(link: &Link) -> Result<HttpHub> {
405 Ok(client(&HubEnv::from_process(), &link.url)?.0)
406}
407
408/// The hub `repo` lands on: its link, unless `local` or `BRAID_HUB=off`
409/// keeps the command in this repository.
410pub(crate) fn linked(repo: &Repo, local: bool) -> Result<Option<Link>> {
411 if local || HubEnv::from_process().hub_off()? {
412 return Ok(None);
413 }
414 Link::read(repo)
415}
416
417/// The link of a repository that must have one.
418fn require_link(repo: &Repo) -> Result<Link> {
419 Link::read(repo)?.context(
420 "this repository is not linked to a hub: `braid hub publish` puts it on one, and `braid hub clone` makes a linked one",
421 )
422}
423
424/// ` --hub <url>`, or nothing for the hub used by default.
425fn hub_flag(url: &str) -> String {
426 if url == braid_hubproto::DEFAULT_HUB_URL {
427 String::new()
428 } else {
429 format!(" --hub {url}")
430 }
431}
432
433pub(crate) fn login(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> {
434 let env = HubEnv::from_process();
435 let path = env.credentials_path()?;
436 let mut creds = Credentials::load(&path)?;
437 let url = creds::hub_url(&env, &creds, args.hub.as_deref())?;
438 let hub = HttpHub::new(&url, None)?;
439 let start = hub.device_start()?;
440 eprintln!(
441 "To sign in to {url}, open {} and enter the code {}",
442 remote::shown(&start.verification_uri),
443 remote::shown(&start.user_code)
444 );
445 eprintln!(
446 "Waiting for the approval; the code expires in {}.",
447 count(start.expires_in.div_ceil(60), "minute")
448 );
449 let signed = device::wait_for_approval(&hub, &start, std::thread::sleep)?;
450 let replaced = creds.hubs.insert(
451 url.clone(),
452 Saved {
453 token: signed.token.expose(),
454 login: signed.login.clone(),
455 expires: signed.expires.clone(),
456 },
457 );
458 creds.default = Some(url.clone());
459 creds.save(&path)?;
460 if env.token.is_some() {
461 eprintln!("braid: note: BRAID_TOKEN is set, and commands use it rather than this token");
462 }
463 // The token this one replaces is revoked, so that signing in again
464 // leaves no live token behind; one the hub refuses is gone already.
465 let revoked_before = match replaced {
466 Some(old) if old.token != signed.token.expose() => match revoke_token(&url, &old) {
467 Ok(()) => true,
468 Err(err) => {
469 if !err
470 .downcast_ref::<HubError>()
471 .is_some_and(HubError::unauthorized)
472 {
473 eprintln!(
474 "braid: note: the token saved before for {url} could not be revoked ({err:#}); it stops working when it expires"
475 );
476 }
477 false
478 }
479 },
480 _ => false,
481 };
482 if cli.json {
483 print_json(&json!({
484 "hub": url,
485 "login": signed.login,
486 "expires": signed.expires,
487 }))?;
488 } else {
489 println!(
490 "Signed in to {url} as {}; the token expires {}",
491 remote::shown(&signed.login),
492 remote::shown(&signed.expires)
493 );
494 if revoked_before {
495 println!("The token saved before was revoked on the hub.");
496 }
497 }
498 Ok(ExitCode::SUCCESS)
499}
500
501pub(crate) fn logout(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> {
502 let env = HubEnv::from_process();
503 let path = env.credentials_path()?;
504 let mut creds = Credentials::load(&path)?;
505 let url = creds::hub_url(&env, &creds, args.hub.as_deref())?;
506 if env.token.is_some() {
507 eprintln!("braid: note: BRAID_TOKEN is set; logout leaves it alone");
508 }
509 let Some(saved) = creds.hubs.remove(&url) else {
510 if cli.json {
511 print_json(&json!({
512 "hub": url,
513 "signed_in": false,
514 "revoked": false,
515 "detail": null,
516 }))?;
517 } else {
518 println!("Not signed in to {url}: no token is saved for it");
519 }
520 return Ok(ExitCode::SUCCESS);
521 };
522 let revoked = revoke(&url, &saved);
523 if creds.default.as_deref() == Some(url.as_str()) {
524 creds.default = None;
525 }
526 creds.save(&path)?;
527 if cli.json {
528 print_json(&json!({
529 "hub": url,
530 "signed_in": true,
531 "revoked": revoked.is_ok(),
532 "detail": revoked.as_ref().err(),
533 }))?;
534 } else {
535 match &revoked {
536 Ok(()) => {
537 println!("Signed out of {url}: the hub revoked the token, and it was deleted here")
538 }
539 Err(why) => println!(
540 "Signed out of {url}: the token was deleted here, but the hub did not revoke it ({why}); it stops working when it expires{}",
541 if saved.expires.is_empty() {
542 String::new()
543 } else {
544 format!(", {}", saved.expires)
545 }
546 ),
547 }
548 }
549 Ok(ExitCode::SUCCESS)
550}
551
552fn whoami(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> {
553 let env = HubEnv::from_process();
554 let creds = env.credentials()?;
555 let url = creds::hub_url(&env, &creds, args.hub.as_deref())?;
556 let (token, source) = creds::token_for(&env, &creds, &url)?;
557 if token.is_none() {
558 match creds::withheld_for(&env, &creds, &url) {
559 Some(meant) => bail!(
560 "no one is signed in to {url}: BRAID_TOKEN is for {meant}; set BRAID_HUB_URL={url} to use it with this hub, or run `braid login{}`",
561 hub_flag(&url)
562 ),
563 None => bail!(
564 "no one is signed in to {url}: run `braid login{}`, or set BRAID_TOKEN",
565 hub_flag(&url)
566 ),
567 }
568 }
569 let hub = HttpHub::new(&url, token)?.with_source(source);
570 let me = match hub.me() {
571 Ok(me) => me,
572 Err(HubError::Api { status: 401, body }) => match source {
573 TokenSource::Environment => bail!(
574 "the hub at {url} refused BRAID_TOKEN ({}): it expired or was revoked; set another, or unset it and run `braid login{}`",
575 remote::shown(&body.detail),
576 hub_flag(&url)
577 ),
578 _ => bail!(
579 "the hub at {url} refused the token saved for it ({}): it expired or was revoked; run `braid login{}`",
580 remote::shown(&body.detail),
581 hub_flag(&url)
582 ),
583 },
584 Err(err @ HubError::Refused { .. }) => return Err(err.into()),
585 // Neither yes nor no: the hub did not say whether the token is
586 // good, so signing in again would not help. Its own exit status
587 // keeps `braid login` for when it does.
588 Err(err) => {
589 eprintln!(
590 "braid: error: cannot tell who is signed in to {url}: {err}; try again once the hub answers"
591 );
592 return Ok(ExitCode::from(CANNOT_TELL));
593 }
594 };
595 let expires = me.token.as_ref().map(|info| info.expires.clone());
596 if cli.json {
597 print_json(&json!({
598 "hub": url,
599 "login": me.login,
600 "name": me.name,
601 "expires": expires,
602 "token": source.code(),
603 }))?;
604 return Ok(ExitCode::SUCCESS);
605 }
606 let from = match source {
607 TokenSource::Environment => " (BRAID_TOKEN)",
608 _ => "",
609 };
610 let login = remote::shown(&me.login);
611 match expires {
612 Some(expires) => println!(
613 "Signed in to {url} as {login}{from}; the token expires {}",
614 remote::shown(&expires)
615 ),
616 None => println!("Signed in to {url} as {login}{from}"),
617 }
618 Ok(ExitCode::SUCCESS)
619}
620
621/// The exit status of `hub whoami` when the hub did not say whether the
622/// token is good: it could not be reached, failed, or did not answer as
623/// the protocol says.
624const CANNOT_TELL: u8 = 3;
625
626fn autopublish(cli: &Cli, args: &AutopublishArgs) -> Result<ExitCode> {
627 let env = HubEnv::from_process();
628 let creds = match args.answer {
629 Some(answer) => {
630 let path = env.credentials_path()?;
631 let mut creds = Credentials::load(&path)?;
632 creds.autopublish = Some(answer == Switch::On);
633 creds.save(&path)?;
634 creds
635 }
636 None => env.credentials()?,
637 };
638 let answer = match creds.autopublish {
639 Some(true) => "on",
640 Some(false) => "off",
641 None => "unset",
642 };
643 if cli.json {
644 print_json(&json!({ "autopublish": answer }))?;
645 } else {
646 println!("{answer}");
647 }
648 Ok(ExitCode::SUCCESS)
649}
650
651/// Revokes a saved token on its hub, saying why it could not.
652fn revoke(url: &str, saved: &Saved) -> Result<(), String> {
653 revoke_token(url, saved).map_err(|err| format!("{err:#}"))
654}
655
656/// Revokes a saved token on its hub: `GET /v1/me` names its id, and
657/// `DELETE /v1/tokens/{id}` revokes it.
658fn revoke_token(url: &str, saved: &Saved) -> Result<()> {
659 let token = Token::parse(&saved.token)
660 .map_err(|_| anyhow::anyhow!("the saved token is not a braid hub token"))?;
661 let own_id = token.id().to_owned();
662 let hub = HttpHub::new(url, Some(token))?;
663 let me = hub.me()?;
664 let id = me.token.map_or(own_id, |info| info.id);
665 hub.delete_token(&id)?;
666 Ok(())
667}
668
669/// A repository name made from `text`, such as a directory's name: every
670/// character other than ASCII letters, digits, `.`, `_` and `-` becomes
671/// `-`, a run of `-` one, and a leading `.` or `-`, a trailing `-` and a
672/// trailing `.git` go; at most 100 characters stay.
673pub(crate) fn repo_name_from(text: &str) -> String {
674 let mut name = String::new();
675 for c in text.chars() {
676 let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
677 c
678 } else {
679 '-'
680 };
681 if !(c == '-' && name.ends_with('-')) {
682 name.push(c);
683 }
684 }
685 let mut name = name.trim_start_matches(['.', '-']).to_owned();
686 loop {
687 let trimmed = name.trim_end_matches('-').len();
688 name.truncate(trimmed);
689 if name.to_ascii_lowercase().ends_with(".git") {
690 name.truncate(name.len() - 4);
691 } else {
692 break;
693 }
694 }
695 // Only ASCII is left, so this cuts between characters.
696 name.truncate(100);
697 name
698}
699
700fn publish(cli: &Cli, args: &PublishArgs) -> Result<ExitCode> {
701 let repo = open_repo(cli)?;
702 let env = HubEnv::from_process();
703 let existing = Link::read(&repo)?;
704 let creds = env.credentials()?;
705 let url = match &existing {
706 Some(link) => link.url.clone(),
707 None => creds::hub_url(&env, &creds, None)?,
708 };
709 let (token, _) = creds::token_for(&env, &creds, &url)?;
710 if token.is_none() {
711 bail!(
712 "publishing needs signing in to {url}: run `braid login{}`, or set BRAID_TOKEN",
713 hub_flag(&url)
714 );
715 }
716 if let Some(mirror) = &args.mirror
717 && let Some((_, rest)) = mirror.split_once("://")
718 && rest
719 .split('/')
720 .next()
721 .is_some_and(|host| host.contains('@'))
722 {
723 bail!(
724 "the mirror URL holds a user name or password: give it without, as the hub pushes with the account's GitHub access"
725 );
726 }
727 let hub = HttpHub::new(&url, token)?.with_max_body(env.max_body()?);
728 let (link, created) = match existing {
729 Some(link) => {
730 if args.public || args.description.is_some() || args.mirror.is_some() {
731 bail!(
732 "this repository is published already, as {} on {}: --public, --description and --mirror apply only when it is created",
733 link.repo,
734 link.url
735 );
736 }
737 if let Some(name) = &args.name
738 && *name != link.repo.name
739 {
740 bail!(
741 "this repository is published already, as {} on {}",
742 link.repo,
743 link.url
744 );
745 }
746 (link, false)
747 }
748 None => {
749 let name = match &args.name {
750 Some(name) if is_repo_name(name) => name.clone(),
751 Some(name) => bail!(
752 "{name:?} is not a repository name: 1 to 100 of letters, digits, '.', '_' and '-', not starting with '.' or ending with \".git\""
753 ),
754 None => {
755 let root =
756 fs::canonicalize(repo.root()).unwrap_or_else(|_| repo.root().to_path_buf());
757 let dir = root
758 .file_name()
759 .map(|name| name.to_string_lossy().into_owned())
760 .unwrap_or_default();
761 let name = repo_name_from(&dir);
762 if !is_repo_name(&name) {
763 bail!(
764 "cannot make a repository name from the directory's name {dir:?}: give NAME"
765 );
766 }
767 name
768 }
769 };
770 let made = hub.create_repo(&RepoCreate {
771 name: name.clone(),
772 private: !args.public,
773 description: args.description.clone().unwrap_or_default(),
774 import: None,
775 mirror: args.mirror.clone(),
776 });
777 let info = match made {
778 Ok(info) => info,
779 Err(HubError::Api { status: 409, body }) if body.error == "exists" => {
780 taken_up(&hub, &name)?
781 }
782 Err(err) if err.may_have_happened() => {
783 return Err(anyhow::Error::new(err).context(format!(
784 "the hub may have made {name} before its answer was lost: run `braid hub publish` again, which takes it up if it holds nothing yet"
785 )));
786 }
787 Err(err) => return Err(err.into()),
788 };
789 let path = RepoPath::new(&info.owner, &info.name)
790 .context("the hub named the new repository in a way braid cannot read")?;
791 let link = Link {
792 url: url.clone(),
793 repo: path,
794 paths: None,
795 };
796 link.write(&repo)?;
797 (link, true)
798 }
799 };
800 let remote = hub.repo(link.repo.clone());
801 let published = publish::publish_refs(&repo, &remote, &cli.agent).with_context(|| {
802 if created {
803 format!(
804 "{} was created on the hub and linked here, but not all of it is there: run `braid hub publish` again",
805 link.repo
806 )
807 } else {
808 format!("cannot publish to {}", link.repo)
809 }
810 })?;
811 // Where the hub's refs are now, for `braid hub status`.
812 fetch::fetch(&repo, &remote, &link, &cli.agent, None)?;
813
814 let address = format!("{}/{}", link.url, link.repo);
815 if cli.json {
816 print_json(&json!({
817 "hub": link.url,
818 "repo": link.repo.to_string(),
819 "url": address,
820 "created": created,
821 "objects": published.sent.objects,
822 "bytes": published.sent.bytes,
823 "refs": published.refs.iter().map(|r| json!({
824 "name": r.name,
825 "id": r.id.to_hex(),
826 "outcome": r.outcome,
827 "head_before": hex(r.head_before),
828 "head": hex(r.head),
829 })).collect::<Vec<_>>(),
830 "skipped": published.skipped.iter().map(|(name, reason)| json!({
831 "name": name,
832 "reason": reason,
833 })).collect::<Vec<_>>(),
834 }))?;
835 return Ok(ExitCode::SUCCESS);
836 }
837 println!(
838 "{} {} at {address}: {} uploaded ({})",
839 if created { "Published" } else { "Updated" },
840 link.repo,
841 count(published.sent.objects, "object"),
842 count(published.sent.bytes, "byte")
843 );
844 for r in &published.refs {
845 let what = match (r.outcome.as_str(), r.head_before) {
846 ("fast-forward", None) => format!("created at {}", r.id.short()),
847 ("fast-forward", Some(before)) => format!("{} -> {}", before.short(), r.id.short()),
848 ("already-applied", _) => format!("on the hub already, at {}", short(r.head)),
849 ("refused", _) if is_tag(&r.name) => format!(
850 "kept: the hub's names {}, and a tag never moves",
851 short(r.head)
852 ),
853 ("refused", _) => format!(
854 "refused: the hub's is at {}, which is not on this one's first-parent chain; `braid hub fetch` brings it in",
855 short(r.head)
856 ),
857 (other, _) => other.to_owned(),
858 };
859 println!(" {:<24} {what}", remote::shown(&r.name));
860 }
861 for (name, reason) in &published.skipped {
862 println!(" {:<24} skipped: {reason}", remote::shown(name));
863 }
864 if created {
865 println!(
866 "Linked: `braid land` and `braid update` go through the hub now (--local keeps them here)."
867 );
868 }
869 Ok(ExitCode::SUCCESS)
870}
871
872/// The caller's repository `name`, which the hub says exists already: one
873/// an earlier `braid hub publish` made before its answer was lost is taken
874/// up when the caller owns it and it holds no ref yet. Any other is
875/// refused, so that nothing is linked to, or uploaded into, a repository
876/// with a history of its own.
877fn taken_up(hub: &HttpHub, name: &str) -> Result<braid_hubproto::api::RepoInfo> {
878 let me = hub.me()?;
879 let path = RepoPath::new(&me.login, name)
880 .with_context(|| format!("the hub names the account {:?}", remote::shown(&me.login)))?;
881 let repository = hub.repo(path.clone());
882 let info = repository.info()?;
883 let refs = repository.refs()?;
884 if !info.owner.eq_ignore_ascii_case(&me.login) || !refs.refs.is_empty() {
885 bail!(
886 "{path} exists on the hub already{}: give another NAME, or, if it is yours and holds nothing you need, delete it on the hub first",
887 if refs.refs.is_empty() {
888 ""
889 } else {
890 ", with refs of its own"
891 }
892 );
893 }
894 Ok(info)
895}
896
897/// What `hub clone` did to the directory before making the repository.
898#[derive(Clone, Copy, Debug)]
899enum Made {
900 Created,
901 WasEmpty,
902}
903
904/// Makes `dir`, or checks that it is empty.
905fn prepare(dir: &Path) -> Result<Made> {
906 match fs::read_dir(dir) {
907 Ok(mut entries) => {
908 if entries.next().is_some() {
909 bail!("{} exists and is not empty", dir.display());
910 }
911 Ok(Made::WasEmpty)
912 }
913 Err(err) if err.kind() == io::ErrorKind::NotFound => {
914 fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
915 Ok(Made::Created)
916 }
917 Err(err) => Err(err).with_context(|| format!("cannot read {}", dir.display())),
918 }
919}
920
921/// Takes back what a failed clone made in `dir`.
922fn unmake(dir: &Path, made: Made) {
923 match made {
924 Made::Created => {
925 let _ = fs::remove_dir_all(dir);
926 }
927 Made::WasEmpty => {
928 if let Ok(entries) = fs::read_dir(dir) {
929 for entry in entries.flatten() {
930 let path = entry.path();
931 let _ = match entry.file_type() {
932 Ok(kind) if kind.is_dir() => fs::remove_dir_all(&path),
933 _ => fs::remove_file(&path),
934 };
935 }
936 }
937 }
938 }
939}
940
941/// A workspace a clone made.
942struct NewWorkspace {
943 name: String,
944 path: PathBuf,
945 branch: String,
946 base: Option<braid_format::ObjectId>,
947 files: usize,
948}
949
950/// The branch a clone's first workspace tracks: the hub's default branch
951/// when the repository has it, or has no branch at all; else `main`,
952/// `master`, its only branch, or its first.
953fn first_branch(names: &[&str], default_branch: &str) -> String {
954 if names.contains(&default_branch)
955 || (names.is_empty() && braid_git::is_branch_name(default_branch))
956 {
957 return default_branch.to_owned();
958 }
959 ["main", "master"]
960 .into_iter()
961 .find(|preferred| names.contains(preferred))
962 .or_else(|| names.first().copied())
963 .unwrap_or("main")
964 .to_owned()
965}
966
967/// Makes a clone's first workspace, the way `braid workspace add` makes
968/// one: in `.braid/work/<name>`, at the head of the branch it tracks.
969fn first_workspace(cli: &Cli, repo: &Repo, default_branch: &str) -> Result<NewWorkspace> {
970 let refs = repo.store().refs()?;
971 let branch = first_branch(&branches(&refs), default_branch);
972 let name = match &cli.workspace {
973 Some(name) => name.clone(),
974 None if WorkspaceLink::is_valid_name(&branch) => branch.clone(),
975 None => "work".to_owned(),
976 };
977 let base = refs.get(&branch);
978 let dir = Workspace::default_dir(repo, &name);
979 let (workspace, files) = Workspace::create(repo, &name, &dir, base, &branch)?;
980 Ok(NewWorkspace {
981 name,
982 path: workspace.dir().to_path_buf(),
983 branch,
984 base,
985 files,
986 })
987}
988
989fn clone(cli: &Cli, args: &CloneArgs) -> Result<ExitCode> {
990 let path: RepoPath = args.source.parse()?;
991 let paths = if args.paths.is_empty() {
992 None
993 } else {
994 Some(
995 args.paths
996 .iter()
997 .map(|path| link::path_prefix(path))
998 .collect::<Result<Vec<_>>>()?,
999 )
1000 };
1001 let env = HubEnv::from_process();
1002 let creds = env.credentials()?;
1003 let url = creds::hub_url(&env, &creds, None)?;
1004 let (hub, _) = client(&env, &url)?;
1005 let remote = hub.repo(path.clone());
1006 // Asked first, so that nothing is made for a repository the hub does
1007 // not show.
1008 let info = remote.info()?;
1009 let dir = args
1010 .dir
1011 .clone()
1012 .unwrap_or_else(|| PathBuf::from(&path.name));
1013 let made = prepare(&dir)?;
1014 let link = Link {
1015 url: url.clone(),
1016 repo: path,
1017 paths,
1018 };
1019 let cloned = (|| -> Result<_> {
1020 let repo = Repo::init_with(&dir, cli.store_options())?;
1021 link.write(&repo)?;
1022 let fetched = fetch::fetch(&repo, &remote, &link, &cli.agent, None)?;
1023 let workspace = match link.paths {
1024 Some(_) => None,
1025 None => Some(first_workspace(cli, &repo, &info.default_branch)?),
1026 };
1027 let root = fs::canonicalize(repo.root()).unwrap_or_else(|_| repo.root().to_path_buf());
1028 Ok((root, fetched, workspace))
1029 })();
1030 let (root, fetched, workspace) = match cloned {
1031 Ok(cloned) => cloned,
1032 Err(err) => {
1033 unmake(&dir, made);
1034 return Err(err);
1035 }
1036 };
1037 if cli.json {
1038 print_json(&json!({
1039 "hub": link.url,
1040 "repo": link.repo.to_string(),
1041 "root": root.to_string_lossy(),
1042 "paths": link.paths,
1043 "objects": fetched.objects,
1044 "refs": refs_json(&fetched),
1045 "workspace": workspace.as_ref().map(|ws| json!({
1046 "name": ws.name,
1047 "path": ws.path.to_string_lossy(),
1048 "branch": ws.branch,
1049 "base": hex(ws.base),
1050 "files": ws.files,
1051 })),
1052 }))?;
1053 return Ok(ExitCode::SUCCESS);
1054 }
1055 let branch_count = fetched
1056 .refs
1057 .iter()
1058 .filter(|r| !is_tag(&r.name) && r.after.is_some())
1059 .count();
1060 let tag_count = fetched
1061 .refs
1062 .iter()
1063 .filter(|r| is_tag(&r.name) && r.after.is_some())
1064 .count();
1065 println!(
1066 "Cloned {} from {} into {}: {}, {} and {}",
1067 link.repo,
1068 link.url,
1069 root.display(),
1070 count(fetched.objects, "object"),
1071 count(branch_count as u64, "branch"),
1072 count(tag_count as u64, "tag")
1073 );
1074 print_skipped(&fetched);
1075 match (&workspace, &link.paths) {
1076 (Some(ws), _) => println!(
1077 "Workspace {} in {} on {} at {}, {}",
1078 ws.name,
1079 ws.path.display(),
1080 remote::shown(&ws.branch),
1081 short(ws.base),
1082 count(ws.files as u64, "file")
1083 ),
1084 (None, Some(paths)) => println!(
1085 "Sparse: only the trees under {} came, so no workspace was made (a workspace is a whole checkout)",
1086 remote::shown(&paths.join(", "))
1087 ),
1088 (None, None) => {}
1089 }
1090 Ok(ExitCode::SUCCESS)
1091}
1092
1093/// The refs of a fetch, as JSON.
1094fn refs_json(fetched: &Fetched) -> Vec<Value> {
1095 fetched
1096 .refs
1097 .iter()
1098 .map(|r| {
1099 let mut value = json!({
1100 "name": r.name,
1101 "hub": r.hub.to_hex(),
1102 "before": hex(r.before),
1103 "after": hex(r.after),
1104 "outcome": r.outcome.code(),
1105 });
1106 if let Outcome::Skipped(reason) = r.outcome {
1107 value["reason"] = Value::String(reason.to_owned());
1108 }
1109 value
1110 })
1111 .collect()
1112}
1113
1114/// What became of a ref, for people.
1115fn describe(r: &RefFetched) -> String {
1116 match r.outcome {
1117 Outcome::Created => format!("created at {}", r.hub.short()),
1118 Outcome::Moved => format!("{} -> {}", short(r.before), r.hub.short()),
1119 Outcome::Same => format!("up to date at {}", r.hub.short()),
1120 Outcome::Ahead => format!(
1121 "kept at {}: it has changesets the hub does not have, on top of the hub's {}; `braid land` from a workspace on it sends them",
1122 short(r.before),
1123 r.hub.short()
1124 ),
1125 Outcome::Diverged if is_tag(&r.name) => format!(
1126 "kept at {}: the hub's names {}, and a tag never moves",
1127 short(r.before),
1128 r.hub.short()
1129 ),
1130 Outcome::Diverged => format!(
1131 "kept at {}: it and the hub's, at {}, each have changesets the other does not",
1132 short(r.before),
1133 r.hub.short()
1134 ),
1135 Outcome::Skipped(reason) => format!("skipped: {reason}"),
1136 }
1137}
1138
1139fn print_skipped(fetched: &Fetched) {
1140 for r in &fetched.refs {
1141 if matches!(r.outcome, Outcome::Skipped(_)) {
1142 println!(" {:<24} {}", remote::shown(&r.name), describe(r));
1143 }
1144 }
1145}
1146
1147fn fetch_command(cli: &Cli) -> Result<ExitCode> {
1148 let repo = open_repo(cli)?;
1149 let link = require_link(&repo)?;
1150 let hub = connect(&link)?;
1151 let remote = hub.repo(link.repo.clone());
1152 let fetched = fetch::fetch(&repo, &remote, &link, &cli.agent, None)?;
1153 if cli.json {
1154 print_json(&json!({
1155 "hub": link.url,
1156 "repo": link.repo.to_string(),
1157 "seq": fetched.seq,
1158 "objects": fetched.objects,
1159 "operation": fetched.operation,
1160 "refs": refs_json(&fetched),
1161 }))?;
1162 return Ok(ExitCode::SUCCESS);
1163 }
1164 let changed: Vec<&RefFetched> = fetched
1165 .refs
1166 .iter()
1167 .filter(|r| r.outcome != Outcome::Same)
1168 .collect();
1169 if fetched.objects == 0 && changed.is_empty() {
1170 println!("Up to date with {}", link.repo);
1171 return Ok(ExitCode::SUCCESS);
1172 }
1173 println!(
1174 "Fetched {} from {}",
1175 count(fetched.objects, "object"),
1176 link.repo
1177 );
1178 for r in changed {
1179 println!(" {:<24} {}", remote::shown(&r.name), describe(r));
1180 }
1181 Ok(ExitCode::SUCCESS)
1182}
1183
1184fn status_command(cli: &Cli) -> Result<ExitCode> {
1185 let repo = open_repo(cli)?;
1186 let link = require_link(&repo)?;
1187 let env = HubEnv::from_process();
1188 let (hub, source) = client(&env, &link.url)?;
1189 let login = if hub.has_token() {
1190 Some(hub.me().map(|me| me.login))
1191 } else {
1192 None
1193 };
1194 let remote = hub.repo(link.repo.clone());
1195 let info = remote.info()?;
1196 let refs = remote.refs()?;
1197 let states = status::compare(&repo, &refs.refs)?;
1198 if cli.json {
1199 print_json(&json!({
1200 "hub": link.url,
1201 "repo": link.repo.to_string(),
1202 "paths": link.paths,
1203 "login": login.as_ref().and_then(|login| login.as_ref().ok()),
1204 "token": source.code(),
1205 "mirror": info.mirror,
1206 "seq": refs.seq,
1207 "branches": states.iter().map(|s| json!({
1208 "name": s.name,
1209 "local": hex(s.local),
1210 "hub": hex(s.hub),
1211 "state": s.state.code(),
1212 })).collect::<Vec<_>>(),
1213 }))?;
1214 return Ok(ExitCode::SUCCESS);
1215 }
1216 match &link.paths {
1217 Some(paths) => println!(
1218 "Linked to {} on {}, sparse: {}",
1219 link.repo,
1220 link.url,
1221 paths.join(", ")
1222 ),
1223 None => println!("Linked to {} on {}", link.repo, link.url),
1224 }
1225 let from = match source {
1226 TokenSource::Environment => " (BRAID_TOKEN)",
1227 _ => "",
1228 };
1229 match &login {
1230 Some(Ok(login)) => println!("Signed in as {}{from}", remote::shown(login)),
1231 Some(Err(err)) => println!("Signed in, but {err}"),
1232 None => println!(
1233 "Not signed in: public repositories only (`braid login{}` signs in)",
1234 hub_flag(&link.url)
1235 ),
1236 }
1237 if let Some(mirror) = &info.mirror {
1238 let state = match (&mirror.outcome, &mirror.last_sync) {
1239 (Some(outcome), Some(when)) => format!("{outcome} at {when}"),
1240 (Some(outcome), None) => outcome.clone(),
1241 _ => "not synced yet".to_owned(),
1242 };
1243 println!(
1244 "Mirror of {}: {} ({})",
1245 remote::shown(&info.default_branch),
1246 remote::shown(&mirror.url),
1247 remote::shown(&state)
1248 );
1249 if let Some(detail) = &mirror.detail {
1250 println!(" {}", remote::shown(detail));
1251 }
1252 }
1253 for s in &states {
1254 let heads = match (s.local, s.hub) {
1255 (Some(here), Some(there)) if here == there => here.short(),
1256 (here, there) => format!("here {}, hub {}", short(here), short(there)),
1257 };
1258 println!(
1259 " {:<24} {:<9} {heads}",
1260 remote::shown(&s.name),
1261 s.state.code()
1262 );
1263 }
1264 Ok(ExitCode::SUCCESS)
1265}
1266
1267#[cfg(test)]
1268mod tests {
1269 use super::*;
1270
1271 #[test]
1272 fn names_from_directories() {
1273 for (dir, name) in [
1274 ("demo", "demo"),
1275 ("My Project", "My-Project"),
1276 (".hidden", "hidden"),
1277 ("repo.git", "repo"),
1278 ("a.git.git", "a"),
1279 ("x y", "x-y"),
1280 ("ñandú", "and"),
1281 ("trailing-", "trailing"),
1282 ] {
1283 assert_eq!(repo_name_from(dir), name, "{dir}");
1284 assert!(is_repo_name(name));
1285 }
1286 assert_eq!(repo_name_from(&"a".repeat(150)).len(), 100);
1287 assert_eq!(repo_name_from("???"), "");
1288 }
1289
1290 #[test]
1291 fn the_first_workspace_tracks_the_default_branch() {
1292 assert_eq!(first_branch(&["dev", "trunk"], "trunk"), "trunk");
1293 assert_eq!(first_branch(&[], "trunk"), "trunk");
1294 assert_eq!(first_branch(&["dev", "master"], "trunk"), "master");
1295 assert_eq!(first_branch(&["dev", "main", "master"], "trunk"), "main");
1296 assert_eq!(first_branch(&["dev", "zeta"], "trunk"), "dev");
1297 }
1298}