Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 6.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `revert`: undo a changeset that landed with a new changeset, and land
5//! that.
6
7use std::process::ExitCode;
8
9use anyhow::{Result, bail};
10use braid_format::ObjectId;
11use braid_repo::Repo;
12use braid_wc::{Identity, RevertRequest};
13use clap::Args;
14use serde_json::json;
15
16use crate::hub::{self, link::Link};
17use crate::work::{IdentityArgs, Report, branches, identity, print_conflicts};
18use crate::{Cli, open_repo, print_json, resolve_changeset};
19
20/// The long help of `revert`.
21pub(crate) const REVERT_HELP: &str =
22 "Undo a changeset that landed on a branch: make a new changeset on it
23whose changes put every file back as its first parent had it, modes,
24symlinks and submodules included, and land that on the branch. The message
25is `Revert \"<subject>\"`, and the changeset has a `reverts` field naming
26the one it undoes.
27
28Landing works as for any change: when the branch has moved on since, the
29revert is rebased onto its head path by path, so later changes to other
30lines and files stay. When a later change touched the same lines, the
31landing stops with conflicts, the branch does not move and the exit status
32is 2: undo the change by hand in a workspace instead.
33
34A changeset without parents cannot be reverted, nor a merge unless
35--mainline 1 says to undo what it brought in against its first parent.
36--no-land only makes the changeset and prints its id. In a repository
37linked to a hub, the revert lands on the hub, then fetches; --local, or
38BRAID_HUB=off, lands here.
39
40With --json it prints revert, the new changeset's id; reverts, the one it
41undoes; branch; and land, the report of the landing as `braid land --help`
42describes it, or null with --no-land.";
43
44#[derive(Debug, Args)]
45pub(crate) struct RevertArgs {
46 /// The changeset to undo: a ref, an id, or a short id (6 hex digits or
47 /// more).
48 revision: String,
49 /// The branch to land the revert on (default: main, master, or the
50 /// repository's only branch).
51 #[arg(long, value_name = "BRANCH")]
52 branch: Option<String>,
53 /// Only make the revert and print its id; do not land it.
54 #[arg(long)]
55 no_land: bool,
56 /// Revert a merge against this parent: only 1, the first, is supported.
57 #[arg(long, value_name = "PARENT", value_parser = clap::value_parser!(u8).range(1..=1))]
58 mainline: Option<u8>,
59 #[command(flatten)]
60 identity: IdentityArgs,
61 /// Land in this repository even if it is linked to a hub.
62 #[arg(long)]
63 local: bool,
64}
65
66/// The branch a command acts on: the one given, or else the repository's
67/// main branch: `main`, `master`, or its only branch.
68pub(crate) fn branch_or_main(repo: &Repo, given: Option<&str>) -> Result<String> {
69 match given {
70 Some(branch) => Ok(branch.to_owned()),
71 None => crate::agents::main_branch(&branches(&repo.store().refs()?)),
72 }
73}
74
75/// Refuses to revert `culprit` on `branch` unless it is on the branch's
76/// first-parent chain, as landing requires: anything else would be stored
77/// first and refused after.
78pub(crate) fn check_on_branch(repo: &Repo, branch: &str, culprit: ObjectId) -> Result<()> {
79 let Some(head) = repo.store().refs()?.get(branch) else {
80 bail!("there is no branch {branch:?} to land the revert on");
81 };
82 if !braid_engine::first_parent_chain_contains(repo.store(), head, culprit, usize::MAX)? {
83 bail!(
84 "changeset {} is not on {branch}'s first-parent chain: only what landed on {branch} can be reverted there",
85 culprit.short()
86 );
87 }
88 Ok(())
89}
90
91/// Lands `change`, a revert made with [`braid_wc::create_revert`], on
92/// `branch`: on the hub of `link`, then fetching, or in this repository.
93pub(crate) fn land_revert(
94 repo: &Repo,
95 link: Option<&Link>,
96 branch: &str,
97 change: ObjectId,
98 agent: &str,
99 committer: &Identity,
100) -> Result<Report> {
101 Ok(match link {
102 Some(link) => {
103 let hub = hub::connect(link)?;
104 let remote = hub.repo(link.repo.clone());
105 let response =
106 hub::land::land_change(repo, &remote, link, branch, change, agent, "braid revert")?;
107 Report::hub(&response)
108 }
109 None => Report::landing(&braid_wc::land_change(
110 repo.store(),
111 branch,
112 change,
113 agent,
114 committer,
115 )?),
116 })
117}
118
119pub(crate) fn revert(cli: &Cli, args: &RevertArgs) -> Result<ExitCode> {
120 let repo = open_repo(cli)?;
121 let culprit = resolve_changeset(&repo, &args.revision)?;
122 let branch = branch_or_main(&repo, args.branch.as_deref())?;
123 let author = identity(&args.identity, &repo)?;
124 let link = if args.no_land {
125 None
126 } else {
127 hub::linked(&repo, args.local)?
128 };
129 if !args.no_land && link.is_none() {
130 check_on_branch(&repo, &branch, culprit)?;
131 }
132 let change = braid_wc::create_revert(
133 repo.store(),
134 &RevertRequest {
135 culprit,
136 allow_merge: args.mainline.is_some(),
137 author: author.clone(),
138 agent: cli.agent.clone(),
139 },
140 )?;
141 let report = if args.no_land {
142 None
143 } else {
144 Some(land_revert(
145 &repo,
146 link.as_ref(),
147 &branch,
148 change,
149 &cli.agent,
150 &author,
151 )?)
152 };
153 let code = report.as_ref().map_or(ExitCode::SUCCESS, Report::exit_code);
154 if cli.json {
155 print_json(&json!({
156 "revert": change.to_hex(),
157 "reverts": culprit.to_hex(),
158 "branch": branch,
159 "land": report.as_ref().map(Report::json),
160 }))?;
161 return Ok(code);
162 }
163 match &report {
164 None => println!(
165 "Made {}, the revert of {}; it has not landed",
166 change.short(),
167 culprit.short()
168 ),
169 Some(report) if report.conflicted() => {
170 println!(
171 "The revert of {} conflicts with what landed on {branch} since; {branch} did not move:",
172 culprit.short()
173 );
174 print_conflicts(&report.conflicts);
175 println!("Undo the change by hand in a workspace instead.");
176 }
177 Some(report) => {
178 println!("Reverted {} with {}", culprit.short(), change.short());
179 report.print_landing(cli);
180 }
181 }
182 Ok(code)
183}