Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid git sync`: the report of `Repo::git_sync`, as text or JSON.
5
6use std::process::ExitCode;
7
8use anyhow::Result;
9use braid_format::{EntryKind, ObjectId};
10use braid_repo::{
11 Conflict, ConflictKind, HunkSide, SyncDirection, SyncOptions, SyncOutcome, SyncReport,
12};
13use serde_json::{Value, json};
14
15use crate::{Cli, open_repo, print_json};
16
17/// Exit status when the sync found conflicts.
18const CONFLICTS: u8 = 2;
19
20/// Exit status when the branches are not in the relation `--direction`
21/// requires.
22const DIVERGED: u8 = 3;
23
24/// `--direction`: which way changes may go.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
26pub(crate) enum Direction {
27 /// Both ways, merging when both sides moved.
28 Both,
29 /// Braid to the remote only.
30 Publish,
31 /// The remote to braid only.
32 Follow,
33}
34
35impl From<Direction> for SyncDirection {
36 fn from(direction: Direction) -> Self {
37 match direction {
38 Direction::Both => SyncDirection::Both,
39 Direction::Publish => SyncDirection::Publish,
40 Direction::Follow => SyncDirection::Follow,
41 }
42 }
43}
44
45/// What the text report says to do about conflicts: the two sides meet in
46/// git, and the guide for agents gives the steps.
47const MERGE_IN_GIT: &str = "Merge them in git and push the merge, then sync again: https://braid.elffuss.com/agents.md shows how, under \"Keeping the git remote up to date\".";
48
49pub(crate) fn git_sync(
50 cli: &Cli,
51 remote: &str,
52 branch: &str,
53 remote_branch: Option<&str>,
54 direction: Direction,
55 dry_run: bool,
56) -> Result<ExitCode> {
57 let repo = open_repo(cli)?;
58 let options = SyncOptions {
59 remote_branch: remote_branch.map(str::to_owned),
60 dry_run,
61 direction: direction.into(),
62 ..SyncOptions::default()
63 };
64 let report = repo.git_sync(remote, branch, &cli.agent, &options)?;
65 if cli.json {
66 let mut value = report_json(&report);
67 value["direction"] = Value::String(options.direction.code().to_owned());
68 print_json(&value)?;
69 } else {
70 print_text(&report);
71 }
72 Ok(match report.outcome {
73 SyncOutcome::Conflicts(_) => ExitCode::from(CONFLICTS),
74 SyncOutcome::Diverged { .. } => ExitCode::from(DIVERGED),
75 ref outcome if outcome.is_success() => ExitCode::SUCCESS,
76 _ => ExitCode::FAILURE,
77 })
78}
79
80fn hex(id: Option<ObjectId>) -> Value {
81 id.map_or(Value::Null, |id| Value::String(id.to_hex()))
82}
83
84fn report_json(report: &SyncReport) -> Value {
85 let mut value = json!({
86 "outcome": report.outcome.code(),
87 "dry_run": report.dry_run,
88 "label": report.label,
89 "branch": report.branch,
90 "remote_branch": report.remote_branch,
91 "remote_ref": report.remote_ref,
92 "before": hex(report.before),
93 "after": hex(report.after),
94 "fetched": report.fetched.map(|(commit, changeset)| json!({
95 "commit": commit.to_hex(),
96 "changeset": changeset.to_hex(),
97 })),
98 "pushed": report.pushed.map(|commit| commit.to_hex()),
99 "imported": report.imported,
100 "operations": report.operations.iter().map(|op| op.seq).collect::<Vec<_>>(),
101 });
102 match &report.outcome {
103 SyncOutcome::Merged {
104 merge,
105 merged_paths,
106 } => {
107 value["merge"] = Value::String(merge.to_hex());
108 value["merged_paths"] = merged_paths
109 .iter()
110 .map(|path| Value::String(String::from_utf8_lossy(path).into_owned()))
111 .collect();
112 }
113 SyncOutcome::Conflicts(conflicts) => {
114 value["conflicts"] = conflicts.iter().map(conflict_json).collect();
115 }
116 SyncOutcome::RemoteMoved { found } => {
117 value["found"] = found.map_or(Value::Null, |oid| Value::String(oid.to_hex()));
118 }
119 SyncOutcome::Rejected { reason } | SyncOutcome::Diverged { reason } => {
120 value["reason"] = Value::String(reason.clone());
121 }
122 _ => {}
123 }
124 value
125}
126
127fn entry_json(entry: &Option<EntryKind>) -> Value {
128 let Some(entry) = entry else {
129 return Value::Null;
130 };
131 match entry {
132 EntryKind::File { blob, size } => {
133 json!({ "kind": "file", "blob": blob.to_hex(), "size": size })
134 }
135 EntryKind::Executable { blob, size } => {
136 json!({ "kind": "executable", "blob": blob.to_hex(), "size": size })
137 }
138 EntryKind::Symlink { blob, size } => {
139 json!({ "kind": "symlink", "blob": blob.to_hex(), "size": size })
140 }
141 EntryKind::Tree { tree } => json!({ "kind": "tree", "tree": tree.to_hex() }),
142 EntryKind::Gitlink { commit } => json!({
143 "kind": "gitlink",
144 "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
145 }),
146 }
147}
148
149fn side_json(side: &HunkSide) -> Value {
150 json!({
151 "start": side.lines.start,
152 "end": side.lines.end,
153 "text": String::from_utf8_lossy(&side.text),
154 })
155}
156
157fn conflict_json(conflict: &Conflict) -> Value {
158 let mut value = json!({
159 "path": String::from_utf8_lossy(&conflict.path),
160 "kind": conflict.kind.code(),
161 "base": entry_json(&conflict.base),
162 "ours": entry_json(&conflict.ours),
163 "theirs": entry_json(&conflict.theirs),
164 });
165 match &conflict.kind {
166 ConflictKind::Content { hunks } => {
167 value["hunks"] = hunks
168 .iter()
169 .map(|hunk| {
170 json!({
171 "base": side_json(&hunk.base),
172 "ours": side_json(&hunk.ours),
173 "theirs": side_json(&hunk.theirs),
174 })
175 })
176 .collect();
177 }
178 ConflictKind::DirectoryRemoved { directory } => {
179 value["directory"] = Value::String(String::from_utf8_lossy(directory).into_owned());
180 }
181 ConflictKind::Case { existing } => {
182 value["existing"] = Value::String(String::from_utf8_lossy(existing).into_owned());
183 }
184 _ => {}
185 }
186 value
187}
188
189fn short(id: Option<ObjectId>) -> String {
190 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
191}
192
193fn print_text(report: &SyncReport) {
194 let (branch, remote) = (&report.branch, &report.remote_ref);
195 let would = |done: &str, planned: &str| {
196 if report.dry_run {
197 planned.to_owned()
198 } else {
199 done.to_owned()
200 }
201 };
202 let pushed = report
203 .pushed
204 .map_or_else(String::new, |commit| commit.to_hex()[..12].to_owned());
205 match &report.outcome {
206 SyncOutcome::UpToDate => println!(
207 "{branch} is up to date with {remote} ({}).",
208 short(report.after)
209 ),
210 SyncOutcome::Created => println!(
211 "{} {branch} at {} from {remote}; {} commits imported.",
212 would("Created", "Would create"),
213 short(report.after),
214 report.imported
215 ),
216 SyncOutcome::FastForwarded => println!(
217 "{} {branch} to {}; {} commits imported.",
218 would("Fast-forwarded", "Would fast-forward"),
219 short(report.after),
220 report.imported
221 ),
222 SyncOutcome::Pushed => println!(
223 "{} {branch} ({}) to {} as {pushed}.",
224 would("Pushed", "Would push"),
225 short(report.after),
226 report.remote_branch
227 ),
228 SyncOutcome::Merged {
229 merge,
230 merged_paths,
231 } => {
232 println!(
233 "{} {remote} into {branch} as {}, and {} it as {pushed}.",
234 would("Merged", "Would merge"),
235 merge.short(),
236 would("pushed", "push")
237 );
238 for path in merged_paths {
239 println!("merged {}", String::from_utf8_lossy(path));
240 }
241 }
242 SyncOutcome::Conflicts(conflicts) => {
243 println!("Conflicts between {branch} and {remote}; nothing moved, nothing was pushed.");
244 for conflict in conflicts {
245 println!(
246 "{:<13} {}",
247 conflict.kind.code(),
248 String::from_utf8_lossy(&conflict.path)
249 );
250 }
251 println!("{MERGE_IN_GIT}");
252 }
253 SyncOutcome::RemoteMoved { found } => {
254 eprintln!(
255 "braid: error: {} moved after the fetch (it is at {} now); nothing was pushed. Sync again.",
256 report.remote_branch,
257 found.map_or_else(|| "nothing".to_owned(), |oid| oid.to_hex())
258 );
259 if report.after != report.before {
260 eprintln!("{branch} is at the merge {}.", short(report.after));
261 }
262 }
263 SyncOutcome::Rejected { reason } => {
264 eprintln!("braid: error: the remote refused the push: {reason}");
265 if report.after != report.before {
266 eprintln!("{branch} is at the merge {}.", short(report.after));
267 }
268 }
269 SyncOutcome::Diverged { reason } => {
270 eprintln!(
271 "braid: error: {reason}: {branch} and {} were left as they were; nothing was recorded, merged or pushed.",
272 report.remote_branch
273 );
274 }
275 other => println!("{}", other.code()),
276 }
277}