Elffuss BraidHub

utopia-ia/elffuss-braid public

2dd40509e7e2 · 7.7 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::{Conflict, ConflictKind, HunkSide, SyncOptions, SyncOutcome, SyncReport};
11use serde_json::{Value, json};
12
13use crate::{Cli, open_repo, print_json};
14
15/// Exit status when the sync found conflicts.
16const CONFLICTS: u8 = 2;
17
18pub(crate) fn git_sync(
19 cli: &Cli,
20 remote: &str,
21 branch: &str,
22 remote_branch: Option<&str>,
23 dry_run: bool,
24) -> Result<ExitCode> {
25 let repo = open_repo(cli)?;
26 let options = SyncOptions {
27 remote_branch: remote_branch.map(str::to_owned),
28 dry_run,
29 ..SyncOptions::default()
30 };
31 let report = repo.git_sync(remote, branch, &cli.agent, &options)?;
32 if cli.json {
33 print_json(&report_json(&report))?;
34 } else {
35 print_text(&report);
36 }
37 Ok(match report.outcome {
38 SyncOutcome::Conflicts(_) => ExitCode::from(CONFLICTS),
39 ref outcome if outcome.is_success() => ExitCode::SUCCESS,
40 _ => ExitCode::FAILURE,
41 })
42}
43
44fn hex(id: Option<ObjectId>) -> Value {
45 id.map_or(Value::Null, |id| Value::String(id.to_hex()))
46}
47
48fn report_json(report: &SyncReport) -> Value {
49 let mut value = json!({
50 "outcome": report.outcome.code(),
51 "dry_run": report.dry_run,
52 "label": report.label,
53 "branch": report.branch,
54 "remote_branch": report.remote_branch,
55 "remote_ref": report.remote_ref,
56 "before": hex(report.before),
57 "after": hex(report.after),
58 "fetched": report.fetched.map(|(commit, changeset)| json!({
59 "commit": commit.to_hex(),
60 "changeset": changeset.to_hex(),
61 })),
62 "pushed": report.pushed.map(|commit| commit.to_hex()),
63 "imported": report.imported,
64 "operations": report.operations.iter().map(|op| op.seq).collect::<Vec<_>>(),
65 });
66 match &report.outcome {
67 SyncOutcome::Merged {
68 merge,
69 merged_paths,
70 } => {
71 value["merge"] = Value::String(merge.to_hex());
72 value["merged_paths"] = merged_paths
73 .iter()
74 .map(|path| Value::String(String::from_utf8_lossy(path).into_owned()))
75 .collect();
76 }
77 SyncOutcome::Conflicts(conflicts) => {
78 value["conflicts"] = conflicts.iter().map(conflict_json).collect();
79 }
80 SyncOutcome::RemoteMoved { found } => {
81 value["found"] = found.map_or(Value::Null, |oid| Value::String(oid.to_hex()));
82 }
83 SyncOutcome::Rejected { reason } => {
84 value["reason"] = Value::String(reason.clone());
85 }
86 _ => {}
87 }
88 value
89}
90
91fn entry_json(entry: &Option<EntryKind>) -> Value {
92 let Some(entry) = entry else {
93 return Value::Null;
94 };
95 match entry {
96 EntryKind::File { blob, size } => {
97 json!({ "kind": "file", "blob": blob.to_hex(), "size": size })
98 }
99 EntryKind::Executable { blob, size } => {
100 json!({ "kind": "executable", "blob": blob.to_hex(), "size": size })
101 }
102 EntryKind::Symlink { blob, size } => {
103 json!({ "kind": "symlink", "blob": blob.to_hex(), "size": size })
104 }
105 EntryKind::Tree { tree } => json!({ "kind": "tree", "tree": tree.to_hex() }),
106 EntryKind::Gitlink { commit } => json!({
107 "kind": "gitlink",
108 "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
109 }),
110 }
111}
112
113fn side_json(side: &HunkSide) -> Value {
114 json!({
115 "start": side.lines.start,
116 "end": side.lines.end,
117 "text": String::from_utf8_lossy(&side.text),
118 })
119}
120
121fn conflict_json(conflict: &Conflict) -> Value {
122 let mut value = json!({
123 "path": String::from_utf8_lossy(&conflict.path),
124 "kind": conflict.kind.code(),
125 "base": entry_json(&conflict.base),
126 "ours": entry_json(&conflict.ours),
127 "theirs": entry_json(&conflict.theirs),
128 });
129 match &conflict.kind {
130 ConflictKind::Content { hunks } => {
131 value["hunks"] = hunks
132 .iter()
133 .map(|hunk| {
134 json!({
135 "base": side_json(&hunk.base),
136 "ours": side_json(&hunk.ours),
137 "theirs": side_json(&hunk.theirs),
138 })
139 })
140 .collect();
141 }
142 ConflictKind::DirectoryRemoved { directory } => {
143 value["directory"] = Value::String(String::from_utf8_lossy(directory).into_owned());
144 }
145 ConflictKind::Case { existing } => {
146 value["existing"] = Value::String(String::from_utf8_lossy(existing).into_owned());
147 }
148 _ => {}
149 }
150 value
151}
152
153fn short(id: Option<ObjectId>) -> String {
154 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
155}
156
157fn print_text(report: &SyncReport) {
158 let (branch, remote) = (&report.branch, &report.remote_ref);
159 let would = |done: &str, planned: &str| {
160 if report.dry_run {
161 planned.to_owned()
162 } else {
163 done.to_owned()
164 }
165 };
166 let pushed = report
167 .pushed
168 .map_or_else(String::new, |commit| commit.to_hex()[..12].to_owned());
169 match &report.outcome {
170 SyncOutcome::UpToDate => println!(
171 "{branch} is up to date with {remote} ({}).",
172 short(report.after)
173 ),
174 SyncOutcome::Created => println!(
175 "{} {branch} at {} from {remote}; {} commits imported.",
176 would("Created", "Would create"),
177 short(report.after),
178 report.imported
179 ),
180 SyncOutcome::FastForwarded => println!(
181 "{} {branch} to {}; {} commits imported.",
182 would("Fast-forwarded", "Would fast-forward"),
183 short(report.after),
184 report.imported
185 ),
186 SyncOutcome::Pushed => println!(
187 "{} {branch} ({}) to {} as {pushed}.",
188 would("Pushed", "Would push"),
189 short(report.after),
190 report.remote_branch
191 ),
192 SyncOutcome::Merged {
193 merge,
194 merged_paths,
195 } => {
196 println!(
197 "{} {remote} into {branch} as {}, and {} it as {pushed}.",
198 would("Merged", "Would merge"),
199 merge.short(),
200 would("pushed", "push")
201 );
202 for path in merged_paths {
203 println!("merged {}", String::from_utf8_lossy(path));
204 }
205 }
206 SyncOutcome::Conflicts(conflicts) => {
207 println!("Conflicts between {branch} and {remote}; nothing moved, nothing was pushed.");
208 for conflict in conflicts {
209 println!(
210 "{:<13} {}",
211 conflict.kind.code(),
212 String::from_utf8_lossy(&conflict.path)
213 );
214 }
215 }
216 SyncOutcome::RemoteMoved { found } => {
217 eprintln!(
218 "braid: error: {} moved after the fetch (it is at {} now); nothing was pushed. Sync again.",
219 report.remote_branch,
220 found.map_or_else(|| "nothing".to_owned(), |oid| oid.to_hex())
221 );
222 if report.after != report.before {
223 eprintln!("{branch} is at the merge {}.", short(report.after));
224 }
225 }
226 SyncOutcome::Rejected { reason } => {
227 eprintln!("braid: error: the remote refused the push: {reason}");
228 if report.after != report.before {
229 eprintln!("{branch} is at the merge {}.", short(report.after));
230 }
231 }
232 other => println!("{}", other.code()),
233 }
234}