| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | | use super::edit::{after_web_commit, signer_for}; |
| 9 | | use super::settings::{csrf, require}; |
| 10 | | use super::{lookup_role, Error, Page, RepoShell, Shell}; |
| 11 | | use crate::auth::{Access, Viewer}; |
| 12 | | use crate::repos::edits; |
| 13 | | use crate::repos::view::{self, FileBody}; |
| 14 | | use crate::Shared; |
| 15 | | use askama::Template; |
| 16 | | use axum::extract::{Form, Path, State}; |
| 17 | | use axum::response::{IntoResponse, Redirect, Response}; |
| 18 | | use oxy_core::repo::FileEdit; |
| 19 | | use std::collections::HashMap; |
| 20 | |
|
| 21 | |
|
| 22 | 5× | pub fn vscode_link(app: &Shared, owner: &str, name: &str, bookmark: &str, path: &str) -> String { |
| 23 | | use super::settings::urlencode; |
| 24 | 5× | let url = format!("{}/{owner}/{name}", app.config.base_url().trim_end_matches('/')); |
| 25 | 5× | format!("vscode://oxygenhub.oxygen-vscode/resolve?url={}&bookmark={}&path={}", urlencode(&url), urlencode(bookmark), urlencode(path)) |
| 26 | 5× | } |
| 27 | |
|
| 28 | |
|
| 29 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 30 | | pub enum Piece { |
| 31 | | |
| 32 | | Plain(String), |
| 33 | | Region(Region), |
| 34 | | } |
| 35 | |
|
| 36 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 37 | | pub struct Region { |
| 38 | | |
| 39 | | pub n: usize, |
| 40 | | pub sides: Vec<Side>, |
| 41 | | } |
| 42 | |
|
| 43 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 44 | | pub struct Side { |
| 45 | | |
| 46 | | pub label: String, |
| 47 | | |
| 48 | | pub text: String, |
| 49 | | |
| 50 | | |
| 51 | | pub deletion: bool, |
| 52 | | } |
| 53 | |
|
| 54 | | impl Side { |
| 55 | | |
| 56 | 18× | pub fn kept(&self) -> &str { |
| 57 | 18× | if self.deletion { |
| 58 | 2× | "" |
| 59 | | } else { |
| 60 | 16× | &self.text |
| 61 | | } |
| 62 | 18× | } |
| 63 | | } |
| 64 | |
|
| 65 | | impl Region { |
| 66 | | |
| 67 | 7× | pub fn all(&self) -> String { |
| 68 | 7× | self.sides.iter().map(Side::kept).collect() |
| 69 | 7× | } |
| 70 | | } |
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | 10× | pub fn parse(marked: &str) -> Option<Vec<Piece>> { |
| 75 | 10× | let mut out = Vec::new(); |
| 76 | 10× | let mut plain = String::new(); |
| 77 | 10× | let mut region: Option<Region> = None; |
| 78 | 10× | let mut lines = marked.split_inclusive('\n').peekable(); |
| 79 | 83× | while let Some(line) = lines.next() { |
| 80 | 73× | let bare = line.trim_end_matches('\n'); |
| 81 | 73× | if let Some(rest) = bare.strip_prefix("<<<<<<< oxy conflict ") { |
| 82 | 11× | if region.is_some() { |
| 83 | 0× | return None; |
| 84 | 11× | } |
| 85 | 11× | if !plain.is_empty() { |
| 86 | 4× | out.push(Piece::Plain(std::mem::take(&mut plain))); |
| 87 | 7× | } |
| 88 | 11× | let (n, label) = header(rest)?; |
| 89 | 11× | let mut side = Side { label, text: String::new(), deletion: false }; |
| 90 | 11× | if lines.peek().map(|l| l.trim_end_matches('\n')) == Some("-------") { |
| 91 | 2× | lines.next(); |
| 92 | 2× | side.deletion = true; |
| 93 | 9× | } |
| 94 | 11× | region = Some(Region { n, sides: vec![side] }); |
| 95 | 62× | } else if let Some(rest) = bare.strip_prefix("======= oxy conflict ") { |
| 96 | 10× | let r = region.as_mut()?; |
| 97 | 10× | let (n, label) = header(rest)?; |
| 98 | 10× | if n != r.n { |
| 99 | 0× | return None; |
| 100 | 10× | } |
| 101 | 10× | r.sides.push(Side { label, text: String::new(), deletion: false }); |
| 102 | 52× | } else if bare.starts_with(">>>>>>> oxy conflict ") { |
| 103 | 10× | out.push(Piece::Region(region.take()?)); |
| 104 | | } else { |
| 105 | 42× | match region.as_mut() { |
| 106 | 23× | Some(r) => r.sides.last_mut()?.text.push_str(line), |
| 107 | 19× | None => plain.push_str(line), |
| 108 | | } |
| 109 | | } |
| 110 | | } |
| 111 | 10× | if region.is_some() { |
| 112 | 1× | return None; |
| 113 | 9× | } |
| 114 | 9× | if !plain.is_empty() { |
| 115 | 9× | out.push(Piece::Plain(plain)); |
| 116 | 9× | } |
| 117 | 9× | Some(out) |
| 118 | 10× | } |
| 119 | |
|
| 120 | |
|
| 121 | 21× | fn header(rest: &str) -> Option<(usize, String)> { |
| 122 | 21× | let (n, tail) = rest.split_once(" of ")?; |
| 123 | 21× | let label = tail.split_once(": ").map(|(_, l)| l.to_string()).unwrap_or_default(); |
| 124 | 21× | Some((n.trim().parse().ok()?, label)) |
| 125 | 21× | } |
| 126 | |
|
| 127 | |
|
| 128 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 129 | | pub enum Choice { |
| 130 | | Side(usize), |
| 131 | | All, |
| 132 | | None, |
| 133 | | Text(String), |
| 134 | | } |
| 135 | |
|
| 136 | |
|
| 137 | |
|
| 138 | 7× | pub fn assemble(pieces: &[Piece], choices: &HashMap<usize, Choice>) -> Result<String, String> { |
| 139 | 7× | let mut out = String::new(); |
| 140 | 24× | for p in pieces { |
| 141 | 24× | match p { |
| 142 | 13× | Piece::Plain(t) => out.push_str(t), |
| 143 | 11× | Piece::Region(r) => match choices.get(&r.n) { |
| 144 | 4× | Some(Choice::Side(i)) => { |
| 145 | 4× | out.push_str(r.sides.get(i.wrapping_sub(1)).ok_or_else(|| format!("conflict {} has no side {i}", r.n))?.kept()) |
| 146 | | } |
| 147 | 1× | Some(Choice::All) => out.push_str(&r.all()), |
| 148 | 2× | Some(Choice::None) => {} |
| 149 | 2× | Some(Choice::Text(t)) => { |
| 150 | 2× | let t = t.replace("\r\n", "\n"); |
| 151 | 2× | out.push_str(&t); |
| 152 | 2× | if !t.is_empty() && !t.ends_with('\n') { |
| 153 | 2× | out.push('\n'); |
| 154 | 2× | } |
| 155 | | } |
| 156 | 2× | None => return Err(format!("choose how to resolve conflict {}", r.n)), |
| 157 | | }, |
| 158 | | } |
| 159 | | } |
| 160 | 4× | Ok(out) |
| 161 | 7× | } |
| 162 | |
|
| 163 | |
|
| 164 | | #[derive(Clone, Debug)] |
| 165 | | pub struct Candidate { |
| 166 | | pub path: String, |
| 167 | | pub content: Vec<u8>, |
| 168 | | |
| 169 | | pub preview: Option<String>, |
| 170 | | } |
| 171 | |
|
| 172 | |
|
| 173 | |
|
| 174 | |
|
| 175 | 13× | fn name_candidates(r: &oxy_core::repo::Repo, snapshot: &oxy_core::state::Snapshot, path: &str) -> Result<Option<Vec<Candidate>>, String> { |
| 176 | | use oxy_core::objects::NodeKind; |
| 177 | | use oxy_core::state::FileContent; |
| 178 | | use oxy_core::tree::TreeConflict; |
| 179 | 13× | let by_node = snapshot.tree.by_node(); |
| 180 | 13× | for c in &snapshot.tree.conflicts { |
| 181 | 3× | let TreeConflict::Name { parent, name, nodes } = c else { continue }; |
| 182 | 3× | let full = if parent.is_root() { |
| 183 | 3× | name.clone() |
| 184 | | } else { |
| 185 | 0× | match by_node.get(parent) { |
| 186 | 0× | Some(e) => format!("{}/{name}", e.path), |
| 187 | 0× | None => continue, |
| 188 | | } |
| 189 | | }; |
| 190 | 3× | if full != path { |
| 191 | 0× | continue; |
| 192 | 3× | } |
| 193 | 3× | let mut out = Vec::new(); |
| 194 | 6× | for n in nodes { |
| 195 | 6× | let Some(e) = by_node.get(n) else { continue }; |
| 196 | 6× | let f = snapshot.files.get(&e.path).ok_or("a candidate is missing")?; |
| 197 | 6× | if f.kind != NodeKind::File { |
| 198 | 0× | return Err("This conflict is between directories or links; resolve it from a client.".into()); |
| 199 | 6× | } |
| 200 | 6× | let content = match &f.content { |
| 201 | 6× | FileContent::Text { bytes, .. } => bytes.clone(), |
| 202 | 0× | FileContent::Opaque { blobs } => match blobs.first() { |
| 203 | 0× | Some(b) => r.read_blob(b).map_err(|e| e.to_string())?, |
| 204 | 0× | None => vec![], |
| 205 | | }, |
| 206 | 0× | FileContent::Dir => continue, |
| 207 | | }; |
| 208 | 6× | let preview = std::str::from_utf8(&content).ok().map(|t| t.lines().take(40).collect::<Vec<_>>().join("\n")); |
| 209 | 6× | out.push(Candidate { path: e.path.clone(), content, preview }); |
| 210 | | } |
| 211 | 3× | out.sort_by(|a, b| a.path.cmp(&b.path)); |
| 212 | 3× | return Ok(Some(out)); |
| 213 | | } |
| 214 | 10× | Ok(None) |
| 215 | 13× | } |
| 216 | |
|
| 217 | |
|
| 218 | |
|
| 219 | 13× | fn replace_candidates( |
| 220 | 13× | r: &oxy_core::repo::Repo, |
| 221 | 13× | state: &oxy_core::state::State, |
| 222 | 13× | snapshot: &oxy_core::state::Snapshot, |
| 223 | 13× | path: &str, |
| 224 | 13× | ) -> Option<Vec<Candidate>> { |
| 225 | | use oxy_core::state::FileContent; |
| 226 | 13× | let f = snapshot.files.get(path)?; |
| 227 | 10× | let FileContent::Opaque { blobs } = &f.content else { return None }; |
| 228 | 3× | if blobs.len() < 2 || f.kind != oxy_core::objects::NodeKind::File { |
| 229 | 0× | return None; |
| 230 | 3× | } |
| 231 | 3× | let writers = state.live_replaces(&f.node); |
| 232 | 3× | let mut out = Vec::new(); |
| 233 | 6× | for (i, b) in blobs.iter().enumerate() { |
| 234 | 6× | let content = r.read_blob(b).ok()?; |
| 235 | 9× | let by = writers.iter().find(|(_, n)| n == b).map(|(h, _)| state.label(h)).unwrap_or_default(); |
| 236 | 6× | let preview = std::str::from_utf8(&content).ok().map(|t| t.lines().take(40).collect::<Vec<_>>().join("\n")); |
| 237 | 6× | out.push(Candidate { path: format!("version {} from change {by}", i + 1), content, preview }); |
| 238 | | } |
| 239 | 3× | Some(out) |
| 240 | 13× | } |
| 241 | |
|
| 242 | |
|
| 243 | | enum Target { |
| 244 | | |
| 245 | | Lines(String), |
| 246 | | |
| 247 | | Name(Vec<Candidate>), |
| 248 | | |
| 249 | | Replace(Vec<Candidate>), |
| 250 | | } |
| 251 | |
|
| 252 | | #[derive(Template)] |
| 253 | | #[template(path = "resolve_name.html")] |
| 254 | | pub struct NamePage { |
| 255 | | shell: Shell, |
| 256 | | repo: RepoShell, |
| 257 | | bookmark: String, |
| 258 | | path: String, |
| 259 | | state: String, |
| 260 | | candidates: Vec<Candidate>, |
| 261 | | |
| 262 | | |
| 263 | | versions: bool, |
| 264 | | vscode: String, |
| 265 | | delegation: Option<String>, |
| 266 | | error: Option<String>, |
| 267 | | message: String, |
| 268 | | } |
| 269 | |
|
| 270 | | #[derive(Template)] |
| 271 | | #[template(path = "resolve.html")] |
| 272 | | pub struct ResolvePage { |
| 273 | | shell: Shell, |
| 274 | | repo: RepoShell, |
| 275 | | bookmark: String, |
| 276 | | path: String, |
| 277 | | state: String, |
| 278 | | pieces: Vec<Piece>, |
| 279 | | |
| 280 | | vscode: String, |
| 281 | | delegation: Option<String>, |
| 282 | | error: Option<String>, |
| 283 | | message: String, |
| 284 | | } |
| 285 | |
|
| 286 | |
|
| 287 | 13× | async fn load(app: &Shared, shell: &Shell, repo: &crate::repos::RepoName, bookmark: &str, path: &str) -> Result<(String, Target), Error> { |
| 288 | 13× | let limit = app.config.limits.render_limit.0; |
| 289 | 13× | let (b, p) = (bookmark.to_string(), path.to_string()); |
| 290 | 13× | let found = app |
| 291 | 13× | .repos |
| 292 | 13× | .read(repo, move |r, cache| { |
| 293 | 13× | let Some(st) = r.view()?.bookmarks.get(&b).copied() else { return Ok(None) }; |
| 294 | 13× | let heads = r.store().get_state(&st)?.heads; |
| 295 | 13× | let loaded = cache.load(r, &heads)?; |
| 296 | 13× | let names = name_candidates(r, &loaded.snapshot, &p); |
| 297 | 13× | let versions = replace_candidates(r, &loaded.state, &loaded.snapshot, &p); |
| 298 | 13× | let file = if names.as_ref().is_ok_and(|n| n.is_some()) { |
| 299 | 3× | None |
| 300 | | } else { |
| 301 | 10× | let target = view::resolve(r, cache, &b)?; |
| 302 | 10× | Some(view::file(r, cache, target, &p, limit)) |
| 303 | | }; |
| 304 | 13× | Ok(Some((st.to_hex(), names, file, versions))) |
| 305 | 13× | }) |
| 306 | 13× | .await |
| 307 | 13× | .map_err(|e| Error::from_repo(shell.clone(), e))?; |
| 308 | 13× | let Some((state, names, file, versions)) = found else { |
| 309 | 0× | return Err(Error::bad(shell.clone(), "Conflicts are resolved on a bookmark.")); |
| 310 | | }; |
| 311 | 13× | if let Some(v) = versions { |
| 312 | 3× | return Ok((state, Target::Replace(v))); |
| 313 | 10× | } |
| 314 | 10× | match names { |
| 315 | 3× | Ok(Some(c)) => return Ok((state, Target::Name(c))), |
| 316 | 0× | Err(msg) => return Err(Error::bad(shell.clone(), &msg)), |
| 317 | 7× | Ok(None) => {} |
| 318 | | } |
| 319 | 7× | let file = match file { |
| 320 | 7× | Some(Ok(f)) => f, |
| 321 | 0× | Some(Err(e)) => return Err(Error::from_repo(shell.clone(), e)), |
| 322 | 0× | None => return Err(Error::bad(shell.clone(), "Nothing to resolve there.")), |
| 323 | | }; |
| 324 | 7× | match file.body { |
| 325 | 7× | FileBody::Text(t) if file.conflicted => Ok((state, Target::Lines(t))), |
| 326 | 0× | FileBody::Text(_) => Err(Error::bad(shell.clone(), "That file has no conflicts on this bookmark.")), |
| 327 | 0× | _ => Err(Error::bad(shell.clone(), "Only text files within the render limit, and name conflicts, are resolved in the browser.")), |
| 328 | | } |
| 329 | 13× | } |
| 330 | |
|
| 331 | | #[allow(clippy::too_many_arguments)] |
| 332 | 3× | async fn page( |
| 333 | 3× | app: &Shared, |
| 334 | 3× | viewer: &Viewer, |
| 335 | 3× | owner: &str, |
| 336 | 3× | name: &str, |
| 337 | 3× | bookmark: &str, |
| 338 | 3× | path: &str, |
| 339 | 3× | error: Option<String>, |
| 340 | 3× | message: Option<String>, |
| 341 | 3× | ) -> Result<Page<ResolvePage>, Error> { |
| 342 | 3× | let shell = Shell::new(app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), viewer); |
| 343 | 3× | let me = require(viewer, &shell)?; |
| 344 | 3× | let (repo, row, role) = lookup_role(app, &shell, viewer, owner, name, Access::Write).await?; |
| 345 | 3× | let (state, target) = load(app, &shell, &repo, bookmark, path).await?; |
| 346 | 3× | let text = match target { |
| 347 | 3× | Target::Lines(t) => t, |
| 348 | 0× | Target::Name(_) | Target::Replace(_) => return Err(Error::bad(shell, "That conflict is resolved by keeping a candidate.")), |
| 349 | | }; |
| 350 | 3× | let Some(pieces) = parse(&text) else { |
| 351 | 0× | return Err(Error::bad(shell, "The conflict markers could not be read; resolve the file in the plain editor.")); |
| 352 | | }; |
| 353 | 3× | let delegation = signer_for(app, me.account.id).await.err(); |
| 354 | | Ok(Page(ResolvePage { |
| 355 | 3× | shell, |
| 356 | 3× | repo: RepoShell::new(app, &row, "conflicts").with_role(role), |
| 357 | 3× | bookmark: bookmark.to_string(), |
| 358 | 3× | path: path.to_string(), |
| 359 | 3× | state, |
| 360 | 3× | pieces, |
| 361 | 3× | vscode: vscode_link(app, owner, name, bookmark, path), |
| 362 | 3× | delegation, |
| 363 | 3× | error, |
| 364 | 3× | message: message.unwrap_or_else(|| format!("Resolve the conflicts in {path}")), |
| 365 | | })) |
| 366 | 3× | } |
| 367 | |
|
| 368 | 3× | pub async fn form( |
| 369 | 3× | State(app): State<Shared>, |
| 370 | 3× | viewer: Viewer, |
| 371 | 3× | Path((owner, name, bookmark, path)): Path<(String, String, String, String)>, |
| 372 | 3× | ) -> Result<Response, Error> { |
| 373 | 3× | let shell = Shell::new(&app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), &viewer); |
| 374 | 3× | let (repo, _, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 375 | 3× | match load(&app, &shell, &repo, &bookmark, &path).await?.1 { |
| 376 | | |
| 377 | 1× | Target::Lines(text) if parse(&text).is_none() => { |
| 378 | 0× | Ok(Redirect::to(&format!("/{owner}/{name}/edit/{bookmark}/{path}")).into_response()) |
| 379 | | } |
| 380 | 1× | Target::Lines(_) => Ok(page(&app, &viewer, &owner, &name, &bookmark, &path, None, None).await?.into_response()), |
| 381 | | Target::Name(_) | Target::Replace(_) => { |
| 382 | 2× | Ok(name_page(&app, &viewer, &owner, &name, &bookmark, &path, None, None).await?.into_response()) |
| 383 | | } |
| 384 | | } |
| 385 | 3× | } |
| 386 | |
|
| 387 | | #[allow(clippy::too_many_arguments)] |
| 388 | 2× | async fn name_page( |
| 389 | 2× | app: &Shared, |
| 390 | 2× | viewer: &Viewer, |
| 391 | 2× | owner: &str, |
| 392 | 2× | name: &str, |
| 393 | 2× | bookmark: &str, |
| 394 | 2× | path: &str, |
| 395 | 2× | error: Option<String>, |
| 396 | 2× | message: Option<String>, |
| 397 | 2× | ) -> Result<Page<NamePage>, Error> { |
| 398 | 2× | let shell = Shell::new(app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), viewer); |
| 399 | 2× | let me = require(viewer, &shell)?; |
| 400 | 2× | let (repo, row, role) = lookup_role(app, &shell, viewer, owner, name, Access::Write).await?; |
| 401 | 2× | let (state, target) = load(app, &shell, &repo, bookmark, path).await?; |
| 402 | 2× | let (candidates, versions) = match target { |
| 403 | 1× | Target::Name(c) => (c, false), |
| 404 | 1× | Target::Replace(c) => (c, true), |
| 405 | 0× | Target::Lines(_) => return Err(Error::bad(shell, "That conflict is resolved region by region.")), |
| 406 | | }; |
| 407 | 2× | let delegation = signer_for(app, me.account.id).await.err(); |
| 408 | | Ok(Page(NamePage { |
| 409 | 2× | shell, |
| 410 | 2× | repo: RepoShell::new(app, &row, "conflicts").with_role(role), |
| 411 | 2× | bookmark: bookmark.to_string(), |
| 412 | 2× | path: path.to_string(), |
| 413 | 2× | state, |
| 414 | 2× | candidates, |
| 415 | 2× | versions, |
| 416 | 2× | vscode: vscode_link(app, owner, name, bookmark, path), |
| 417 | 2× | delegation, |
| 418 | 2× | error, |
| 419 | 2× | message: message.unwrap_or_else(|| { |
| 420 | 2× | if versions { |
| 421 | 1× | format!("Resolve the conflicting versions of {path}") |
| 422 | | } else { |
| 423 | 1× | format!("Resolve the name conflict at {path}") |
| 424 | | } |
| 425 | 2× | }), |
| 426 | | })) |
| 427 | 2× | } |
| 428 | |
|
| 429 | 5× | pub async fn save( |
| 430 | 5× | State(app): State<Shared>, |
| 431 | 5× | viewer: Viewer, |
| 432 | 5× | Path((owner, name, bookmark, path)): Path<(String, String, String, String)>, |
| 433 | 5× | Form(f): Form<HashMap<String, String>>, |
| 434 | 5× | ) -> Result<Response, Error> { |
| 435 | 5× | let shell = Shell::new(&app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), &viewer); |
| 436 | 5× | let me = require(&viewer, &shell)?; |
| 437 | 5× | csrf(&viewer, f.get("_csrf").map(String::as_str).unwrap_or(""), &shell)?; |
| 438 | 5× | let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 439 | 5× | let message = f.get("message").map(|m| m.trim().to_string()).unwrap_or_default(); |
| 440 | 5× | let again = |msg: String| { |
| 441 | 2× | let (app, viewer, owner, name, bookmark, path, message) = |
| 442 | 2× | (app.clone(), viewer.clone(), owner.clone(), name.clone(), bookmark.clone(), path.clone(), message.clone()); |
| 443 | 2× | async move { page(&app, &viewer, &owner, &name, &bookmark, &path, Some(msg), Some(message)).await.map(IntoResponse::into_response) } |
| 444 | 2× | }; |
| 445 | 5× | let (state, target) = load(&app, &shell, &repo, &bookmark, &path).await?; |
| 446 | 5× | let stale = f.get("state") != Some(&state); |
| 447 | 3× | let text = match target { |
| 448 | 3× | Target::Lines(t) => t, |
| 449 | 1× | Target::Name(candidates) | Target::Replace(candidates) if candidates.is_empty() => { |
| 450 | 0× | return again("There are no candidates to keep.".into()).await; |
| 451 | | } |
| 452 | 1× | Target::Replace(candidates) => { |
| 453 | 1× | let again = |msg: String| { |
| 454 | 0× | let (app, viewer, owner, name, bookmark, path, message) = |
| 455 | 0× | (app.clone(), viewer.clone(), owner.clone(), name.clone(), bookmark.clone(), path.clone(), message.clone()); |
| 456 | 0× | async move { |
| 457 | 0× | name_page(&app, &viewer, &owner, &name, &bookmark, &path, Some(msg), Some(message)) |
| 458 | 0× | .await |
| 459 | 0× | .map(IntoResponse::into_response) |
| 460 | 0× | } |
| 461 | 0× | }; |
| 462 | 1× | if stale { |
| 463 | 0× | return again(format!("{bookmark} has moved since this page was loaded; the versions below are as they are now.")).await; |
| 464 | 1× | } |
| 465 | 1× | let Some(keep) = f.get("keep").and_then(|k| k.parse::<usize>().ok()).and_then(|k| candidates.get(k)) else { |
| 466 | 0× | return again("Choose the version to keep.".into()).await; |
| 467 | | }; |
| 468 | 1× | if message.is_empty() { |
| 469 | 0× | return again("Describe the resolution.".into()).await; |
| 470 | 1× | } |
| 471 | 1× | let signer = match signer_for(&app, me.account.id).await { |
| 472 | 1× | Ok(s) => s, |
| 473 | 0× | Err(msg) => return again(msg).await, |
| 474 | | }; |
| 475 | | |
| 476 | 1× | let edit = vec![FileEdit { path: path.clone(), content: Some(keep.content.clone()) }]; |
| 477 | 1× | let done = match edits::commit(&app.repos, &repo, bookmark.clone(), bookmark.clone(), edit, message.clone(), signer).await { |
| 478 | 1× | Ok(d) => d, |
| 479 | 0× | Err(e) => return again(e.to_string()).await, |
| 480 | | }; |
| 481 | 1× | after_web_commit(&app, &me.account, &row, &owner, &name, &done, &message).await; |
| 482 | 1× | let url = format!("/{owner}/{name}/change/{}", done.change.to_hex()); |
| 483 | 1× | share(&app, room(&row, &bookmark, &path), crate::live::RoomEvent::Landed { url: url.clone(), by: me.account.username.clone() }); |
| 484 | 1× | return Ok(Redirect::to(&url).into_response()); |
| 485 | | } |
| 486 | 1× | Target::Name(candidates) => { |
| 487 | 1× | let again = |msg: String| { |
| 488 | 0× | let (app, viewer, owner, name, bookmark, path, message) = |
| 489 | 0× | (app.clone(), viewer.clone(), owner.clone(), name.clone(), bookmark.clone(), path.clone(), message.clone()); |
| 490 | 0× | async move { |
| 491 | 0× | name_page(&app, &viewer, &owner, &name, &bookmark, &path, Some(msg), Some(message)) |
| 492 | 0× | .await |
| 493 | 0× | .map(IntoResponse::into_response) |
| 494 | 0× | } |
| 495 | 0× | }; |
| 496 | 1× | if stale { |
| 497 | 0× | return again(format!("{bookmark} has moved since this page was loaded; the candidates below are as they are now.")).await; |
| 498 | 1× | } |
| 499 | 1× | let Some(keep) = f.get("keep").and_then(|k| k.parse::<usize>().ok()).and_then(|k| candidates.get(k)) else { |
| 500 | 0× | return again("Choose the candidate to keep.".into()).await; |
| 501 | | }; |
| 502 | 1× | if message.is_empty() { |
| 503 | 0× | return again("Describe the resolution.".into()).await; |
| 504 | 1× | } |
| 505 | 1× | let signer = match signer_for(&app, me.account.id).await { |
| 506 | 1× | Ok(s) => s, |
| 507 | 0× | Err(msg) => return again(msg).await, |
| 508 | | }; |
| 509 | | |
| 510 | | |
| 511 | | |
| 512 | 2× | let mut edit: Vec<FileEdit> = candidates.iter().map(|c| FileEdit { path: c.path.clone(), content: None }).collect(); |
| 513 | 1× | edit.push(FileEdit { path: path.clone(), content: Some(keep.content.clone()) }); |
| 514 | 1× | let done = match edits::commit(&app.repos, &repo, bookmark.clone(), bookmark.clone(), edit, message.clone(), signer).await { |
| 515 | 1× | Ok(d) => d, |
| 516 | 0× | Err(e) => return again(e.to_string()).await, |
| 517 | | }; |
| 518 | 1× | after_web_commit(&app, &me.account, &row, &owner, &name, &done, &message).await; |
| 519 | 1× | let url = format!("/{owner}/{name}/change/{}", done.change.to_hex()); |
| 520 | 1× | share(&app, room(&row, &bookmark, &path), crate::live::RoomEvent::Landed { url: url.clone(), by: me.account.username.clone() }); |
| 521 | 1× | return Ok(Redirect::to(&url).into_response()); |
| 522 | | } |
| 523 | | }; |
| 524 | 3× | if stale { |
| 525 | 1× | return again(format!("{bookmark} has moved since this page was loaded; the conflicts below are as they are now.")).await; |
| 526 | 2× | } |
| 527 | 2× | let Some(pieces) = parse(&text) else { return again("The conflict markers could not be read.".into()).await }; |
| 528 | 2× | let mut choices = HashMap::new(); |
| 529 | 4× | for p in &pieces { |
| 530 | 4× | if let Piece::Region(r) = p { |
| 531 | 2× | let choice = match f.get(&format!("r{}", r.n)).map(String::as_str) { |
| 532 | 1× | Some("all") => Choice::All, |
| 533 | 1× | Some("none") => Choice::None, |
| 534 | 1× | Some("text") => Choice::Text(f.get(&format!("t{}", r.n)).cloned().unwrap_or_default()), |
| 535 | 0× | Some(s) => match s.strip_prefix("side").and_then(|i| i.parse().ok()) { |
| 536 | 0× | Some(i) => Choice::Side(i), |
| 537 | 0× | None => continue, |
| 538 | | }, |
| 539 | 1× | None => continue, |
| 540 | | }; |
| 541 | 1× | choices.insert(r.n, choice); |
| 542 | 2× | } |
| 543 | | } |
| 544 | 2× | let content = match assemble(&pieces, &choices) { |
| 545 | 1× | Ok(c) => c, |
| 546 | 1× | Err(msg) => return again(msg).await, |
| 547 | | }; |
| 548 | 1× | if message.is_empty() { |
| 549 | 0× | return again("Describe the resolution.".into()).await; |
| 550 | 1× | } |
| 551 | 1× | let signer = match signer_for(&app, me.account.id).await { |
| 552 | 1× | Ok(s) => s, |
| 553 | 0× | Err(msg) => return again(msg).await, |
| 554 | | }; |
| 555 | 1× | let edit = vec![FileEdit { path: path.clone(), content: Some(content.into_bytes()) }]; |
| 556 | 1× | let done = match edits::commit(&app.repos, &repo, bookmark.clone(), bookmark.clone(), edit, message.clone(), signer).await { |
| 557 | 1× | Ok(d) => d, |
| 558 | 0× | Err(e) => return again(e.to_string()).await, |
| 559 | | }; |
| 560 | 1× | after_web_commit(&app, &me.account, &row, &owner, &name, &done, &message).await; |
| 561 | 1× | let url = format!("/{owner}/{name}/change/{}", done.change.to_hex()); |
| 562 | 1× | share(&app, room(&row, &bookmark, &path), crate::live::RoomEvent::Landed { url: url.clone(), by: me.account.username.clone() }); |
| 563 | 1× | Ok(Redirect::to(&url).into_response()) |
| 564 | 5× | } |
| 565 | |
|
| 566 | | #[cfg(test)] |
| 567 | | mod tests { |
| 568 | | use super::*; |
| 569 | |
|
| 570 | | const MARKED: &str = "a\n<<<<<<< oxy conflict 1 of 2, side 1 of 2: change 0202\nfrom-2\n======= oxy conflict 1 of 2, side 2 of 2: change 0303\nfrom-3\nmore-3\n>>>>>>> oxy conflict 1 of 2 end\nb\n<<<<<<< oxy conflict 2 of 2, side 1 of 2: deleted by change 0404\n-------\ngone\n======= oxy conflict 2 of 2, side 2 of 2: change 0505\nadded\n>>>>>>> oxy conflict 2 of 2 end\nc\n"; |
| 571 | |
|
| 572 | | #[test] |
| 573 | 1× | fn markers_parse_into_regions_and_sides() { |
| 574 | 1× | let p = parse(MARKED).unwrap(); |
| 575 | 1× | assert_eq!(p.len(), 5); |
| 576 | 1× | assert_eq!(p[0], Piece::Plain("a\n".into())); |
| 577 | 1× | let Piece::Region(r1) = &p[1] else { panic!() }; |
| 578 | 1× | assert_eq!((r1.n, r1.sides.len()), (1, 2)); |
| 579 | 1× | assert_eq!((r1.sides[0].label.as_str(), r1.sides[0].text.as_str()), ("change 0202", "from-2\n")); |
| 580 | 1× | assert_eq!(r1.sides[1].text, "from-3\nmore-3\n"); |
| 581 | 1× | let Piece::Region(r2) = &p[3] else { panic!() }; |
| 582 | 1× | assert!(r2.sides[0].deletion && r2.sides[0].text == "gone\n" && r2.sides[0].kept().is_empty()); |
| 583 | 1× | assert_eq!(r2.sides[0].label, "deleted by change 0404"); |
| 584 | 1× | assert_eq!(p[4], Piece::Plain("c\n".into())); |
| 585 | 1× | assert!(parse("<<<<<<< oxy conflict 1 of 1, side 1 of 2: change x\nno end\n").is_none()); |
| 586 | 1× | assert_eq!(parse("plain\n").unwrap(), vec![Piece::Plain("plain\n".into())]); |
| 587 | 1× | } |
| 588 | |
|
| 589 | | #[test] |
| 590 | 1× | fn choices_assemble_the_file() { |
| 591 | 1× | let p = parse(MARKED).unwrap(); |
| 592 | 4× | let pick = |a: Choice, b: Choice| assemble(&p, &HashMap::from([(1, a), (2, b)])); |
| 593 | 1× | assert_eq!(pick(Choice::Side(2), Choice::Side(1)).unwrap(), "a\nfrom-3\nmore-3\nb\nc\n", "the deletion wins: nothing"); |
| 594 | 1× | assert_eq!(pick(Choice::All, Choice::Side(2)).unwrap(), "a\nfrom-2\nfrom-3\nmore-3\nb\nadded\nc\n"); |
| 595 | 1× | assert_eq!(pick(Choice::None, Choice::Text("mine".into())).unwrap(), "a\nb\nmine\nc\n", "own text ends its line"); |
| 596 | 1× | assert!(pick(Choice::Side(3), Choice::None).unwrap_err().contains("no side 3")); |
| 597 | 1× | assert!(assemble(&p, &HashMap::from([(1, Choice::None)])).unwrap_err().contains("conflict 2")); |
| 598 | 1× | } |
| 599 | | } |
| 600 | |
|
| 601 | |
|
| 602 | |
|
| 603 | 5× | fn room(row: &crate::db::repos::RepoRow, bookmark: &str, path: &str) -> crate::live::RoomKey { |
| 604 | 5× | crate::live::RoomKey { repo_id: row.id, bookmark: bookmark.to_string(), path: path.to_string() } |
| 605 | 5× | } |
| 606 | |
|
| 607 | |
|
| 608 | |
|
| 609 | |
|
| 610 | 4× | fn share(app: &Shared, key: crate::live::RoomKey, event: crate::live::RoomEvent) -> bool { |
| 611 | 4× | let here = app.rooms.apply(&key, &event); |
| 612 | 4× | app.bus.publish(crate::bus::Event::Room { room: key, event }); |
| 613 | 4× | here |
| 614 | 4× | } |
| 615 | |
|
| 616 | | #[derive(serde::Deserialize)] |
| 617 | | pub struct LiveQuery { |
| 618 | | |
| 619 | | client: String, |
| 620 | | } |
| 621 | |
|
| 622 | |
|
| 623 | |
|
| 624 | |
|
| 625 | |
|
| 626 | 1× | pub async fn live_events( |
| 627 | 1× | State(app): State<Shared>, |
| 628 | 1× | viewer: Viewer, |
| 629 | 1× | Path((owner, name, bookmark, path)): Path<(String, String, String, String)>, |
| 630 | 1× | axum::extract::Query(q): axum::extract::Query<LiveQuery>, |
| 631 | 1× | ) -> Result<axum::response::Sse<impl futures::Stream<Item = Result<axum::response::sse::Event, std::convert::Infallible>>>, Error> { |
| 632 | | use futures::StreamExt; |
| 633 | 1× | let shell = Shell::new(&app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), &viewer); |
| 634 | 1× | let me = require(&viewer, &shell)?; |
| 635 | 1× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 636 | 5× | let client: String = q.client.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(64).collect(); |
| 637 | 1× | if client.is_empty() { |
| 638 | 0× | return Err(Error::bad(shell, "A live view needs a client id.")); |
| 639 | 1× | } |
| 640 | 1× | let key = room(&row, &bookmark, &path); |
| 641 | 1× | let (rx, snapshot) = app.rooms.join(key.clone(), &client, &me.account.username); |
| 642 | 1× | let seat = app.rooms.seat(key, &client); |
| 643 | 4× | let event = |e: &crate::live::LiveEvent| { |
| 644 | 4× | let kind = match e { |
| 645 | 1× | crate::live::LiveEvent::Snapshot { .. } => "snapshot", |
| 646 | 1× | crate::live::LiveEvent::Presence { .. } => "presence", |
| 647 | 1× | crate::live::LiveEvent::Choice { .. } => "choice", |
| 648 | 1× | crate::live::LiveEvent::Landed { .. } => "landed", |
| 649 | | }; |
| 650 | 4× | Ok(axum::response::sse::Event::default().event(kind).data(serde_json::to_string(e).unwrap_or_default())) |
| 651 | 4× | }; |
| 652 | 1× | let first = futures::stream::once(std::future::ready(event(&snapshot))); |
| 653 | 3× | let rest = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(move |item| { |
| 654 | | |
| 655 | 3× | let _held = &seat; |
| 656 | 3× | std::future::ready(item.ok().map(|e| event(&e))) |
| 657 | 3× | }); |
| 658 | 1× | Ok(axum::response::Sse::new(futures::StreamExt::take_until(first.chain(rest), crate::shutdown::stopping())) |
| 659 | 1× | .keep_alive(axum::response::sse::KeepAlive::default())) |
| 660 | 1× | } |
| 661 | |
|
| 662 | | #[derive(serde::Deserialize)] |
| 663 | | pub struct LiveChoice { |
| 664 | | #[serde(rename = "_csrf")] |
| 665 | | csrf_token: String, |
| 666 | | client: String, |
| 667 | | |
| 668 | | region: String, |
| 669 | | choice: String, |
| 670 | | #[serde(default)] |
| 671 | | text: String, |
| 672 | | } |
| 673 | |
|
| 674 | |
|
| 675 | |
|
| 676 | |
|
| 677 | 2× | pub async fn live_choose( |
| 678 | 2× | State(app): State<Shared>, |
| 679 | 2× | viewer: Viewer, |
| 680 | 2× | Path((owner, name, bookmark, path)): Path<(String, String, String, String)>, |
| 681 | 2× | axum::Json(c): axum::Json<LiveChoice>, |
| 682 | 2× | ) -> Result<axum::http::StatusCode, Error> { |
| 683 | 2× | let shell = Shell::new(&app, &format!("/{owner}/{name}/resolve/{bookmark}/{path}"), &viewer); |
| 684 | 2× | let me = require(&viewer, &shell)?; |
| 685 | 2× | csrf(&viewer, &c.csrf_token, &shell)?; |
| 686 | 2× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 687 | 2× | let valid_region = c.region == "keep" || c.region.parse::<usize>().is_ok(); |
| 688 | 2× | let valid_choice = matches!(c.choice.as_str(), "all" | "none" | "text") |
| 689 | 2× | || c.choice.strip_prefix("side").is_some_and(|i| i.parse::<usize>().is_ok()) |
| 690 | 1× | || (c.region == "keep" && c.choice.parse::<usize>().is_ok()); |
| 691 | 2× | if !valid_region || !valid_choice || c.text.len() > 1 << 20 { |
| 692 | 1× | return Err(Error::bad(shell, "That is not a choice.")); |
| 693 | 1× | } |
| 694 | 1× | let choice = crate::live::Choice { choice: c.choice, text: c.text, by: me.account.username.clone() }; |
| 695 | 1× | Ok(if share(&app, room(&row, &bookmark, &path), crate::live::RoomEvent::Choice { region: c.region, choice, client: c.client }) { |
| 696 | 1× | axum::http::StatusCode::NO_CONTENT |
| 697 | | } else { |
| 698 | 0× | axum::http::StatusCode::GONE |
| 699 | | }) |
| 700 | 2× | } |