Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 12.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub fork`, `sync-fork` and `jobs`: forking a repository, bringing
5//! what its upstream landed into a fork, and the jobs that do it.
6//!
7//! A fork is made by a job of the hub (section 20 of `docs/hub.md`): `fork`
8//! asks for it, then waits until the job ends, unless `--no-wait`, and may
9//! clone the fork it made. Exit statuses as the other hub commands: 0
10//! done, 1 refused (a fork or a job that failed too), 2 when a fork and its
11//! upstream diverged, 3 when the hub could not be reached or failed.
12
13use std::fmt::Write;
14use std::path::PathBuf;
15use std::process::ExitCode;
16use std::thread::sleep;
17use std::time::Duration;
18
19use anyhow::{Context, Result};
20use braid_hubproto::RepoPath;
21use braid_hubproto::forks::{self as proto, ForkStarted, Job, Jobs, SyncedUpstream};
22use clap::Args;
23use serde_json::json;
24
25use super::creds::{self, HubEnv};
26use super::http::HttpHub;
27use super::remote::{HubError, shown};
28use super::social_common::{
29 CONFLICTS, HubRepoArg, REFUSED, exit_for, hub_repo, idempotency_key, print,
30};
31use super::{CloneArgs, HubAction};
32use crate::Cli;
33
34/// How long `--wait` waits between two looks at a job.
35const POLL: Duration = Duration::from_millis(500);
36
37/// The hub signed in to: BRAID_HUB_URL, else the hub signed in to last,
38/// else the public hub.
39fn signed_in_hub() -> Result<HttpHub> {
40 let env = HubEnv::from_process();
41 let creds = env.credentials()?;
42 let url = creds::hub_url(&env, &creds, None)?;
43 Ok(super::client(&env, &url)?.0)
44}
45
46/// What a command answers when the hub refused it or could not be
47/// reached: the error, and the exit status it calls for.
48fn failed(err: &HubError) -> ExitCode {
49 eprintln!("braid: error: {err}");
50 ExitCode::from(exit_for(err))
51}
52
53/// `text` as a value of a query string: everything but letters, digits
54/// and `-._~` percent-encoded.
55fn query_value(text: &str) -> String {
56 let mut out = String::with_capacity(text.len());
57 for byte in text.bytes() {
58 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
59 out.push(char::from(byte));
60 } else {
61 let _ = write!(out, "%{byte:02X}");
62 }
63 }
64 out
65}
66
67/// A job id given on the command line, checked before it names a route:
68/// `j_` and 26 characters of `a-z 2-7`.
69fn job_arg(id: &str) -> Result<&str> {
70 let valid = id.strip_prefix("j_").is_some_and(|rest| {
71 rest.len() == 26
72 && rest
73 .bytes()
74 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
75 });
76 if !valid {
77 anyhow::bail!("{id:?} is not a job id: j_ and 26 characters of a-z and 2-7");
78 }
79 Ok(id)
80}
81
82/// Asks for the job `id` until it ends.
83fn wait_for(hub: &HttpHub, id: &str) -> Result<Job, HubError> {
84 loop {
85 let job: Job = hub.call_json("GET", &format!("/v1/jobs/{id}"), &[], None)?;
86 if job.is_finished() {
87 return Ok(job);
88 }
89 sleep(POLL);
90 }
91}
92
93/// A job, in one line or two, for people: every field as the hub sent it,
94/// escaped.
95fn described(job: &Job) -> String {
96 let mut out = format!(
97 "{} {} {}",
98 shown(&job.id),
99 shown(&job.kind),
100 shown(&job.state)
101 );
102 if let Some(repo) = &job.repo {
103 let _ = write!(out, " {}", shown(repo));
104 }
105 if job.progress.objects > 0 && !job.is_finished() {
106 let _ = write!(out, " ({} objects so far)", job.progress.objects);
107 }
108 if let Some(error) = &job.error {
109 let _ = write!(out, "\n {}", shown(error));
110 }
111 out
112}
113
114/// The exit status of a job that ended: 0 when it did what it was asked or
115/// had nothing to do, 1 otherwise.
116fn ended(job: &Job) -> ExitCode {
117 match job.state.as_str() {
118 proto::DONE | proto::SKIPPED => ExitCode::SUCCESS,
119 _ => ExitCode::from(REFUSED),
120 }
121}
122
123/// `hub fork`.
124#[derive(Debug, Args)]
125pub(crate) struct ForkArgs {
126 // Not named `repo`: that is the id of the global --repo.
127 /// The repository to fork: OWNER/NAME.
128 #[arg(value_name = "OWNER/NAME")]
129 pub(crate) source: String,
130 /// The fork's name in your account (default: the repository's).
131 #[arg(long, value_name = "NAME")]
132 pub(crate) name: Option<String>,
133 /// Make the fork private (a fork of a private repository always is).
134 #[arg(long)]
135 pub(crate) private: bool,
136 /// Clone the fork once it is made, into DIR (default: its name).
137 #[arg(long, value_name = "DIR", num_args = 0..=1)]
138 pub(crate) clone: Option<Option<PathBuf>>,
139 /// Do not wait for the fork to be made: print its job, and return.
140 #[arg(long, conflicts_with = "clone")]
141 pub(crate) no_wait: bool,
142}
143
144pub(crate) fn fork(cli: &Cli, args: &ForkArgs) -> Result<ExitCode> {
145 let path: RepoPath = args
146 .source
147 .parse()
148 .with_context(|| format!("{:?} is not OWNER/NAME", args.source))?;
149 let hub = signed_in_hub()?;
150 let mut body = json!({});
151 if let Some(name) = &args.name {
152 body["name"] = json!(name);
153 }
154 if args.private {
155 body["private"] = json!(true);
156 }
157 // Sent again after a lost answer, the request is not made twice.
158 let key = idempotency_key();
159 let route = format!("{}/forks", path.api_path());
160 let started: ForkStarted =
161 match hub.call_json("POST", &route, &[("Idempotency-Key", &key)], Some(&body)) {
162 Ok(started) => started,
163 Err(err) => return Ok(failed(&err)),
164 };
165 let fork = format!("{}/{}", started.repo.owner, started.repo.name);
166 // Checked as the id it says it is before it names a route, or a line.
167 let Ok(id) = job_arg(&started.job.id) else {
168 return Ok(failed(&HubError::Protocol(format!(
169 "the hub named its job {}, which is not a job id",
170 shown(&started.job.id)
171 ))));
172 };
173 if args.no_wait {
174 print(cli, &serde_json::to_value(&started)?, || {
175 format!(
176 "Forking {path} into {}: job {id} is {}. `braid hub jobs {id} --wait` waits for it.",
177 shown(&fork),
178 shown(&started.job.state),
179 )
180 })?;
181 return Ok(ExitCode::SUCCESS);
182 }
183 let job = match wait_for(&hub, id) {
184 Ok(job) => job,
185 Err(err) => return Ok(failed(&err)),
186 };
187 let value = json!({"job": job, "repo": started.repo});
188 if job.state != proto::DONE {
189 if cli.json {
190 crate::print_json(&value)?;
191 } else {
192 eprintln!(
193 "braid: error: forking {path} into {} did not go through: {}",
194 shown(&fork),
195 shown(job.error.as_deref().unwrap_or(&job.state))
196 );
197 }
198 return Ok(ended(&job));
199 }
200 print(cli, &value, || {
201 format!("Forked {path} into {}.", shown(&fork))
202 })?;
203 match &args.clone {
204 Some(dir) => super::hub(
205 cli,
206 &HubAction::Clone(CloneArgs {
207 source: fork,
208 dir: dir.clone(),
209 paths: Vec::new(),
210 }),
211 ),
212 None => Ok(ExitCode::SUCCESS),
213 }
214}
215
216/// `hub sync-fork`.
217#[derive(Debug, Args)]
218pub(crate) struct SyncForkArgs {
219 #[command(flatten)]
220 pub(crate) repo: HubRepoArg,
221 /// The branch or tag to bring up to date (default: the fork's default
222 /// branch); the upstream's of the same name is brought in.
223 #[arg(long = "ref", value_name = "REF")]
224 pub(crate) reference: Option<String>,
225}
226
227pub(crate) fn sync_fork(cli: &Cli, args: &SyncForkArgs) -> Result<ExitCode> {
228 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
229 let mut body = json!({});
230 if let Some(reference) = &args.reference {
231 body["ref"] = json!(reference);
232 }
233 let route = format!("{}/sync-upstream", path.api_path());
234 let synced: SyncedUpstream = match hub.call_json("POST", &route, &[], Some(&body)) {
235 Ok(synced) => synced,
236 Err(err) => return Ok(failed(&err)),
237 };
238 let reference = shown(&synced.reference);
239 print(cli, &serde_json::to_value(&synced)?, || {
240 match synced.outcome.as_str() {
241 proto::FAST_FORWARD => format!(
242 "Synced {reference} of {path} with its upstream: it moved to {}.",
243 synced
244 .head
245 .map_or_else(|| "nothing".to_owned(), |head| head.short().to_string())
246 ),
247 proto::DIVERGED => format!(
248 "{reference} of {path} and its upstream diverged: the upstream has {}{} changesets it lacks, and it has its own. Merge the upstream's {reference} into it, then land.",
249 synced.behind,
250 if synced.more { "+" } else { "" }
251 ),
252 _ => format!("{reference} of {path} is up to date with its upstream."),
253 }
254 })?;
255 if synced.outcome == proto::DIVERGED {
256 return Ok(ExitCode::from(CONFLICTS));
257 }
258 Ok(ExitCode::SUCCESS)
259}
260
261/// `hub jobs`.
262#[derive(Debug, Args)]
263pub(crate) struct JobsArgs {
264 /// The job to show (default: list your jobs, newest first).
265 #[arg(value_name = "ID")]
266 pub(crate) id: Option<String>,
267 /// Wait until the job ends; the exit status is 1 when it failed or was
268 /// cancelled.
269 #[arg(long, requires = "id")]
270 pub(crate) wait: bool,
271 /// The most jobs to list, 1 to 100 (default: 30).
272 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100), conflicts_with = "id")]
273 pub(crate) limit: Option<u32>,
274 /// Where to start: the `next` of the page before.
275 #[arg(long, value_name = "CURSOR", conflicts_with = "id")]
276 pub(crate) after: Option<String>,
277}
278
279pub(crate) fn jobs(cli: &Cli, args: &JobsArgs) -> Result<ExitCode> {
280 let hub = signed_in_hub()?;
281 if let Some(id) = &args.id {
282 let id = job_arg(id)?;
283 let job: Job = if args.wait {
284 match wait_for(&hub, id) {
285 Ok(job) => job,
286 Err(err) => return Ok(failed(&err)),
287 }
288 } else {
289 match hub.call_json("GET", &format!("/v1/jobs/{id}"), &[], None) {
290 Ok(job) => job,
291 Err(err) => return Ok(failed(&err)),
292 }
293 };
294 print(cli, &serde_json::to_value(&job)?, || described(&job))?;
295 return Ok(if args.wait {
296 ended(&job)
297 } else {
298 ExitCode::SUCCESS
299 });
300 }
301 let mut query = Vec::new();
302 if let Some(limit) = args.limit {
303 query.push(format!("limit={limit}"));
304 }
305 if let Some(after) = &args.after {
306 query.push(format!("after={}", query_value(after)));
307 }
308 let mut route = "/v1/jobs".to_owned();
309 if !query.is_empty() {
310 route = format!("{route}?{}", query.join("&"));
311 }
312 let page: Jobs = match hub.call_json("GET", &route, &[], None) {
313 Ok(page) => page,
314 Err(err) => return Ok(failed(&err)),
315 };
316 print(cli, &serde_json::to_value(&page)?, || {
317 let mut out = String::new();
318 if page.jobs.is_empty() {
319 out.push_str("No jobs.");
320 }
321 for job in &page.jobs {
322 if !out.is_empty() {
323 out.push('\n');
324 }
325 out.push_str(&described(job));
326 }
327 if let Some(next) = &page.next {
328 let _ = write!(out, "\nMore: braid hub jobs --after {}", shown(next));
329 }
330 out
331 })?;
332 Ok(ExitCode::SUCCESS)
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn job_ids_and_query_values() {
341 assert!(job_arg("j_abcdefghijklmnopqrstuvwxyz").is_ok());
342 for bad in [
343 "",
344 "j_",
345 "j_ABCDEFGHIJKLMNOPQRSTUVWXYZ",
346 "j_../../v1",
347 "r_abcdefghijklmnopqrstuvwxyz",
348 ] {
349 assert!(job_arg(bad).is_err(), "{bad:?}");
350 }
351 assert_eq!(query_value("j42"), "j42");
352 assert_eq!(query_value("a/b c"), "a%2Fb%20c");
353 let job = Job {
354 id: "j_abcdefghijklmnopqrstuvwxyz".into(),
355 kind: proto::FORK.into(),
356 state: proto::FAILED.into(),
357 repo: Some("bob/demo".into()),
358 error: Some("too large\u{1b}[31m".into()),
359 created: "t".into(),
360 ..Job::default()
361 };
362 let text = described(&job);
363 assert!(text.starts_with("j_abcdefghijklmnopqrstuvwxyz fork failed bob/demo"));
364 assert!(!text.contains('\u{1b}'), "{text:?}");
365 assert_eq!(ended(&job), ExitCode::from(REFUSED));
366 // Every field a hub sends reaches the terminal escaped, not only
367 // the error.
368 let hostile = Job {
369 id: "j_\u{1b}[2J".into(),
370 kind: "fork\u{1b}]0;title\u{7}".into(),
371 state: "done\u{1b}[31m".into(),
372 ..job
373 };
374 let text = described(&hostile);
375 assert!(
376 !text.contains('\u{1b}') && !text.contains('\u{7}'),
377 "{text:?}"
378 );
379 }
380}