Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 5 |
| use std::path::{Path, PathBuf}; |
| 6 |
| 7 | use serde_json::json; |
| 8 | use vcs_core::merge::{self, Mode}; |
| 9 | use vcs_core::tree::{self, Files}; |
| 10 | use vcs_core::version::Version; |
| 11 | use vcs_core::{Id, diff}; |
| 12 |
| 13 | use crate::app::{App, Session, ensure_dir_empty}; |
| 14 | use crate::db::{Change, Conflict, Project, Save, Workspace}; |
| 15 | use crate::host::{LandRequest, Landed}; |
| 16 | use crate::ids; |
| 17 | use crate::out::{Fail, Out, Report}; |
| 18 | use crate::secrets; |
| 19 | use crate::ws::{self, CowSource, Index}; |
| 20 |
| 21 | // Labels people see. |
| 22 |
| 23 | fn main_label(n: Option<u64>) -> String { |
| 24 | match n { |
| 25 | Some(n) => format!("main {n}"), |
| 26 | None => "an empty main".into(), |
| 27 | } |
| 28 | } |
| 29 |
| 30 | fn base_text(app: &App, project: &Project, c: &Change) -> String { |
| 31 | if let Some(on) = &c.on_change { |
| 32 | return format!("change {} (not landed yet)", app.short(project, on)); |
| 33 | } |
| 34 | if let Some(after) = &c.after_change { |
| 35 | let landed = app.db.change(after).ok().flatten().and_then(|a| a.version); |
| 36 | return match landed { |
| 37 | Some(n) => format!("what you landed as main {n} (change {})", app.short(project, after)), |
| 38 | None => format!("change {}", app.short(project, after)), |
| 39 | }; |
| 40 | } |
| 41 | main_label(c.base_version) |
| 42 | } |
| 43 |
| 44 | fn change_json(app: &App, project: &Project, c: &Change) -> serde_json::Value { |
| 45 | json!({ |
| 46 | "id": c.id, |
| 47 | "short": app.short(project, &c.id), |
| 48 | "title": c.title, |
| 49 | "body": c.body, |
| 50 | "state": c.state, |
| 51 | "base": c.base_version, |
| 52 | "on": c.on_change, |
| 53 | "saves": c.saves, |
| 54 | "version": c.version, |
| 55 | "author": c.author, |
| 56 | "conflicts": c.conflicts.iter().map(|x| &x.path).collect::<Vec<_>>(), |
| 57 | }) |
| 58 | } |
| 59 |
| 60 | fn require_title(c: &Change) -> Result<(), Fail> { |
| 61 | if c.title.trim().is_empty() { |
| 62 | return Err(Fail::new("no_description", format!("change {} has no description", c.id)) |
| 63 | .state("nothing changed; your change is saved") |
| 64 | .next(format!("vcs land -m \"what you did\""))); |
| 65 | } |
| 66 | Ok(()) |
| 67 | } |
| 68 |
| 69 | // Start. |
| 70 |
| 71 | pub fn init(app: &App, folder: Option<PathBuf>) -> Out { |
| 72 | let root = folder.map(|f| app.cwd.join(f)).unwrap_or_else(|| app.cwd.clone()); |
| 73 | std::fs::create_dir_all(&root)?; |
| 74 | let root = crate::sys::canonical(&root)?; |
| 75 | if ws::find(&root).is_some() { |
| 76 | return Err(Fail::new("bad_usage", format!("{} is already in a vcs workspace", root.display())).state("nothing changed")); |
| 77 | } |
| 78 | let project = Project { |
| 79 | id: format!("local-{}", ids::new_workspace_id()), |
| 80 | address: root.to_string_lossy().into_owned(), |
| 81 | kind: "local".into(), |
| 82 | api: None, |
| 83 | checked: ids::now(), |
| 84 | }; |
| 85 | app.db.put_project(&project)?; |
| 86 | let empty = app.store.put(&tree::empty())?; |
| 87 | let author = app.author(&project); |
| 88 | let change = Change::new(ids::new_change_id(), &project.id, empty, None, &author); |
| 89 | app.db.put_change(&change)?; |
| 90 | let workspace = Workspace { id: ids::new_workspace_id(), project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: vec![] }; |
| 91 | ws::write_id(&root, &workspace.id)?; |
| 92 | app.db.put_workspace(&workspace)?; |
| 93 | let mut s = app.session_at(&root)?; |
| 94 | let saved = app.save(&mut s)?; |
| 95 | let mut r = Report::new(); |
| 96 | r.line("project", format!("{} (on this machine only)", project.address)) |
| 97 | .line("workspace", root.display().to_string()) |
| 98 | .line("change", format!("{} new{}", app.short(&project, &change.id), if saved.is_empty() { ", empty" } else { ", holds the files already here" })) |
| 99 | .set("project", project.address.clone()) |
| 100 | .set("workspace", root.display().to_string()) |
| 101 | .set("change", change_json(app, &project, &saved)) |
| 102 | .next("add or edit files, then vcs land -m \"First version\""); |
| 103 | Ok(r) |
| 104 | } |
| 105 |
| 106 | /// `vcs get`. |
| 107 | /// `vcs get`: a new workspace on a new change (on main, or on the change |
| 108 | /// `on` when it's given), or on an existing change. |
| 109 | pub fn get(app: &App, target: &str, folder: Option<PathBuf>, change_id: Option<String>, only: Vec<String>, on: Option<String>) -> Out { |
| 110 | let project = resolve_project(app, target)?; |
| 111 | let name = project.address.trim_end_matches('/').rsplit('/').next().unwrap_or("project").to_string(); |
| 112 | let root = app.cwd.join(folder.unwrap_or_else(|| PathBuf::from(&name))); |
| 113 | ensure_dir_empty(&root)?; |
| 114 | let main = app.refresh(&project)?; |
| 115 | let only: Vec<String> = only.into_iter().map(|o| o.trim_matches('/').to_string()).filter(|o| !o.is_empty()).collect(); |
| 116 |
| 117 | let author = app.author(&project); |
| 118 | let workspace_id = ids::new_workspace_id(); |
| 119 | let mut took_from = None; |
| 120 | let (change, tree) = match change_id { |
| 121 | Some(text) => { |
| 122 | let mut c = app.find_change(&project, &text)?; |
| 123 | if c.state == "landed" || c.state == "dropped" { |
| 124 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 125 | } |
| 126 | took_from = take_over(app, &project, &mut c, &workspace_id, &root)?; |
| 127 | let t = c.tree(); |
| 128 | (c, t) |
| 129 | } |
| 130 | None => { |
| 131 | let parent = match &on { |
| 132 | Some(text) => { |
| 133 | let parent = app.find_change(&project, text)?; |
| 134 | if parent.state == "landed" || parent.state == "dropped" { |
| 135 | return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)).state("nothing changed")); |
| 136 | } |
| 137 | if project.hosted() { |
| 138 | crate::remote::Remote::for_project(&project).fetch_saves(&app.db, &app.store, &project, &parent)?; |
| 139 | } |
| 140 | Some(parent) |
| 141 | } |
| 142 | None => None, |
| 143 | }; |
| 144 | let mut c = match &parent { |
| 145 | Some(p) => Change::new(ids::new_change_id(), &project.id, p.tree(), None, &author), |
| 146 | None => { |
| 147 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 148 | Change::new(ids::new_change_id(), &project.id, base, main.as_ref().map(|v| v.n), &author) |
| 149 | } |
| 150 | }; |
| 151 | c.on_change = parent.map(|p| p.id); |
| 152 | app.db.put_change(&c)?; |
| 153 | let base = c.base_tree; |
| 154 | (c, base) |
| 155 | } |
| 156 | }; |
| 157 |
| 158 | std::fs::create_dir_all(&root)?; |
| 159 | let root = crate::sys::canonical(&root)?; |
| 160 | let workspace = Workspace { id: workspace_id, project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: only.clone() }; |
| 161 | ws::write_id(&root, &workspace.id)?; |
| 162 |
| 163 | // Copy unchanged files from the most recent workspace of this project. |
| 164 | let source = app.db.project_workspaces(&project.id)?.into_iter().find(|w| w.path.join(ws::DIR).is_dir() && w.path != root); |
| 165 | let source_index = source.as_ref().map(|w| Index::load(&w.path)); |
| 166 | app.host(&project).fetch_tree(&app.store, &project, &tree, None)?; |
| 167 | let files = app.files(&tree)?; |
| 168 | let cow = match (&source, &source_index) { |
| 169 | (Some(w), Some(i)) => Some(CowSource { root: &w.path, index: i }), |
| 170 | _ => None, |
| 171 | }; |
| 172 | let mut index = ws::materialize(&root, &app.store, &Index::default(), &files, &only, cow)?; |
| 173 | index.save(&root)?; |
| 174 | app.db.put_workspace(&workspace)?; |
| 175 | let mut copied = Vec::new(); |
| 176 | if let Some(w) = &source { |
| 177 | for folder in ws::config(&root).workspace.copy { |
| 178 | let folder = folder.trim_matches('/'); |
| 179 | if folder.is_empty() || folder.contains("..") { |
| 180 | continue; |
| 181 | } |
| 182 | let n = ws::copy_folder(&w.path.join(folder), &root.join(folder))?; |
| 183 | if n > 0 { |
| 184 | copied.push(format!("{folder} from {} ({n} files)", w.path.display())); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | let _ = crate::remote::pull_mine(app, &project); |
| 189 | let mine = app.place_mine(&project, &root)?; |
| 190 | // One save now: it records the tree in the index and reads every new |
| 191 | // folder once, so the first command after this one is quick. |
| 192 | let mut fresh = app.session_at(&root)?; |
| 193 | app.save(&mut fresh)?; |
| 194 |
| 195 | let mut r = Report::new(); |
| 196 | r.line("workspace", format!("{} ({})", root.display(), project.address)); |
| 197 | if let Some(from) = &took_from { |
| 198 | r.line("took over", format!("from {from}")); |
| 199 | } |
| 200 | let state = if change.is_empty() { "new, empty".to_string() } else { format!("{} saves", change.saves) }; |
| 201 | r.line("change", format!("{} {}, on {}", app.short(&project, &change.id), state, base_text(app, &project, &change))); |
| 202 | if !only.is_empty() { |
| 203 | r.line("only", only.join(", ")); |
| 204 | } |
| 205 | for c in &copied { |
| 206 | r.line("copied", c.clone()); |
| 207 | } |
| 208 | if mine > 0 { |
| 209 | r.line("yours", format!("{mine} private files (like .env) placed")); |
| 210 | } |
| 211 | r.set("workspace", root.display().to_string()) |
| 212 | .set("project", project.address.clone()) |
| 213 | .set("main", main.as_ref().map(|v| v.n)) |
| 214 | .set("change", change_json(app, &project, &change)) |
| 215 | .next("edit files, then vcs land -m \"what you did\""); |
| 216 | Ok(r) |
| 217 | } |
| 218 |
| 219 | /// A project by address: a hosted `host/owner/name`, or a local folder. |
| 220 | fn resolve_project(app: &App, target: &str) -> Result<Project, Fail> { |
| 221 | let path = app.cwd.join(target); |
| 222 | if target.starts_with('/') || target.starts_with('.') || target.starts_with('~') || path.join(ws::DIR).is_dir() { |
| 223 | let root = ws::find(&path).ok_or_else(|| { |
| 224 | Fail::new("not_found", format!("{target} isn't a vcs workspace")).state("nothing changed").next("vcs init <folder> to start a project there") |
| 225 | })?; |
| 226 | let id = ws::read_id(&root)?; |
| 227 | let w = app.db.workspace(&id)?.ok_or_else(|| Fail::new("not_found", "that workspace isn't known on this machine"))?; |
| 228 | return app.db.project(&w.project)?.ok_or_else(|| Fail::new("not_found", "that workspace's project is missing")); |
| 229 | } |
| 230 | crate::remote::project(app, target) |
| 231 | } |
| 232 |
| 233 | /// Makes `workspace` the one holding `change`: on the host (the other |
| 234 | /// workspace finds out on its next save) and on this machine. |
| 235 | fn take_over(app: &App, project: &Project, change: &mut Change, workspace: &str, path: &Path) -> Result<Option<String>, Fail> { |
| 236 | let mut previous = None; |
| 237 | if project.hosted() { |
| 238 | let remote = crate::remote::Remote::for_project(project); |
| 239 | remote.fetch_saves(&app.db, &app.store, project, change)?; |
| 240 | previous = remote.hold(&change.id, workspace, &crate::remote::label(path))?; |
| 241 | *change = app.change(&change.id)?; |
| 242 | } |
| 243 | if let Some(holder) = app.db.workspace_holding(&change.id)? |
| 244 | && holder.id != workspace |
| 245 | { |
| 246 | previous = Some(holder.path.display().to_string()); |
| 247 | release(app, project, holder)?; |
| 248 | } |
| 249 | Ok(previous) |
| 250 | } |
| 251 |
| 252 | // See. |
| 253 |
| 254 | pub fn status(app: &App, which: Option<String>) -> Out { |
| 255 | let mut s = app.session()?; |
| 256 | let current = app.save(&mut s)?; |
| 257 | let mut c = match which { |
| 258 | Some(text) => app.find_change(&s.project, &text)?, |
| 259 | None => current, |
| 260 | }; |
| 261 | c = settle_review(app, &mut s, c)?; |
| 262 | let review = if c.state == "open" { app.db.review(&c.id)? } else { None }; |
| 263 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; |
| 264 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; |
| 265 | let main = app.main(&s.project)?; |
| 266 | let mut r = Report::new(); |
| 267 | r.line("project", s.project.address.clone()).line("workspace", s.root.display().to_string()); |
| 268 | let who = if c.author == app.author(&s.project) { "yours".to_string() } else { c.author.clone() }; |
| 269 | let title = if c.title.is_empty() { "(no description yet)".to_string() } else { format!("\"{}\"", c.title) }; |
| 270 | r.line("change", format!("{} {} {}, {}", app.short(&s.project, &c.id), title, c.state, who)); |
| 271 | match c.state.as_str() { |
| 272 | "landed" => { |
| 273 | r.line("landed", format!("as main {}", c.version.map(|v| v.to_string()).unwrap_or("?".into()))); |
| 274 | } |
| 275 | "waiting" => { |
| 276 | r.line("waiting", "for someone with landing rights to land it"); |
| 277 | } |
| 278 | _ => { |
| 279 | let behind = match (c.base_version, &main) { |
| 280 | (Some(b), Some(m)) if m.n > b && c.on_change.is_none() => format!(" (main is at {}; land merges the difference)", m.n), |
| 281 | _ => String::new(), |
| 282 | }; |
| 283 | r.line("based on", format!("{}{behind}", base_text(app, &s.project, &c))); |
| 284 | } |
| 285 | } |
| 286 | if let Some(link) = &review { |
| 287 | r.line("review", format!("change request {link}; it lands when its approvals and checks pass")); |
| 288 | r.set("review", link.clone()); |
| 289 | } |
| 290 | if c.saves > 0 { |
| 291 | let last = app.db.save(&c.id, c.saves)?.map(|sv| sv.at).unwrap_or(c.updated); |
| 292 | r.line("saved", format!("{} (save {})", ids::ago(last), c.saves)); |
| 293 | } |
| 294 | let changes = tree::diff_trees(&app.store, &c.base_tree, &c.tree())?; |
| 295 | let mut list = Vec::new(); |
| 296 | for (path, change) in &changes { |
| 297 | let mark = match change { |
| 298 | tree::Change::Added(_) => "A", |
| 299 | tree::Change::Removed(_) => "D", |
| 300 | tree::Change::Modified(..) => "M", |
| 301 | }; |
| 302 | list.push(format!("{mark} {path}")); |
| 303 | } |
| 304 | if list.is_empty() { |
| 305 | r.line("files", "no changes yet"); |
| 306 | } else { |
| 307 | let shown: Vec<String> = list.iter().take(50).cloned().collect(); |
| 308 | let more = if list.len() > 50 { format!("\n… and {} more", list.len() - 50) } else { String::new() }; |
| 309 | r.line("files", format!("{}{more}", shown.join("\n"))); |
| 310 | } |
| 311 | if !c.conflicts.is_empty() { |
| 312 | r.line("conflicts", c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join("\n")); |
| 313 | } |
| 314 | r.set("project", s.project.address.clone()) |
| 315 | .set("workspace", s.root.display().to_string()) |
| 316 | .set("change", change_json(app, &s.project, &c)) |
| 317 | .set("main", main.as_ref().map(|v| v.n)) |
| 318 | .set("files", list.clone()); |
| 319 | if c.state == "open" { |
| 320 | if !c.conflicts.is_empty() { |
| 321 | r.next(format!("fix the marked lines in {}, then vcs land", c.conflicts[0].path)); |
| 322 | } else if list.is_empty() { |
| 323 | r.next("edit files, then vcs land -m \"what you did\""); |
| 324 | } else if c.title.is_empty() { |
| 325 | r.next("vcs land -m \"what you did\""); |
| 326 | } else { |
| 327 | r.next("vcs land"); |
| 328 | } |
| 329 | } |
| 330 | Ok(r) |
| 331 | } |
| 332 |
| 333 | /// Resolves a reference: a version number, `main`, a change, or change:save. |
| 334 | fn resolve_tree(app: &App, project: &Project, text: &str) -> Result<(Id, String), Fail> { |
| 335 | if text == "main" { |
| 336 | let v = app.refresh(project)?.ok_or_else(|| Fail::new("not_found", "main has no versions yet"))?; |
| 337 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 338 | return Ok((v.tree, format!("main {}", v.n))); |
| 339 | } |
| 340 | if let Some(n) = text.parse::<u64>().ok().or(crate::tags::find(app, project, text)?) { |
| 341 | let v = version(app, project, n)?; |
| 342 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 343 | return Ok((v.tree, format!("main {n}"))); |
| 344 | } |
| 345 | if let Some((id, save)) = text.split_once(':') { |
| 346 | let c = app.find_change(project, id)?; |
| 347 | let n: i64 = save.parse().map_err(|_| Fail::new("bad_usage", format!("{text}: save numbers are whole numbers")))?; |
| 348 | let sv = app.db.save(&c.id, n)?.ok_or_else(|| Fail::new("not_found", format!("change {} has no save {n}", c.id)))?; |
| 349 | return Ok((sv.tree, format!("save {n} of {}", app.short(project, &c.id)))); |
| 350 | } |
| 351 | let c = app.find_change(project, text)?; |
| 352 | Ok((c.tree(), format!("change {}", app.short(project, &c.id)))) |
| 353 | } |
| 354 |
| 355 | fn version(app: &App, project: &Project, n: u64) -> Result<Version, Fail> { |
| 356 | app.version(project, n)?.ok_or_else(|| Fail::new("not_found", format!("main has no version {n}")).state("nothing changed")) |
| 357 | } |
| 358 |
| 359 | pub fn diff_cmd(app: &App, paths: Vec<String>, change: Option<String>, from: Option<String>, to: Option<String>, stat: bool) -> Out { |
| 360 | let mut s = app.session()?; |
| 361 | let current = app.save(&mut s)?; |
| 362 | let c = match change { |
| 363 | Some(t) => app.find_change(&s.project, &t)?, |
| 364 | None => current, |
| 365 | }; |
| 366 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; |
| 367 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; |
| 368 | let (a, a_label) = match &from { |
| 369 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 370 | None => (c.base_tree, "base".to_string()), |
| 371 | }; |
| 372 | let (b, b_label) = match &to { |
| 373 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 374 | None => (c.tree(), "change".to_string()), |
| 375 | }; |
| 376 | let paths: Vec<String> = paths.into_iter().map(|p| p.trim_matches('/').to_string()).collect(); |
| 377 | let mut text = String::new(); |
| 378 | let mut stats = Vec::new(); |
| 379 | let (mut adds, mut dels) = (0usize, 0usize); |
| 380 | for (path, ch) in tree::diff_trees(&app.store, &a, &b)? { |
| 381 | if !paths.is_empty() && !paths.iter().any(|p| p == "." || tree::under(&path, p)) { |
| 382 | continue; |
| 383 | } |
| 384 | let (old, new) = match ch { |
| 385 | tree::Change::Added(e) => (None, Some(e)), |
| 386 | tree::Change::Removed(e) => (Some(e), None), |
| 387 | tree::Change::Modified(o, n) => (Some(o), Some(n)), |
| 388 | }; |
| 389 | let read = |e: Option<tree::Entry>| -> Result<Vec<u8>, Fail> { |
| 390 | match e { |
| 391 | Some(e) => Ok(app.store.read_file(&e.id)?), |
| 392 | None => Ok(Vec::new()), |
| 393 | } |
| 394 | }; |
| 395 | let (ob, nb) = (read(old)?, read(new)?); |
| 396 | if diff::is_binary(&ob) || diff::is_binary(&nb) { |
| 397 | text.push_str(&format!("Binary file {path} changed\n")); |
| 398 | stats.push(json!({ "path": path, "binary": true })); |
| 399 | continue; |
| 400 | } |
| 401 | let (added, removed) = diff::counts(&ob, &nb); |
| 402 | adds += added; |
| 403 | dels += removed; |
| 404 | stats.push(json!({ "path": path, "added": added, "removed": removed })); |
| 405 | if !stat { |
| 406 | text.push_str(&format!("--- {}\n+++ {}\n", if old.is_some() { format!("a/{path}") } else { "/dev/null".into() }, if new.is_some() { format!("b/{path}") } else { "/dev/null".into() })); |
| 407 | if old.is_some() && new.is_some() && old.unwrap().kind != new.unwrap().kind { |
| 408 | text.push_str(&format!("kind {} → {}\n", old.unwrap().kind.name(), new.unwrap().kind.name())); |
| 409 | } |
| 410 | text.push_str(&diff::unified(&ob, &nb, 3)); |
| 411 | } else { |
| 412 | text.push_str(&format!("{path} | +{added} -{removed}\n")); |
| 413 | } |
| 414 | } |
| 415 | let mut r = Report::new(); |
| 416 | if text.is_empty() { |
| 417 | r.line("diff", format!("no differences between {a_label} and {b_label}")); |
| 418 | } else { |
| 419 | r.raw(text); |
| 420 | if stat { |
| 421 | r.raw(format!("{} files, +{adds} -{dels}\n", stats.len())); |
| 422 | } |
| 423 | } |
| 424 | r.set("from", a_label).set("to", b_label).set("files", stats).set("added", adds).set("removed", dels); |
| 425 | Ok(r) |
| 426 | } |
| 427 |
| 428 | pub fn log(app: &App, what: Option<String>, changes: bool, saves: bool, ops: bool, limit: i64) -> Out { |
| 429 | let mut s = app.session()?; |
| 430 | let current = app.save(&mut s)?; |
| 431 | let mut r = Report::new(); |
| 432 | if changes { |
| 433 | let list = crate::remote::visible_changes(app, &s.project)?; |
| 434 | let mut rows = Vec::new(); |
| 435 | for c in &list { |
| 436 | if c.state != "open" && c.state != "waiting" { |
| 437 | continue; |
| 438 | } |
| 439 | if c.is_empty() && c.id != current.id { |
| 440 | continue; |
| 441 | } |
| 442 | let held = app.db.workspace_holding(&c.id)?.map(|w| w.path.display().to_string()).unwrap_or_else(|| "no workspace here".into()); |
| 443 | let title = if c.title.is_empty() { "(no description)".to_string() } else { c.title.clone() }; |
| 444 | let here = if c.id == current.id { " ← this workspace" } else { "" }; |
| 445 | r.raw(format!("{} {:<8} {} {} [{}]{here}\n", app.short(&s.project, &c.id), c.state, title, c.author, held)); |
| 446 | rows.push(json!({ "change": change_json(app, &s.project, c), "workspace": held })); |
| 447 | } |
| 448 | if rows.is_empty() { |
| 449 | r.line("changes", "no open changes"); |
| 450 | } |
| 451 | r.set("changes", rows); |
| 452 | return Ok(r); |
| 453 | } |
| 454 | if saves { |
| 455 | let list = app.db.saves(¤t.id)?; |
| 456 | for sv in &list { |
| 457 | r.raw(format!("{}:{} {} ({})\n", app.short(&s.project, ¤t.id), sv.n, ids::clock(sv.at), ids::ago(sv.at))); |
| 458 | } |
| 459 | if list.is_empty() { |
| 460 | r.line("saves", "nothing saved yet in this change"); |
| 461 | } |
| 462 | r.set("saves", list.iter().map(|sv| json!({ "n": sv.n, "at": sv.at, "tree": sv.tree })).collect::<Vec<_>>()); |
| 463 | return Ok(r); |
| 464 | } |
| 465 | if ops { |
| 466 | let list = app.db.ops(&s.ws.id, limit)?; |
| 467 | for (op, undone) in &list { |
| 468 | r.raw(format!("{} {:<9} {}{}\n", ids::clock(op.at), op.kind, op_summary(op), if *undone { " (undone)" } else { "" })); |
| 469 | } |
| 470 | if list.is_empty() { |
| 471 | r.line("operations", "none yet in this workspace"); |
| 472 | } |
| 473 | r.set("ops", list.iter().map(|(op, undone)| json!({ "kind": op.kind, "at": op.at, "undone": undone, "data": op.data })).collect::<Vec<_>>()); |
| 474 | return Ok(r); |
| 475 | } |
| 476 | if let Some(what) = what { |
| 477 | if let Some(n) = what.parse::<u64>().ok().or(crate::tags::find(app, &s.project, &what)?) { |
| 478 | let v = version(app, &s.project, n)?; |
| 479 | let prev_tree = match n { |
| 480 | 1 => tree::empty_id(), |
| 481 | _ => version(app, &s.project, n - 1)?.tree, |
| 482 | }; |
| 483 | app.host(&s.project).fetch_tree(&app.store, &s.project, &v.tree, None)?; |
| 484 | app.host(&s.project).fetch_tree(&app.store, &s.project, &prev_tree, None)?; |
| 485 | let changed = tree::diff_trees(&app.store, &prev_tree, &v.tree)?; |
| 486 | r.line("version", format!("main {}", v.n)) |
| 487 | .line("title", v.title.clone()) |
| 488 | .line("author", v.author.clone()) |
| 489 | .line("landed", format!("{} ({})", ids::clock(v.time), ids::ago(v.time))); |
| 490 | if !v.change.is_empty() { |
| 491 | r.line("change", v.change.clone()); |
| 492 | } |
| 493 | if !v.body.is_empty() { |
| 494 | r.line("about", v.body.clone()); |
| 495 | } |
| 496 | if let Some(g) = &v.git { |
| 497 | r.line("git", g.clone()); |
| 498 | } |
| 499 | r.line("files", changed.keys().take(50).cloned().collect::<Vec<_>>().join("\n")); |
| 500 | r.set("version", serde_json::to_value(&v).unwrap_or_default()).set("files", changed.keys().cloned().collect::<Vec<_>>()); |
| 501 | return Ok(r); |
| 502 | } |
| 503 | if crate::history::is_path(&app.cwd, &what) { |
| 504 | let path = crate::history::workspace_path(app, &s.root, &what); |
| 505 | return crate::history::log_path(app, &s.project, &path, limit.max(1) as usize); |
| 506 | } |
| 507 | let c = app.find_change(&s.project, &what)?; |
| 508 | r.line("change", app.short(&s.project, &c.id)) |
| 509 | .line("title", if c.title.is_empty() { "(no description)".into() } else { c.title.clone() }) |
| 510 | .line("state", c.state.clone()) |
| 511 | .line("author", c.author.clone()) |
| 512 | .line("saves", c.saves.to_string()); |
| 513 | if let Some(v) = c.version { |
| 514 | r.line("landed", format!("as main {v}")); |
| 515 | } |
| 516 | r.set("change", change_json(app, &s.project, &c)); |
| 517 | return Ok(r); |
| 518 | } |
| 519 | app.refresh(&s.project)?; |
| 520 | let mut list = app.db.versions(&s.project.id, limit)?; |
| 521 | let start = app.db.history_from(&s.project.id)?; |
| 522 | if (list.len() as i64) < limit && start > 1 { |
| 523 | // Older than this machine keeps: fetch them now. |
| 524 | app.history(&s.project, start.saturating_sub((limit - list.len() as i64) as u64))?; |
| 525 | list = app.db.versions(&s.project.id, limit)?; |
| 526 | } |
| 527 | for v in &list { |
| 528 | r.raw(format!("{:>6} {} {} {}\n", v.n, v.title, short_author(&v.author), ids::ago(v.time))); |
| 529 | } |
| 530 | if list.is_empty() { |
| 531 | r.line("main", "no versions yet"); |
| 532 | r.next("vcs land -m \"First version\""); |
| 533 | } |
| 534 | r.set("versions", list.iter().map(|v| json!({ "n": v.n, "title": v.title, "author": v.author, "time": v.time, "change": v.change, "git": v.git })).collect::<Vec<_>>()); |
| 535 | Ok(r) |
| 536 | } |
| 537 |
| 538 | fn short_author(author: &str) -> String { |
| 539 | author.split(" <").next().unwrap_or(author).to_string() |
| 540 | } |
| 541 |
| 542 | fn op_summary(op: &crate::db::Op) -> String { |
| 543 | let d = &op.data; |
| 544 | let s = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 545 | match op.kind.as_str() { |
| 546 | "land" => format!("change {} as main {}", s("change"), d.get("version").and_then(|v| v.as_u64()).unwrap_or(0)), |
| 547 | "sync" => format!("change {} onto {}", s("change"), s("onto")), |
| 548 | "new" | "switch" => format!("from {} to {}", s("from"), s("to")), |
| 549 | "drop" => format!("change {}", s("change")), |
| 550 | "describe" => format!("change {}", s("change")), |
| 551 | "restore" => format!("{} from {}", s("paths"), s("source")), |
| 552 | "access" => format!("{} → {}", s("target"), s("who")), |
| 553 | "undo" => s("what"), |
| 554 | _ => String::new(), |
| 555 | } |
| 556 | } |
| 557 |
| 558 | // Work. |
| 559 |
| 560 | pub fn new(app: &App, title: Option<String>, on: Option<String>) -> Out { |
| 561 | let mut s = app.session()?; |
| 562 | let current = app.save(&mut s)?; |
| 563 | let author = app.author(&s.project); |
| 564 | let mut c = match &on { |
| 565 | Some(text) => { |
| 566 | let parent = app.find_change(&s.project, text)?; |
| 567 | if parent.state == "landed" || parent.state == "dropped" { |
| 568 | return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)) |
| 569 | .state("nothing changed") |
| 570 | .next("vcs new")); |
| 571 | } |
| 572 | if s.project.hosted() { |
| 573 | crate::remote::Remote::for_project(&s.project).fetch_saves(&app.db, &app.store, &s.project, &parent)?; |
| 574 | } |
| 575 | let mut c = Change::new(ids::new_change_id(), &s.project.id, parent.tree(), None, &author); |
| 576 | c.on_change = Some(parent.id.clone()); |
| 577 | c |
| 578 | } |
| 579 | None => { |
| 580 | let main = app.refresh(&s.project)?; |
| 581 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 582 | Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &author) |
| 583 | } |
| 584 | }; |
| 585 | if let Some(t) = title { |
| 586 | set_description(&mut c, &[t]); |
| 587 | } |
| 588 | app.db.put_change(&c)?; |
| 589 | app.show_tree(&s, &c.base_tree)?; |
| 590 | app.put_workspace_change(&mut s, &c.id)?; |
| 591 | app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": c.id }))?; |
| 592 | let mut r = Report::new(); |
| 593 | r.line("change", format!("{} new, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 594 | let kept = if current.is_empty() { "(it was empty)".to_string() } else { "is saved; vcs switch goes back to it".to_string() }; |
| 595 | r.line("kept", format!("{} {kept}", app.short(&s.project, ¤t.id))); |
| 596 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 597 | r.next("edit files, then vcs land"); |
| 598 | Ok(r) |
| 599 | } |
| 600 |
| 601 | fn set_description(c: &mut Change, parts: &[String]) { |
| 602 | let text = parts.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect::<Vec<_>>().join("\n\n"); |
| 603 | let mut lines = text.splitn(2, '\n'); |
| 604 | c.title = lines.next().unwrap_or("").trim().to_string(); |
| 605 | c.body = lines.next().unwrap_or("").trim().to_string(); |
| 606 | } |
| 607 |
| 608 | pub fn describe(app: &App, parts: Vec<String>) -> Out { |
| 609 | let mut s = app.session()?; |
| 610 | let mut c = app.save(&mut s)?; |
| 611 | if parts.iter().all(|p| p.trim().is_empty()) { |
| 612 | return Err(Fail::new("bad_usage", "give a description").state("nothing changed").next("vcs describe \"Title\" \"More detail\"")); |
| 613 | } |
| 614 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 615 | set_description(&mut c, &parts); |
| 616 | app.db.put_change(&c)?; |
| 617 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 618 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 619 | let mut r = Report::new(); |
| 620 | r.line("change", format!("{} \"{}\"", app.short(&s.project, &c.id), c.title)).set("change", change_json(app, &s.project, &c)); |
| 621 | r.next("vcs land"); |
| 622 | Ok(r) |
| 623 | } |
| 624 |
| 625 | pub fn switch(app: &App, target: &str) -> Out { |
| 626 | let mut s = app.session()?; |
| 627 | let current = app.save(&mut s)?; |
| 628 | let mut c = app.find_change(&s.project, target)?; |
| 629 | if c.id == current.id { |
| 630 | let mut r = Report::new(); |
| 631 | r.line("change", format!("{} is already this workspace's change", app.short(&s.project, &c.id))); |
| 632 | return Ok(r); |
| 633 | } |
| 634 | if c.state == "landed" || c.state == "dropped" { |
| 635 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)) |
| 636 | .state("nothing changed") |
| 637 | .next(if c.state == "dropped" { "vcs undo (if you just dropped it)" } else { "vcs new" })); |
| 638 | } |
| 639 | let took_from = take_over(app, &s.project, &mut c, &s.ws.id.clone(), &s.root.clone())?; |
| 640 | if let Some(from) = &took_from { |
| 641 | app.notes.borrow_mut().push(format!("took change {} over from {from}", c.id)); |
| 642 | } |
| 643 | app.show_tree(&s, &c.tree())?; |
| 644 | app.put_workspace_change(&mut s, &c.id)?; |
| 645 | app.db.add_op(&s.ws.id, "switch", &json!({ "from": current.id, "to": c.id }))?; |
| 646 | let mut r = Report::new(); |
| 647 | let title = if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) }; |
| 648 | r.line("change", format!("{}{title}, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 649 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 650 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 651 | r.next("keep working, then vcs land"); |
| 652 | Ok(r) |
| 653 | } |
| 654 |
| 655 | /// Moves another workspace on this machine off a change someone took over: |
| 656 | /// it gets a fresh change on the same base, so its next save can't touch the |
| 657 | /// taken change. |
| 658 | fn release(app: &App, project: &Project, mut holder: Workspace) -> Result<(), Fail> { |
| 659 | let taken = app.change(&holder.change)?; |
| 660 | let mut fresh = Change::new(ids::new_change_id(), &project.id, taken.tree(), None, &taken.author); |
| 661 | fresh.title = format!("Rescued from {}", taken.id); |
| 662 | fresh.after_change = Some(taken.id.clone()); |
| 663 | app.db.put_change(&fresh)?; |
| 664 | holder.change = fresh.id; |
| 665 | app.db.put_workspace(&holder)?; |
| 666 | Ok(()) |
| 667 | } |
| 668 |
| 669 | pub fn drop(app: &App, target: Option<String>) -> Out { |
| 670 | let mut s = app.session()?; |
| 671 | let current = app.save(&mut s)?; |
| 672 | let mut c = match target { |
| 673 | Some(t) => app.find_change(&s.project, &t)?, |
| 674 | None => current.clone(), |
| 675 | }; |
| 676 | if c.state == "landed" { |
| 677 | return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))) |
| 678 | .state("nothing changed") |
| 679 | .next(format!("vcs undo {}", c.version.unwrap_or(0)))); |
| 680 | } |
| 681 | c.state = "dropped".into(); |
| 682 | app.db.put_change(&c)?; |
| 683 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 684 | let mut r = Report::new(); |
| 685 | let mut data = json!({ "change": c.id, "current": c.id == current.id }); |
| 686 | r.line("dropped", format!("{}{}", app.short(&s.project, &c.id), if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) })); |
| 687 | if c.id == current.id { |
| 688 | let main = app.refresh(&s.project)?; |
| 689 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 690 | let fresh = Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &app.author(&s.project)); |
| 691 | app.db.put_change(&fresh)?; |
| 692 | app.show_tree(&s, &base)?; |
| 693 | app.put_workspace_change(&mut s, &fresh.id)?; |
| 694 | data["replacement"] = json!(fresh.id); |
| 695 | r.line("change", format!("{} new, on {}", app.short(&s.project, &fresh.id), main_label(main.map(|v| v.n)))); |
| 696 | } |
| 697 | app.db.add_op(&s.ws.id, "drop", &data)?; |
| 698 | r.set("dropped", c.id.clone()); |
| 699 | r.next("vcs undo brings it back"); |
| 700 | Ok(r) |
| 701 | } |
| 702 |
| 703 | // Finish. |
| 704 |
| 705 | pub fn sync(app: &App) -> Out { |
| 706 | let mut s = app.session()?; |
| 707 | let saved = app.save(&mut s)?; |
| 708 | let mut c = settle_review(app, &mut s, saved)?; |
| 709 | if c.state != "open" { |
| 710 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 711 | } |
| 712 | // Onto the change it's stacked on while that hasn't landed, else main. |
| 713 | let parent = match &c.on_change { |
| 714 | // A scheduled change lands on the host on its own: ask whether it has. |
| 715 | Some(p) => Some(match app.change(p)? { |
| 716 | pc if pc.state == "scheduled" && s.project.hosted() => crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, &pc.id)?.unwrap_or(pc), |
| 717 | pc => pc, |
| 718 | }), |
| 719 | None => None, |
| 720 | }; |
| 721 | let (target_tree, target_version, label, still_on) = match parent.as_ref().filter(|p| p.state == "open" || p.state == "waiting" || p.state == "scheduled") { |
| 722 | Some(p) => (p.tree(), None, format!("change {}", app.short(&s.project, &p.id)), Some(p.id.clone())), |
| 723 | None => { |
| 724 | let main = app.refresh(&s.project)?; |
| 725 | let t = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 726 | app.host(&s.project).fetch_tree(&app.store, &s.project, &t, Some(&c.base_tree))?; |
| 727 | (t, main.as_ref().map(|v| v.n), main_label(main.as_ref().map(|v| v.n)), None) |
| 728 | } |
| 729 | }; |
| 730 | if target_tree == c.base_tree { |
| 731 | let mut r = Report::new(); |
| 732 | r.line("synced", format!("{} is already on {label}", app.short(&s.project, &c.id))).set("change", change_json(app, &s.project, &c)); |
| 733 | r.next("vcs land"); |
| 734 | return Ok(r); |
| 735 | } |
| 736 | let ours_label = label.clone(); |
| 737 | let theirs_label = format!("your change {}", app.short(&s.project, &c.id)); |
| 738 | let m = merge::trees(&app.store, Some(&c.base_tree), &target_tree, &c.tree(), Mode::Sync, (&ours_label, &theirs_label))?; |
| 739 | for o in m.objects.objects.values() { |
| 740 | app.store.put(o)?; |
| 741 | } |
| 742 | let before = json!({ |
| 743 | "change": c.id, "onto": label, |
| 744 | "base_tree": c.base_tree, "base_version": c.base_version, "on_change": c.on_change, |
| 745 | "after_change": c.after_change, "head_tree": c.head_tree, "conflicts": c.conflicts, |
| 746 | }); |
| 747 | let was = base_text(app, &s.project, &c); |
| 748 | c.base_tree = target_tree; |
| 749 | c.base_version = target_version; |
| 750 | c.on_change = still_on; |
| 751 | c.after_change = None; |
| 752 | c.head_tree = Some(m.tree); |
| 753 | c.saves += 1; |
| 754 | c.conflicts = m.conflicts.iter().map(|x| Conflict { path: x.path.clone(), version: target_version }).collect(); |
| 755 | app.db.add_save(&Save { change: c.id.clone(), n: c.saves, tree: m.tree, base_tree: target_tree, at: ids::now(), uploaded: false }, &s.ws.id)?; |
| 756 | app.db.put_change(&c)?; |
| 757 | app.show_tree(&s, &m.tree)?; |
| 758 | app.db.add_op(&s.ws.id, "sync", &before)?; |
| 759 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 760 | let mut r = Report::new(); |
| 761 | r.line("synced", format!("{} onto {label} (was {was})", app.short(&s.project, &c.id))); |
| 762 | for x in &m.conflicts { |
| 763 | r.line("conflict", x.path.clone()); |
| 764 | } |
| 765 | for n in &m.notes { |
| 766 | r.line("note", n.message.clone()); |
| 767 | } |
| 768 | r.set("change", change_json(app, &s.project, &c)) |
| 769 | .set("conflicts", m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>()) |
| 770 | .set("notes", m.notes.iter().map(|n| n.message.clone()).collect::<Vec<_>>()); |
| 771 | if m.conflicts.is_empty() { |
| 772 | r.next("vcs land"); |
| 773 | } else { |
| 774 | r.exit = 3; |
| 775 | r.next(format!("fix the marked lines in {}, then vcs land", m.conflicts.iter().map(|x| x.path.as_str()).collect::<Vec<_>>().join(", "))); |
| 776 | } |
| 777 | Ok(r) |
| 778 | } |
| 779 |
| 780 | /// Runs vcs.toml's `[land] run` commands in the workspace, in order, their |
| 781 | /// output on stderr; the first that fails stops the landing. |
| 782 | fn run_before_land(root: &Path) -> Result<(), Fail> { |
| 783 | for command in ws::config(root).land.run { |
| 784 | let mut shell = if cfg!(windows) { std::process::Command::new("cmd") } else { std::process::Command::new("sh") }; |
| 785 | shell.args(if cfg!(windows) { ["/C", command.as_str()] } else { ["-c", command.as_str()] }); |
| 786 | let status = shell |
| 787 | .current_dir(root) |
| 788 | .stdin(std::process::Stdio::null()) |
| 789 | .stdout(std::io::stderr()) |
| 790 | .status() |
| 791 | .map_err(|e| Fail::new("checks_failed", format!("couldn't run \"{command}\" from vcs.toml: {e}")).state("main didn't change; your change is saved"))?; |
| 792 | if !status.success() { |
| 793 | return Err(Fail::new("checks_failed", format!("\"{command}\" (vcs.toml [land] run) failed, so nothing landed")) |
| 794 | .state("main didn't change; your change is saved") |
| 795 | .next("fix what it found, then vcs land (vcs land --no-run lands without running it)")); |
| 796 | } |
| 797 | } |
| 798 | Ok(()) |
| 799 | } |
| 800 |
| 801 | pub fn land(app: &App, target: Option<String>, messages: Vec<String>, allow_secrets: bool, run: bool, at: Option<String>, with: Vec<PathBuf>) -> Out { |
| 802 | let mut s = app.session()?; |
| 803 | let at = match at.as_deref() { |
| 804 | None => None, |
| 805 | Some(words) => { |
| 806 | let t = ids::parse_future(words) |
| 807 | .ok_or_else(|| Fail::new("bad_usage", format!("can't read --at {words:?}; try \"fri 9:00\", \"in 2h\" or \"2026-11-02 09:00\"")).state("nothing changed"))?; |
| 808 | if !s.project.hosted() { |
| 809 | return Err(Fail::new("bad_usage", "landing at a set time needs a host, which lands it then").state("nothing changed").next("vcs publish <host/owner/name>")); |
| 810 | } |
| 811 | Some(t) |
| 812 | } |
| 813 | }; |
| 814 | if !with.is_empty() { |
| 815 | return land_together(app, &mut s, &with, messages, allow_secrets, run, at); |
| 816 | } |
| 817 | // Saved here only: the landing itself carries the change to the host. |
| 818 | let current = app.save_local(&mut s)?; |
| 819 | let current = settle_review(app, &mut s, current)?; |
| 820 | // This workspace's change and what it's stacked on are its own; a change |
| 821 | // named on the command line is someone else's unless it's the current one. |
| 822 | let own_stack = target.is_none(); |
| 823 | let mut c = match target { |
| 824 | Some(t) => { |
| 825 | let found = app.find_change(&s.project, &t)?; |
| 826 | // Someone else's change: take the host's newest state and content. |
| 827 | if s.project.hosted() && found.id != current.id { |
| 828 | crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, &found.id)?.unwrap_or(found) |
| 829 | } else { |
| 830 | found |
| 831 | } |
| 832 | } |
| 833 | None => current.clone(), |
| 834 | }; |
| 835 | if !messages.is_empty() { |
| 836 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 837 | set_description(&mut c, &messages); |
| 838 | app.db.put_change(&c)?; |
| 839 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 840 | } |
| 841 | if c.state == "landed" { |
| 842 | return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))).state("nothing changed")); |
| 843 | } |
| 844 | if c.state == "dropped" { |
| 845 | return Err(Fail::new("bad_usage", format!("change {} was dropped", c.id)).state("nothing changed").next("vcs undo (if you just dropped it)")); |
| 846 | } |
| 847 | if c.is_empty() { |
| 848 | let mut f = Fail::new("empty_change", format!("change {} has nothing to land", app.short(&s.project, &c.id))).state("nothing changed"); |
| 849 | if c.after_change.is_some() { |
| 850 | f = f.next("you're on a fresh change after a landing; edit files first"); |
| 851 | } else { |
| 852 | f = f.next("edit files first"); |
| 853 | } |
| 854 | return Err(f); |
| 855 | } |
| 856 | if !c.conflicts.is_empty() { |
| 857 | return Err(Fail::new("conflict", format!("change {} still has conflict markers", app.short(&s.project, &c.id))) |
| 858 | .detail(c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 859 | .state("main didn't change; your change is saved") |
| 860 | .next("fix the marked lines, then vcs land")); |
| 861 | } |
| 862 | require_title(&c)?; |
| 863 | // The workspace's files are this change's: its own checks run on them. |
| 864 | if run && own_stack { |
| 865 | run_before_land(&s.root)?; |
| 866 | } |
| 867 |
| 868 | // Land what it's stacked on first, in order. |
| 869 | let mut stack = vec![c.clone()]; |
| 870 | let mut parent = c.on_change.clone(); |
| 871 | while let Some(p) = parent { |
| 872 | let pc = app.change(&p)?; |
| 873 | if pc.state != "open" && pc.state != "waiting" { |
| 874 | break; |
| 875 | } |
| 876 | require_title(&pc)?; |
| 877 | parent = pc.on_change.clone(); |
| 878 | stack.push(pc); |
| 879 | } |
| 880 | stack.reverse(); |
| 881 |
| 882 | let mut r = Report::new(); |
| 883 | let mut landed_versions = Vec::new(); |
| 884 | for (i, item) in stack.iter().enumerate() { |
| 885 | let mut item = app.change(&item.id)?; |
| 886 | let host = app.host(&s.project); |
| 887 | host.fetch_tree(&app.store, &s.project, &item.base_tree, None)?; |
| 888 | host.fetch_tree(&app.store, &s.project, &item.tree(), Some(&item.base_tree))?; |
| 889 | if !allow_secrets { |
| 890 | let found = secrets::scan(&app.store, &item.base_tree, &item.tree())?; |
| 891 | if let Some(hit) = found.first() { |
| 892 | return Err(Fail::new("secret", format!("change {} looks like it has a secret: {} line {} ({})", app.short(&s.project, &item.id), hit.path, hit.line, hit.kind)) |
| 893 | .detail(format!("{}:{}", hit.path, hit.line)) |
| 894 | .state(if i == 0 { "main didn't change; your change is saved".to_string() } else { format!("{} landed before this; the rest didn't", landed_versions.len()) }) |
| 895 | .next(format!("remove it from {} (put real secrets in .env, which stays yours), then vcs land", hit.path)) |
| 896 | .set("secrets", serde_json::to_value(&found).unwrap_or_default())); |
| 897 | } |
| 898 | } |
| 899 | // A change of this workspace's goes up with its landing, in one call. |
| 900 | let own = s.project.hosted() && (own_stack || item.id == current.id); |
| 901 | let pending = if own { app.db.unuploaded_saves(&item.id)? } else { Vec::new() }; |
| 902 | let request = LandRequest { |
| 903 | change: item.id.clone(), |
| 904 | base_tree: item.base_tree, |
| 905 | tree: item.tree(), |
| 906 | title: item.title.clone(), |
| 907 | body: item.body.clone(), |
| 908 | author: item.author.clone(), |
| 909 | allow_secrets, |
| 910 | at, |
| 911 | record: own.then(|| crate::wire::PutChange { |
| 912 | change: crate::remote::Remote::record(&item), |
| 913 | workspace: s.ws.id.clone(), |
| 914 | label: crate::remote::label(&s.root), |
| 915 | save: pending.last().map(|sv| crate::wire::SaveRecord { n: sv.n, tree: sv.tree, base_tree: sv.base_tree, at: sv.at, workspace: s.ws.id.clone() }), |
| 916 | }), |
| 917 | }; |
| 918 | let outcome = match host.land(&app.db, &app.store, &s.project, &request) { |
| 919 | Ok(o) => o, |
| 920 | Err(e) => { |
| 921 | let fail = Fail::from(e); |
| 922 | if fail.code == "held_elsewhere" { |
| 923 | // Another workspace took the change over: a normal save |
| 924 | // moves this one's work to a new change. |
| 925 | let rescued = app.save(&mut s)?; |
| 926 | return Err(Fail::new("held_elsewhere", format!("{}; this workspace's work is in change {}", fail.message, app.short(&s.project, &rescued.id))) |
| 927 | .state("main didn't change") |
| 928 | .next("vcs land")); |
| 929 | } |
| 930 | return Err(fail); |
| 931 | } |
| 932 | }; |
| 933 | for sv in &pending { |
| 934 | app.db.mark_uploaded(&item.id, sv.n)?; |
| 935 | } |
| 936 | match outcome { |
| 937 | Landed::Landed { version } => { |
| 938 | item.state = "landed".into(); |
| 939 | item.version = Some(version.n); |
| 940 | app.db.put_change(&item)?; |
| 941 | app.db.put_version(&s.project.id, &version)?; |
| 942 | landed_versions.push((item.id.clone(), version.clone())); |
| 943 | r.line("landed", format!("{} as main {} \"{}\"", app.short(&s.project, &item.id), version.n, version.title)); |
| 944 | } |
| 945 | Landed::Conflict { main, conflicts } => { |
| 946 | let state = if landed_versions.is_empty() { |
| 947 | "main didn't change; your change is saved".to_string() |
| 948 | } else { |
| 949 | format!("{} before it landed; this one and the rest didn't", landed_versions.iter().map(|(id, v)| format!("{} as main {}", app.short(&s.project, id), v.n)).collect::<Vec<_>>().join(", ")) |
| 950 | }; |
| 951 | let mut f = Fail::new("conflict", format!("can't land {}: {} {} conflict with main {main}", app.short(&s.project, &item.id), conflicts.len(), if conflicts.len() == 1 { "file" } else { "files" })); |
| 952 | for x in &conflicts { |
| 953 | f = f.detail(format!("{}{}", x.path, if x.kind == "text" { String::new() } else { format!(" ({})", x.kind) })); |
| 954 | } |
| 955 | return Err(f.state(state).next("vcs sync, fix the conflicts in those files, then vcs land") |
| 956 | .set("conflicts", serde_json::to_value(&conflicts).unwrap_or_default()) |
| 957 | .set("main", main)); |
| 958 | } |
| 959 | Landed::Waiting { asked, reason } => { |
| 960 | item.state = "waiting".into(); |
| 961 | app.db.put_change(&item)?; |
| 962 | r.line("waiting", format!("{} {reason}", app.short(&s.project, &item.id))); |
| 963 | if !asked.is_empty() { |
| 964 | r.line("asked", asked.join(", ")); |
| 965 | } |
| 966 | r.exit = 5; |
| 967 | r.set("waiting", json!({ "change": item.id, "asked": asked })); |
| 968 | r.next(format!("vcs status {} later", app.short(&s.project, &item.id))); |
| 969 | // The workspace moves on, so later edits don't change what's waiting. |
| 970 | if item.id == current.id { |
| 971 | let fresh = continue_after(app, &mut s, &item)?; |
| 972 | r.line("change", format!("{} new, on top of the waiting change", app.short(&s.project, &fresh.id))); |
| 973 | } |
| 974 | return Ok(r); |
| 975 | } |
| 976 | Landed::ChecksFailed { check, log } => { |
| 977 | return Err(Fail::new("checks_failed", format!("can't land {}: check \"{check}\" failed on the merged result", app.short(&s.project, &item.id))) |
| 978 | .detail(log.map(|l| format!("log: {l}")).unwrap_or_default()) |
| 979 | .state("main didn't change; your change is saved") |
| 980 | .next("fix it, then vcs land again")); |
| 981 | } |
| 982 | Landed::Review { number, url, blockers, at: when } => { |
| 983 | // The workspace stays on the change: landing again after more |
| 984 | // edits updates the same change request. |
| 985 | app.db.set_review(&item.id, Some(&format!("#{number} {url}")))?; |
| 986 | r.line("review", format!("{} is change request #{number}, {url}", app.short(&s.project, &item.id))); |
| 987 | for b in &blockers { |
| 988 | r.line("waiting on", b.clone()); |
| 989 | } |
| 990 | match when { |
| 991 | Some(t) => r.line("lands", format!("at {} or after, once its approvals and checks pass", ids::clock(t))), |
| 992 | None => r.line("lands", "when its approvals and checks pass (Upstream merges it, and it comes into main)"), |
| 993 | }; |
| 994 | r.exit = 5; |
| 995 | r.set("review", json!({ "change": item.id, "number": number, "url": url, "blockers": blockers })); |
| 996 | r.next("keep working; vcs land again updates it, and vcs status shows where it is"); |
| 997 | return Ok(r); |
| 998 | } |
| 999 | Landed::Scheduled { at } => { |
| 1000 | item.state = "scheduled".into(); |
| 1001 | app.db.put_change(&item)?; |
| 1002 | r.line("scheduled", format!("{} lands at {}", app.short(&s.project, &item.id), ids::clock(at))); |
| 1003 | r.set("scheduled", json!({ "change": item.id, "at": at })); |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | if landed_versions.is_empty() { |
| 1008 | // All of it is scheduled: the workspace goes on on top of it. |
| 1009 | if stack.iter().any(|x| x.id == current.id) { |
| 1010 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 1011 | r.line("change", format!("{} new, on top of the scheduled change", app.short(&s.project, &fresh.id))); |
| 1012 | } |
| 1013 | r.next("keep working; the host lands it then, as it is now"); |
| 1014 | return Ok(r); |
| 1015 | } |
| 1016 | let (last_id, last_version) = landed_versions.last().cloned().unwrap(); |
| 1017 | if let Some(prev) = app.db.version(&s.project.id, last_version.n.saturating_sub(1))? |
| 1018 | && let Some(first) = stack.first() |
| 1019 | && let Some(b) = first.base_version |
| 1020 | && prev.n > b |
| 1021 | { |
| 1022 | r.line("merged", format!("with {} versions that landed since main {b}", prev.n - b)); |
| 1023 | } |
| 1024 | app.db.add_op(&s.ws.id, "land", &json!({ "change": last_id, "version": last_version.n, "stack": stack.iter().map(|c| c.id.clone()).collect::<Vec<_>>() }))?; |
| 1025 | if stack.iter().any(|x| x.id == current.id) { |
| 1026 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 1027 | r.line("change", format!("{} new, empty, on top of what you just landed", app.short(&s.project, &fresh.id))); |
| 1028 | r.set("change", change_json(app, &s.project, &fresh)); |
| 1029 | } |
| 1030 | r.set("landed", landed_versions.iter().map(|(id, v)| json!({ "change": id, "version": v.n, "title": v.title })).collect::<Vec<_>>()) |
| 1031 | .set("main", last_version.n); |
| 1032 | r.next("keep working, or vcs sync to bring in others' work"); |
| 1033 | Ok(r) |
| 1034 | } |
| 1035 |
| 1036 | /// One workspace's part of a landing together: its change, checked and |
| 1037 | /// uploaded, and the host's landing request for it. |
| 1038 | fn together_part(app: &App, s: &mut Session, messages: &[String], allow_secrets: bool, run: bool) -> Result<(Change, serde_json::Value), Fail> { |
| 1039 | let saved = app.save_local(s)?; |
| 1040 | let mut c = settle_review(app, s, saved)?; |
| 1041 | let short = app.short(&s.project, &c.id); |
| 1042 | if !messages.is_empty() { |
| 1043 | set_description(&mut c, messages); |
| 1044 | app.db.put_change(&c)?; |
| 1045 | } |
| 1046 | let place = s.root.display().to_string(); |
| 1047 | if c.state != "open" { |
| 1048 | return Err(Fail::new("bad_usage", format!("{place}: change {short} is {}", c.state)).state("nothing landed")); |
| 1049 | } |
| 1050 | if c.is_empty() { |
| 1051 | return Err(Fail::new("empty_change", format!("{place}: change {short} has nothing to land")).state("nothing landed").next("edit files there first")); |
| 1052 | } |
| 1053 | if !c.conflicts.is_empty() { |
| 1054 | return Err(Fail::new("conflict", format!("{place}: change {short} still has conflict markers")).state("nothing landed").next(format!("fix the marked lines in {place}, then land again"))); |
| 1055 | } |
| 1056 | if let Some(p) = &c.on_change |
| 1057 | && app.change(p)?.state != "landed" |
| 1058 | { |
| 1059 | return Err(Fail::new("bad_usage", format!("{place}: change {short} is on top of a change that hasn't landed")).state("nothing landed").next(format!("land that first (vcs -C {place} land)"))); |
| 1060 | } |
| 1061 | require_title(&c)?; |
| 1062 | if run { |
| 1063 | run_before_land(&s.root)?; |
| 1064 | } |
| 1065 | if !allow_secrets && let Some(hit) = secrets::scan(&app.store, &c.base_tree, &c.tree())?.first() { |
| 1066 | return Err(Fail::new("secret", format!("{place}: {} line {} looks like a {}", hit.path, hit.line, hit.kind)).state("nothing landed").next(format!("remove it from {}, then land again", hit.path))); |
| 1067 | } |
| 1068 | let remote = crate::remote::Remote::for_project(&s.project); |
| 1069 | remote.upload_change(&app.db, &app.store, &s.project, &c.base_tree, Some(&c.tree()))?; |
| 1070 | let pending = app.db.unuploaded_saves(&c.id)?; |
| 1071 | let request = LandRequest { |
| 1072 | change: c.id.clone(), |
| 1073 | base_tree: c.base_tree, |
| 1074 | tree: c.tree(), |
| 1075 | title: c.title.clone(), |
| 1076 | body: c.body.clone(), |
| 1077 | author: c.author.clone(), |
| 1078 | allow_secrets, |
| 1079 | at: None, |
| 1080 | record: Some(crate::wire::PutChange { |
| 1081 | change: crate::remote::Remote::record(&c), |
| 1082 | workspace: s.ws.id.clone(), |
| 1083 | label: crate::remote::label(&s.root), |
| 1084 | save: pending.last().map(|sv| crate::wire::SaveRecord { n: sv.n, tree: sv.tree, base_tree: sv.base_tree, at: sv.at, workspace: s.ws.id.clone() }), |
| 1085 | }), |
| 1086 | }; |
| 1087 | for sv in &pending { |
| 1088 | app.db.mark_uploaded(&c.id, sv.n)?; |
| 1089 | } |
| 1090 | let (_, owner, name) = crate::remote::split_address(&s.project.address)?; |
| 1091 | Ok((c, json!({ "project": format!("{owner}/{name}"), "land": request }))) |
| 1092 | } |
| 1093 |
| 1094 | /// `vcs land --with <workspace>...`: this workspace's change and the other |
| 1095 | /// workspaces' (in other projects on the same host) land together, all of |
| 1096 | /// them or none. Under review rules, or with --at, each waits (in review, or |
| 1097 | /// held as it is) and the host lands them all once every one is ready. |
| 1098 | fn land_together(app: &App, s: &mut Session, with: &[PathBuf], messages: Vec<String>, allow_secrets: bool, run: bool, at: Option<i64>) -> Out { |
| 1099 | if !s.project.hosted() { |
| 1100 | return Err(Fail::new("bad_usage", "landing together needs a host, which lands every part at once").state("nothing changed").next("vcs publish <host/owner/name>")); |
| 1101 | } |
| 1102 | let mut others = Vec::new(); |
| 1103 | for path in with { |
| 1104 | let root = ws::find(&app.cwd.join(path)).ok_or_else(|| Fail::new("not_found", format!("{} isn't in a vcs workspace", path.display())).state("nothing changed"))?; |
| 1105 | let other = app.session_at(&root)?; |
| 1106 | if other.project.api != s.project.api { |
| 1107 | return Err(Fail::new("bad_usage", format!("{} is on another host; landing together is on one host", root.display())).state("nothing changed")); |
| 1108 | } |
| 1109 | if other.project.id == s.project.id || others.iter().any(|o: &Session| o.project.id == other.project.id) { |
| 1110 | return Err(Fail::new("bad_usage", format!("{} is in a project that's already in this landing: one change per project", root.display())).state("nothing changed")); |
| 1111 | } |
| 1112 | others.push(other); |
| 1113 | } |
| 1114 | let mut changes = Vec::new(); |
| 1115 | let mut parts = Vec::new(); |
| 1116 | for i in 0..=others.len() { |
| 1117 | let session: &mut Session = if i == 0 { &mut *s } else { &mut others[i - 1] }; |
| 1118 | let (c, part) = together_part(app, session, if i == 0 { &messages } else { &[] }, allow_secrets, run)?; |
| 1119 | changes.push(c); |
| 1120 | parts.push(part); |
| 1121 | } |
| 1122 | let mut body = json!({ "parts": parts }); |
| 1123 | if let Some(t) = at { |
| 1124 | body["at"] = json!(t); |
| 1125 | } |
| 1126 | let answer: serde_json::Value = crate::remote::Remote::for_project(&s.project).post_host("/land-together", &body)?; |
| 1127 | let mut r = Report::new(); |
| 1128 | let sessions: Vec<&mut Session> = std::iter::once(&mut *s).chain(others.iter_mut()).collect(); |
| 1129 | let mut sessions = sessions; |
| 1130 | match answer["outcome"].as_str() { |
| 1131 | Some("landed") => { |
| 1132 | for (session, c) in sessions.iter_mut().zip(&changes) { |
| 1133 | let (_, owner, name) = crate::remote::split_address(&session.project.address)?; |
| 1134 | let project = format!("{owner}/{name}"); |
| 1135 | let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); |
| 1136 | let version: Version = serde_json::from_value(part["version"].clone()).map_err(|e| Fail::new("failed", format!("the host's answer for {project} was off: {e}")))?; |
| 1137 | let mut done = c.clone(); |
| 1138 | done.state = "landed".into(); |
| 1139 | done.version = Some(version.n); |
| 1140 | app.db.put_change(&done)?; |
| 1141 | app.db.put_version(&session.project.id, &version)?; |
| 1142 | r.line("landed", format!("{} as main {} of {project} \"{}\"", app.short(&session.project, &c.id), version.n, version.title)); |
| 1143 | continue_after(app, session, &done)?; |
| 1144 | } |
| 1145 | r.set("landed", answer["parts"].clone()); |
| 1146 | r.next("keep working; each workspace is on a fresh change"); |
| 1147 | } |
| 1148 | Some("together") => { |
| 1149 | let mut reviews = 0; |
| 1150 | for (session, c) in sessions.iter_mut().zip(&changes) { |
| 1151 | let (_, owner, name) = crate::remote::split_address(&session.project.address)?; |
| 1152 | let project = format!("{owner}/{name}"); |
| 1153 | let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); |
| 1154 | let short = app.short(&session.project, &c.id); |
| 1155 | if let (Some(number), Some(url)) = (part["review"]["number"].as_u64(), part["review"]["url"].as_str()) { |
| 1156 | reviews += 1; |
| 1157 | app.db.set_review(&c.id, Some(&format!("#{number} {url}")))?; |
| 1158 | r.line("review", format!("{short} in {project} is change request #{number}, {url}")); |
| 1159 | } else { |
| 1160 | let mut held = c.clone(); |
| 1161 | held.state = "scheduled".into(); |
| 1162 | app.db.put_change(&held)?; |
| 1163 | r.line("held", format!("{short} in {project}, as it is now")); |
| 1164 | continue_after(app, session, &held)?; |
| 1165 | } |
| 1166 | } |
| 1167 | let when = answer["at"].as_i64().map(|t| format!(" at {} or after", ids::clock(t))).unwrap_or_default(); |
| 1168 | r.line("lands", format!("all together{when}, once every change request's approvals and checks pass")); |
| 1169 | if reviews > 0 { |
| 1170 | r.exit = 5; |
| 1171 | } |
| 1172 | r.set("together", answer.clone()); |
| 1173 | r.next("keep working; the host lands them all when every part is ready"); |
| 1174 | } |
| 1175 | Some("refused") => { |
| 1176 | let project = answer["project"].as_str().unwrap_or("a project"); |
| 1177 | let landed: Landed = serde_json::from_value(answer["landed"].clone()).map_err(|e| Fail::new("failed", format!("the host's answer was off: {e}")))?; |
| 1178 | let (code, why) = match &landed { |
| 1179 | Landed::Conflict { main, conflicts } => ("conflict", format!("conflicts with main {main} of {project} in {}", conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", "))), |
| 1180 | Landed::Waiting { reason, .. } => ("waiting", format!("{project}: {reason}")), |
| 1181 | _ => ("failed", format!("{project} couldn't land its part")), |
| 1182 | }; |
| 1183 | return Err(Fail::new(code, format!("nothing landed: {why}")).state("main didn't change in any of them; every change is saved").next(format!("in {project}'s workspace: vcs sync, fix it, then land together again"))); |
| 1184 | } |
| 1185 | _ => return Err(Fail::new("failed", format!("the host answered {answer}"))), |
| 1186 | } |
| 1187 | Ok(r) |
| 1188 | } |
| 1189 |
| 1190 | /// A change in review: the host says whether its change request merged |
| 1191 | /// meanwhile, and if it did and it's the workspace's change, the workspace |
| 1192 | /// moves on to a fresh change on top of it, as after a land. |
| 1193 | fn settle_review(app: &App, s: &mut Session, c: Change) -> Result<Change, Fail> { |
| 1194 | if !s.project.hosted() || app.db.review(&c.id)?.is_none() { |
| 1195 | return Ok(c); |
| 1196 | } |
| 1197 | let found: Result<serde_json::Value, _> = crate::remote::Remote::for_project(&s.project).get_json(&format!("/changes/{}", c.id)); |
| 1198 | let Ok(found) = found else { return Ok(c) }; |
| 1199 | let Ok(record) = serde_json::from_value::<crate::wire::ChangeRecord>(found["change"].clone()) else { return Ok(c) }; |
| 1200 | let adopted = crate::remote::Remote::adopt(&app.db, &s.project, &record)?; |
| 1201 | if adopted.state == "landed" && s.ws.change == adopted.id { |
| 1202 | // On from what the workspace has (a sync may have moved it since). |
| 1203 | let mut done = c; |
| 1204 | done.state = "landed".into(); |
| 1205 | done.version = adopted.version; |
| 1206 | return continue_after(app, s, &done); |
| 1207 | } |
| 1208 | Ok(adopted) |
| 1209 | } |
| 1210 |
| 1211 | /// After a landing (or a land that's waiting), the workspace continues on a |
| 1212 | /// fresh change on top of what it had, without touching files. |
| 1213 | fn continue_after(app: &App, s: &mut Session, done: &Change) -> Result<Change, Fail> { |
| 1214 | let mut fresh = Change::new(ids::new_change_id(), &s.project.id, done.tree(), None, &app.author(&s.project)); |
| 1215 | if done.state == "waiting" || done.state == "scheduled" { |
| 1216 | fresh.on_change = Some(done.id.clone()); |
| 1217 | } else { |
| 1218 | fresh.after_change = Some(done.id.clone()); |
| 1219 | } |
| 1220 | app.db.put_change(&fresh)?; |
| 1221 | app.put_workspace_change(s, &fresh.id)?; |
| 1222 | Ok(fresh) |
| 1223 | } |
| 1224 |
| 1225 | // Fix. |
| 1226 |
| 1227 | pub fn undo(app: &App, version_n: Option<u64>) -> Out { |
| 1228 | let mut s = app.session()?; |
| 1229 | let current = app.save(&mut s)?; |
| 1230 | if let Some(n) = version_n { |
| 1231 | let (v, revert) = take_back(app, &s, n)?; |
| 1232 | let mut r = Report::new(); |
| 1233 | r.line("undid", format!("main {} (\"{}\"): main {} takes it back out", v.n, v.title, revert.n)); |
| 1234 | if let Some(mut c) = app.db.change(&v.change)? { |
| 1235 | c.state = "open".into(); |
| 1236 | c.version = None; |
| 1237 | app.db.put_change(&c)?; |
| 1238 | r.line("change", format!("{} is open again; vcs switch {} to work on it", app.short(&s.project, &c.id), app.short(&s.project, &c.id))); |
| 1239 | } |
| 1240 | app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back main {}", v.n) }))?; |
| 1241 | r.set("undid", v.n).set("main", revert.n); |
| 1242 | return Ok(r); |
| 1243 | } |
| 1244 | let op = app.db.last_op(&s.ws.id)?.ok_or_else(|| Fail::new("nothing_to_undo", "nothing to undo in this workspace").state("nothing changed"))?; |
| 1245 | let d = op.data.clone(); |
| 1246 | let text = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 1247 | let mut r = Report::new(); |
| 1248 | match op.kind.as_str() { |
| 1249 | "new" | "switch" => { |
| 1250 | let back = app.change(&text("from"))?; |
| 1251 | app.show_tree(&s, &back.tree())?; |
| 1252 | app.put_workspace_change(&mut s, &back.id)?; |
| 1253 | r.line("undid", format!("{}: back on change {}", op.kind, app.short(&s.project, &back.id))); |
| 1254 | if current.is_empty() && op.kind == "new" { |
| 1255 | let mut gone = current.clone(); |
| 1256 | gone.state = "dropped".into(); |
| 1257 | app.db.put_change(&gone)?; |
| 1258 | } else { |
| 1259 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 1260 | } |
| 1261 | } |
| 1262 | "drop" => { |
| 1263 | let mut c = app.change(&text("change"))?; |
| 1264 | c.state = "open".into(); |
| 1265 | app.db.put_change(&c)?; |
| 1266 | if d.get("current").and_then(|v| v.as_bool()) == Some(true) { |
| 1267 | app.show_tree(&s, &c.tree())?; |
| 1268 | app.put_workspace_change(&mut s, &c.id)?; |
| 1269 | if let Some(rep) = d.get("replacement").and_then(|v| v.as_str()) { |
| 1270 | if let Some(mut x) = app.db.change(rep)? && x.is_empty() { |
| 1271 | x.state = "dropped".into(); |
| 1272 | app.db.put_change(&x)?; |
| 1273 | } |
| 1274 | } |
| 1275 | } |
| 1276 | r.line("undid", format!("drop: change {} is back", app.short(&s.project, &c.id))); |
| 1277 | } |
| 1278 | "describe" => { |
| 1279 | let mut c = app.change(&text("change"))?; |
| 1280 | c.title = text("title"); |
| 1281 | c.body = text("body"); |
| 1282 | app.db.put_change(&c)?; |
| 1283 | r.line("undid", format!("describe: change {} has its old description", app.short(&s.project, &c.id))); |
| 1284 | } |
| 1285 | "sync" => { |
| 1286 | let mut c = app.change(&text("change"))?; |
| 1287 | let id = |k: &str| d.get(k).and_then(|v| v.as_str()).and_then(Id::parse); |
| 1288 | c.base_tree = id("base_tree").unwrap_or(c.base_tree); |
| 1289 | c.base_version = d.get("base_version").and_then(|v| v.as_u64()); |
| 1290 | c.on_change = d.get("on_change").and_then(|v| v.as_str()).map(str::to_string); |
| 1291 | c.after_change = d.get("after_change").and_then(|v| v.as_str()).map(str::to_string); |
| 1292 | c.head_tree = id("head_tree"); |
| 1293 | c.conflicts = serde_json::from_value(d.get("conflicts").cloned().unwrap_or_default()).unwrap_or_default(); |
| 1294 | c.saves += 1; |
| 1295 | app.db.add_save(&Save { change: c.id.clone(), n: c.saves, tree: c.tree(), base_tree: c.base_tree, at: ids::now(), uploaded: false }, &s.ws.id)?; |
| 1296 | app.db.put_change(&c)?; |
| 1297 | app.show_tree(&s, &c.tree())?; |
| 1298 | r.line("undid", format!("sync: change {} is back on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 1299 | } |
| 1300 | "restore" => { |
| 1301 | let tree = d.get("before").and_then(|v| v.as_str()).and_then(Id::parse).ok_or_else(|| Fail::new("failed", "the restore can't be undone"))?; |
| 1302 | app.show_tree(&s, &tree)?; |
| 1303 | app.save(&mut s)?; |
| 1304 | r.line("undid", format!("restore of {}", text("paths"))); |
| 1305 | } |
| 1306 | "land" => { |
| 1307 | let n = d.get("version").and_then(|v| v.as_u64()).unwrap_or(0); |
| 1308 | let (v, revert) = take_back(app, &s, n)?; |
| 1309 | let mut c = app.change(&text("change"))?; |
| 1310 | c.state = "open".into(); |
| 1311 | c.version = None; |
| 1312 | // Edits made since the land come along. |
| 1313 | let after = current; |
| 1314 | c.head_tree = Some(after.tree()); |
| 1315 | if after.id != c.id { |
| 1316 | let mut x = after.clone(); |
| 1317 | x.state = "dropped".into(); |
| 1318 | app.db.put_change(&x)?; |
| 1319 | } |
| 1320 | c.saves += 1; |
| 1321 | app.db.add_save(&Save { change: c.id.clone(), n: c.saves, tree: c.tree(), base_tree: c.base_tree, at: ids::now(), uploaded: false }, &s.ws.id)?; |
| 1322 | app.db.put_change(&c)?; |
| 1323 | app.put_workspace_change(&mut s, &c.id)?; |
| 1324 | r.line("undid", format!("land of {}: main {} takes main {} back out", app.short(&s.project, &c.id), revert.n, v.n)) |
| 1325 | .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); |
| 1326 | r.next("fix it, then vcs land"); |
| 1327 | } |
| 1328 | "access" => { |
| 1329 | crate::access::undo(app, &s, &d)?; |
| 1330 | r.line("undid", format!("access change for {}", text("target"))); |
| 1331 | } |
| 1332 | "undo" => { |
| 1333 | return Err(Fail::new("nothing_to_undo", "the last thing here was an undo of a landed version; land it again to bring it back").state("nothing changed")); |
| 1334 | } |
| 1335 | other => return Err(Fail::new("failed", format!("can't undo {other}")).state("nothing changed")), |
| 1336 | } |
| 1337 | app.db.mark_undone(op.id)?; |
| 1338 | r.set("undid", op.kind.clone()).set("data", d); |
| 1339 | Ok(r) |
| 1340 | } |
| 1341 |
| 1342 | /// Lands a change that reverses version `n` on the latest main. |
| 1343 | fn take_back(app: &App, s: &Session, n: u64) -> Result<(Version, Version), Fail> { |
| 1344 | let v = version(app, &s.project, n)?; |
| 1345 | let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; |
| 1346 | let main = app.refresh(&s.project)?.ok_or_else(|| Fail::new("not_found", "main has no versions"))?; |
| 1347 | let host = app.host(&s.project); |
| 1348 | for t in [&v.tree, &before, &main.tree] { |
| 1349 | host.fetch_tree(&app.store, &s.project, t, None)?; |
| 1350 | } |
| 1351 | // Merge "version → version before it" onto main. |
| 1352 | let m = merge::trees(&app.store, Some(&v.tree), &main.tree, &before, Mode::Land, ("main", "the undo"))?; |
| 1353 | if !m.clean() { |
| 1354 | return Err(Fail::new("conflict", format!("can't take back main {n}: later versions changed the same lines")) |
| 1355 | .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 1356 | .state("main didn't change") |
| 1357 | .next("make a new change that undoes it by hand, then vcs land")); |
| 1358 | } |
| 1359 | for o in m.objects.objects.values() { |
| 1360 | app.store.put(o)?; |
| 1361 | } |
| 1362 | let request = LandRequest { |
| 1363 | change: ids::new_change_id(), |
| 1364 | base_tree: main.tree, |
| 1365 | tree: m.tree, |
| 1366 | title: format!("Take back main {n}: {}", v.title), |
| 1367 | body: format!("Undoes main {n}."), |
| 1368 | author: app.author(&s.project), |
| 1369 | allow_secrets: true, |
| 1370 | record: None, |
| 1371 | at: None, |
| 1372 | }; |
| 1373 | match host.land(&app.db, &app.store, &s.project, &request)? { |
| 1374 | Landed::Landed { version } => { |
| 1375 | app.db.put_version(&s.project.id, &version)?; |
| 1376 | Ok((v, version)) |
| 1377 | } |
| 1378 | Landed::Conflict { .. } => Err(Fail::new("conflict", format!("main moved while taking back main {n}")).state("main didn't change").next("vcs undo again")), |
| 1379 | Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state("main didn't change")), |
| 1380 | Landed::ChecksFailed { check, .. } => Err(Fail::new("checks_failed", format!("check \"{check}\" failed on the undo")).state("main didn't change")), |
| 1381 | Landed::Review { number, url, .. } => Err(Fail::new("waiting", format!("the repository's rules send the undo through review: #{number}, {url}")) |
| 1382 | .state("main didn't change yet; it lands once the change request's approvals and checks pass") |
| 1383 | .set("review", json!({ "number": number, "url": url }))), |
| 1384 | Landed::Scheduled { .. } => Err(Fail::new("failed", "the host kept the undo for later, which it shouldn't").state("main didn't change")), |
| 1385 | } |
| 1386 | } |
| 1387 |
| 1388 | /// `vcs show <file> [--from <version|change|change:save>]`: the file as it |
| 1389 | /// is in main's latest version (or in --from), printed as it is. |
| 1390 | pub fn show(app: &App, path: String, from: Option<String>) -> Out { |
| 1391 | use base64::Engine; |
| 1392 | use std::io::Write; |
| 1393 | let s = app.session()?; |
| 1394 | let path = crate::history::workspace_path(app, &s.root, &path); |
| 1395 | let from = from.unwrap_or_else(|| "main".to_string()); |
| 1396 | // A tag is the version it names. |
| 1397 | let from = match crate::tags::find(app, &s.project, &from)? { |
| 1398 | Some(n) => n.to_string(), |
| 1399 | None => from, |
| 1400 | }; |
| 1401 | // A version of a hosted project is read where it is, not fetched whole. |
| 1402 | let mut found: Option<(Vec<u8>, String)> = None; |
| 1403 | if s.project.hosted() && (from == "main" || from.parse::<u64>().is_ok()) { |
| 1404 | #[derive(serde::Deserialize)] |
| 1405 | struct HostFile { |
| 1406 | version: u64, |
| 1407 | base64: Option<String>, |
| 1408 | } |
| 1409 | let version = if from == "main" { String::new() } else { format!("&version={from}") }; |
| 1410 | let f: HostFile = crate::remote::Remote::for_project(&s.project).get_json(&format!("/file?path={}{version}", crate::history::encode(&path)))?; |
| 1411 | // Over 1 MB (or a submodule): below, from the version's objects. |
| 1412 | if let Some(b) = f.base64 { |
| 1413 | let content = base64::engine::general_purpose::STANDARD.decode(b).map_err(|e| anyhow::anyhow!("the host sent a bad file: {e}"))?; |
| 1414 | found = Some((content, format!("main {}", f.version))); |
| 1415 | } |
| 1416 | } |
| 1417 | let (content, label) = match found { |
| 1418 | Some(f) => f, |
| 1419 | None => { |
| 1420 | let (tree, label) = resolve_tree(app, &s.project, &from)?; |
| 1421 | match tree::lookup(&app.store, &tree, &path)? { |
| 1422 | Some(e) if e.kind == tree::EntryKind::Tree => return Err(Fail::new("bad_usage", format!("{path} is a folder in {label}")).state("nothing changed")), |
| 1423 | Some(e) if e.kind == tree::EntryKind::Gitlink => return Err(Fail::new("bad_usage", format!("{path} is a git submodule in {label}")).state("nothing changed")), |
| 1424 | Some(e) => (vcs_core::chunk::read_file(&app.store, &e.id)?, label), |
| 1425 | None => return Err(Fail::new("not_found", format!("there's no {path} in {label}")).state("nothing changed")), |
| 1426 | } |
| 1427 | } |
| 1428 | }; |
| 1429 | if !app.json { |
| 1430 | std::io::stdout().write_all(&content).map_err(anyhow::Error::from)?; |
| 1431 | } |
| 1432 | let mut r = Report::new(); |
| 1433 | r.set("path", path).set("from", label).set("base64", base64::engine::general_purpose::STANDARD.encode(&content)); |
| 1434 | Ok(r) |
| 1435 | } |
| 1436 |
| 1437 | pub fn restore(app: &App, paths: Vec<String>, at: Option<String>, from: Option<String>) -> Out { |
| 1438 | let mut s = app.session()?; |
| 1439 | let c = app.save(&mut s)?; |
| 1440 | if paths.is_empty() { |
| 1441 | return Err(Fail::new("bad_usage", "say which files to restore (. for all)").state("nothing changed").next("vcs restore <file>")); |
| 1442 | } |
| 1443 | let (source, label) = match (&at, &from) { |
| 1444 | (Some(_), Some(_)) => return Err(Fail::new("bad_usage", "use --at or --from, not both").state("nothing changed")), |
| 1445 | (Some(when), None) => { |
| 1446 | let t = ids::parse_time(when).ok_or_else(|| Fail::new("bad_usage", format!("can't read the time \"{when}\"")).next("use \"10 min ago\", \"2h ago\" or 15:30"))?; |
| 1447 | let sv = app.db.save_at(&s.ws.id, t)?.ok_or_else(|| { |
| 1448 | Fail::new("not_found", format!("nothing was saved in this workspace by {}", ids::clock(t))).state("nothing changed") |
| 1449 | })?; |
| 1450 | (sv.tree, format!("save {} ({})", sv.n, ids::ago(sv.at))) |
| 1451 | } |
| 1452 | (None, Some(r)) => resolve_tree(app, &s.project, r)?, |
| 1453 | (None, None) => (c.base_tree, "the change's base".to_string()), |
| 1454 | }; |
| 1455 | let src = app.files(&source)?; |
| 1456 | let mut now = app.files(&c.tree())?; |
| 1457 | let wants: Vec<String> = paths.iter().map(|p| { |
| 1458 | let abs = app.cwd.join(p); |
| 1459 | abs.strip_prefix(&s.root).ok().and_then(crate::sys::tree_path).unwrap_or_else(|| p.replace('\\', "/")) |
| 1460 | }).map(|p| p.trim_matches('/').to_string()).map(|p| if p == "." { String::new() } else { p }).collect(); |
| 1461 | let mut touched = 0; |
| 1462 | for want in &wants { |
| 1463 | let before: Vec<String> = now.keys().filter(|p| tree::under(p, want)).cloned().collect(); |
| 1464 | for p in before { |
| 1465 | now.remove(&p); |
| 1466 | touched += 1; |
| 1467 | } |
| 1468 | for (p, e) in src.iter().filter(|(p, _)| tree::under(p, want)) { |
| 1469 | now.insert(p.clone(), *e); |
| 1470 | touched += 1; |
| 1471 | } |
| 1472 | } |
| 1473 | if touched == 0 { |
| 1474 | return Err(Fail::new("not_found", format!("no files match {}", paths.join(", "))).state("nothing changed")); |
| 1475 | } |
| 1476 | let (tree_id, objects) = tree::build(&now); |
| 1477 | for o in &objects { |
| 1478 | app.store.put(o)?; |
| 1479 | } |
| 1480 | let before_tree = c.tree(); |
| 1481 | app.show_tree(&s, &tree_id)?; |
| 1482 | let saved = app.save(&mut s)?; |
| 1483 | app.db.add_op(&s.ws.id, "restore", &json!({ "change": c.id, "before": before_tree, "paths": paths.join(" "), "source": label }))?; |
| 1484 | let mut r = Report::new(); |
| 1485 | r.line("restored", format!("{} from {label}", paths.join(", "))); |
| 1486 | r.set("restored", paths.clone()).set("source", label).set("change", change_json(app, &s.project, &saved)); |
| 1487 | r.next(format!("vcs diff {} to check", paths.join(" "))); |
| 1488 | Ok(r) |
| 1489 | } |
| 1490 |
| 1491 | pub fn guide() -> Out { |
| 1492 | let mut r = Report::new(); |
| 1493 | r.raw(include_str!("../../GUIDE.md")); |
| 1494 | r.set("guide", include_str!("../../GUIDE.md")); |
| 1495 | Ok(r) |
| 1496 | } |
| 1497 |
| 1498 | /// Files a workspace tracks, by path, for helpers. |
| 1499 | pub fn tracked(root: &Path) -> BTreeMap<String, ()> { |
| 1500 | Index::load(root).entries.keys().map(|k| (k.clone(), ())).collect() |
| 1501 | } |
| 1502 |
| 1503 | #[allow(dead_code)] |
| 1504 | fn files_to_vec(files: &Files) -> Vec<String> { |
| 1505 | files.keys().cloned().collect() |
| 1506 | } |
| 1507 |