Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 82.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub request`: change requests (section 19 of `docs/hub.md`) from
5//! the command line.
6//!
7//! - `create` opens one: from the workspace's changesets, which it first
8//! puts on a new branch on the hub, or from a branch already there.
9//! - `list`, `show` and `diff` read them; `comment` and `review` answer
10//! them.
11//! - `update` gives one a new revision, from the workspace as it is now.
12//! - `land` lands the snapshot that was read, and nothing else.
13//! - `close`, `reopen` and `ready` change their state.
14//! - `checkout` brings one's snapshot into this repository as a branch,
15//! through the request itself, so that whoever reads the repository it
16//! is on fetches it without reading the one it comes from.
17//!
18//! The repository is `-R OWNER/NAME`, else the one this repository is
19//! linked to or, when that one is a fork, the repository it was forked
20//! from, where its change requests go. Creating commands send an
21//! `Idempotency-Key`, and send the request once more with the same key
22//! when the answer was lost, so that nothing is made twice. Exit statuses:
23//! 0 done, 1 refused, 2 conflicts, 3 when the hub could not be reached or
24//! failed. Titles, texts, logins and names come from anyone: printed
25//! without `--json`, they go through [`shown`].
26
27use std::fmt::Write as _;
28use std::io::Write as _;
29use std::path::PathBuf;
30use std::process::ExitCode;
31
32use anyhow::{Context, Result, bail};
33use braid_engine::read_changeset;
34use braid_format::{Kind, ObjectId, Objects};
35use braid_hubproto::RepoPath;
36use braid_hubproto::api::{LandMode, LandRequest, Me, MissingRequest, RepoInfo};
37use braid_hubproto::history::{ChangesetSummary, DiffPage};
38use braid_hubproto::names::glob_matches;
39use braid_hubproto::requests::{
40 self as proto, HeadSpec, NewRequest, NewRequestComment, NewReview, Request, RequestComment,
41 RequestComments, RequestLand, RequestLanded, RequestPatch, RequestUpdate, Requests, Review,
42 Reviews,
43};
44use braid_hubproto::scope::{ParsedScope, Right};
45use braid_repo::{Location, Repo, WorkspaceLink};
46use braid_store::{RefUpdate, Store};
47use braid_wc::Workspace;
48use clap::{Args, Subcommand, ValueEnum};
49use serde::de::DeserializeOwned;
50use serde_json::{Value, json};
51
52use super::creds::{self, HubEnv};
53use super::fetch::{fetch, haves, whole};
54use super::http::{HttpHub, HttpRepo};
55use super::land::{OffBranch, hub_stack, land, once_on_hub, send_stack};
56use super::link::Link;
57use super::remote::{HubError, Remote, shown};
58use super::social_common::{
59 CONFLICTS, REFUSED, agent, body_text, exit_for, idempotency_key, print,
60};
61use super::transfer::store_stream;
62use super::verify::land_note;
63use crate::work::count;
64use crate::{Cli, open_repo, print_json};
65
66/// The longest slug a title gives a branch, in characters.
67const MAX_SLUG: usize = 40;
68
69/// How many names a new branch tries, `<slug>`, `<slug>-2` and so on,
70/// before it gives up.
71const MAX_NAMES: usize = 100;
72
73/// The most comments, and the most reviews, `show` reads: a page of each.
74const SHOWN: usize = 100;
75
76/// The most pages of a diff `--json` reads.
77const MAX_PAGES: u64 = 10_000;
78
79/// The loop that settles a request's conflicts, for the long helps.
80macro_rules! conflict_loop {
81 () => {
82 "When a request conflicts with its base (`braid hub request show N` says
83so, and landing it exits with status 2), its author settles the conflicts
84in the workspace it came from, and gives the request a new revision:
85
86 braid hub sync-fork bring what the base landed into the fork
87 (in a clone of the repository itself, skip
88 this: `braid update` fetches the base)
89 braid update rebase the workspace onto it: exit status 2,
90 the conflicts are in the working copy
91 (edit the files) take the conflict markers out
92 braid resolve PATH... mark each conflict that is not about content
93 braid commit finish the rebase
94 braid hub request update N the request's next revision: what the
95 workspace holds now"
96 };
97}
98
99/// The long help of `hub request`.
100pub(crate) const REQUEST_HELP: &str = concat!(
101 "Open, review, update and land change requests: the work of a branch
102proposed for a branch of a repository on the hub, reviewed, and landed
103exactly as it was shown.
104
105The repository is -R OWNER/NAME, else the one this repository is linked to
106or, when that one is a fork, the repository it was forked from, where its
107change requests go.
108
109To contribute to a repository you may read but not write to, fork it and
110clone the fork (`braid hub fork OWNER/NAME --clone`), commit in the fork's
111workspace, then run `braid hub request create --title TITLE` there: braid
112puts the workspace's changesets on a branch request/<slug> of the fork, and
113opens the request on the repository it was forked from.
114
115",
116 conflict_loop!(),
117 "
118
119Exit statuses: 0 done, or landed; 1 refused (the snapshot moved, the base
120no longer holds where the stack starts, not allowed, not found); 2
121conflicts, printed as `braid land --json` prints them; 3 the hub could not
122be reached, or failed.
123
124create, comment and review send an Idempotency-Key, and send the request
125once more with the same key when the answer was lost: the hub then gives
126the first answer again rather than doing it twice. With --json each
127command prints what the hub answered."
128);
129
130/// The long help of `hub request create`.
131pub(crate) const CREATE_HELP: &str =
132 "Open a change request on the repository: -R OWNER/NAME, else the one this
133repository is linked to or, when that one is a fork, the repository it was
134forked from.
135
136Without --head, in a workspace: the workspace's changesets that its branch
137on the hub lacks, as `braid land` finds them (with any changesets of the
138local branch below them that the hub's branch lacks), are uploaded, put on
139a new branch on the hub, and proposed for the base:
140
141 request/<login>/<slug> on the repository itself, when you may write to
142 it and your token may land there (a land:<glob>
143 right that matches the name; request/<slug> when
144 only that one matches)
145 request/<slug> otherwise, on the fork this repository is linked
146 to; in a clone of the repository itself, fork it
147 first (`braid hub fork OWNER/NAME --clone`)
148
149<slug> comes from the title: lowercase ASCII letters, digits and '-', at
150most 40 characters, with -2, -3 and so on when the name holds other work.
151The workspace and its branch do not move. Like `braid land`, it refuses a
152workspace with uncommitted changes or a rebase in progress.
153
154With --head [OWNER/NAME:]BRANCH, the request proposes that branch as it is
155on the hub: a branch of OWNER/NAME, else of the repository this one is
156linked to (of the target, outside a linked repository).
157
158A head in a private repository other than the target publishes what it
159brings to everyone who reads the target: an admin of the head says so
160with --expose, and only when that is meant.
161
162It prints the request's number and its address; with --json, the request
163as the hub answered it.";
164
165/// The long help of `hub request update`.
166pub(crate) const UPDATE_HELP: &str = concat!(
167 "Give a change request a new revision, its author only. In a workspace,
168the workspace's changesets that its branch on the hub lacks are uploaded
169and put on the request's head branch: as a fast-forward when they build on
170it; otherwise in its place, since the new revision replaces what the
171request proposed. The hub then makes the revision. Reviews of earlier
172revisions no longer count.
173
174With --head, no workspace is needed: the new revision is what the head
175branch holds on the hub now, or the changeset ID, which that branch must
176hold on its first-parent chain.
177
178",
179 conflict_loop!(),
180 "
181
182With --json it prints the request as the hub answered it."
183);
184
185/// The long help of `hub request land`.
186pub(crate) const LAND_HELP: &str = concat!(
187 "Land a change request on its base: the snapshot --expect names, or else
188the one it proposes now, which is read first and printed. What lands is
189what was reviewed: when the request moved to another snapshot since, the
190hub lands nothing, and the exit status is 1 (moved).
191
192--mode rebase (the default) fast-forwards the base, or rebases the stack
193onto it; ff-only refuses unless it is a fast-forward (exit status 1).
194Landing needs write and a land:<glob> right that matches the base, and the
195approvals the repository asks for.
196
197Exit statuses: 0 landed; 1 refused (moved, not_on_branch when the base no
198longer holds where the stack starts, not allowed, not found); 2 conflicts,
199printed as `braid land --json` prints them: the request stays open, and its
200author settles them; 3 the hub could not be reached, or failed.
201
202",
203 conflict_loop!(),
204 "
205
206With --json it prints {request, land}: the request as it is now, and the
207landing as `POST …/land` answers it, with verify when the hub verifies the
208base. While the hub holds the base red, braid also says so on standard
209error, as `braid land` does."
210);
211
212/// The long help of `hub request checkout`.
213pub(crate) const CHECKOUT_HELP: &str =
214 "Bring a change request's snapshot into this repository, as the branch
215request/<N> (or --branch NAME). Its changesets, and what they need, come
216through the request itself, so that whoever reads the repository the
217request is on fetches it, even without reading the repository it comes
218from. The branch is created, or moved forward; one with changesets the
219snapshot lacks stays where it is, unless --force.
220
221`braid workspace add NAME --track BRANCH` then makes a workspace on it;
222`braid log`, `braid show` and `braid cat-object` read it as it is.
223
224With --json it prints request, repo, branch, snapshot, before (where the
225branch was, or null), outcome (created, moved or same) and objects (how
226many came).";
227
228/// `hub request`.
229#[derive(Debug, Args)]
230pub(crate) struct RequestArgs {
231 #[command(subcommand)]
232 pub(crate) action: RequestAction,
233}
234
235/// What `hub request` does.
236#[derive(Debug, Subcommand)]
237pub(crate) enum RequestAction {
238 /// Open a change request: from the workspace's changesets, or from a
239 /// branch on the hub.
240 #[command(long_about = CREATE_HELP)]
241 Create(CreateArgs),
242 /// List a repository's change requests, newest first.
243 List(ListArgs),
244 /// Show a change request: what it proposes, whether it lands, its
245 /// reviews and comments.
246 Show(ShowArgs),
247 /// Print the diff of a change request.
248 Diff(DiffArgs),
249 /// Comment on a change request, or on a line of its diff.
250 Comment(CommentArgs),
251 /// Review a change request: approve it, ask for changes, or comment.
252 Review(ReviewArgs),
253 /// Give a change request a new revision: the workspace as it is now.
254 #[command(long_about = UPDATE_HELP)]
255 Update(UpdateArgs),
256 /// Land the snapshot of a change request that was read (exit status 2
257 /// on conflicts).
258 #[command(long_about = LAND_HELP)]
259 Land(LandArgs),
260 /// Close a change request without landing it.
261 Close(NumberArgs),
262 /// Open a closed change request again.
263 Reopen(NumberArgs),
264 /// Mark a draft change request ready for review.
265 Ready(NumberArgs),
266 /// Bring a change request's snapshot into this repository, as a branch.
267 #[command(long_about = CHECKOUT_HELP)]
268 Checkout(CheckoutArgs),
269}
270
271/// A text, from the command line or a file.
272#[derive(Debug, Args)]
273pub(crate) struct BodyArgs {
274 /// The text, Markdown.
275 #[arg(long, value_name = "TEXT")]
276 pub(crate) body: Option<String>,
277 /// Read the text from this file; `-` reads standard input.
278 #[arg(long, value_name = "FILE")]
279 pub(crate) body_file: Option<PathBuf>,
280}
281
282impl BodyArgs {
283 fn text(&self) -> Result<Option<String>> {
284 body_text(self.body.as_deref(), self.body_file.as_deref())
285 }
286}
287
288/// `-R/--hub-repo`: the repository whose change requests a command acts
289/// on.
290#[derive(Clone, Debug, Default, Args)]
291pub(crate) struct TargetArg {
292 /// The repository on the hub, OWNER/NAME (default: the one this
293 /// repository is linked to or, when that is a fork, the repository it
294 /// was forked from).
295 #[arg(short = 'R', long = "hub-repo", value_name = "OWNER/NAME")]
296 pub(crate) hub_repo: Option<String>,
297}
298
299/// `hub request create`.
300#[derive(Debug, Args)]
301pub(crate) struct CreateArgs {
302 #[command(flatten)]
303 pub(crate) repo: TargetArg,
304 /// Its title, one line.
305 #[arg(long, value_name = "TITLE")]
306 pub(crate) title: String,
307 #[command(flatten)]
308 pub(crate) body: BodyArgs,
309 /// Propose this branch, as it is on the hub, instead of the
310 /// workspace's changesets: a branch of OWNER/NAME, else of the
311 /// repository this one is linked to.
312 #[arg(long, value_name = "[OWNER/NAME:]BRANCH")]
313 pub(crate) head: Option<String>,
314 /// The branch it proposes the work for (default: the target's default
315 /// branch).
316 #[arg(long, value_name = "BRANCH")]
317 pub(crate) base: Option<String>,
318 /// Publish what a private head brings to everyone who reads the
319 /// target: needed, from an admin of the head, when the head is in a
320 /// private repository other than the target.
321 #[arg(long)]
322 pub(crate) expose: bool,
323 /// Open it as a draft, which does not land until it is marked ready.
324 #[arg(long)]
325 pub(crate) draft: bool,
326 /// Ask this account to review it; given again, more (the target's
327 /// writers only).
328 #[arg(long = "reviewer", value_name = "LOGIN")]
329 pub(crate) reviewers: Vec<String>,
330}
331
332/// Which change requests `request list` shows.
333#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
334pub(crate) enum StateArg {
335 /// Those open.
336 Open,
337 /// Those closed or landed.
338 Closed,
339 /// Those landed.
340 Landed,
341 /// Every one.
342 All,
343}
344
345impl StateArg {
346 fn as_str(self) -> &'static str {
347 match self {
348 StateArg::Open => "open",
349 StateArg::Closed => "closed",
350 StateArg::Landed => "landed",
351 StateArg::All => "all",
352 }
353 }
354}
355
356/// `hub request list`.
357#[derive(Debug, Args)]
358pub(crate) struct ListArgs {
359 #[command(flatten)]
360 pub(crate) repo: TargetArg,
361 /// Which requests, by state.
362 #[arg(long, value_enum, default_value_t = StateArg::Open)]
363 pub(crate) state: StateArg,
364 /// Only those this account opened.
365 #[arg(long, value_name = "LOGIN")]
366 pub(crate) author: Option<String>,
367 /// Only those proposed for this branch.
368 #[arg(long, value_name = "BRANCH")]
369 pub(crate) base: Option<String>,
370 /// Only those this account is asked to review.
371 #[arg(long, value_name = "LOGIN")]
372 pub(crate) reviewer: Option<String>,
373 /// The most requests to list, 1 to 100 (default: 30).
374 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))]
375 pub(crate) limit: Option<u32>,
376 /// Where to start: the `next` of the page before.
377 #[arg(long, value_name = "CURSOR")]
378 pub(crate) after: Option<String>,
379}
380
381/// `hub request show`.
382#[derive(Debug, Args)]
383pub(crate) struct ShowArgs {
384 /// The request's number.
385 #[arg(value_name = "NUMBER")]
386 pub(crate) number: u64,
387 #[command(flatten)]
388 pub(crate) repo: TargetArg,
389 /// Show its diff too.
390 #[arg(long)]
391 pub(crate) diff: bool,
392}
393
394/// `hub request diff`.
395#[derive(Debug, Args)]
396pub(crate) struct DiffArgs {
397 /// The request's number.
398 #[arg(value_name = "NUMBER")]
399 pub(crate) number: u64,
400 #[command(flatten)]
401 pub(crate) repo: TargetArg,
402 /// The revision whose diff to show, from its merge base to its
403 /// snapshot, or A..B for what changed from revision A to revision B
404 /// (default: the current revision).
405 #[arg(long, value_name = "REV")]
406 pub(crate) rev: Option<String>,
407 /// Only the diff of this file, from the repository's root.
408 #[arg(long, value_name = "PATH")]
409 pub(crate) path: Option<String>,
410}
411
412/// The side of a diff a line comment is on.
413#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
414pub(crate) enum SideArg {
415 /// The version before.
416 Old,
417 /// The version after.
418 New,
419}
420
421impl SideArg {
422 fn as_str(self) -> &'static str {
423 match self {
424 SideArg::Old => proto::OLD,
425 SideArg::New => proto::NEW,
426 }
427 }
428}
429
430/// `hub request comment`.
431#[derive(Debug, Args)]
432pub(crate) struct CommentArgs {
433 /// The request's number.
434 #[arg(value_name = "NUMBER")]
435 pub(crate) number: u64,
436 #[command(flatten)]
437 pub(crate) repo: TargetArg,
438 #[command(flatten)]
439 pub(crate) body: BodyArgs,
440 /// For a comment on a line of the diff: the file, as the diff names it.
441 #[arg(long, value_name = "PATH", requires = "line")]
442 pub(crate) path: Option<String>,
443 /// For a comment on a line of the diff: the line, counted from 1.
444 #[arg(long, value_name = "N", requires = "path")]
445 pub(crate) line: Option<u64>,
446 /// The side of the diff the line is on (default: new).
447 #[arg(long, value_enum, requires = "line")]
448 pub(crate) side: Option<SideArg>,
449 /// The revision whose diff the line is in (default: the current one).
450 #[arg(long, value_name = "N", requires = "line")]
451 pub(crate) revision: Option<u64>,
452}
453
454/// What a review says.
455#[derive(Debug, Args)]
456#[group(required = true, multiple = false)]
457pub(crate) struct VerdictArgs {
458 /// Approve the request's current revision.
459 #[arg(long)]
460 pub(crate) approve: bool,
461 /// Ask for changes before it lands (say which, with a text).
462 #[arg(long)]
463 pub(crate) request_changes: bool,
464 /// Only comment (with a text).
465 #[arg(long)]
466 pub(crate) comment: bool,
467}
468
469impl VerdictArgs {
470 fn as_str(&self) -> &'static str {
471 if self.approve {
472 proto::APPROVE
473 } else if self.request_changes {
474 proto::REQUEST_CHANGES
475 } else {
476 proto::COMMENT
477 }
478 }
479}
480
481/// `hub request review`.
482#[derive(Debug, Args)]
483pub(crate) struct ReviewArgs {
484 /// The request's number.
485 #[arg(value_name = "NUMBER")]
486 pub(crate) number: u64,
487 #[command(flatten)]
488 pub(crate) repo: TargetArg,
489 #[command(flatten)]
490 pub(crate) verdict: VerdictArgs,
491 #[command(flatten)]
492 pub(crate) body: BodyArgs,
493 /// The revision you reviewed: the hub refuses the review (moved) when
494 /// the request has moved past it since.
495 #[arg(long, value_name = "N")]
496 pub(crate) revision: Option<u64>,
497}
498
499/// `hub request update`.
500#[derive(Debug, Args)]
501pub(crate) struct UpdateArgs {
502 /// The request's number.
503 #[arg(value_name = "NUMBER")]
504 pub(crate) number: u64,
505 #[command(flatten)]
506 pub(crate) repo: TargetArg,
507 /// Without a workspace: what the head branch holds on the hub now, or
508 /// the changeset ID on its first-parent chain.
509 #[arg(long, value_name = "ID", num_args = 0..=1)]
510 pub(crate) head: Option<Option<String>>,
511}
512
513/// How `request land` lands.
514#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
515pub(crate) enum ModeArg {
516 /// Fast-forward, or rebase the stack onto the base.
517 Rebase,
518 /// Fast-forward only; refuse otherwise.
519 FfOnly,
520}
521
522impl From<ModeArg> for LandMode {
523 fn from(mode: ModeArg) -> LandMode {
524 match mode {
525 ModeArg::Rebase => LandMode::Rebase,
526 ModeArg::FfOnly => LandMode::FfOnly,
527 }
528 }
529}
530
531/// `hub request land`.
532#[derive(Debug, Args)]
533pub(crate) struct LandArgs {
534 /// The request's number.
535 #[arg(value_name = "NUMBER")]
536 pub(crate) number: u64,
537 #[command(flatten)]
538 pub(crate) repo: TargetArg,
539 /// The snapshot to land, the one you reviewed, in full: nothing lands
540 /// when the request proposes another one now (default: the one it
541 /// proposes when it is read).
542 #[arg(long, value_name = "SNAPSHOT")]
543 pub(crate) expect: Option<String>,
544 /// How it lands.
545 #[arg(long, value_enum, default_value_t = ModeArg::Rebase)]
546 pub(crate) mode: ModeArg,
547}
548
549/// `hub request close`, `reopen` and `ready`.
550#[derive(Debug, Args)]
551pub(crate) struct NumberArgs {
552 /// The request's number.
553 #[arg(value_name = "NUMBER")]
554 pub(crate) number: u64,
555 #[command(flatten)]
556 pub(crate) repo: TargetArg,
557}
558
559/// `hub request checkout`.
560#[derive(Debug, Args)]
561pub(crate) struct CheckoutArgs {
562 /// The request's number.
563 #[arg(value_name = "NUMBER")]
564 pub(crate) number: u64,
565 #[command(flatten)]
566 pub(crate) repo: TargetArg,
567 /// The branch to put its snapshot on (default: `request/<NUMBER>`).
568 #[arg(long, value_name = "NAME")]
569 pub(crate) branch: Option<String>,
570 /// Move the branch even when it holds changesets the snapshot lacks
571 /// (`braid undo` takes that back).
572 #[arg(long)]
573 pub(crate) force: bool,
574}
575
576pub(crate) fn request(cli: &Cli, args: &RequestArgs) -> Result<ExitCode> {
577 let done = match &args.action {
578 RequestAction::Create(args) => create(cli, args),
579 RequestAction::List(args) => list(cli, args),
580 RequestAction::Show(args) => show(cli, args),
581 RequestAction::Diff(args) => diff(cli, args),
582 RequestAction::Comment(args) => comment(cli, args),
583 RequestAction::Review(args) => review(cli, args),
584 RequestAction::Update(args) => update(cli, args),
585 RequestAction::Land(args) => land_request(cli, args),
586 RequestAction::Close(args) => change(
587 cli,
588 args,
589 &RequestPatch {
590 state: Some(proto::CLOSED.to_owned()),
591 ..RequestPatch::default()
592 },
593 "Closed",
594 ),
595 RequestAction::Reopen(args) => change(
596 cli,
597 args,
598 &RequestPatch {
599 state: Some(proto::OPEN.to_owned()),
600 ..RequestPatch::default()
601 },
602 "Reopened",
603 ),
604 RequestAction::Ready(args) => change(
605 cli,
606 args,
607 &RequestPatch {
608 draft: Some(false),
609 ..RequestPatch::default()
610 },
611 "Marked ready for review:",
612 ),
613 RequestAction::Checkout(args) => checkout(cli, args),
614 };
615 match done {
616 Ok(code) => Ok(code),
617 // The hub refused, or could not be reached: said here, with the
618 // exit status that tells the two apart.
619 Err(err) => match hub_error(&err) {
620 Some(hub) => {
621 eprintln!("braid: error: {err:#}");
622 Ok(ExitCode::from(exit_for(hub)))
623 }
624 None => Err(err),
625 },
626 }
627}
628
629/// The hub's error behind `err`, if a request to the hub is why it failed.
630fn hub_error(err: &anyhow::Error) -> Option<&HubError> {
631 err.chain()
632 .find_map(|cause| cause.downcast_ref::<HubError>())
633}
634
635/// A text of several lines from the hub, as braid prints it: each line as
636/// [`shown`] shows text, its line breaks and tabs kept.
637fn shown_lines(text: &str) -> String {
638 text.split('\n')
639 .map(|line| line.split('\t').map(shown).collect::<Vec<_>>().join("\t"))
640 .collect::<Vec<_>>()
641 .join("\n")
642}
643
644/// `text` as a value of a query string: everything but letters, digits
645/// and `-._~` percent-encoded.
646fn encoded(text: &str) -> String {
647 let mut out = String::with_capacity(text.len());
648 for byte in text.bytes() {
649 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
650 out.push(char::from(byte));
651 } else {
652 let _ = write!(out, "%{byte:02X}");
653 }
654 }
655 out
656}
657
658/// A ref's name as the end of a route: each part between slashes
659/// [`encoded`], the slashes kept.
660fn encoded_ref(name: &str) -> String {
661 name.split('/').map(encoded).collect::<Vec<_>>().join("/")
662}
663
664/// Whether `a` and `b` name the same repository: owners and names compare
665/// without regard to case, as the hub compares them.
666fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
667 a.owner.eq_ignore_ascii_case(&b.owner) && a.name.eq_ignore_ascii_case(&b.name)
668}
669
670/// The route of request `number` of `target`.
671fn request_route(target: &RepoPath, number: u64) -> String {
672 format!("{}/requests/{number}", target.api_path())
673}
674
675/// A changeset id given on the command line: 64 hex digits, as the hub
676/// names snapshots.
677fn full_id(text: &str, what: &str) -> Result<ObjectId> {
678 text.parse()
679 .map_err(|_| anyhow::anyhow!("{text:?} is not {what}: give its full id, 64 hex digits"))
680}
681
682/// The name a title gives a branch: its ASCII letters, lowercased, and its
683/// digits, every other run of characters one `-`, without `-` at either
684/// end, at most [`MAX_SLUG`] characters; `change` when nothing is left.
685fn slug(title: &str) -> String {
686 let mut out = String::new();
687 for c in title.chars() {
688 if c.is_ascii_alphanumeric() {
689 out.push(c.to_ascii_lowercase());
690 } else if !out.is_empty() && !out.ends_with('-') {
691 out.push('-');
692 }
693 }
694 // Only ASCII is left, so this cuts between characters.
695 out.truncate(MAX_SLUG);
696 let out = out.trim_end_matches('-');
697 if out.is_empty() {
698 "change".to_owned()
699 } else {
700 out.to_owned()
701 }
702}
703
704/// `slug`, or for `n` above 1 `slug-n`, cut so that it keeps within
705/// [`MAX_SLUG`] characters.
706fn numbered(slug: &str, n: usize) -> String {
707 if n <= 1 {
708 return slug.to_owned();
709 }
710 let suffix = format!("-{n}");
711 let keep = MAX_SLUG.saturating_sub(suffix.len()).min(slug.len());
712 format!("{}{suffix}", slug[..keep].trim_end_matches('-'))
713}
714
715/// Sends a request that creates something with the `Idempotency-Key`
716/// `key`, and sends it once more, with the same key, when its answer was
717/// lost: the hub then gives the first answer again rather than doing it
718/// twice.
719fn create_with<T: DeserializeOwned>(
720 hub: &HttpHub,
721 route: &str,
722 body: &Value,
723 key: &str,
724) -> Result<T, HubError> {
725 let headers = [("Idempotency-Key", key)];
726 match hub.call_json("POST", route, &headers, Some(body)) {
727 Err(err) if err.may_have_happened() => hub.call_json("POST", route, &headers, Some(body)),
728 answer => answer,
729 }
730}
731
732/// [`create_with`], with a new key. When the answer was lost twice, the
733/// error says that the hub may have made `what` all the same, and where to
734/// look.
735fn create_once<T: DeserializeOwned>(
736 hub: &HttpHub,
737 route: &str,
738 body: &Value,
739 what: &str,
740 look: &str,
741) -> Result<T> {
742 create_with(hub, route, body, &idempotency_key()).map_err(|err| {
743 if err.may_have_happened() {
744 anyhow::Error::new(err).context(format!(
745 "the hub may have made {what} before its answer was lost: {look} shows whether it did"
746 ))
747 } else {
748 err.into()
749 }
750 })
751}
752
753/// Where a command acts.
754struct Place {
755 /// The hub.
756 hub: HttpHub,
757 /// Its URL, for the addresses of its pages.
758 url: String,
759 /// The repository whose change requests the command acts on.
760 target: RepoPath,
761 /// The link of the repository the command runs in, when it is linked.
762 link: Option<Link>,
763}
764
765/// The repository `info` was forked from, when the hub names it: only to
766/// those who may read it.
767fn upstream_of(info: &RepoInfo) -> Option<RepoPath> {
768 info.fork_of
769 .as_ref()
770 .and_then(|up| RepoPath::new(&up.owner, &up.name).ok())
771}
772
773/// The link of the repository the command runs in, when it is in one that
774/// is linked to a hub.
775fn linked(cli: &Cli) -> Result<Option<Link>> {
776 match open_repo(cli) {
777 Ok(repo) => Link::read(&repo),
778 // Outside any repository, -R says where.
779 Err(_) if cli.repo.is_none() => Ok(None),
780 Err(err) => Err(err),
781 }
782}
783
784/// Where a command acts: `given` (OWNER/NAME) on the hub signed in to;
785/// else, in a repository linked to a hub, the repository it is linked to
786/// or, when that is a fork, the repository it was forked from.
787fn place_for(link: Option<Link>, given: Option<&str>) -> Result<Place> {
788 if let Some(text) = given {
789 let target: RepoPath = text
790 .parse()
791 .with_context(|| format!("{text:?} is not OWNER/NAME"))?;
792 let env = HubEnv::from_process();
793 let creds = env.credentials()?;
794 let url = creds::hub_url(&env, &creds, None)?;
795 let (hub, _) = super::client(&env, &url)?;
796 return Ok(Place {
797 hub,
798 url,
799 target,
800 link,
801 });
802 }
803 let link = link.context(
804 "no repository named: give -R OWNER/NAME, or run this in a repository linked to a hub",
805 )?;
806 let hub = super::connect(&link)?;
807 let info = hub.repo(link.repo.clone()).info()?;
808 let target = upstream_of(&info).unwrap_or_else(|| link.repo.clone());
809 Ok(Place {
810 hub,
811 url: link.url.clone(),
812 target,
813 link: Some(link),
814 })
815}
816
817/// [`place_for`] the repository the command runs in.
818fn place(cli: &Cli, given: Option<&str>) -> Result<Place> {
819 place_for(linked(cli)?, given)
820}
821
822/// The workspace a command acts on, and its repository.
823struct Found {
824 repo: Repo,
825 name: String,
826 /// Where its `.braid` file was found, when it was found by looking.
827 dir: Option<PathBuf>,
828}
829
830impl Found {
831 /// The workspace `--workspace` names, or the one the current directory
832 /// is in, as `braid land` finds it.
833 fn find(cli: &Cli) -> Result<Found> {
834 if let Some(name) = &cli.workspace {
835 return Ok(Found {
836 repo: open_repo(cli)?,
837 name: name.clone(),
838 dir: None,
839 });
840 }
841 let cwd = std::env::current_dir()?;
842 match braid_repo::locate(&cwd)? {
843 Location::Workspace { dir, link } => {
844 let repo = match &cli.repo {
845 Some(root) => Repo::open_with(root, cli.store_options())?,
846 None => Repo::open_with(&link.repository, cli.store_options())?,
847 };
848 Ok(Found {
849 repo,
850 name: link.name,
851 dir: Some(dir),
852 })
853 }
854 Location::Root(_) => bail!(
855 "not in a workspace: run this in the workspace whose changesets to propose, or name a branch on the hub with --head"
856 ),
857 }
858 }
859
860 fn open(&self) -> Result<Workspace<'_>> {
861 Ok(match &self.dir {
862 Some(dir) => Workspace::at(&self.repo, &self.name, dir)?,
863 None => Workspace::open(&self.repo, &self.name)?,
864 })
865 }
866
867 /// The repository's link, which these commands need.
868 fn link(&self) -> Result<Link> {
869 Link::read(&self.repo)?.context(
870 "this repository is not linked to a hub: `braid hub clone` makes a linked one (of a fork of yours, `braid hub fork OWNER/NAME --clone`)",
871 )
872 }
873}
874
875/// What a workspace proposes: the changesets `braid land` would land, as
876/// its branch stands on the hub.
877struct Work {
878 /// The changesets, oldest first: never none.
879 changes: Vec<ObjectId>,
880 /// The hub's head of the branch.
881 head: Option<ObjectId>,
882}
883
884impl Work {
885 /// The workspace's changesets that its branch on the hub lacks, after
886 /// any changesets of the local branch below them that the hub's branch
887 /// lacks, as `braid land` finds them, once fetched from `remote`. The
888 /// caller has checked the workspace first, with [`Workspace::stack`],
889 /// so that uncommitted changes and a rebase in progress are refused, as
890 /// a landing refuses them, before the hub is asked anything.
891 fn of(
892 repo: &Repo,
893 workspace: &Workspace<'_>,
894 remote: &impl Remote,
895 link: &Link,
896 agent: &str,
897 ) -> Result<Work> {
898 let fetched = fetch(repo, remote, link, agent, None).context(
899 "cannot fetch from the hub, so nothing was proposed: run the command again once it answers",
900 )?;
901 let stack = workspace.stack(None)?;
902 let head = fetched.hub_head(&stack.branch);
903 let changes = hub_stack(repo, &stack, head, &fetched)?;
904 if changes.is_empty() {
905 bail!(
906 "nothing to propose: the workspace holds no changeset that {} lacks on the hub; commit the work first",
907 stack.branch
908 );
909 }
910 let most = remote.max_ids();
911 if changes.len() > most {
912 bail!(
913 "the workspace holds a stack of {} changesets, more than the {most} the hub takes in one go, so nothing was sent",
914 changes.len()
915 );
916 }
917 // As in a landing: changesets below the workspace's own that the
918 // hub's branch had once, and no longer has, were taken off it on
919 // purpose, and a request would bring them back.
920 if changes.len() > stack.changes.len()
921 && let Some(seen) = once_on_hub(repo, &stack.branch, changes[0])?
922 {
923 bail!(
924 "the hub's {} no longer has {} of the changesets below this workspace's own: it was at {} when this repository saw it, so someone took them off, and the request would bring them back; nothing was sent",
925 stack.branch,
926 count(changes.len() - stack.changes.len(), "changeset"),
927 seen.short()
928 );
929 }
930 Ok(Work { changes, head })
931 }
932
933 /// The changeset on top.
934 fn last(&self) -> ObjectId {
935 self.changes[self.changes.len() - 1]
936 }
937
938 /// Uploads to `remote` what it lacks of the changesets: what they
939 /// reach beyond their base and the hub's head of the workspace's
940 /// branch, those of the two `remote` holds.
941 fn upload(&self, store: &Store, remote: &HttpRepo<'_>, link: &Link) -> Result<()> {
942 let base = read_changeset(store, self.changes[0])?
943 .parents
944 .first()
945 .copied();
946 let known: Vec<ObjectId> = base.into_iter().chain(self.head).collect();
947 let lacked = if known.is_empty() {
948 Vec::new()
949 } else {
950 remote.lacks(&known)?
951 };
952 let have: Vec<ObjectId> = known
953 .into_iter()
954 .filter(|id| !lacked.contains(id))
955 .collect();
956 send_stack(store, remote, link, self.last(), &have, self.changes.len()).context(
957 "cannot upload the changesets to the hub, so nothing was proposed: run the command again, which sends only what the hub still lacks",
958 )
959 }
960}
961
962/// The landing of `changes`, fast-forward only, on `branch`.
963fn ff_only(branch: &str, changes: &[ObjectId], agent: &str) -> LandRequest {
964 LandRequest {
965 reference: branch.to_owned(),
966 changes: changes.to_vec(),
967 mode: LandMode::FfOnly,
968 agent: Some(agent.to_owned()),
969 }
970}
971
972/// Puts the work on a new branch of `remote`, `prefix` and the slug, with
973/// `-2`, `-3` and so on when the name holds other work; a branch an earlier
974/// try made, at the work's top, is taken up. A landing that only
975/// fast-forwards never puts the work on top of someone else's. Returns the
976/// branch's name.
977fn new_branch(
978 store: &Store,
979 remote: &HttpRepo<'_>,
980 prefix: &str,
981 slug: &str,
982 work: &Work,
983 agent: &str,
984) -> Result<String> {
985 let last = work.last();
986 let refs = remote.refs()?.refs;
987 for n in 1..=MAX_NAMES {
988 let name = format!("{prefix}{}", numbered(slug, n));
989 match refs.get(&name) {
990 Some(head) if *head == last => return Ok(name),
991 Some(_) => continue,
992 None => {}
993 }
994 let landed = land(
995 store,
996 remote,
997 &ff_only(&name, &work.changes, agent),
998 OffBranch::Stack,
999 )
1000 .context("cannot put the changesets on a branch of the hub, so nothing was proposed")?;
1001 if matches!(landed.outcome.as_str(), "fast-forward" | "already-applied")
1002 && landed.head == Some(last)
1003 {
1004 return Ok(name);
1005 }
1006 // Made by someone else meanwhile: the next name.
1007 }
1008 bail!(
1009 "the names from {prefix}{slug} to {prefix}{} all hold other work on the hub: give another --title",
1010 numbered(slug, MAX_NAMES)
1011 )
1012}
1013
1014/// Whether the caller may land on `name` in `target`: it writes there, as
1015/// `info` says, and its token has a `land:<glob>` right for `target` whose
1016/// glob matches `name`, as the hub decides.
1017fn may_land(me: &Me, target: &RepoPath, info: &RepoInfo, name: &str) -> bool {
1018 if !matches!(info.permission.as_str(), "write" | "admin") {
1019 return false;
1020 }
1021 let Some(token) = &me.token else {
1022 return false;
1023 };
1024 token
1025 .scopes
1026 .iter()
1027 .filter_map(|scope| ParsedScope::parse(scope).ok())
1028 .filter(|scope| scope.repo.matches(target))
1029 .flat_map(|scope| scope.rights)
1030 .any(|right| matches!(right, Right::Land(glob) if glob_matches(&glob, name)))
1031}
1032
1033/// The prefix of the branch a new request of `login` goes on in `target`,
1034/// when the caller may put it there: `request/<login>/`, or `request/`
1035/// when only that one is open to its land rights.
1036fn prefix_on(me: &Me, target: &RepoPath, info: &RepoInfo, slug: &str) -> Option<String> {
1037 [format!("request/{}/", me.login), "request/".to_owned()]
1038 .into_iter()
1039 .find(|prefix| may_land(me, target, info, &format!("{prefix}{slug}")))
1040}
1041
1042/// What `request create` prints in words.
1043fn created_text(target: &RepoPath, request: &Request, address: &str) -> String {
1044 format!(
1045 "Opened {target}#{}: {}\n {} -> {}, {}\n {}",
1046 request.number,
1047 shown(&request.title),
1048 head_name(target, request),
1049 shown(&request.base.reference),
1050 count(request.stack.len(), "changeset"),
1051 shown(address)
1052 )
1053}
1054
1055fn create(cli: &Cli, args: &CreateArgs) -> Result<ExitCode> {
1056 let body = args.body.text()?;
1057 let new = |head: HeadSpec| NewRequest {
1058 title: args.title.clone(),
1059 body: body.clone(),
1060 head,
1061 base: args.base.clone(),
1062 expose: args.expose,
1063 draft: args.draft,
1064 reviewers: args.reviewers.clone(),
1065 agent: agent(cli),
1066 };
1067 if let Some(head) = &args.head {
1068 let place = place(cli, args.repo.hub_repo.as_deref())?;
1069 let (named, branch) = match head.split_once(':') {
1070 Some((repo, branch)) => (
1071 Some(
1072 repo.parse::<RepoPath>()
1073 .with_context(|| format!("{repo:?} is not OWNER/NAME"))?,
1074 ),
1075 branch,
1076 ),
1077 None => (None, head.as_str()),
1078 };
1079 if branch.is_empty() {
1080 bail!("--head names a branch: [OWNER/NAME:]BRANCH");
1081 }
1082 // A branch of this repository's, unless another is named.
1083 let repo = named
1084 .or_else(|| {
1085 place
1086 .link
1087 .as_ref()
1088 .filter(|link| link.url == place.url)
1089 .map(|link| link.repo.clone())
1090 })
1091 .filter(|repo| !same_repo(repo, &place.target));
1092 let asked = new(HeadSpec {
1093 repo: repo.map(|repo| repo.to_string()),
1094 reference: branch.to_owned(),
1095 });
1096 return open_request(cli, &place.hub, &place.url, &place.target, &asked);
1097 }
1098
1099 let found = Found::find(cli)?;
1100 let workspace = found.open()?;
1101 workspace.stack(None)?;
1102 let link = found.link()?;
1103 let hub = super::connect(&link)?;
1104 let linked = hub.repo(link.repo.clone());
1105 let linked_info = linked.info()?;
1106 let target = match &args.repo.hub_repo {
1107 Some(text) => text
1108 .parse::<RepoPath>()
1109 .with_context(|| format!("{text:?} is not OWNER/NAME"))?,
1110 None => upstream_of(&linked_info).unwrap_or_else(|| link.repo.clone()),
1111 };
1112 let same = same_repo(&target, &link.repo);
1113 let target_info = if same {
1114 linked_info.clone()
1115 } else {
1116 hub.repo(target.clone()).info()?
1117 };
1118 let me = hub.me()?;
1119 let slug = slug(&args.title);
1120 // On the target itself when the caller may land there; on the fork
1121 // this repository is linked to otherwise.
1122 let (head_path, head_info, prefix) = match prefix_on(&me, &target, &target_info, &slug) {
1123 Some(prefix) => (target.clone(), &target_info, prefix),
1124 None if !same => (link.repo.clone(), &linked_info, "request/".to_owned()),
1125 None => bail!(
1126 "putting the work on a branch of {target} needs write there, and a land:<glob> right that matches request/{}/{slug}: fork it (`braid hub fork {target} --clone`), commit in the fork's workspace, and open the request from there",
1127 me.login
1128 ),
1129 };
1130 if head_info.private && !same_repo(&head_path, &target) && !args.expose {
1131 bail!(
1132 "{head_path} is private: a request from it publishes what it brings to everyone who reads {target}; an admin of {head_path} opens it with --expose, when that is meant"
1133 );
1134 }
1135 let work = Work::of(&found.repo, &workspace, &linked, &link, &cli.agent)?;
1136 let store = found.repo.store();
1137 let remote = hub.repo(head_path.clone());
1138 work.upload(store, &remote, &link)?;
1139 let branch = new_branch(store, &remote, &prefix, &slug, &work, &cli.agent)?;
1140 let asked = new(HeadSpec {
1141 repo: (!same_repo(&head_path, &target)).then(|| head_path.to_string()),
1142 reference: branch,
1143 });
1144 open_request(cli, &hub, &link.url, &target, &asked)
1145}
1146
1147/// Opens the request `asked` on `target`, and prints it.
1148fn open_request(
1149 cli: &Cli,
1150 hub: &HttpHub,
1151 url: &str,
1152 target: &RepoPath,
1153 asked: &NewRequest,
1154) -> Result<ExitCode> {
1155 let route = format!("{}/requests", target.api_path());
1156 let mut made: Request = create_once(
1157 hub,
1158 &route,
1159 &serde_json::to_value(asked)?,
1160 "the request",
1161 &format!("`braid hub request list -R {target}`"),
1162 )?;
1163 made.html = None;
1164 let address = format!("{url}/{target}/requests/{}", made.number);
1165 print(cli, &serde_json::to_value(&made)?, || {
1166 created_text(target, &made, &address)
1167 })?;
1168 Ok(ExitCode::SUCCESS)
1169}
1170
1171/// A request in a line: its number, its title, and what it is unless open.
1172fn line(request: &Request) -> String {
1173 let mut out = format!("#{} {}", request.number, shown(&request.title));
1174 if request.draft {
1175 out.push_str(" [draft]");
1176 }
1177 match request.state.as_str() {
1178 proto::LANDED => out.push_str(" (landed)"),
1179 proto::CLOSED => out.push_str(" (closed)"),
1180 _ => {}
1181 }
1182 out
1183}
1184
1185/// Where a request's head is, for people: `owner/name:branch`, or the
1186/// branch alone in `target` itself, or in a repository the caller may not
1187/// read, which the hub does not name.
1188fn head_name(target: &RepoPath, request: &Request) -> String {
1189 let branch = shown(&request.head.reference);
1190 match &request.head.repo {
1191 Some(repo)
1192 if !(repo.owner.eq_ignore_ascii_case(&target.owner)
1193 && repo.name.eq_ignore_ascii_case(&target.name)) =>
1194 {
1195 format!("{}/{}:{branch}", shown(&repo.owner), shown(&repo.name))
1196 }
1197 _ => branch,
1198 }
1199}
1200
1201fn list(cli: &Cli, args: &ListArgs) -> Result<ExitCode> {
1202 let place = place(cli, args.repo.hub_repo.as_deref())?;
1203 let target = &place.target;
1204 let mut query = vec![format!("state={}", args.state.as_str())];
1205 for (name, value) in [
1206 ("author", &args.author),
1207 ("base", &args.base),
1208 ("reviewer", &args.reviewer),
1209 ("after", &args.after),
1210 ] {
1211 if let Some(value) = value {
1212 query.push(format!("{name}={}", encoded(value)));
1213 }
1214 }
1215 if let Some(limit) = args.limit {
1216 query.push(format!("limit={limit}"));
1217 }
1218 let route = format!("{}/requests?{}", target.api_path(), query.join("&"));
1219 let page: Requests = place.hub.call_json("GET", &route, &[], None)?;
1220 print(cli, &serde_json::to_value(&page)?, || {
1221 let mut out = String::new();
1222 if page.requests.is_empty() {
1223 out.push_str("No change requests.");
1224 }
1225 for request in &page.requests {
1226 if !out.is_empty() {
1227 out.push('\n');
1228 }
1229 let _ = write!(
1230 out,
1231 "{}, by {}: {} -> {}",
1232 line(request),
1233 shown(&request.author),
1234 head_name(target, request),
1235 shown(&request.base.reference)
1236 );
1237 }
1238 if let Some(next) = &page.next {
1239 let _ = write!(
1240 out,
1241 "\nMore: braid hub request list -R {target} --state {} --after {}",
1242 args.state.as_str(),
1243 shown(next)
1244 );
1245 }
1246 out
1247 })?;
1248 Ok(ExitCode::SUCCESS)
1249}
1250
1251/// Conflicts as `braid land` prints them, a line each: the kind, the path,
1252/// and the regions of a content conflict, the directory removed, or the
1253/// path collided with.
1254fn conflicts_text(conflicts: &[Value]) -> String {
1255 let mut out = String::new();
1256 for conflict in conflicts {
1257 let text = |key: &str| shown(conflict[key].as_str().unwrap_or(""));
1258 let regions = conflict["hunks"].as_array().map_or(0, Vec::len);
1259 let detail = if regions > 0 {
1260 format!(" ({})", count(regions, "region"))
1261 } else if let Some(directory) = conflict["directory"].as_str() {
1262 format!(" (directory {} removed)", shown(directory))
1263 } else if let Some(existing) = conflict["existing"].as_str() {
1264 format!(" (collides with {})", shown(existing))
1265 } else {
1266 String::new()
1267 };
1268 let _ = writeln!(out, " {:<13} {}{detail}", text("kind"), text("path"));
1269 }
1270 out
1271}
1272
1273/// Whether a request lands now, in words.
1274fn mergeable_text(request: &Request) -> String {
1275 let base = shown(&request.base.reference);
1276 match request.mergeable.state.as_str() {
1277 proto::CLEAN => format!("Lands cleanly on {base} as it stands."),
1278 proto::CONFLICTS => format!(
1279 "Conflicts with {base}:\n{}",
1280 conflicts_text(&request.mergeable.conflicts).trim_end()
1281 ),
1282 proto::NEEDS_UPDATE => {
1283 format!("{base} moved to a history its stack is not built on: its author updates it.")
1284 }
1285 _ => "Whether it lands cleanly is being worked out: show it again in a moment.".to_owned(),
1286 }
1287}
1288
1289/// A changeset of a stack in a line: its short id, summary and author.
1290fn changeset_line(entry: &ChangesetSummary) -> String {
1291 format!(
1292 " {} {} ({})",
1293 entry.id.short(),
1294 shown(&entry.summary),
1295 shown(&entry.author.name)
1296 )
1297}
1298
1299/// A comment's heading: who wrote it and when, and what line it is about.
1300fn comment_heading(comment: &RequestComment) -> String {
1301 let mut out = format!(
1302 "{} on {}",
1303 shown(&comment.comment.author),
1304 shown(&comment.comment.created)
1305 );
1306 if let (Some(path), Some(line)) = (&comment.path, comment.line) {
1307 let _ = write!(
1308 out,
1309 ", on {}:{line} ({})",
1310 shown(path),
1311 shown(comment.side.as_deref().unwrap_or(proto::NEW))
1312 );
1313 if let Some(revision) = comment.revision {
1314 let _ = write!(out, " of revision {revision}");
1315 }
1316 if comment.outdated {
1317 out.push_str(", outdated");
1318 }
1319 }
1320 out
1321}
1322
1323/// A comment's text, or why it is hidden.
1324fn comment_body(comment: &RequestComment) -> String {
1325 match &comment.comment.hidden {
1326 Some(reason) if comment.comment.body.is_empty() => format!("(hidden: {})", shown(reason)),
1327 _ => shown_lines(comment.comment.body.trim_end()),
1328 }
1329}
1330
1331/// A request, its reviews and its comments, for people.
1332fn described(
1333 target: &RepoPath,
1334 request: &Request,
1335 reviews: &[Review],
1336 comments: &[RequestComment],
1337) -> String {
1338 let mut out = format!("{target}{}\n", line(request));
1339 let via = request
1340 .agent
1341 .as_deref()
1342 .map_or_else(String::new, |agent| format!(", via {}", shown(agent)));
1343 let _ = writeln!(
1344 out,
1345 "Opened by {} on {}{via}",
1346 shown(&request.author),
1347 shown(&request.created)
1348 );
1349 let _ = writeln!(
1350 out,
1351 "Proposes {} at {} for {}, revision {}",
1352 head_name(target, request),
1353 request.head.snapshot.short(),
1354 shown(&request.base.reference),
1355 request.revision
1356 );
1357 match request.state.as_str() {
1358 proto::LANDED => {
1359 if let Some(landed) = &request.landed {
1360 let _ = writeln!(
1361 out,
1362 "Landed as {} by {} on {}",
1363 landed.head.short(),
1364 shown(&landed.by),
1365 shown(&landed.at)
1366 );
1367 }
1368 }
1369 proto::CLOSED => {
1370 let _ = writeln!(
1371 out,
1372 "Closed by {} on {}",
1373 shown(request.closed_by.as_deref().unwrap_or("?")),
1374 shown(request.closed.as_deref().unwrap_or("?"))
1375 );
1376 }
1377 _ => {
1378 let _ = writeln!(out, "{}", mergeable_text(request));
1379 if let Some(attempt) = &request.last_attempt {
1380 let _ = writeln!(
1381 out,
1382 "The last landing ended in {}: {} on {}",
1383 shown(&attempt.outcome),
1384 shown(&attempt.by),
1385 shown(&attempt.at)
1386 );
1387 }
1388 }
1389 }
1390 let approvals = &request.approvals;
1391 let _ = write!(out, "Approvals: {}", approvals.count);
1392 if !approvals.by.is_empty() {
1393 let _ = write!(out, " ({})", shown(&approvals.by.join(", ")));
1394 }
1395 let _ = writeln!(out, ", {} needed", approvals.required);
1396 if !request.review_requests.is_empty() {
1397 let _ = writeln!(
1398 out,
1399 "Review asked of {}",
1400 shown(&request.review_requests.join(", "))
1401 );
1402 }
1403 if !request.closes.is_empty() {
1404 let numbers: Vec<String> = request.closes.iter().map(|n| format!("#{n}")).collect();
1405 let _ = writeln!(out, "Closes {}", numbers.join(", "));
1406 }
1407 if !request.head.available {
1408 out.push_str("What it brings is no longer held on the hub.\n");
1409 }
1410 if !request.stack.is_empty() {
1411 let _ = writeln!(out, "Stack, oldest first:");
1412 for entry in &request.stack {
1413 let _ = writeln!(out, "{}", changeset_line(entry));
1414 }
1415 }
1416 if !request.brings.is_empty() {
1417 let _ = writeln!(out, "Also brings:");
1418 for entry in &request.brings {
1419 let _ = writeln!(out, "{}", changeset_line(entry));
1420 }
1421 }
1422 if !request.body.trim().is_empty() {
1423 let _ = write!(out, "\n{}\n", shown_lines(request.body.trim_end()));
1424 }
1425 for review in reviews {
1426 let verdict = match review.verdict.as_str() {
1427 proto::APPROVE => "approves",
1428 proto::REQUEST_CHANGES => "asks for changes",
1429 _ => "comments",
1430 };
1431 let mut notes = format!("revision {}", review.revision);
1432 if review.binding {
1433 notes.push_str(", binding");
1434 }
1435 if review.stale {
1436 notes.push_str(", stale");
1437 }
1438 let _ = write!(
1439 out,
1440 "\n--- {} {verdict} on {} ({notes})",
1441 shown(&review.author),
1442 shown(&review.created)
1443 );
1444 if !review.body.trim().is_empty() {
1445 let _ = write!(out, "\n{}", shown_lines(review.body.trim_end()));
1446 }
1447 for comment in &review.comments {
1448 let _ = write!(
1449 out,
1450 "\n {}: {}",
1451 comment_heading(comment),
1452 comment_body(comment)
1453 );
1454 }
1455 out.push('\n');
1456 }
1457 for comment in comments {
1458 let _ = write!(
1459 out,
1460 "\n--- {}\n{}\n",
1461 comment_heading(comment),
1462 comment_body(comment)
1463 );
1464 }
1465 out
1466}
1467
1468/// The query of a request's diff: its revision or range, and its file.
1469fn diff_query(rev: Option<&str>, path: Option<&str>) -> Vec<String> {
1470 let mut query = Vec::new();
1471 if let Some(rev) = rev {
1472 query.push(format!("rev={}", encoded(rev)));
1473 }
1474 if let Some(path) = path {
1475 query.push(format!("path={}", encoded(path.trim_matches('/'))));
1476 }
1477 query
1478}
1479
1480/// The diff `route` (`…/requests/{n}/diff`) answers, as text, as the hub
1481/// writes it.
1482fn diff_text(hub: &HttpHub, route: &str, query: &[String]) -> Result<Vec<u8>, HubError> {
1483 let route = if query.is_empty() {
1484 route.to_owned()
1485 } else {
1486 format!("{route}?{}", query.join("&"))
1487 };
1488 hub.call("GET", &route, &[("Accept", "text/x-diff")], None)
1489}
1490
1491/// Every page of the diff `route` (`…/requests/{n}/diff`) answers, as one.
1492fn diff_pages(hub: &HttpHub, route: &str, query: &[String]) -> Result<DiffPage, HubError> {
1493 let mut all = DiffPage::default();
1494 let mut number = 1;
1495 while number <= MAX_PAGES {
1496 let mut parts = vec![format!("page={number}")];
1497 parts.extend(query.iter().cloned());
1498 let page: DiffPage =
1499 hub.call_json("GET", &format!("{route}?{}", parts.join("&")), &[], None)?;
1500 all.files.extend(page.files);
1501 match page.next_page {
1502 Some(next) if next > number => number = next,
1503 _ => break,
1504 }
1505 }
1506 Ok(all)
1507}
1508
1509fn show(cli: &Cli, args: &ShowArgs) -> Result<ExitCode> {
1510 let place = place(cli, args.repo.hub_repo.as_deref())?;
1511 let route = request_route(&place.target, args.number);
1512 let mut request: Request = place.hub.call_json("GET", &route, &[], None)?;
1513 request.html = None;
1514 let comments: RequestComments =
1515 place
1516 .hub
1517 .call_json("GET", &format!("{route}/comments?limit={SHOWN}"), &[], None)?;
1518 let reviews: Reviews =
1519 place
1520 .hub
1521 .call_json("GET", &format!("{route}/reviews?limit={SHOWN}"), &[], None)?;
1522 let diff_route = format!("{route}/diff");
1523 if cli.json {
1524 let mut value = json!({
1525 "request": request,
1526 "comments": comments.comments,
1527 "next": comments.next,
1528 "reviews": reviews.reviews,
1529 });
1530 if args.diff {
1531 value["diff"] = serde_json::to_value(diff_pages(&place.hub, &diff_route, &[])?)?;
1532 }
1533 print_json(&value)?;
1534 return Ok(ExitCode::SUCCESS);
1535 }
1536 let mut text = described(
1537 &place.target,
1538 &request,
1539 &reviews.reviews,
1540 &comments.comments,
1541 );
1542 if let Some(next) = &comments.next {
1543 let _ = writeln!(
1544 text,
1545 "\nMore comments: braid hub api GET '{route}/comments?after={}'",
1546 shown(next)
1547 );
1548 }
1549 let mut out = std::io::stdout().lock();
1550 writeln!(out, "{}", text.trim_end())?;
1551 if args.diff {
1552 let diff = diff_text(&place.hub, &diff_route, &[])?;
1553 writeln!(out)?;
1554 out.write_all(&diff)?;
1555 }
1556 out.flush()?;
1557 Ok(ExitCode::SUCCESS)
1558}
1559
1560fn diff(cli: &Cli, args: &DiffArgs) -> Result<ExitCode> {
1561 let place = place(cli, args.repo.hub_repo.as_deref())?;
1562 let route = format!("{}/diff", request_route(&place.target, args.number));
1563 let query = diff_query(args.rev.as_deref(), args.path.as_deref());
1564 if cli.json {
1565 print_json(&serde_json::to_value(diff_pages(
1566 &place.hub, &route, &query,
1567 )?)?)?;
1568 return Ok(ExitCode::SUCCESS);
1569 }
1570 let text = diff_text(&place.hub, &route, &query)?;
1571 let mut out = std::io::stdout().lock();
1572 out.write_all(&text)?;
1573 out.flush()?;
1574 Ok(ExitCode::SUCCESS)
1575}
1576
1577fn comment(cli: &Cli, args: &CommentArgs) -> Result<ExitCode> {
1578 let Some(body) = args.body.text()? else {
1579 bail!("a comment needs its text: give --body, or --body-file (- reads standard input)");
1580 };
1581 let place = place(cli, args.repo.hub_repo.as_deref())?;
1582 let asked = NewRequestComment {
1583 body,
1584 path: args.path.clone(),
1585 line: args.line,
1586 side: args.side.map(|side| side.as_str().to_owned()),
1587 revision: args.revision,
1588 agent: agent(cli),
1589 };
1590 let route = format!("{}/comments", request_route(&place.target, args.number));
1591 let look = format!(
1592 "`braid hub request show {} -R {}`",
1593 args.number, place.target
1594 );
1595 let mut said: RequestComment = create_once(
1596 &place.hub,
1597 &route,
1598 &serde_json::to_value(&asked)?,
1599 "the comment",
1600 &look,
1601 )?;
1602 said.comment.html = None;
1603 print(cli, &serde_json::to_value(&said)?, || {
1604 match (&said.path, said.line) {
1605 (Some(path), Some(line)) => format!(
1606 "Commented on line {line} of {} in {}#{}.",
1607 shown(path),
1608 place.target,
1609 args.number
1610 ),
1611 _ => format!("Commented on {}#{}.", place.target, args.number),
1612 }
1613 })?;
1614 Ok(ExitCode::SUCCESS)
1615}
1616
1617fn review(cli: &Cli, args: &ReviewArgs) -> Result<ExitCode> {
1618 let body = args.body.text()?;
1619 let verdict = args.verdict.as_str();
1620 if verdict != proto::APPROVE && body.as_deref().is_none_or(|text| text.trim().is_empty()) {
1621 bail!(
1622 "a review that asks for changes or comments says what: give --body, or --body-file (- reads standard input)"
1623 );
1624 }
1625 let place = place(cli, args.repo.hub_repo.as_deref())?;
1626 let asked = NewReview {
1627 verdict: verdict.to_owned(),
1628 body,
1629 comments: Vec::new(),
1630 revision: args.revision,
1631 agent: agent(cli),
1632 };
1633 let route = format!("{}/reviews", request_route(&place.target, args.number));
1634 let look = format!(
1635 "`braid hub request show {} -R {}`",
1636 args.number, place.target
1637 );
1638 let said: Review = create_once(
1639 &place.hub,
1640 &route,
1641 &serde_json::to_value(&asked)?,
1642 "the review",
1643 &look,
1644 )?;
1645 print(cli, &serde_json::to_value(&said)?, || {
1646 let what = match said.verdict.as_str() {
1647 proto::APPROVE => "Approved",
1648 proto::REQUEST_CHANGES => "Asked for changes on",
1649 _ => "Commented on",
1650 };
1651 let counts = if said.verdict == proto::COMMENT {
1652 ""
1653 } else if said.binding {
1654 ": it counts"
1655 } else {
1656 ": it does not count, since only the repository's writers other than the request's author approve or ask for changes"
1657 };
1658 format!(
1659 "{what} revision {} of {}#{}{counts}.",
1660 said.revision, place.target, args.number
1661 )
1662 })?;
1663 Ok(ExitCode::SUCCESS)
1664}
1665
1666/// Changes request `number` as `patch` says, and prints it.
1667fn change(cli: &Cli, args: &NumberArgs, patch: &RequestPatch, done: &str) -> Result<ExitCode> {
1668 let place = place(cli, args.repo.hub_repo.as_deref())?;
1669 let route = request_route(&place.target, args.number);
1670 let mut request: Request =
1671 place
1672 .hub
1673 .call_json("PATCH", &route, &[], Some(&serde_json::to_value(patch)?))?;
1674 request.html = None;
1675 print(cli, &serde_json::to_value(&request)?, || {
1676 format!("{done} {}{}", place.target, line(&request))
1677 })?;
1678 Ok(ExitCode::SUCCESS)
1679}
1680
1681/// Puts `changes` on `branch` of `remote` (`path`), the head of a change
1682/// request: as a fast-forward when they build on it, or when it is gone;
1683/// otherwise the branch is taken off where it stands, if it still stands
1684/// there, and made again at their top, since the new revision replaces
1685/// what the request proposed.
1686fn put_on_head(
1687 store: &Store,
1688 hub: &HttpHub,
1689 remote: &HttpRepo<'_>,
1690 path: &RepoPath,
1691 branch: &str,
1692 changes: &[ObjectId],
1693 agent: &str,
1694) -> Result<()> {
1695 let landing = ff_only(branch, changes, agent);
1696 let landed = land(store, remote, &landing, OffBranch::Stack)
1697 .context("cannot put the changesets on the request's branch, so it was not updated")?;
1698 match landed.outcome.as_str() {
1699 "fast-forward" | "already-applied" => return Ok(()),
1700 "refused" => {}
1701 other => bail!(
1702 "the hub answered `{}` to putting the changesets on {branch}: the request was not updated",
1703 shown(other)
1704 ),
1705 }
1706 let stood = landed.head_before.with_context(|| {
1707 format!("the hub refused a landing on {branch} without saying where it stands")
1708 })?;
1709 let route = format!(
1710 "{}/refs/{}?expect={}",
1711 path.api_path(),
1712 encoded_ref(branch),
1713 stood.to_hex()
1714 );
1715 hub.call("DELETE", &route, &[], None).with_context(|| {
1716 format!("cannot replace {branch} of {path}, the request's head, so it was not updated")
1717 })?;
1718 let again = land(store, remote, &landing, OffBranch::Stack).with_context(|| {
1719 format!(
1720 "{branch} of {path} was taken off to be made again, and could not be: run the command again, which makes it"
1721 )
1722 })?;
1723 if again.outcome != "fast-forward" {
1724 bail!(
1725 "{branch} of {path} came back elsewhere before braid made it again: the request was not updated; run the command again"
1726 );
1727 }
1728 Ok(())
1729}
1730
1731/// Asks the hub for request `number`'s next revision: what the head
1732/// branch holds, or `head` on it; prints the request.
1733fn revise(
1734 cli: &Cli,
1735 hub: &HttpHub,
1736 target: &RepoPath,
1737 number: u64,
1738 head: Option<ObjectId>,
1739) -> Result<ExitCode> {
1740 let route = format!("{}/update", request_route(target, number));
1741 let asked = serde_json::to_value(RequestUpdate { head })?;
1742 let mut request: Request = hub.call_json("POST", &route, &[], Some(&asked))?;
1743 request.html = None;
1744 print(cli, &serde_json::to_value(&request)?, || {
1745 format!(
1746 "Updated {target}#{number} to revision {}: it proposes {} now, {}.",
1747 request.revision,
1748 request.head.snapshot.short(),
1749 count(request.stack.len(), "changeset")
1750 )
1751 })?;
1752 Ok(ExitCode::SUCCESS)
1753}
1754
1755fn update(cli: &Cli, args: &UpdateArgs) -> Result<ExitCode> {
1756 if let Some(head) = &args.head {
1757 let place = place(cli, args.repo.hub_repo.as_deref())?;
1758 let head = head
1759 .as_deref()
1760 .map(|text| full_id(text, "a changeset"))
1761 .transpose()?;
1762 return revise(cli, &place.hub, &place.target, args.number, head);
1763 }
1764 let found = Found::find(cli)?;
1765 let workspace = found.open()?;
1766 workspace.stack(None)?;
1767 let link = found.link()?;
1768 let hub = super::connect(&link)?;
1769 let linked = hub.repo(link.repo.clone());
1770 let target = match &args.repo.hub_repo {
1771 Some(text) => text
1772 .parse::<RepoPath>()
1773 .with_context(|| format!("{text:?} is not OWNER/NAME"))?,
1774 None => upstream_of(&linked.info()?).unwrap_or_else(|| link.repo.clone()),
1775 };
1776 let number = args.number;
1777 let mut request: Request = hub.call_json("GET", &request_route(&target, number), &[], None)?;
1778 request.html = None;
1779 if request.state != proto::OPEN {
1780 bail!(
1781 "{target}#{number} is {}: only an open request takes a new revision",
1782 shown(&request.state)
1783 );
1784 }
1785 let me = hub.me()?;
1786 if !me.login.eq_ignore_ascii_case(&request.author) {
1787 bail!(
1788 "{target}#{number} is {}'s: only its author gives it a new revision",
1789 shown(&request.author)
1790 );
1791 }
1792 let Some(head) = &request.head.repo else {
1793 bail!(
1794 "the head of {target}#{number} is in a repository you may no longer read, so it cannot take a new revision"
1795 );
1796 };
1797 let head_path = RepoPath::new(&head.owner, &head.name).with_context(|| {
1798 format!(
1799 "the hub names the head's repository {}/{}",
1800 shown(&head.owner),
1801 shown(&head.name)
1802 )
1803 })?;
1804 let work = Work::of(&found.repo, &workspace, &linked, &link, &cli.agent)?;
1805 if work.last() == request.head.snapshot {
1806 print(cli, &serde_json::to_value(&request)?, || {
1807 format!(
1808 "{target}#{number} proposes {} already: nothing to update.",
1809 request.head.snapshot.short()
1810 )
1811 })?;
1812 return Ok(ExitCode::SUCCESS);
1813 }
1814 let store = found.repo.store();
1815 let remote = hub.repo(head_path.clone());
1816 work.upload(store, &remote, &link)?;
1817 put_on_head(
1818 store,
1819 &hub,
1820 &remote,
1821 &head_path,
1822 &request.head.reference,
1823 &work.changes,
1824 &cli.agent,
1825 )?;
1826 revise(cli, &hub, &target, number, Some(work.last()))
1827}
1828
1829/// What `request land` prints in words.
1830fn landed_text(target: &RepoPath, number: u64, landed: &RequestLanded) -> String {
1831 let land = &landed.land;
1832 let base = shown(&land.reference);
1833 let head = land
1834 .head
1835 .map_or_else(|| "(none)".to_owned(), |id| id.short());
1836 match land.outcome.as_str() {
1837 "fast-forward" => format!("Landed {target}#{number} on {base} (fast-forward), at {head}."),
1838 "rebased" => format!("Landed {target}#{number} on {base}, rebased: {base} is at {head}."),
1839 "already-applied" => format!("{base} had the work of {target}#{number} already: landed."),
1840 "conflicts" => format!(
1841 "{target}#{number} does not land on {base}: {} conflicts with {base} at {}, which did not move:\n{}The request stays open: its author settles the conflicts, and updates it (`braid hub request update --help`).",
1842 land.change
1843 .map_or_else(|| "a changeset".to_owned(), |id| id.short()),
1844 land.head_before
1845 .map_or_else(|| "(none)".to_owned(), |id| id.short()),
1846 conflicts_text(&land.conflicts)
1847 ),
1848 "refused" => format!(
1849 "{base} refused the landing of {target}#{number}: it is not a fast-forward. Land it without --mode ff-only to rebase it, or have its author update it."
1850 ),
1851 other => format!(
1852 "The landing of {target}#{number} on {base} ended with {}.",
1853 shown(other)
1854 ),
1855 }
1856}
1857
1858fn land_request(cli: &Cli, args: &LandArgs) -> Result<ExitCode> {
1859 let place = place(cli, args.repo.hub_repo.as_deref())?;
1860 let target = &place.target;
1861 let number = args.number;
1862 let route = request_route(target, number);
1863 let snapshot = match &args.expect {
1864 Some(text) => full_id(text, "a snapshot")?,
1865 None => {
1866 let request: Request = place.hub.call_json("GET", &route, &[], None)?;
1867 let snapshot = request.head.snapshot;
1868 if !cli.json {
1869 println!(
1870 "Landing {target}#{number} at snapshot {snapshot}, as the hub shows it now."
1871 );
1872 }
1873 snapshot
1874 }
1875 };
1876 let asked = serde_json::to_value(RequestLand {
1877 snapshot,
1878 mode: args.mode.into(),
1879 agent: agent(cli),
1880 })?;
1881 let mut landed: RequestLanded = place
1882 .hub
1883 .call_json("POST", &format!("{route}/land"), &[], Some(&asked))
1884 .map_err(|err| {
1885 let what = if err.may_have_happened() {
1886 format!(
1887 "cannot tell whether {target}#{number} landed, since the hub's answer was lost: `braid hub request show {number} -R {target}` says"
1888 )
1889 } else {
1890 format!("{target}#{number} did not land")
1891 };
1892 anyhow::Error::new(err).context(what)
1893 })?;
1894 landed.request.html = None;
1895 let code = match landed.land.outcome.as_str() {
1896 "fast-forward" | "rebased" | "already-applied" => ExitCode::SUCCESS,
1897 "conflicts" => ExitCode::from(CONFLICTS),
1898 _ => ExitCode::from(REFUSED),
1899 };
1900 print(cli, &serde_json::to_value(&landed)?, || {
1901 landed_text(target, number, &landed)
1902 })?;
1903 // The base, red on a hub that verifies it, as `braid land` says.
1904 if let Some(verify) = &landed.land.verify
1905 && let Some(note) = land_note(&landed.land.reference, verify, Some(target))
1906 {
1907 eprintln!("braid: {note}");
1908 }
1909 Ok(code)
1910}
1911
1912/// The branch `request checkout` puts a snapshot on, checked: a name a
1913/// branch may have, outside braid's own namespaces.
1914fn checkout_branch(given: Option<&str>, number: u64) -> Result<String> {
1915 let branch = given.map_or_else(|| format!("request/{number}"), str::to_owned);
1916 if !braid_repo::is_branch(&branch) || !braid_git::is_branch_name(&branch) {
1917 bail!("{branch:?} cannot name a branch: give --branch another name");
1918 }
1919 Ok(branch)
1920}
1921
1922fn checkout(cli: &Cli, args: &CheckoutArgs) -> Result<ExitCode> {
1923 let repo = open_repo(cli).context(
1924 "checkout brings a change request into a repository: run it in one, such as a clone of the repository the request is on",
1925 )?;
1926 let place = place_for(Link::read(&repo)?, args.repo.hub_repo.as_deref())?;
1927 let target = &place.target;
1928 let route = request_route(target, args.number);
1929 let request: Request = place.hub.call_json("GET", &route, &[], None)?;
1930 let number = request.number;
1931 if !request.head.available {
1932 bail!(
1933 "what {target}#{number} brings is no longer held on the hub: it lets go of it a while after a request closes"
1934 );
1935 }
1936 let snapshot = request.head.snapshot;
1937 let branch = checkout_branch(args.branch.as_deref(), number)?;
1938 let store = repo.store();
1939 let refs = store.refs()?;
1940 let before = refs.get(&branch);
1941 // A sparse clone of this hub takes the trees under its paths only.
1942 let paths = place
1943 .link
1944 .as_ref()
1945 .filter(|link| link.url == place.url)
1946 .and_then(|link| link.paths.clone());
1947 let sparse = paths.is_some();
1948 // What a ref points at is whole: a branch at the snapshot needs nothing.
1949 let mut objects = 0;
1950 if before != Some(snapshot) {
1951 let mut have = haves(store, &refs, &[])?;
1952 have.truncate(place.hub.repo(target.clone()).max_ids().max(1));
1953 let asked = MissingRequest {
1954 want: vec![snapshot],
1955 have,
1956 history: None,
1957 paths: paths.clone(),
1958 limit: None,
1959 after: None,
1960 };
1961 let stream = place
1962 .hub
1963 .post_for_objects(&format!("{route}/missing"), &asked)?;
1964 let received = store_stream(store, stream)?;
1965 if !matches!(store.stat(&snapshot)?, Some((Kind::Changeset, _))) {
1966 bail!(
1967 "the hub's object stream did not hold changeset {snapshot}, which was asked for: nothing moved here"
1968 );
1969 }
1970 let prefixes: Option<Vec<Vec<u8>>> =
1971 paths.map(|paths| paths.into_iter().map(String::into_bytes).collect());
1972 whole(store, &received, prefixes.as_deref())?;
1973 objects = received.objects;
1974 }
1975 let outcome = match before {
1976 None => "created",
1977 Some(at) if at == snapshot => "same",
1978 Some(at) => {
1979 let mut history = repo.history();
1980 let forward = history.first_parent_chain_contains(snapshot, at, usize::MAX)?;
1981 history.flush()?;
1982 if !forward && !args.force {
1983 bail!(
1984 "{branch} is at {}, which the snapshot of {target}#{number} does not hold on its first-parent chain, so it stays there: give --branch another name, or --force to move it (`braid undo` takes that back)",
1985 at.short()
1986 );
1987 }
1988 "moved"
1989 }
1990 };
1991 if outcome != "same" {
1992 let description = format!("hub request checkout {target}#{number}");
1993 store
1994 .transact(&cli.agent, &description, |current| {
1995 if current.get(&branch) != before {
1996 return Err(format!(
1997 "{branch} moved while the request came: run the command again"
1998 ));
1999 }
2000 Ok(vec![RefUpdate::new(branch.clone(), before, Some(snapshot))])
2001 })
2002 .map_err(|err| anyhow::anyhow!("{err}"))?;
2003 }
2004 let value = json!({
2005 "request": number,
2006 "repo": target.to_string(),
2007 "branch": branch,
2008 "snapshot": snapshot.to_hex(),
2009 "before": before.map(|id| id.to_hex()),
2010 "outcome": outcome,
2011 "objects": objects,
2012 });
2013 print(cli, &value, || {
2014 let shell_branch = crate::shell_word(&branch);
2015 let next = if sparse {
2016 // A sparse repository holds no workspace.
2017 format!("`braid cat-object {shell_branch}:PATH` reads its files.")
2018 } else {
2019 let workspace = branch.replace('/', "-");
2020 let workspace = if WorkspaceLink::is_valid_name(&workspace) {
2021 workspace
2022 } else {
2023 "review".to_owned()
2024 };
2025 format!(
2026 "`braid workspace add {workspace} --track {shell_branch}` makes a workspace on it."
2027 )
2028 };
2029 let done = match outcome {
2030 "same" => format!(
2031 "{} is at the snapshot of {target}#{number} already, {}.",
2032 shown(&branch),
2033 snapshot.short()
2034 ),
2035 _ => format!(
2036 "Checked out {target}#{number} as {}, at {}: {} came.",
2037 shown(&branch),
2038 snapshot.short(),
2039 count(objects, "object")
2040 ),
2041 };
2042 format!("{done}\n{next}")
2043 })?;
2044 Ok(ExitCode::SUCCESS)
2045}
2046
2047#[cfg(test)]
2048mod tests {
2049 use super::*;
2050 use std::collections::HashMap;
2051 use std::io::{BufRead, BufReader, Read, Write};
2052 use std::net::{TcpListener, TcpStream};
2053 use std::sync::{Arc, Mutex};
2054
2055 #[test]
2056 fn slugs_and_names() {
2057 for (title, slug_of) in [
2058 ("Faster parsing!", "faster-parsing"),
2059 (" Fix #12: the parser ", "fix-12-the-parser"),
2060 ("Ñandú 2", "and-2"),
2061 ("???", "change"),
2062 ("", "change"),
2063 ("UPPER_case", "upper-case"),
2064 ] {
2065 assert_eq!(slug(title), slug_of, "{title:?}");
2066 }
2067 let long = slug(&"word ".repeat(30));
2068 assert!(long.len() <= MAX_SLUG, "{long}");
2069 assert!(!long.ends_with('-'), "{long}");
2070 // Numbered names keep within the length, and never end in two
2071 // dashes.
2072 assert_eq!(numbered("fix", 1), "fix");
2073 assert_eq!(numbered("fix", 2), "fix-2");
2074 let cut = numbered(&"a".repeat(MAX_SLUG), 17);
2075 assert_eq!(cut.len(), MAX_SLUG);
2076 assert!(cut.ends_with("a-17"), "{cut}");
2077 assert_eq!(
2078 numbered(&format!("{}-b", "a".repeat(37)), 10),
2079 format!("{}-10", "a".repeat(37))
2080 );
2081 // Ref names keep their slashes in a route, and lose nothing else.
2082 assert_eq!(encoded_ref("request/ada/fix-2"), "request/ada/fix-2");
2083 assert_eq!(encoded_ref("a b/c?d"), "a%20b/c%3Fd");
2084 assert_eq!(checkout_branch(None, 3).unwrap(), "request/3");
2085 assert!(checkout_branch(Some("review/x"), 3).is_ok());
2086 for bad in ["remote/hub/x", "tags/v1", "a..b", ""] {
2087 assert!(checkout_branch(Some(bad), 3).is_err(), "{bad:?}");
2088 }
2089 }
2090
2091 #[test]
2092 fn land_rights_as_the_hub_decides_them() {
2093 let target: RepoPath = "ada/demo".parse().unwrap();
2094 let info = |permission: &str| RepoInfo {
2095 owner: "ada".into(),
2096 name: "demo".into(),
2097 permission: permission.into(),
2098 ..RepoInfo::default()
2099 };
2100 let me = |scopes: &[(&str, &[&str])]| -> Me {
2101 serde_json::from_value(json!({
2102 "login": "carol",
2103 "token": {
2104 "id": "t1",
2105 "scopes": scopes
2106 .iter()
2107 .map(|(repo, rights)| json!({"repo": repo, "rights": rights}))
2108 .collect::<Vec<_>>(),
2109 "expires": "2099-01-01T00:00:00Z",
2110 },
2111 }))
2112 .unwrap()
2113 };
2114 let everything = me(&[("*", &["read", "write", "land:*"])]);
2115 assert_eq!(
2116 prefix_on(&everything, &target, &info("write"), "fix").as_deref(),
2117 Some("request/carol/")
2118 );
2119 // A glob of one level: the branch goes one level down.
2120 let one = me(&[("ada/demo", &["read", "write", "land:request/*"])]);
2121 assert_eq!(
2122 prefix_on(&one, &target, &info("write"), "fix").as_deref(),
2123 Some("request/")
2124 );
2125 // A reader, or a token for another repository, lands nowhere here.
2126 assert_eq!(prefix_on(&everything, &target, &info("read"), "fix"), None);
2127 let elsewhere = me(&[("bob/*", &["read", "write", "land:*"])]);
2128 assert_eq!(prefix_on(&elsewhere, &target, &info("admin"), "fix"), None);
2129 let main_only = me(&[("ada/demo", &["write", "land:main"])]);
2130 assert_eq!(prefix_on(&main_only, &target, &info("write"), "fix"), None);
2131 // The token of a CI job, which posts verdicts, lands nowhere.
2132 let verdicts = me(&[("ada/demo", &["read", "verify:main"])]);
2133 assert_eq!(prefix_on(&verdicts, &target, &info("write"), "fix"), None);
2134 // Beside a scope that lands it takes nothing away. Nor does a scope
2135 // with a right this braid cannot read, as a braid older than
2136 // `verify:` rights reads one: that scope is left out, and the
2137 // others count.
2138 let both = me(&[
2139 ("ada/demo", &["read", "verify:main"]),
2140 ("ada/demo", &["write", "land:request/*"]),
2141 ]);
2142 assert_eq!(
2143 prefix_on(&both, &target, &info("write"), "fix").as_deref(),
2144 Some("request/")
2145 );
2146 let unread = me(&[
2147 ("ada/demo", &["read", "someday:main"]),
2148 ("ada/demo", &["write", "land:request/*"]),
2149 ]);
2150 assert_eq!(
2151 prefix_on(&unread, &target, &info("write"), "fix").as_deref(),
2152 Some("request/")
2153 );
2154 }
2155
2156 /// A request read off a connection: its `Idempotency-Key` and its body.
2157 fn read_request(stream: &TcpStream) -> (String, String) {
2158 let mut reader = BufReader::new(stream);
2159 let mut key = String::new();
2160 let mut length = 0;
2161 loop {
2162 let mut line = String::new();
2163 reader.read_line(&mut line).unwrap();
2164 let line = line.trim_end();
2165 if line.is_empty() {
2166 break;
2167 }
2168 if let Some((name, value)) = line.split_once(':') {
2169 match name.trim().to_ascii_lowercase().as_str() {
2170 "idempotency-key" => key = value.trim().to_owned(),
2171 "content-length" => length = value.trim().parse().unwrap(),
2172 _ => {}
2173 }
2174 }
2175 }
2176 let mut body = vec![0; length];
2177 reader.read_exact(&mut body).unwrap();
2178 (key, String::from_utf8(body).unwrap())
2179 }
2180
2181 /// Answers a request with `status` and the JSON `body`, and closes.
2182 fn answer(mut stream: TcpStream, status: &str, body: &str) {
2183 write!(
2184 stream,
2185 "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2186 body.len()
2187 )
2188 .unwrap();
2189 }
2190
2191 #[test]
2192 fn idempotent_retry() {
2193 // A hub that keeps what each key made, as the hub does: the first
2194 // request makes request 7, and its answer is lost, the connection
2195 // closed before a word; the same key again gets that answer.
2196 let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
2197 let address = listener.local_addr().unwrap();
2198 let seen: Arc<Mutex<Vec<(String, String)>>> = Arc::default();
2199 let made = Arc::new(Mutex::new(0));
2200 let server = {
2201 let seen = Arc::clone(&seen);
2202 let made = Arc::clone(&made);
2203 std::thread::spawn(move || {
2204 let mut kept: HashMap<String, String> = HashMap::new();
2205 for attempt in 0..2 {
2206 let (stream, _) = listener.accept().unwrap();
2207 let (key, body) = read_request(&stream);
2208 seen.lock().unwrap().push((key.clone(), body));
2209 let reply = kept
2210 .entry(key)
2211 .or_insert_with(|| {
2212 *made.lock().unwrap() += 1;
2213 r#"{"number":7}"#.to_owned()
2214 })
2215 .clone();
2216 if attempt == 0 {
2217 drop(stream);
2218 } else {
2219 answer(stream, "201 Created", &reply);
2220 }
2221 }
2222 })
2223 };
2224 let hub = HttpHub::new(&format!("http://{address}"), None).unwrap();
2225 let body = json!({"title": "Faster", "head": {"ref": "request/faster"}});
2226 let opened: Value = create_with(&hub, "/v1/r/ada/demo/requests", &body, "k1").unwrap();
2227 server.join().unwrap();
2228 assert_eq!(opened["number"], 7);
2229 let seen = seen.lock().unwrap();
2230 assert_eq!(seen.len(), 2);
2231 assert_eq!(seen[0], seen[1], "the same key and body, sent again");
2232 assert_eq!(seen[0].0, "k1");
2233 assert_eq!(serde_json::from_str::<Value>(&seen[0].1).unwrap(), body);
2234 assert_eq!(*made.lock().unwrap(), 1, "made once");
2235
2236 // A refusal is an answer: it is not sent again.
2237 let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
2238 let address = listener.local_addr().unwrap();
2239 let server = std::thread::spawn(move || {
2240 let (stream, _) = listener.accept().unwrap();
2241 read_request(&stream);
2242 answer(
2243 stream,
2244 "409 Conflict",
2245 r#"{"error":"exists","detail":"change request 7 proposes request/faster for main already"}"#,
2246 );
2247 // Nothing else comes: the next connection is refused once the
2248 // listener is gone.
2249 });
2250 let hub = HttpHub::new(&format!("http://{address}"), None).unwrap();
2251 let refused = create_with::<Value>(&hub, "/v1/r/ada/demo/requests", &body, "k2");
2252 server.join().unwrap();
2253 match refused {
2254 Err(HubError::Api { status: 409, body }) => assert_eq!(body.error, "exists"),
2255 other => panic!("{other:?}"),
2256 }
2257 }
2258
2259 #[test]
2260 fn requests_in_words() {
2261 let target: RepoPath = "ada/demo".parse().unwrap();
2262 let mut request: Request = serde_json::from_value(json!({
2263 "number": 3,
2264 "title": "Faster\u{1b}[2J",
2265 "state": "open",
2266 "author": "bob",
2267 "head": {
2268 "repo": {"owner": "bob", "name": "demo"},
2269 "ref": "request/faster",
2270 "snapshot": "11".repeat(32),
2271 "available": true,
2272 },
2273 "base": {"ref": "main"},
2274 "revision": 2,
2275 "created": "2026-10-18T12:00:00Z",
2276 "updated": "2026-10-18T12:00:00Z",
2277 }))
2278 .unwrap();
2279 assert_eq!(line(&request), "#3 Faster\\u{1b}[2J");
2280 assert_eq!(head_name(&target, &request), "bob/demo:request/faster");
2281 request.draft = true;
2282 request.state = proto::LANDED.into();
2283 assert_eq!(line(&request), "#3 Faster\\u{1b}[2J [draft] (landed)");
2284 // A head in the target, or that the caller may not read: the
2285 // branch alone.
2286 request.head.repo = None;
2287 assert_eq!(head_name(&target, &request), "request/faster");
2288 let text = described(&target, &request, &[], &[]);
2289 assert!(text.starts_with("ada/demo#3 Faster"), "{text}");
2290 assert!(!text.contains('\u{1b}'), "{text}");
2291 let conflicts = conflicts_text(&[
2292 json!({"path": "a.txt", "kind": "CONTENT", "hunks": [{}, {}]}),
2293 json!({"path": "d/x", "kind": "DIR_REMOVED", "directory": "d", "hunks": []}),
2294 ]);
2295 assert_eq!(
2296 conflicts,
2297 " CONTENT a.txt (2 regions)\n DIR_REMOVED d/x (directory d removed)\n"
2298 );
2299 }
2300}