Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 20.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub github`: granting the hub GitHub access, and syncing your
5//! GitHub repositories to it (sections 2 and 23 of `docs/hub.md`).
6//!
7//! - `grant [--public-only]`: a device flow run through the hub, as `braid
8//! login` runs one: braid prints a web address and a code, and waits
9//! until you enter the code on GitHub and approve.
10//! - `repos [--refresh]`: the repositories you own on GitHub, each with
11//! the name it takes on the hub and whether it may be imported.
12//! - `sync (--all | FULL_NAME...)`: imports them, each kept as a mirror
13//! that follows GitHub, in a batch of jobs; `--wait` waits for the batch
14//! to end.
15//! - `status [BATCH]`, `cancel BATCH` and `retry BATCH FULL_NAME`: how a
16//! batch stands, cancelling what has not started, and importing again
17//! what failed or was skipped.
18//!
19//! Exit statuses as the other hub commands: 0 done, 1 refused (and, for a
20//! sync, anything that failed or was skipped), 3 when the hub could not be
21//! reached or failed.
22
23use std::collections::BTreeMap;
24use std::fmt::Write;
25use std::process::ExitCode;
26use std::thread::sleep;
27use std::time::Duration;
28
29use anyhow::{Result, bail};
30use braid_hubproto::api::DeviceStart;
31use braid_hubproto::onboard::{
32 self as proto, GithubRepos, GrantPoll, RepoPick, SyncBatch, SyncRequest, SyncStarted,
33};
34use clap::{Args, Subcommand};
35use serde_json::json;
36
37use super::creds::{self, HubEnv};
38use super::http::HttpHub;
39use super::remote::{HubError, shown};
40use super::social_common::{REFUSED, exit_for, idempotency_key, print};
41use crate::Cli;
42
43/// How long `sync --wait` waits between two looks at the batch.
44const POLL: Duration = Duration::from_millis(500);
45
46/// The long help of `hub github sync`.
47const SYNC_HELP: &str = "Import repositories you own on GitHub to the hub, each kept as a mirror
48that follows GitHub: what lands on the hub is pushed to GitHub, and what is
49pushed to GitHub is brought to the hub, merged when both moved (--follow
50ff-only brings it only when nothing landed on the hub meanwhile, --follow off
51never brings it). Name them as `braid hub github repos` lists them
52(OWNER/NAME), or ask for --all: every one that may be imported, most
53recently pushed first, as many as your account has room for.
54
55A repository takes its own name on the hub, unless --name OWNER/NAME=NEW
56gives another; a name that starts with '.' takes '_' instead. Private
57repositories stay private; public ones stay public, unless --all-private.
58--reserve-tdm reserves text and data mining of what is imported. An archived
59repository is imported without a mirror; an empty one is made empty, with
60its mirror set.
61
62The hub needs your GitHub access first: `braid hub github grant`. One sync
63runs at a time. With --wait, braid waits until every import ended, and the
64exit status is 1 when any failed or was skipped. With --json it prints the
65batch, its queued and skipped repositories, or with --wait the batch as it
66ended (as `braid hub github status --json`).";
67
68/// `hub github`.
69#[derive(Debug, Args)]
70pub(crate) struct GithubArgs {
71 #[command(subcommand)]
72 pub(crate) action: GithubAction,
73}
74
75/// What `hub github` does.
76#[derive(Debug, Subcommand)]
77pub(crate) enum GithubAction {
78 /// Grant the hub access to your GitHub repositories, with a code you
79 /// enter on GitHub.
80 Grant(GrantArgs),
81 /// List the repositories you own on GitHub, and what each would become
82 /// on the hub.
83 Repos(ReposArgs),
84 /// Import repositories you own on GitHub to the hub, each kept as a
85 /// mirror.
86 #[command(long_about = SYNC_HELP)]
87 Sync(SyncArgs),
88 /// Show how a sync stands: the latest, or BATCH.
89 Status(StatusArgs),
90 /// Cancel the imports of a sync that have not started.
91 Cancel(CancelArgs),
92 /// Import again a repository of a sync that failed or was skipped.
93 Retry(RetryArgs),
94}
95
96/// `hub github grant`.
97#[derive(Debug, Args)]
98pub(crate) struct GrantArgs {
99 /// Grant access to your public repositories only (GitHub's
100 /// public_repo), not your private ones (repo).
101 #[arg(long)]
102 pub(crate) public_only: bool,
103}
104
105/// `hub github repos`.
106#[derive(Debug, Args)]
107pub(crate) struct ReposArgs {
108 /// Ask GitHub again rather than take the hub's listing of the last ten
109 /// minutes (at most once a minute).
110 #[arg(long)]
111 pub(crate) refresh: bool,
112}
113
114/// `hub github sync`.
115#[derive(Debug, Args)]
116pub(crate) struct SyncArgs {
117 /// Every repository that may be imported, as many as there is room for.
118 #[arg(long, conflicts_with = "repos")]
119 pub(crate) all: bool,
120 /// The repositories to import: OWNER/NAME on GitHub.
121 #[arg(value_name = "FULL_NAME", required_unless_present = "all")]
122 pub(crate) repos: Vec<String>,
123 /// The name a repository takes on the hub: OWNER/NAME=NEW.
124 #[arg(long = "name", value_name = "FULL_NAME=NAME")]
125 pub(crate) names: Vec<String>,
126 /// Import public repositories as private too.
127 #[arg(long)]
128 pub(crate) all_private: bool,
129 /// Reserve text and data mining of the repositories imported.
130 #[arg(long)]
131 pub(crate) reserve_tdm: bool,
132 /// How each mirror takes in what is pushed to GitHub.
133 #[arg(long, value_name = "POLICY", default_value = "merge",
134 value_parser = [proto::FOLLOW_MERGE, proto::FOLLOW_FF_ONLY, proto::FOLLOW_OFF])]
135 pub(crate) follow: String,
136 /// Wait until every import ended.
137 #[arg(long)]
138 pub(crate) wait: bool,
139}
140
141/// `hub github status`.
142#[derive(Debug, Args)]
143pub(crate) struct StatusArgs {
144 /// The sync (default: the latest).
145 #[arg(value_name = "BATCH")]
146 pub(crate) batch: Option<String>,
147}
148
149/// `hub github cancel`.
150#[derive(Debug, Args)]
151pub(crate) struct CancelArgs {
152 /// The sync.
153 #[arg(value_name = "BATCH")]
154 pub(crate) batch: String,
155}
156
157/// `hub github retry`.
158#[derive(Debug, Args)]
159pub(crate) struct RetryArgs {
160 /// The sync.
161 #[arg(value_name = "BATCH")]
162 pub(crate) batch: String,
163 /// The repository to import again: OWNER/NAME on GitHub.
164 #[arg(value_name = "FULL_NAME")]
165 pub(crate) full_name: String,
166 /// The name it takes on the hub this time.
167 #[arg(long, value_name = "NAME")]
168 pub(crate) name: Option<String>,
169}
170
171pub(crate) fn github(cli: &Cli, args: &GithubArgs) -> Result<ExitCode> {
172 match &args.action {
173 GithubAction::Grant(args) => grant(cli, args),
174 GithubAction::Repos(args) => repos(cli, args),
175 GithubAction::Sync(args) => sync(cli, args),
176 GithubAction::Status(args) => status(cli, args),
177 GithubAction::Cancel(args) => cancel(cli, args),
178 GithubAction::Retry(args) => retry(cli, args),
179 }
180}
181
182/// The hub signed in to: BRAID_HUB_URL, else the hub signed in to last,
183/// else the public hub.
184fn signed_in_hub() -> Result<HttpHub> {
185 let env = HubEnv::from_process();
186 let creds = env.credentials()?;
187 let url = creds::hub_url(&env, &creds, None)?;
188 Ok(super::client(&env, &url)?.0)
189}
190
191/// What a command answers when the hub refused it or could not be
192/// reached: the error, and the exit status it calls for.
193fn failed(err: &HubError) -> ExitCode {
194 eprintln!("braid: error: {err}");
195 ExitCode::from(exit_for(err))
196}
197
198/// A batch id given on the command line, checked before it names a route:
199/// `b_` and 26 characters of `a-z 2-7`.
200fn batch_arg(id: &str) -> Result<&str> {
201 let valid = id.strip_prefix("b_").is_some_and(|rest| {
202 rest.len() == 26
203 && rest
204 .bytes()
205 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
206 });
207 if !valid {
208 bail!("{id:?} is not a sync's id: b_ and 26 characters of a-z and 2-7");
209 }
210 Ok(id)
211}
212
213/// `hub github grant`: starts the grant, prints where to approve it, and
214/// polls until GitHub says.
215fn grant(cli: &Cli, args: &GrantArgs) -> Result<ExitCode> {
216 let hub = signed_in_hub()?;
217 let scope = if args.public_only {
218 proto::SCOPE_PUBLIC
219 } else {
220 proto::SCOPE_PRIVATE
221 };
222 let body = json!({ "scope": scope });
223 let start: DeviceStart =
224 match hub.call_json("POST", "/v1/github/access/device", &[], Some(&body)) {
225 Ok(start) => start,
226 Err(err) => return Ok(failed(&err)),
227 };
228 eprintln!(
229 "To grant the hub access to your {} GitHub repositories, open {} and enter the code {}",
230 if args.public_only {
231 "public"
232 } else {
233 "private and public"
234 },
235 shown(&start.verification_uri),
236 shown(&start.user_code)
237 );
238 let mut interval = start.interval.max(1);
239 let mut waited = 0u64;
240 loop {
241 if waited >= start.expires_in {
242 bail!(
243 "the code expired before the grant was approved: run `braid hub github grant` again"
244 );
245 }
246 sleep(Duration::from_secs(interval));
247 waited = waited.saturating_add(interval);
248 let poll = json!({ "poll": start.poll });
249 match hub.call_json::<GrantPoll>("POST", "/v1/github/access/device/poll", &[], Some(&poll))
250 {
251 Ok(GrantPoll::Pending) => {}
252 Ok(GrantPoll::SlowDown { interval: asked }) => interval = asked.max(interval),
253 Ok(GrantPoll::Denied) => {
254 eprintln!("braid: error: the grant was denied on GitHub: nothing changed");
255 return Ok(ExitCode::from(REFUSED));
256 }
257 Ok(GrantPoll::Expired) => {
258 bail!(
259 "the code expired before the grant was approved: run `braid hub github grant` again"
260 )
261 }
262 Ok(GrantPoll::Ok { login, scope }) => {
263 let value = json!({ "login": login, "scope": scope });
264 print(cli, &value, || {
265 format!(
266 "GitHub access granted for {} ({}). `braid hub github repos` lists your repositories.",
267 shown(&login),
268 shown(&scope)
269 )
270 })?;
271 return Ok(ExitCode::SUCCESS);
272 }
273 // Asked to wait: wait as long as the hub says, then poll again.
274 Err(HubError::Api { status: 429, body }) => {
275 interval = body.retry_after.unwrap_or(interval).max(interval);
276 }
277 Err(err) => return Ok(failed(&err)),
278 }
279 }
280}
281
282/// A repository of a listing, in one line, for people: every field as the
283/// hub sent it, escaped.
284fn listed_line(repo: &proto::GithubRepo) -> String {
285 let mut marks = Vec::new();
286 if repo.private {
287 marks.push("private");
288 }
289 if repo.fork {
290 marks.push("fork");
291 }
292 if repo.archived {
293 marks.push("archived");
294 }
295 if repo.empty {
296 marks.push("empty");
297 }
298 let mut out = format!(
299 "{} {}",
300 if repo.eligible { "+" } else { "-" },
301 shown(&repo.full_name)
302 );
303 if !marks.is_empty() {
304 let _ = write!(out, " ({})", marks.join(", "));
305 }
306 let _ = write!(out, " -> {}", shown(&repo.hub_name));
307 if let Some(synced) = &repo.synced {
308 let _ = write!(out, " synced as {}", shown(synced));
309 } else if let Some(reason) = &repo.reason {
310 let _ = write!(out, " {}", shown(reason));
311 }
312 out
313}
314
315/// `hub github repos`.
316fn repos(cli: &Cli, args: &ReposArgs) -> Result<ExitCode> {
317 let hub = signed_in_hub()?;
318 let route = if args.refresh {
319 "/v1/github/repos?refresh=1"
320 } else {
321 "/v1/github/repos"
322 };
323 let listed: GithubRepos = match hub.call_json("GET", route, &[], None) {
324 Ok(listed) => listed,
325 Err(err) => return Ok(failed(&err)),
326 };
327 print(cli, &serde_json::to_value(&listed)?, || {
328 let mut out = String::new();
329 if listed.repos.is_empty() {
330 out.push_str("No repositories on GitHub that the access you granted shows.");
331 }
332 for repo in &listed.repos {
333 if !out.is_empty() {
334 out.push('\n');
335 }
336 out.push_str(&listed_line(repo));
337 }
338 let _ = write!(
339 out,
340 "\nRoom left on the hub: {} repositories, {} MiB.",
341 listed.quota.repos_left,
342 listed.quota.bytes_left >> 20
343 );
344 if listed.truncated {
345 out.push_str("\nGitHub has more: these are the most recently pushed.");
346 }
347 out
348 })?;
349 Ok(ExitCode::SUCCESS)
350}
351
352/// The names `--name FULL_NAME=NAME` gives, by full name.
353fn names_of(given: &[String]) -> Result<BTreeMap<String, String>> {
354 let mut names = BTreeMap::new();
355 for pair in given {
356 let Some((full_name, name)) = pair.split_once('=') else {
357 bail!("--name takes OWNER/NAME=NEW, not {pair:?}");
358 };
359 if !full_name.contains('/') || name.is_empty() {
360 bail!("--name takes OWNER/NAME=NEW, not {pair:?}");
361 }
362 names.insert(full_name.to_owned(), name.to_owned());
363 }
364 Ok(names)
365}
366
367/// A batch, in lines, for people: every field as the hub sent it, escaped.
368fn described(batch: &SyncBatch) -> String {
369 let counts = &batch.counts;
370 let mut out = format!(
371 "Sync {}: {}. {} imported, {} under way, {} queued, {} failed, {} skipped, {} cancelled.",
372 shown(&batch.batch),
373 shown(&batch.state),
374 counts.done,
375 counts.running + counts.waiting,
376 counts.queued,
377 counts.failed,
378 counts.skipped,
379 counts.cancelled
380 );
381 for item in &batch.repos {
382 let _ = write!(
383 out,
384 "\n {} -> {} {}",
385 shown(&item.full_name),
386 shown(&item.hub_name),
387 shown(&item.state)
388 );
389 if let Some(error) = &item.error {
390 let _ = write!(out, ": {}", shown(error));
391 }
392 }
393 out
394}
395
396/// Asks for the batch `id` until it ends.
397fn wait_for(hub: &HttpHub, id: &str) -> Result<SyncBatch, HubError> {
398 loop {
399 let batch: SyncBatch = hub.call_json("GET", &format!("/v1/github/sync/{id}"), &[], None)?;
400 if batch.state != proto::BATCH_RUNNING {
401 return Ok(batch);
402 }
403 sleep(POLL);
404 }
405}
406
407/// `hub github sync`.
408fn sync(cli: &Cli, args: &SyncArgs) -> Result<ExitCode> {
409 let request = SyncRequest {
410 all: args.all,
411 repos: args
412 .repos
413 .iter()
414 .map(|full_name| RepoPick::Name(full_name.clone()))
415 .collect(),
416 names: names_of(&args.names)?,
417 keep_public: !args.all_private,
418 reserve_tdm: args.reserve_tdm,
419 follow: args.follow.clone(),
420 };
421 for full_name in &args.repos {
422 if !full_name.contains('/') {
423 bail!("{full_name:?} is not OWNER/NAME on GitHub");
424 }
425 }
426 let hub = signed_in_hub()?;
427 let body = serde_json::to_value(&request)?;
428 // Sent again after a lost answer, the batch is not made twice.
429 let key = idempotency_key();
430 let started: SyncStarted = match hub.call_json(
431 "POST",
432 "/v1/github/sync",
433 &[("Idempotency-Key", &key)],
434 Some(&body),
435 ) {
436 Ok(started) => started,
437 Err(err) => return Ok(failed(&err)),
438 };
439 let Ok(id) = batch_arg(&started.batch) else {
440 return Ok(failed(&HubError::Protocol(format!(
441 "the hub named the sync {}, which is not a sync's id",
442 shown(&started.batch)
443 ))));
444 };
445 if !args.wait {
446 print(cli, &serde_json::to_value(&started)?, || {
447 let mut out = format!(
448 "Sync {id}: {} queued, {} skipped. `braid hub github status {id}` shows how it goes.",
449 started.queued.len(),
450 started.skipped.len()
451 );
452 for skipped in &started.skipped {
453 let _ = write!(
454 out,
455 "\n skipped {}: {}",
456 shown(&skipped.full_name),
457 shown(&skipped.reason)
458 );
459 }
460 out
461 })?;
462 return Ok(if started.skipped.is_empty() {
463 ExitCode::SUCCESS
464 } else {
465 ExitCode::from(REFUSED)
466 });
467 }
468 if !cli.json {
469 eprintln!(
470 "Sync {id}: {} queued, {} skipped; waiting for the imports.",
471 started.queued.len(),
472 started.skipped.len()
473 );
474 }
475 let batch = match wait_for(&hub, id) {
476 Ok(batch) => batch,
477 Err(err) => return Ok(failed(&err)),
478 };
479 print(cli, &serde_json::to_value(&batch)?, || described(&batch))?;
480 Ok(if batch.all_done() {
481 ExitCode::SUCCESS
482 } else {
483 ExitCode::from(REFUSED)
484 })
485}
486
487/// `hub github status`.
488fn status(cli: &Cli, args: &StatusArgs) -> Result<ExitCode> {
489 let route = match &args.batch {
490 Some(batch) => format!("/v1/github/sync/{}", batch_arg(batch)?),
491 None => "/v1/github/sync".to_owned(),
492 };
493 let hub = signed_in_hub()?;
494 let batch: SyncBatch = match hub.call_json("GET", &route, &[], None) {
495 Ok(batch) => batch,
496 Err(err) => return Ok(failed(&err)),
497 };
498 print(cli, &serde_json::to_value(&batch)?, || described(&batch))?;
499 Ok(ExitCode::SUCCESS)
500}
501
502/// `hub github cancel`.
503fn cancel(cli: &Cli, args: &CancelArgs) -> Result<ExitCode> {
504 let id = batch_arg(&args.batch)?;
505 let hub = signed_in_hub()?;
506 let batch: SyncBatch =
507 match hub.call_json("DELETE", &format!("/v1/github/sync/{id}"), &[], None) {
508 Ok(batch) => batch,
509 Err(err) => return Ok(failed(&err)),
510 };
511 print(cli, &serde_json::to_value(&batch)?, || described(&batch))?;
512 Ok(ExitCode::SUCCESS)
513}
514
515/// `hub github retry`.
516fn retry(cli: &Cli, args: &RetryArgs) -> Result<ExitCode> {
517 let id = batch_arg(&args.batch)?;
518 let hub = signed_in_hub()?;
519 let batch: SyncBatch = match hub.call_json("GET", &format!("/v1/github/sync/{id}"), &[], None) {
520 Ok(batch) => batch,
521 Err(err) => return Ok(failed(&err)),
522 };
523 let Some(item) = batch
524 .repos
525 .iter()
526 .find(|item| item.full_name.eq_ignore_ascii_case(&args.full_name))
527 else {
528 eprintln!(
529 "braid: error: {} is not a repository of sync {id}",
530 shown(&args.full_name)
531 );
532 return Ok(ExitCode::from(REFUSED));
533 };
534 let mut body = json!({ "github_id": item.github_id });
535 if let Some(name) = &args.name {
536 body["name"] = json!(name);
537 }
538 let started: SyncStarted = match hub.call_json(
539 "POST",
540 &format!("/v1/github/sync/{id}/retry"),
541 &[],
542 Some(&body),
543 ) {
544 Ok(started) => started,
545 Err(err) => return Ok(failed(&err)),
546 };
547 print(cli, &serde_json::to_value(&started)?, || {
548 let queued = started
549 .queued
550 .first()
551 .map_or_else(String::new, |queued| shown(&queued.hub_name));
552 format!(
553 "Importing {} again, as {queued}. `braid hub github status {id}` shows how it goes.",
554 shown(&args.full_name)
555 )
556 })?;
557 Ok(ExitCode::SUCCESS)
558}
559
560#[cfg(test)]
561mod tests {
562 use super::*;
563
564 #[test]
565 fn arguments_are_checked_before_they_name_a_route() {
566 assert!(batch_arg("b_abcdefghijklmnopqrstuvwxyz").is_ok());
567 for bad in ["", "b_", "j_abcdefghijklmnopqrstuvwxyz", "b_../../v1/x"] {
568 assert!(batch_arg(bad).is_err(), "{bad:?}");
569 }
570 let names = names_of(&["ada/.github=dotgithub".to_owned()]).unwrap();
571 assert_eq!(names["ada/.github"], "dotgithub");
572 assert!(names_of(&["demo=x".to_owned()]).is_err());
573 assert!(names_of(&["ada/demo=".to_owned()]).is_err());
574 assert!(names_of(&["ada/demo".to_owned()]).is_err());
575 }
576
577 #[test]
578 fn what_the_hub_says_reaches_the_terminal_escaped() {
579 let repo = proto::GithubRepo {
580 full_name: "ada/demo\u{1b}[2J".into(),
581 hub_name: "demo".into(),
582 private: true,
583 reason: Some("name taken\u{7}".into()),
584 ..proto::GithubRepo::default()
585 };
586 let line = listed_line(&repo);
587 assert!(line.starts_with("- ada/demo"), "{line:?}");
588 assert!(
589 !line.contains('\u{1b}') && !line.contains('\u{7}'),
590 "{line:?}"
591 );
592 let batch = SyncBatch {
593 batch: "b_x\u{1b}]0;t\u{7}".into(),
594 state: "done".into(),
595 repos: vec![proto::BatchItem {
596 full_name: "ada/demo".into(),
597 hub_name: "demo".into(),
598 state: "failed".into(),
599 error: Some("no\u{1b}[31m".into()),
600 ..proto::BatchItem::default()
601 }],
602 ..SyncBatch::default()
603 };
604 let text = described(&batch);
605 assert!(
606 !text.contains('\u{1b}') && !text.contains('\u{7}'),
607 "{text:?}"
608 );
609 }
610}