| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! What the commands of stars, issues, forks, requests and the rest share: |
| 5 | //! the repository a command names, printing JSON or text, the body of a |
| 6 | //! text, idempotency keys, the agent's label, and the exit statuses. |
| 7 | //! |
| 8 | //! Exit statuses: 0 when done, 1 when the hub refused, 2 on conflicts, 3 |
| 9 | //! when the hub could not be reached or failed, so that signing in again |
| 10 | //! would not help. |
| 11 | |
| 12 | #![allow(dead_code)] |
| 13 | |
| 14 | use std::collections::hash_map::RandomState; |
| 15 | use std::hash::{BuildHasher, Hasher}; |
| 16 | use std::io::Read; |
| 17 | use std::path::Path; |
| 18 | use std::process::ExitCode; |
| 19 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 20 | |
| 21 | use anyhow::{Context, Result, bail}; |
| 22 | use braid_hubproto::RepoPath; |
| 23 | use clap::Args; |
| 24 | use serde_json::Value; |
| 25 | |
| 26 | use super::creds::{self, HubEnv}; |
| 27 | use super::http::HttpHub; |
| 28 | use super::link::Link; |
| 29 | use super::remote::HubError; |
| 30 | use crate::{Cli, open_repo, print_json}; |
| 31 | |
| 32 | /// Done. |
| 33 | pub(crate) const DONE: u8 = 0; |
| 34 | |
| 35 | /// The hub refused: the request is not allowed, or not valid. |
| 36 | pub(crate) const REFUSED: u8 = 1; |
| 37 | |
| 38 | /// Conflicts, printed as `braid land --json` prints them. |
| 39 | pub(crate) const CONFLICTS: u8 = 2; |
| 40 | |
| 41 | /// The hub could not be reached, or failed. |
| 42 | pub(crate) const UNREACHABLE: u8 = 3; |
| 43 | |
| 44 | /// The largest body of an issue, a comment or a review, in bytes. |
| 45 | pub(crate) const MAX_TEXT: usize = 64 * 1024; |
| 46 | |
| 47 | /// `-R/--hub-repo`, for the commands that act on a repository. |
| 48 | #[derive(Clone, Debug, Default, Args)] |
| 49 | pub(crate) struct HubRepoArg { |
| 50 | /// The repository on the hub, OWNER/NAME (default: the one this |
| 51 | /// repository is linked to). |
| 52 | #[arg(short = 'R', long = "hub-repo", value_name = "OWNER/NAME")] |
| 53 | pub(crate) hub_repo: Option<String>, |
| 54 | } |
| 55 | |
| 56 | /// The hub and the repository a command acts on: `given` (OWNER/NAME) on |
| 57 | /// the hub signed in to, else the repository this one is linked to, on its |
| 58 | /// hub. |
| 59 | pub(crate) fn hub_repo(cli: &Cli, given: Option<&str>) -> Result<(HttpHub, RepoPath)> { |
| 60 | if let Some(text) = given { |
| 61 | let path: RepoPath = text |
| 62 | .parse() |
| 63 | .with_context(|| format!("{text:?} is not OWNER/NAME"))?; |
| 64 | let env = HubEnv::from_process(); |
| 65 | let creds = env.credentials()?; |
| 66 | let url = creds::hub_url(&env, &creds, None)?; |
| 67 | let (hub, _) = super::client(&env, &url)?; |
| 68 | return Ok((hub, path)); |
| 69 | } |
| 70 | let repo = open_repo(cli).context( |
| 71 | "no repository named: give -R OWNER/NAME, or run this in a repository linked to a hub", |
| 72 | )?; |
| 73 | let link = |
| 74 | Link::read(&repo)?.context("this repository is not linked to a hub: give -R OWNER/NAME")?; |
| 75 | Ok((super::connect(&link)?, link.repo)) |
| 76 | } |
| 77 | |
| 78 | /// Prints `value` with `--json`, and `text` otherwise. |
| 79 | pub(crate) fn print(cli: &Cli, value: &Value, text: impl FnOnce() -> String) -> Result<()> { |
| 80 | if cli.json { |
| 81 | print_json(value) |
| 82 | } else { |
| 83 | println!("{}", text()); |
| 84 | Ok(()) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// The body of a text: `--body`, or `--body-file` (`-` reads standard |
| 89 | /// input), at most [`MAX_TEXT`] bytes of UTF-8; `None` when neither is |
| 90 | /// given. |
| 91 | pub(crate) fn body_text(body: Option<&str>, file: Option<&Path>) -> Result<Option<String>> { |
| 92 | let text = match (body, file) { |
| 93 | (Some(_), Some(_)) => bail!("give --body or --body-file, not both"), |
| 94 | (None, None) => return Ok(None), |
| 95 | (Some(text), None) => text.to_owned(), |
| 96 | (None, Some(path)) => { |
| 97 | let mut bytes = Vec::new(); |
| 98 | let limit = MAX_TEXT as u64 + 1; |
| 99 | if path == Path::new("-") { |
| 100 | std::io::stdin() |
| 101 | .lock() |
| 102 | .take(limit) |
| 103 | .read_to_end(&mut bytes) |
| 104 | .context("cannot read standard input")?; |
| 105 | } else { |
| 106 | std::fs::File::open(path) |
| 107 | .and_then(|file| file.take(limit).read_to_end(&mut bytes)) |
| 108 | .with_context(|| format!("cannot read {}", path.display()))?; |
| 109 | } |
| 110 | String::from_utf8(bytes).context("the body is not UTF-8")? |
| 111 | } |
| 112 | }; |
| 113 | if text.len() > MAX_TEXT { |
| 114 | bail!("the body is longer than {MAX_TEXT} bytes, the most the hub takes"); |
| 115 | } |
| 116 | Ok(Some(text)) |
| 117 | } |
| 118 | |
| 119 | /// A new `Idempotency-Key`: 32 hex digits that differ between calls and |
| 120 | /// processes, so that a command sent again after a lost answer is not done |
| 121 | /// twice. |
| 122 | pub(crate) fn idempotency_key() -> String { |
| 123 | let nanos = SystemTime::now() |
| 124 | .duration_since(UNIX_EPOCH) |
| 125 | .map_or(0, |since| since.as_nanos()); |
| 126 | let half = || { |
| 127 | let mut hasher = RandomState::new().build_hasher(); |
| 128 | hasher.write_u128(nanos); |
| 129 | hasher.write_u32(std::process::id()); |
| 130 | hasher.finish() |
| 131 | }; |
| 132 | format!("{:016x}{:016x}", half(), half()) |
| 133 | } |
| 134 | |
| 135 | /// The agent label a command sends: the global `--agent` (or |
| 136 | /// `BRAID_AGENT`), unless it is the default, `cli`. |
| 137 | pub(crate) fn agent(cli: &Cli) -> Option<String> { |
| 138 | (cli.agent != "cli").then(|| cli.agent.clone()) |
| 139 | } |
| 140 | |
| 141 | /// The exit status of a request that failed with `err`: [`UNREACHABLE`] |
| 142 | /// when the hub could not be reached or failed, [`REFUSED`] otherwise. |
| 143 | pub(crate) fn exit_for(err: &HubError) -> u8 { |
| 144 | match err { |
| 145 | HubError::Api { status, .. } if *status < 500 => REFUSED, |
| 146 | HubError::Refused { .. } => REFUSED, |
| 147 | _ => UNREACHABLE, |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// What a command that is not in this version of braid answers. |
| 152 | pub(crate) fn not_yet(command: &str) -> Result<ExitCode> { |
| 153 | bail!("braid hub {command} is not available in this version of braid") |
| 154 | } |
| 155 | |
| 156 | #[cfg(test)] |
| 157 | mod tests { |
| 158 | use super::*; |
| 159 | |
| 160 | #[test] |
| 161 | fn keys_bodies_and_statuses() { |
| 162 | let key = idempotency_key(); |
| 163 | assert_eq!(key.len(), 32); |
| 164 | assert!(key.bytes().all(|b| b.is_ascii_hexdigit())); |
| 165 | assert_ne!(idempotency_key(), key); |
| 166 | |
| 167 | assert_eq!(body_text(None, None).unwrap(), None); |
| 168 | assert_eq!(body_text(Some("hi"), None).unwrap().as_deref(), Some("hi")); |
| 169 | assert!(body_text(Some("a"), Some(Path::new("b"))).is_err()); |
| 170 | let dir = tempfile::tempdir().unwrap(); |
| 171 | let file = dir.path().join("body.md"); |
| 172 | std::fs::write(&file, "from a file\n").unwrap(); |
| 173 | assert_eq!( |
| 174 | body_text(None, Some(&file)).unwrap().as_deref(), |
| 175 | Some("from a file\n") |
| 176 | ); |
| 177 | std::fs::write(&file, vec![b'a'; MAX_TEXT + 1]).unwrap(); |
| 178 | assert!(body_text(None, Some(&file)).is_err()); |
| 179 | assert!(body_text(Some(&"a".repeat(MAX_TEXT + 1)), None).is_err()); |
| 180 | |
| 181 | let refused = HubError::api(403, "forbidden", "no"); |
| 182 | assert_eq!(exit_for(&refused), REFUSED); |
| 183 | let failed = HubError::api(500, "internal", "failed"); |
| 184 | assert_eq!(exit_for(&failed), UNREACHABLE); |
| 185 | let away = HubError::Transport { |
| 186 | hub: "https://hub.example".into(), |
| 187 | detail: "refused".into(), |
| 188 | }; |
| 189 | assert_eq!(exit_for(&away), UNREACHABLE); |
| 190 | } |
| 191 | } |