Elffuss BraidHub

utopia-ia/elffuss-braid public

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