| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `braid hub explore` and `user`: finding public repositories, and an |
| 5 | //! account's profile. |
| 6 | //! |
| 7 | //! Each is one request of section 16 of `docs/hub.md` (section 17 for an |
| 8 | //! account's stars and follows) to the hub signed in to: BRAID_HUB_URL, |
| 9 | //! else the hub signed in to last, else the public hub. Neither needs a |
| 10 | //! sign-in; with a token, an account's private repositories the token may |
| 11 | //! read are counted and listed as well. Exit statuses as the other hub |
| 12 | //! commands: 0 done, 1 refused, 3 when the hub could not be reached or |
| 13 | //! failed. |
| 14 | |
| 15 | use std::fmt::Write; |
| 16 | use std::process::ExitCode; |
| 17 | |
| 18 | use anyhow::{Result, bail}; |
| 19 | use braid_hubproto::cards::{RepoCard, RepoCards, UserCards}; |
| 20 | use braid_hubproto::explore::{self as proto, Profile}; |
| 21 | use braid_hubproto::names::is_owner; |
| 22 | use clap::{Args, ValueEnum}; |
| 23 | |
| 24 | use super::creds::{self, HubEnv}; |
| 25 | use super::http::HttpHub; |
| 26 | use super::remote::{HubError, shown}; |
| 27 | use super::social_common::{exit_for, print}; |
| 28 | use crate::Cli; |
| 29 | |
| 30 | /// The hub signed in to: BRAID_HUB_URL, else the hub signed in to last, |
| 31 | /// else the public hub; with the token saved for it, if any. |
| 32 | fn signed_in_hub() -> Result<HttpHub> { |
| 33 | let env = HubEnv::from_process(); |
| 34 | let creds = env.credentials()?; |
| 35 | let url = creds::hub_url(&env, &creds, None)?; |
| 36 | Ok(super::client(&env, &url)?.0) |
| 37 | } |
| 38 | |
| 39 | /// What a command answers when the hub refused it or could not be |
| 40 | /// reached: the error, and the exit status it calls for. |
| 41 | fn failed(err: &HubError) -> ExitCode { |
| 42 | eprintln!("braid: error: {err}"); |
| 43 | ExitCode::from(exit_for(err)) |
| 44 | } |
| 45 | |
| 46 | /// `text` as a value of a query string: letters, digits, `-._~` and `/` as |
| 47 | /// they are, and every other byte percent-encoded. |
| 48 | fn query_value(text: &str) -> String { |
| 49 | let mut out = String::with_capacity(text.len()); |
| 50 | for byte in text.bytes() { |
| 51 | if byte.is_ascii_alphanumeric() || b"-._~/".contains(&byte) { |
| 52 | out.push(char::from(byte)); |
| 53 | } else { |
| 54 | let _ = write!(out, "%{byte:02X}"); |
| 55 | } |
| 56 | } |
| 57 | out |
| 58 | } |
| 59 | |
| 60 | /// `route` with the query string of `pairs`, those with a value. |
| 61 | fn with_query(route: &str, pairs: &[(&str, Option<String>)]) -> String { |
| 62 | let mut out = route.to_owned(); |
| 63 | for (name, value) in pairs { |
| 64 | if let Some(value) = value { |
| 65 | out.push(if out.contains('?') { '&' } else { '?' }); |
| 66 | let _ = write!(out, "{name}={}", query_value(value)); |
| 67 | } |
| 68 | } |
| 69 | out |
| 70 | } |
| 71 | |
| 72 | /// A login given on the command line, checked as the hub checks it. |
| 73 | fn login_arg(login: &str) -> Result<String> { |
| 74 | if !is_owner(login) { |
| 75 | bail!( |
| 76 | "{login:?} is not a login: 1 to 39 letters, digits and hyphens, with no hyphen at either end and no two in a row" |
| 77 | ); |
| 78 | } |
| 79 | Ok(login.to_ascii_lowercase()) |
| 80 | } |
| 81 | |
| 82 | /// A count of things, as words: `1 star`, `3 stars`. |
| 83 | fn counted(n: u64, one: &str, many: &str) -> String { |
| 84 | format!("{n} {}", if n == 1 { one } else { many }) |
| 85 | } |
| 86 | |
| 87 | /// Repositories, a few lines each: the name, whether private, where it was |
| 88 | /// forked from, its stars and last landing, its description and topics; |
| 89 | /// `empty` when there are none, and how to ask for the next page. What the |
| 90 | /// hub says goes through [`shown`]: names, descriptions and topics are |
| 91 | /// anyone's text, and no control character of theirs reaches a terminal. |
| 92 | fn cards_text(cards: &RepoCards, empty: &str, more: &str) -> String { |
| 93 | let mut out = String::new(); |
| 94 | if cards.repos.is_empty() { |
| 95 | out.push_str(empty); |
| 96 | } |
| 97 | for card in &cards.repos { |
| 98 | if !out.is_empty() { |
| 99 | out.push('\n'); |
| 100 | } |
| 101 | out.push_str(&card_line(card)); |
| 102 | if !card.description.is_empty() { |
| 103 | let _ = write!(out, "\n {}", shown(&card.description)); |
| 104 | } |
| 105 | if !card.topics.is_empty() { |
| 106 | let _ = write!(out, "\n Topics: {}", shown(&card.topics.join(", "))); |
| 107 | } |
| 108 | } |
| 109 | if let Some(next) = &cards.next { |
| 110 | let _ = write!(out, "\nMore: {more} --after {}", shown(next)); |
| 111 | } |
| 112 | out |
| 113 | } |
| 114 | |
| 115 | /// The first line of a repository: `owner/name (private, fork of x/y), 3 |
| 116 | /// stars, updated 2026-10-18`. |
| 117 | fn card_line(card: &RepoCard) -> String { |
| 118 | let mut out = format!("{}/{}", shown(&card.owner), shown(&card.name)); |
| 119 | let mut notes = Vec::new(); |
| 120 | if card.private { |
| 121 | notes.push("private".to_owned()); |
| 122 | } |
| 123 | if let Some(upstream) = &card.fork_of { |
| 124 | notes.push(format!( |
| 125 | "fork of {}/{}", |
| 126 | shown(&upstream.owner), |
| 127 | shown(&upstream.name) |
| 128 | )); |
| 129 | } |
| 130 | if !notes.is_empty() { |
| 131 | let _ = write!(out, " ({})", notes.join(", ")); |
| 132 | } |
| 133 | let _ = write!(out, ", {}", counted(card.stars, "star", "stars")); |
| 134 | if let Some(pushed) = &card.pushed { |
| 135 | let _ = write!( |
| 136 | out, |
| 137 | ", updated {}", |
| 138 | shown(pushed.get(..10).unwrap_or(pushed)) |
| 139 | ); |
| 140 | } |
| 141 | out |
| 142 | } |
| 143 | |
| 144 | /// The order of explore and search. |
| 145 | #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] |
| 146 | pub(crate) enum ExploreSort { |
| 147 | /// Best match first: the default with a query. |
| 148 | Match, |
| 149 | /// The latest landing first: the default without one. |
| 150 | Recent, |
| 151 | /// The most stars first. |
| 152 | Stars, |
| 153 | /// The newest first. |
| 154 | New, |
| 155 | } |
| 156 | |
| 157 | impl ExploreSort { |
| 158 | fn as_str(self) -> &'static str { |
| 159 | match self { |
| 160 | ExploreSort::Match => proto::MATCH, |
| 161 | ExploreSort::Recent => proto::RECENT, |
| 162 | ExploreSort::Stars => proto::STARS, |
| 163 | ExploreSort::New => proto::NEW, |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// `hub explore`. |
| 169 | #[derive(Debug, Args)] |
| 170 | pub(crate) struct ExploreArgs { |
| 171 | /// What to look for: words that start words of a repository's owner, |
| 172 | /// name, description or topics; every one must match. |
| 173 | #[arg(value_name = "QUERY")] |
| 174 | pub(crate) query: Vec<String>, |
| 175 | /// Only the repositories with this topic. |
| 176 | #[arg(long, value_name = "TOPIC")] |
| 177 | pub(crate) topic: Option<String>, |
| 178 | /// Only the repositories of this account. |
| 179 | #[arg(long, value_name = "LOGIN")] |
| 180 | pub(crate) owner: Option<String>, |
| 181 | /// The order (default: match with a query, else recent). |
| 182 | #[arg(long, value_enum)] |
| 183 | pub(crate) sort: Option<ExploreSort>, |
| 184 | /// List forks too. |
| 185 | #[arg(long)] |
| 186 | pub(crate) forks: bool, |
| 187 | /// The most repositories to list, 1 to 100 (default: 30). |
| 188 | #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))] |
| 189 | pub(crate) limit: Option<u32>, |
| 190 | /// Where to start: the `next` of the page before. |
| 191 | #[arg(long, value_name = "CURSOR")] |
| 192 | pub(crate) after: Option<String>, |
| 193 | } |
| 194 | |
| 195 | pub(crate) fn explore(cli: &Cli, args: &ExploreArgs) -> Result<ExitCode> { |
| 196 | let query = args.query.join(" "); |
| 197 | if let Err(err) = proto::terms(&query) { |
| 198 | bail!("{err}"); |
| 199 | } |
| 200 | let owner = args.owner.as_deref().map(login_arg).transpose()?; |
| 201 | let route = with_query( |
| 202 | "/v1/explore", |
| 203 | &[ |
| 204 | ("q", (!query.is_empty()).then(|| query.clone())), |
| 205 | ("topic", args.topic.clone()), |
| 206 | ("owner", owner), |
| 207 | ("sort", args.sort.map(|sort| sort.as_str().to_owned())), |
| 208 | ("forks", args.forks.then(|| "1".to_owned())), |
| 209 | ("limit", args.limit.map(|limit| limit.to_string())), |
| 210 | ("after", args.after.clone()), |
| 211 | ], |
| 212 | ); |
| 213 | let hub = signed_in_hub()?; |
| 214 | let page: RepoCards = match hub.call_json("GET", &route, &[], None) { |
| 215 | Ok(page) => page, |
| 216 | Err(err) => return Ok(failed(&err)), |
| 217 | }; |
| 218 | print(cli, &serde_json::to_value(&page)?, || { |
| 219 | cards_text( |
| 220 | &page, |
| 221 | "No public repository matches.", |
| 222 | "the same command with", |
| 223 | ) |
| 224 | })?; |
| 225 | Ok(ExitCode::SUCCESS) |
| 226 | } |
| 227 | |
| 228 | /// `hub user`. |
| 229 | #[derive(Debug, Args)] |
| 230 | pub(crate) struct UserArgs { |
| 231 | /// The account. |
| 232 | #[arg(value_name = "LOGIN")] |
| 233 | pub(crate) login: String, |
| 234 | /// List its repositories you may read. |
| 235 | #[arg(long, group = "list")] |
| 236 | pub(crate) repos: bool, |
| 237 | /// List what it starred that you may read. |
| 238 | #[arg(long, group = "list")] |
| 239 | pub(crate) stars: bool, |
| 240 | /// List the accounts that follow it. |
| 241 | #[arg(long, group = "list")] |
| 242 | pub(crate) followers: bool, |
| 243 | /// List the accounts it follows. |
| 244 | #[arg(long, group = "list")] |
| 245 | pub(crate) following: bool, |
| 246 | /// The most entries of a list, 1 to 100 (default: 30). |
| 247 | #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))] |
| 248 | pub(crate) limit: Option<u32>, |
| 249 | /// Where a list starts: the `next` of the page before. |
| 250 | #[arg(long, value_name = "CURSOR")] |
| 251 | pub(crate) after: Option<String>, |
| 252 | } |
| 253 | |
| 254 | /// What `hub user` shows of an account. |
| 255 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 256 | enum Shown { |
| 257 | Profile, |
| 258 | Repos, |
| 259 | Stars, |
| 260 | Followers, |
| 261 | Following, |
| 262 | } |
| 263 | |
| 264 | impl UserArgs { |
| 265 | fn shown(&self) -> Shown { |
| 266 | if self.repos { |
| 267 | Shown::Repos |
| 268 | } else if self.stars { |
| 269 | Shown::Stars |
| 270 | } else if self.followers { |
| 271 | Shown::Followers |
| 272 | } else if self.following { |
| 273 | Shown::Following |
| 274 | } else { |
| 275 | Shown::Profile |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | pub(crate) fn user(cli: &Cli, args: &UserArgs) -> Result<ExitCode> { |
| 281 | let login = login_arg(&args.login)?; |
| 282 | let shown = args.shown(); |
| 283 | let page = [ |
| 284 | ("limit", args.limit.map(|limit| limit.to_string())), |
| 285 | ("after", args.after.clone()), |
| 286 | ]; |
| 287 | let route = match shown { |
| 288 | Shown::Profile => format!("/v1/users/{login}"), |
| 289 | Shown::Repos => with_query(&format!("/v1/users/{login}/repos"), &page), |
| 290 | Shown::Stars => with_query(&format!("/v1/users/{login}/starred"), &page), |
| 291 | Shown::Followers => with_query(&format!("/v1/users/{login}/followers"), &page), |
| 292 | Shown::Following => with_query(&format!("/v1/users/{login}/following"), &page), |
| 293 | }; |
| 294 | let hub = signed_in_hub()?; |
| 295 | let answer: serde_json::Value = match hub.call_json("GET", &route, &[], None) { |
| 296 | Ok(answer) => answer, |
| 297 | Err(err) => return Ok(failed(&err)), |
| 298 | }; |
| 299 | let flag = match shown { |
| 300 | Shown::Profile => "", |
| 301 | Shown::Repos => " --repos", |
| 302 | Shown::Stars => " --stars", |
| 303 | Shown::Followers => " --followers", |
| 304 | Shown::Following => " --following", |
| 305 | }; |
| 306 | let more = format!("braid hub user {login}{flag}"); |
| 307 | let text = match shown { |
| 308 | Shown::Profile => profile_text(&serde_json::from_value(answer.clone())?), |
| 309 | Shown::Repos => cards_text( |
| 310 | &serde_json::from_value(answer.clone())?, |
| 311 | "No repositories you may read.", |
| 312 | &more, |
| 313 | ), |
| 314 | Shown::Stars => cards_text( |
| 315 | &serde_json::from_value(answer.clone())?, |
| 316 | "No stars of repositories you may read.", |
| 317 | &more, |
| 318 | ), |
| 319 | Shown::Followers => users_text( |
| 320 | &serde_json::from_value(answer.clone())?, |
| 321 | "No followers.", |
| 322 | &more, |
| 323 | ), |
| 324 | Shown::Following => users_text( |
| 325 | &serde_json::from_value(answer.clone())?, |
| 326 | "Follows nobody.", |
| 327 | &more, |
| 328 | ), |
| 329 | }; |
| 330 | print(cli, &answer, || text)?; |
| 331 | Ok(ExitCode::SUCCESS) |
| 332 | } |
| 333 | |
| 334 | /// An account in words: its login and name, when it joined, its counts, |
| 335 | /// and whether you follow it; what the hub says through [`shown`]. |
| 336 | fn profile_text(profile: &Profile) -> String { |
| 337 | let login = shown(&profile.login); |
| 338 | let mut out = login.clone(); |
| 339 | if let Some(name) = profile.name.as_deref().filter(|name| !name.is_empty()) { |
| 340 | let _ = write!(out, " ({})", shown(name)); |
| 341 | } |
| 342 | let _ = write!( |
| 343 | out, |
| 344 | "\nJoined {}", |
| 345 | shown(profile.created.get(..10).unwrap_or(&profile.created)) |
| 346 | ); |
| 347 | let stars = match profile.stars { |
| 348 | Some(stars) => counted(stars, "star", "stars"), |
| 349 | None => "stars kept private".to_owned(), |
| 350 | }; |
| 351 | let _ = write!( |
| 352 | out, |
| 353 | "\n{}, {stars}, {}, {} following", |
| 354 | counted(profile.repos, "repository", "repositories"), |
| 355 | counted(profile.followers, "follower", "followers"), |
| 356 | profile.following |
| 357 | ); |
| 358 | if profile.viewer.as_ref().is_some_and(|viewer| viewer.follows) { |
| 359 | let _ = write!(out, "\nYou follow {login}."); |
| 360 | } |
| 361 | out |
| 362 | } |
| 363 | |
| 364 | /// Accounts, one a line, with their names and since when; what the hub |
| 365 | /// says through [`shown`]. |
| 366 | fn users_text(users: &UserCards, empty: &str, more: &str) -> String { |
| 367 | let mut out = String::new(); |
| 368 | if users.users.is_empty() { |
| 369 | out.push_str(empty); |
| 370 | } |
| 371 | for user in &users.users { |
| 372 | if !out.is_empty() { |
| 373 | out.push('\n'); |
| 374 | } |
| 375 | out.push_str(&shown(&user.login)); |
| 376 | if let Some(name) = user.name.as_deref().filter(|name| !name.is_empty()) { |
| 377 | let _ = write!(out, " ({})", shown(name)); |
| 378 | } |
| 379 | let _ = write!( |
| 380 | out, |
| 381 | ", since {}", |
| 382 | shown(user.since.get(..10).unwrap_or(&user.since)) |
| 383 | ); |
| 384 | } |
| 385 | if let Some(next) = &users.next { |
| 386 | let _ = write!(out, "\nMore: {more} --after {}", shown(next)); |
| 387 | } |
| 388 | out |
| 389 | } |
| 390 | |
| 391 | #[cfg(test)] |
| 392 | mod tests { |
| 393 | use super::*; |
| 394 | use braid_hubproto::cards::RepoRef; |
| 395 | use braid_hubproto::explore::ProfileViewer; |
| 396 | |
| 397 | #[test] |
| 398 | fn routes_carry_their_query() { |
| 399 | assert_eq!(query_value("ada/demo x&y"), "ada/demo%20x%26y"); |
| 400 | assert_eq!( |
| 401 | with_query( |
| 402 | "/v1/explore", |
| 403 | &[ |
| 404 | ("q", Some("rust cli".into())), |
| 405 | ("topic", None), |
| 406 | ("forks", Some("1".into())) |
| 407 | ] |
| 408 | ), |
| 409 | "/v1/explore?q=rust%20cli&forks=1" |
| 410 | ); |
| 411 | assert_eq!(with_query("/v1/explore", &[("q", None)]), "/v1/explore"); |
| 412 | assert_eq!(login_arg("Ada").unwrap(), "ada"); |
| 413 | assert!(login_arg("a--b").is_err()); |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn repositories_and_accounts_in_words() { |
| 418 | let card = RepoCard { |
| 419 | owner: "bob".into(), |
| 420 | name: "tool".into(), |
| 421 | private: true, |
| 422 | description: "A tool".into(), |
| 423 | topics: vec!["rust".into(), "cli".into()], |
| 424 | stars: 1, |
| 425 | created: "2026-01-01T00:00:00Z".into(), |
| 426 | pushed: Some("2026-10-18T09:00:00Z".into()), |
| 427 | default_branch: "main".into(), |
| 428 | fork_of: Some(RepoRef { |
| 429 | owner: "ada".into(), |
| 430 | name: "tool".into(), |
| 431 | }), |
| 432 | ..RepoCard::default() |
| 433 | }; |
| 434 | let text = cards_text( |
| 435 | &RepoCards { |
| 436 | repos: vec![card], |
| 437 | next: Some("r2.x".into()), |
| 438 | }, |
| 439 | "none", |
| 440 | "braid hub user bob --repos", |
| 441 | ); |
| 442 | assert_eq!( |
| 443 | text, |
| 444 | "bob/tool (private, fork of ada/tool), 1 star, updated 2026-10-18\n A tool\n Topics: rust, cli\nMore: braid hub user bob --repos --after r2.x" |
| 445 | ); |
| 446 | let profile = Profile { |
| 447 | login: "ada".into(), |
| 448 | name: Some("Ada Lovelace".into()), |
| 449 | created: "2026-10-01T00:00:00Z".into(), |
| 450 | followers: 1, |
| 451 | following: 2, |
| 452 | repos: 3, |
| 453 | stars: None, |
| 454 | viewer: Some(ProfileViewer { follows: true }), |
| 455 | }; |
| 456 | assert_eq!( |
| 457 | profile_text(&profile), |
| 458 | "ada (Ada Lovelace)\nJoined 2026-10-01\n3 repositories, stars kept private, 1 follower, 2 following\nYou follow ada." |
| 459 | ); |
| 460 | assert_eq!( |
| 461 | users_text(&UserCards::default(), "No followers.", "x"), |
| 462 | "No followers." |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn what_the_hub_says_drives_no_terminal() { |
| 468 | // What a hub not to be trusted could send in any field: a title for |
| 469 | // the terminal, its bell, and a clear screen. |
| 470 | let evil = "\u{1b}]0;owned\u{7}\u{1b}[2J"; |
| 471 | let bad = |text: &str| format!("{text}{evil}"); |
| 472 | let card = RepoCard { |
| 473 | owner: bad("bob"), |
| 474 | name: bad("tool"), |
| 475 | description: bad("A tool\nMore: run this"), |
| 476 | topics: vec![bad("rust")], |
| 477 | pushed: Some(bad("2026")), |
| 478 | fork_of: Some(RepoRef { |
| 479 | owner: bad("ada"), |
| 480 | name: bad("tool"), |
| 481 | }), |
| 482 | ..RepoCard::default() |
| 483 | }; |
| 484 | let cards = cards_text( |
| 485 | &RepoCards { |
| 486 | repos: vec![card], |
| 487 | next: Some(bad("r2")), |
| 488 | }, |
| 489 | "none", |
| 490 | "braid hub explore", |
| 491 | ); |
| 492 | let profile = profile_text(&Profile { |
| 493 | login: bad("ada"), |
| 494 | name: Some(bad("Ada")), |
| 495 | created: bad("2026"), |
| 496 | viewer: Some(ProfileViewer { follows: true }), |
| 497 | ..Profile::default() |
| 498 | }); |
| 499 | let users = users_text( |
| 500 | &UserCards { |
| 501 | users: vec![braid_hubproto::cards::UserCard { |
| 502 | login: bad("bob"), |
| 503 | name: Some(bad("Bob")), |
| 504 | since: bad("2026"), |
| 505 | }], |
| 506 | next: Some(bad("f1")), |
| 507 | }, |
| 508 | "none", |
| 509 | "braid hub user ada --followers", |
| 510 | ); |
| 511 | for text in [&cards, &profile, &users] { |
| 512 | assert!(!text.contains(['\u{1b}', '\u{7}']), "{text:?}"); |
| 513 | assert!(text.contains("\\u{1b}]0;owned\\u{7}\\u{1b}[2J"), "{text:?}"); |
| 514 | } |
| 515 | // A line break in a description prints no line of braid's. |
| 516 | assert_eq!( |
| 517 | cards |
| 518 | .lines() |
| 519 | .filter(|line| line.starts_with("More:")) |
| 520 | .count(), |
| 521 | 1 |
| 522 | ); |
| 523 | assert!(cards.contains("A tool\\nMore: run this"), "{cards:?}"); |
| 524 | } |
| 525 | } |