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 = root.canonicalize()?; |
| 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 s = app.session_at(&root)?; |
| 94 | let saved = app.save(&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 | pub fn get(app: &App, target: &str, folder: Option<PathBuf>, change_id: Option<String>, only: Vec<String>) -> Out { |
| 108 | let project = resolve_project(app, target)?; |
| 109 | let name = project.address.trim_end_matches('/').rsplit('/').next().unwrap_or("project").to_string(); |
| 110 | let root = app.cwd.join(folder.unwrap_or_else(|| PathBuf::from(&name))); |
| 111 | ensure_dir_empty(&root)?; |
| 112 | let main = app.refresh(&project)?; |
| 113 | let only: Vec<String> = only.into_iter().map(|o| o.trim_matches('/').to_string()).filter(|o| !o.is_empty()).collect(); |
| 114 |
| 115 | let author = app.author(&project); |
| 116 | let (change, tree) = match change_id { |
| 117 | Some(text) => { |
| 118 | let mut c = app.find_change(&project, &text)?; |
| 119 | if c.state == "landed" || c.state == "dropped" { |
| 120 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 121 | } |
| 122 | take_over(app, &project, &mut c)?; |
| 123 | let t = c.tree(); |
| 124 | (c, t) |
| 125 | } |
| 126 | None => { |
| 127 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 128 | let c = Change::new(ids::new_change_id(), &project.id, base, main.as_ref().map(|v| v.n), &author); |
| 129 | app.db.put_change(&c)?; |
| 130 | (c, base) |
| 131 | } |
| 132 | }; |
| 133 |
| 134 | std::fs::create_dir_all(&root)?; |
| 135 | let root = root.canonicalize()?; |
| 136 | let workspace = Workspace { id: ids::new_workspace_id(), project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: only.clone() }; |
| 137 | ws::write_id(&root, &workspace.id)?; |
| 138 |
| 139 | // Copy unchanged files from the most recent workspace of this project. |
| 140 | let source = app.db.project_workspaces(&project.id)?.into_iter().find(|w| w.path.join(ws::DIR).is_dir() && w.path != root); |
| 141 | let source_index = source.as_ref().map(|w| Index::load(&w.path)); |
| 142 | app.host(&project).fetch_tree(&app.store, &project, &tree, None)?; |
| 143 | let files = app.files(&tree)?; |
| 144 | let cow = match (&source, &source_index) { |
| 145 | (Some(w), Some(i)) => Some(CowSource { root: &w.path, index: i }), |
| 146 | _ => None, |
| 147 | }; |
| 148 | let mut index = ws::materialize(&root, &app.store, &Index::default(), &files, &only, cow)?; |
| 149 | index.save(&root)?; |
| 150 | app.db.put_workspace(&workspace)?; |
| 151 | let mut copied = Vec::new(); |
| 152 | if let Some(w) = &source { |
| 153 | for folder in ws::config(&root).workspace.copy { |
| 154 | let folder = folder.trim_matches('/'); |
| 155 | if folder.is_empty() || folder.contains("..") { |
| 156 | continue; |
| 157 | } |
| 158 | let n = ws::copy_folder(&w.path.join(folder), &root.join(folder))?; |
| 159 | if n > 0 { |
| 160 | copied.push(format!("{folder} from {} ({n} files)", w.path.display())); |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | let mine = app.place_mine(&project, &root)?; |
| 165 |
| 166 | let mut r = Report::new(); |
| 167 | r.line("workspace", format!("{} ({})", root.display(), project.address)); |
| 168 | let state = if change.is_empty() { "new, empty".to_string() } else { format!("{} saves", change.saves) }; |
| 169 | r.line("change", format!("{} {}, on {}", app.short(&project, &change.id), state, base_text(app, &project, &change))); |
| 170 | if !only.is_empty() { |
| 171 | r.line("only", only.join(", ")); |
| 172 | } |
| 173 | for c in &copied { |
| 174 | r.line("copied", c.clone()); |
| 175 | } |
| 176 | if mine > 0 { |
| 177 | r.line("yours", format!("{mine} private files (like .env) placed")); |
| 178 | } |
| 179 | r.set("workspace", root.display().to_string()) |
| 180 | .set("project", project.address.clone()) |
| 181 | .set("main", main.as_ref().map(|v| v.n)) |
| 182 | .set("change", change_json(app, &project, &change)) |
| 183 | .next("edit files, then vcs land -m \"what you did\""); |
| 184 | Ok(r) |
| 185 | } |
| 186 |
| 187 | /// A project by address: a hosted `host/owner/name`, or a local folder. |
| 188 | fn resolve_project(app: &App, target: &str) -> Result<Project, Fail> { |
| 189 | let path = app.cwd.join(target); |
| 190 | if target.starts_with('/') || target.starts_with('.') || target.starts_with('~') || path.join(ws::DIR).is_dir() { |
| 191 | let root = ws::find(&path).ok_or_else(|| { |
| 192 | Fail::new("not_found", format!("{target} isn't a vcs workspace")).state("nothing changed").next("vcs init <folder> to start a project there") |
| 193 | })?; |
| 194 | let id = ws::read_id(&root)?; |
| 195 | let w = app.db.workspace(&id)?.ok_or_else(|| Fail::new("not_found", "that workspace isn't known on this machine"))?; |
| 196 | return app.db.project(&w.project)?.ok_or_else(|| Fail::new("not_found", "that workspace's project is missing")); |
| 197 | } |
| 198 | crate::remote::project(app, target) |
| 199 | } |
| 200 |
| 201 | /// Makes this machine's workspace the one holding `change`. |
| 202 | fn take_over(app: &App, project: &Project, change: &mut Change) -> Result<(), Fail> { |
| 203 | if project.hosted() { |
| 204 | crate::remote::Remote::for_project(project).fetch_saves(&app.db, &app.store, project, change)?; |
| 205 | } |
| 206 | if let Some(holder) = app.db.workspace_holding(&change.id)? { |
| 207 | // Another workspace here holds it: move that one to a fresh change. |
| 208 | let _ = holder; |
| 209 | } |
| 210 | Ok(()) |
| 211 | } |
| 212 |
| 213 | // See. |
| 214 |
| 215 | pub fn status(app: &App, which: Option<String>) -> Out { |
| 216 | let s = app.session()?; |
| 217 | let current = app.save(&s)?; |
| 218 | let c = match which { |
| 219 | Some(text) => app.find_change(&s.project, &text)?, |
| 220 | None => current, |
| 221 | }; |
| 222 | let main = app.main(&s.project)?; |
| 223 | let mut r = Report::new(); |
| 224 | r.line("project", s.project.address.clone()).line("workspace", s.root.display().to_string()); |
| 225 | let who = if c.author == app.author(&s.project) { "yours".to_string() } else { c.author.clone() }; |
| 226 | let title = if c.title.is_empty() { "(no description yet)".to_string() } else { format!("\"{}\"", c.title) }; |
| 227 | r.line("change", format!("{} {} {}, {}", app.short(&s.project, &c.id), title, c.state, who)); |
| 228 | match c.state.as_str() { |
| 229 | "landed" => { |
| 230 | r.line("landed", format!("as main {}", c.version.map(|v| v.to_string()).unwrap_or("?".into()))); |
| 231 | } |
| 232 | "waiting" => { |
| 233 | r.line("waiting", "for someone with landing rights to land it"); |
| 234 | } |
| 235 | _ => { |
| 236 | let behind = match (c.base_version, &main) { |
| 237 | (Some(b), Some(m)) if m.n > b && c.on_change.is_none() => format!(" (main is at {}; land merges the difference)", m.n), |
| 238 | _ => String::new(), |
| 239 | }; |
| 240 | r.line("based on", format!("{}{behind}", base_text(app, &s.project, &c))); |
| 241 | } |
| 242 | } |
| 243 | if c.saves > 0 { |
| 244 | let last = app.db.save(&c.id, c.saves)?.map(|sv| sv.at).unwrap_or(c.updated); |
| 245 | r.line("saved", format!("{} (save {})", ids::ago(last), c.saves)); |
| 246 | } |
| 247 | let base_files = app.files(&c.base_tree)?; |
| 248 | let files = app.files(&c.tree())?; |
| 249 | let changes = tree::diff(&base_files, &files); |
| 250 | let mut list = Vec::new(); |
| 251 | for (path, change) in &changes { |
| 252 | let mark = match change { |
| 253 | tree::Change::Added(_) => "A", |
| 254 | tree::Change::Removed(_) => "D", |
| 255 | tree::Change::Modified(..) => "M", |
| 256 | }; |
| 257 | list.push(format!("{mark} {path}")); |
| 258 | } |
| 259 | if list.is_empty() { |
| 260 | r.line("files", "no changes yet"); |
| 261 | } else { |
| 262 | let shown: Vec<String> = list.iter().take(50).cloned().collect(); |
| 263 | let more = if list.len() > 50 { format!("\n… and {} more", list.len() - 50) } else { String::new() }; |
| 264 | r.line("files", format!("{}{more}", shown.join("\n"))); |
| 265 | } |
| 266 | if !c.conflicts.is_empty() { |
| 267 | r.line("conflicts", c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join("\n")); |
| 268 | } |
| 269 | r.set("project", s.project.address.clone()) |
| 270 | .set("workspace", s.root.display().to_string()) |
| 271 | .set("change", change_json(app, &s.project, &c)) |
| 272 | .set("main", main.as_ref().map(|v| v.n)) |
| 273 | .set("files", list.clone()); |
| 274 | if c.state == "open" { |
| 275 | if !c.conflicts.is_empty() { |
| 276 | r.next(format!("fix the marked lines in {}, then vcs land", c.conflicts[0].path)); |
| 277 | } else if list.is_empty() { |
| 278 | r.next("edit files, then vcs land -m \"what you did\""); |
| 279 | } else if c.title.is_empty() { |
| 280 | r.next("vcs land -m \"what you did\""); |
| 281 | } else { |
| 282 | r.next("vcs land"); |
| 283 | } |
| 284 | } |
| 285 | Ok(r) |
| 286 | } |
| 287 |
| 288 | /// Resolves a reference: a version number, `main`, a change, or change:save. |
| 289 | fn resolve_tree(app: &App, project: &Project, text: &str) -> Result<(Id, String), Fail> { |
| 290 | if text == "main" { |
| 291 | let v = app.refresh(project)?.ok_or_else(|| Fail::new("not_found", "main has no versions yet"))?; |
| 292 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 293 | return Ok((v.tree, format!("main {}", v.n))); |
| 294 | } |
| 295 | if let Ok(n) = text.parse::<u64>() { |
| 296 | let v = version(app, project, n)?; |
| 297 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 298 | return Ok((v.tree, format!("main {n}"))); |
| 299 | } |
| 300 | if let Some((id, save)) = text.split_once(':') { |
| 301 | let c = app.find_change(project, id)?; |
| 302 | let n: i64 = save.parse().map_err(|_| Fail::new("bad_usage", format!("{text}: save numbers are whole numbers")))?; |
| 303 | let sv = app.db.save(&c.id, n)?.ok_or_else(|| Fail::new("not_found", format!("change {} has no save {n}", c.id)))?; |
| 304 | return Ok((sv.tree, format!("save {n} of {}", app.short(project, &c.id)))); |
| 305 | } |
| 306 | let c = app.find_change(project, text)?; |
| 307 | Ok((c.tree(), format!("change {}", app.short(project, &c.id)))) |
| 308 | } |
| 309 |
| 310 | fn version(app: &App, project: &Project, n: u64) -> Result<Version, Fail> { |
| 311 | if let Some(v) = app.db.version(&project.id, n)? { |
| 312 | return Ok(v); |
| 313 | } |
| 314 | app.refresh(project)?; |
| 315 | app.db.version(&project.id, n)?.ok_or_else(|| Fail::new("not_found", format!("main has no version {n}")).state("nothing changed")) |
| 316 | } |
| 317 |
| 318 | pub fn diff_cmd(app: &App, paths: Vec<String>, change: Option<String>, from: Option<String>, to: Option<String>, stat: bool) -> Out { |
| 319 | let s = app.session()?; |
| 320 | let current = app.save(&s)?; |
| 321 | let c = match change { |
| 322 | Some(t) => app.find_change(&s.project, &t)?, |
| 323 | None => current, |
| 324 | }; |
| 325 | let (a, a_label) = match &from { |
| 326 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 327 | None => (c.base_tree, "base".to_string()), |
| 328 | }; |
| 329 | let (b, b_label) = match &to { |
| 330 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 331 | None => (c.tree(), "change".to_string()), |
| 332 | }; |
| 333 | let fa = app.files(&a)?; |
| 334 | let fb = app.files(&b)?; |
| 335 | let paths: Vec<String> = paths.into_iter().map(|p| p.trim_matches('/').to_string()).collect(); |
| 336 | let mut text = String::new(); |
| 337 | let mut stats = Vec::new(); |
| 338 | let (mut adds, mut dels) = (0usize, 0usize); |
| 339 | for (path, ch) in tree::diff(&fa, &fb) { |
| 340 | if !paths.is_empty() && !paths.iter().any(|p| p == "." || tree::under(&path, p)) { |
| 341 | continue; |
| 342 | } |
| 343 | let (old, new) = match ch { |
| 344 | tree::Change::Added(e) => (None, Some(e)), |
| 345 | tree::Change::Removed(e) => (Some(e), None), |
| 346 | tree::Change::Modified(o, n) => (Some(o), Some(n)), |
| 347 | }; |
| 348 | let read = |e: Option<tree::Entry>| -> Result<Vec<u8>, Fail> { |
| 349 | match e { |
| 350 | Some(e) => Ok(app.store.read_file(&e.id)?), |
| 351 | None => Ok(Vec::new()), |
| 352 | } |
| 353 | }; |
| 354 | let (ob, nb) = (read(old)?, read(new)?); |
| 355 | if diff::is_binary(&ob) || diff::is_binary(&nb) { |
| 356 | text.push_str(&format!("Binary file {path} changed\n")); |
| 357 | stats.push(json!({ "path": path, "binary": true })); |
| 358 | continue; |
| 359 | } |
| 360 | let (added, removed) = diff::counts(&ob, &nb); |
| 361 | adds += added; |
| 362 | dels += removed; |
| 363 | stats.push(json!({ "path": path, "added": added, "removed": removed })); |
| 364 | if !stat { |
| 365 | 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() })); |
| 366 | if old.is_some() && new.is_some() && old.unwrap().kind != new.unwrap().kind { |
| 367 | text.push_str(&format!("kind {} → {}\n", old.unwrap().kind.name(), new.unwrap().kind.name())); |
| 368 | } |
| 369 | text.push_str(&diff::unified(&ob, &nb, 3)); |
| 370 | } else { |
| 371 | text.push_str(&format!("{path} | +{added} -{removed}\n")); |
| 372 | } |
| 373 | } |
| 374 | let mut r = Report::new(); |
| 375 | if text.is_empty() { |
| 376 | r.line("diff", format!("no differences between {a_label} and {b_label}")); |
| 377 | } else { |
| 378 | r.raw(text); |
| 379 | if stat { |
| 380 | r.raw(format!("{} files, +{adds} -{dels}\n", stats.len())); |
| 381 | } |
| 382 | } |
| 383 | r.set("from", a_label).set("to", b_label).set("files", stats).set("added", adds).set("removed", dels); |
| 384 | Ok(r) |
| 385 | } |
| 386 |
| 387 | pub fn log(app: &App, what: Option<String>, changes: bool, saves: bool, ops: bool, limit: i64) -> Out { |
| 388 | let s = app.session()?; |
| 389 | let current = app.save(&s)?; |
| 390 | let mut r = Report::new(); |
| 391 | if changes { |
| 392 | let list = crate::remote::visible_changes(app, &s.project)?; |
| 393 | let mut rows = Vec::new(); |
| 394 | for c in &list { |
| 395 | if c.state != "open" && c.state != "waiting" { |
| 396 | continue; |
| 397 | } |
| 398 | if c.is_empty() && c.id != current.id { |
| 399 | continue; |
| 400 | } |
| 401 | let held = app.db.workspace_holding(&c.id)?.map(|w| w.path.display().to_string()).unwrap_or_else(|| "no workspace here".into()); |
| 402 | let title = if c.title.is_empty() { "(no description)".to_string() } else { c.title.clone() }; |
| 403 | let here = if c.id == current.id { " ← this workspace" } else { "" }; |
| 404 | r.raw(format!("{} {:<8} {} {} [{}]{here}\n", app.short(&s.project, &c.id), c.state, title, c.author, held)); |
| 405 | rows.push(json!({ "change": change_json(app, &s.project, c), "workspace": held })); |
| 406 | } |
| 407 | if rows.is_empty() { |
| 408 | r.line("changes", "no open changes"); |
| 409 | } |
| 410 | r.set("changes", rows); |
| 411 | return Ok(r); |
| 412 | } |
| 413 | if saves { |
| 414 | let list = app.db.saves(¤t.id)?; |
| 415 | for sv in &list { |
| 416 | r.raw(format!("{}:{} {} ({})\n", app.short(&s.project, ¤t.id), sv.n, ids::clock(sv.at), ids::ago(sv.at))); |
| 417 | } |
| 418 | if list.is_empty() { |
| 419 | r.line("saves", "nothing saved yet in this change"); |
| 420 | } |
| 421 | r.set("saves", list.iter().map(|sv| json!({ "n": sv.n, "at": sv.at, "tree": sv.tree })).collect::<Vec<_>>()); |
| 422 | return Ok(r); |
| 423 | } |
| 424 | if ops { |
| 425 | let list = app.db.ops(&s.ws.id, limit)?; |
| 426 | for (op, undone) in &list { |
| 427 | r.raw(format!("{} {:<9} {}{}\n", ids::clock(op.at), op.kind, op_summary(op), if *undone { " (undone)" } else { "" })); |
| 428 | } |
| 429 | if list.is_empty() { |
| 430 | r.line("operations", "none yet in this workspace"); |
| 431 | } |
| 432 | r.set("ops", list.iter().map(|(op, undone)| json!({ "kind": op.kind, "at": op.at, "undone": undone, "data": op.data })).collect::<Vec<_>>()); |
| 433 | return Ok(r); |
| 434 | } |
| 435 | if let Some(what) = what { |
| 436 | if let Ok(n) = what.parse::<u64>() { |
| 437 | let v = version(app, &s.project, n)?; |
| 438 | let prev_tree = match n { |
| 439 | 1 => tree::empty_id(), |
| 440 | _ => version(app, &s.project, n - 1)?.tree, |
| 441 | }; |
| 442 | app.host(&s.project).fetch_tree(&app.store, &s.project, &v.tree, None)?; |
| 443 | app.host(&s.project).fetch_tree(&app.store, &s.project, &prev_tree, None)?; |
| 444 | let changed = tree::diff(&app.files(&prev_tree)?, &app.files(&v.tree)?); |
| 445 | r.line("version", format!("main {}", v.n)) |
| 446 | .line("title", v.title.clone()) |
| 447 | .line("author", v.author.clone()) |
| 448 | .line("landed", format!("{} ({})", ids::clock(v.time), ids::ago(v.time))); |
| 449 | if !v.change.is_empty() { |
| 450 | r.line("change", v.change.clone()); |
| 451 | } |
| 452 | if !v.body.is_empty() { |
| 453 | r.line("about", v.body.clone()); |
| 454 | } |
| 455 | if let Some(g) = &v.git { |
| 456 | r.line("git", g.clone()); |
| 457 | } |
| 458 | r.line("files", changed.keys().take(50).cloned().collect::<Vec<_>>().join("\n")); |
| 459 | r.set("version", serde_json::to_value(&v).unwrap_or_default()).set("files", changed.keys().cloned().collect::<Vec<_>>()); |
| 460 | return Ok(r); |
| 461 | } |
| 462 | let c = app.find_change(&s.project, &what)?; |
| 463 | r.line("change", app.short(&s.project, &c.id)) |
| 464 | .line("title", if c.title.is_empty() { "(no description)".into() } else { c.title.clone() }) |
| 465 | .line("state", c.state.clone()) |
| 466 | .line("author", c.author.clone()) |
| 467 | .line("saves", c.saves.to_string()); |
| 468 | if let Some(v) = c.version { |
| 469 | r.line("landed", format!("as main {v}")); |
| 470 | } |
| 471 | r.set("change", change_json(app, &s.project, &c)); |
| 472 | return Ok(r); |
| 473 | } |
| 474 | app.refresh(&s.project)?; |
| 475 | let list = app.db.versions(&s.project.id, limit)?; |
| 476 | for v in &list { |
| 477 | r.raw(format!("{:>6} {} {} {}\n", v.n, v.title, short_author(&v.author), ids::ago(v.time))); |
| 478 | } |
| 479 | if list.is_empty() { |
| 480 | r.line("main", "no versions yet"); |
| 481 | r.next("vcs land -m \"First version\""); |
| 482 | } |
| 483 | 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<_>>()); |
| 484 | Ok(r) |
| 485 | } |
| 486 |
| 487 | fn short_author(author: &str) -> String { |
| 488 | author.split(" <").next().unwrap_or(author).to_string() |
| 489 | } |
| 490 |
| 491 | fn op_summary(op: &crate::db::Op) -> String { |
| 492 | let d = &op.data; |
| 493 | let s = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 494 | match op.kind.as_str() { |
| 495 | "land" => format!("change {} as main {}", s("change"), d.get("version").and_then(|v| v.as_u64()).unwrap_or(0)), |
| 496 | "sync" => format!("change {} onto {}", s("change"), s("onto")), |
| 497 | "new" | "switch" => format!("from {} to {}", s("from"), s("to")), |
| 498 | "drop" => format!("change {}", s("change")), |
| 499 | "describe" => format!("change {}", s("change")), |
| 500 | "restore" => format!("{} from {}", s("paths"), s("source")), |
| 501 | "access" => format!("{} → {}", s("target"), s("who")), |
| 502 | "undo" => s("what"), |
| 503 | _ => String::new(), |
| 504 | } |
| 505 | } |
| 506 |
| 507 | // Work. |
| 508 |
| 509 | pub fn new(app: &App, title: Option<String>, on: Option<String>) -> Out { |
| 510 | let mut s = app.session()?; |
| 511 | let current = app.save(&s)?; |
| 512 | let author = app.author(&s.project); |
| 513 | let mut c = match &on { |
| 514 | Some(text) => { |
| 515 | let parent = app.find_change(&s.project, text)?; |
| 516 | if parent.state == "landed" || parent.state == "dropped" { |
| 517 | return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)) |
| 518 | .state("nothing changed") |
| 519 | .next("vcs new")); |
| 520 | } |
| 521 | if s.project.hosted() { |
| 522 | crate::remote::Remote::for_project(&s.project).fetch_saves(&app.db, &app.store, &s.project, &parent)?; |
| 523 | } |
| 524 | let mut c = Change::new(ids::new_change_id(), &s.project.id, parent.tree(), None, &author); |
| 525 | c.on_change = Some(parent.id.clone()); |
| 526 | c |
| 527 | } |
| 528 | None => { |
| 529 | let main = app.refresh(&s.project)?; |
| 530 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 531 | Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &author) |
| 532 | } |
| 533 | }; |
| 534 | if let Some(t) = title { |
| 535 | set_description(&mut c, &[t]); |
| 536 | } |
| 537 | app.db.put_change(&c)?; |
| 538 | app.show_tree(&s, &c.base_tree)?; |
| 539 | app.put_workspace_change(&mut s, &c.id)?; |
| 540 | app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": c.id }))?; |
| 541 | let mut r = Report::new(); |
| 542 | r.line("change", format!("{} new, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 543 | let kept = if current.is_empty() { "(it was empty)".to_string() } else { "is saved; vcs switch goes back to it".to_string() }; |
| 544 | r.line("kept", format!("{} {kept}", app.short(&s.project, ¤t.id))); |
| 545 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 546 | r.next("edit files, then vcs land"); |
| 547 | Ok(r) |
| 548 | } |
| 549 |
| 550 | fn set_description(c: &mut Change, parts: &[String]) { |
| 551 | let text = parts.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect::<Vec<_>>().join("\n\n"); |
| 552 | let mut lines = text.splitn(2, '\n'); |
| 553 | c.title = lines.next().unwrap_or("").trim().to_string(); |
| 554 | c.body = lines.next().unwrap_or("").trim().to_string(); |
| 555 | } |
| 556 |
| 557 | pub fn describe(app: &App, parts: Vec<String>) -> Out { |
| 558 | let s = app.session()?; |
| 559 | let mut c = app.save(&s)?; |
| 560 | if parts.iter().all(|p| p.trim().is_empty()) { |
| 561 | return Err(Fail::new("bad_usage", "give a description").state("nothing changed").next("vcs describe \"Title\" \"More detail\"")); |
| 562 | } |
| 563 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 564 | set_description(&mut c, &parts); |
| 565 | app.db.put_change(&c)?; |
| 566 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 567 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 568 | let mut r = Report::new(); |
| 569 | r.line("change", format!("{} \"{}\"", app.short(&s.project, &c.id), c.title)).set("change", change_json(app, &s.project, &c)); |
| 570 | r.next("vcs land"); |
| 571 | Ok(r) |
| 572 | } |
| 573 |
| 574 | pub fn switch(app: &App, target: &str) -> Out { |
| 575 | let mut s = app.session()?; |
| 576 | let current = app.save(&s)?; |
| 577 | let mut c = app.find_change(&s.project, target)?; |
| 578 | if c.id == current.id { |
| 579 | let mut r = Report::new(); |
| 580 | r.line("change", format!("{} is already this workspace's change", app.short(&s.project, &c.id))); |
| 581 | return Ok(r); |
| 582 | } |
| 583 | if c.state == "landed" || c.state == "dropped" { |
| 584 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)) |
| 585 | .state("nothing changed") |
| 586 | .next(if c.state == "dropped" { "vcs undo (if you just dropped it)" } else { "vcs new" })); |
| 587 | } |
| 588 | take_over(app, &s.project, &mut c)?; |
| 589 | // Another workspace on this machine held it: move that one off it. |
| 590 | if let Some(holder) = app.db.workspace_holding(&c.id)? |
| 591 | && holder.id != s.ws.id |
| 592 | { |
| 593 | release(app, &s.project, holder)?; |
| 594 | } |
| 595 | app.show_tree(&s, &c.tree())?; |
| 596 | app.put_workspace_change(&mut s, &c.id)?; |
| 597 | app.db.add_op(&s.ws.id, "switch", &json!({ "from": current.id, "to": c.id }))?; |
| 598 | let mut r = Report::new(); |
| 599 | let title = if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) }; |
| 600 | r.line("change", format!("{}{title}, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 601 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 602 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 603 | r.next("keep working, then vcs land"); |
| 604 | Ok(r) |
| 605 | } |
| 606 |
| 607 | /// Moves another workspace on this machine off a change someone took over: |
| 608 | /// it gets a fresh change on the same base, so its next save can't touch the |
| 609 | /// taken change. |
| 610 | fn release(app: &App, project: &Project, mut holder: Workspace) -> Result<(), Fail> { |
| 611 | let taken = app.change(&holder.change)?; |
| 612 | let mut fresh = Change::new(ids::new_change_id(), &project.id, taken.tree(), None, &taken.author); |
| 613 | fresh.title = format!("Rescued from {}", taken.id); |
| 614 | fresh.after_change = Some(taken.id.clone()); |
| 615 | app.db.put_change(&fresh)?; |
| 616 | holder.change = fresh.id; |
| 617 | app.db.put_workspace(&holder)?; |
| 618 | Ok(()) |
| 619 | } |
| 620 |
| 621 | pub fn drop(app: &App, target: Option<String>) -> Out { |
| 622 | let mut s = app.session()?; |
| 623 | let current = app.save(&s)?; |
| 624 | let mut c = match target { |
| 625 | Some(t) => app.find_change(&s.project, &t)?, |
| 626 | None => current.clone(), |
| 627 | }; |
| 628 | if c.state == "landed" { |
| 629 | return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))) |
| 630 | .state("nothing changed") |
| 631 | .next(format!("vcs undo {}", c.version.unwrap_or(0)))); |
| 632 | } |
| 633 | c.state = "dropped".into(); |
| 634 | app.db.put_change(&c)?; |
| 635 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 636 | let mut r = Report::new(); |
| 637 | let mut data = json!({ "change": c.id, "current": c.id == current.id }); |
| 638 | r.line("dropped", format!("{}{}", app.short(&s.project, &c.id), if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) })); |
| 639 | if c.id == current.id { |
| 640 | let main = app.refresh(&s.project)?; |
| 641 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 642 | let fresh = Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &app.author(&s.project)); |
| 643 | app.db.put_change(&fresh)?; |
| 644 | app.show_tree(&s, &base)?; |
| 645 | app.put_workspace_change(&mut s, &fresh.id)?; |
| 646 | data["replacement"] = json!(fresh.id); |
| 647 | r.line("change", format!("{} new, on {}", app.short(&s.project, &fresh.id), main_label(main.map(|v| v.n)))); |
| 648 | } |
| 649 | app.db.add_op(&s.ws.id, "drop", &data)?; |
| 650 | r.set("dropped", c.id.clone()); |
| 651 | r.next("vcs undo brings it back"); |
| 652 | Ok(r) |
| 653 | } |
| 654 |
| 655 | // Finish. |
| 656 |
| 657 | pub fn sync(app: &App) -> Out { |
| 658 | let s = app.session()?; |
| 659 | let mut c = app.save(&s)?; |
| 660 | if c.state != "open" { |
| 661 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 662 | } |
| 663 | // Onto the change it's stacked on while that hasn't landed, else main. |
| 664 | let parent = match &c.on_change { |
| 665 | Some(p) => Some(app.change(p)?), |
| 666 | None => None, |
| 667 | }; |
| 668 | let (target_tree, target_version, label, still_on) = match parent.as_ref().filter(|p| p.state == "open" || p.state == "waiting") { |
| 669 | Some(p) => (p.tree(), None, format!("change {}", app.short(&s.project, &p.id)), Some(p.id.clone())), |
| 670 | None => { |
| 671 | let main = app.refresh(&s.project)?; |
| 672 | let t = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 673 | app.host(&s.project).fetch_tree(&app.store, &s.project, &t, Some(&c.base_tree))?; |
| 674 | (t, main.as_ref().map(|v| v.n), main_label(main.as_ref().map(|v| v.n)), None) |
| 675 | } |
| 676 | }; |
| 677 | if target_tree == c.base_tree { |
| 678 | let mut r = Report::new(); |
| 679 | r.line("synced", format!("{} is already on {label}", app.short(&s.project, &c.id))).set("change", change_json(app, &s.project, &c)); |
| 680 | r.next("vcs land"); |
| 681 | return Ok(r); |
| 682 | } |
| 683 | let ours_label = label.clone(); |
| 684 | let theirs_label = format!("your change {}", app.short(&s.project, &c.id)); |
| 685 | let m = merge::trees(&app.store, Some(&c.base_tree), &target_tree, &c.tree(), Mode::Sync, (&ours_label, &theirs_label))?; |
| 686 | for o in m.objects.objects.values() { |
| 687 | app.store.put(o)?; |
| 688 | } |
| 689 | let before = json!({ |
| 690 | "change": c.id, "onto": label, |
| 691 | "base_tree": c.base_tree, "base_version": c.base_version, "on_change": c.on_change, |
| 692 | "after_change": c.after_change, "head_tree": c.head_tree, "conflicts": c.conflicts, |
| 693 | }); |
| 694 | let was = base_text(app, &s.project, &c); |
| 695 | c.base_tree = target_tree; |
| 696 | c.base_version = target_version; |
| 697 | c.on_change = still_on; |
| 698 | c.after_change = None; |
| 699 | c.head_tree = Some(m.tree); |
| 700 | c.saves += 1; |
| 701 | c.conflicts = m.conflicts.iter().map(|x| Conflict { path: x.path.clone(), version: target_version }).collect(); |
| 702 | 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)?; |
| 703 | app.db.put_change(&c)?; |
| 704 | app.show_tree(&s, &m.tree)?; |
| 705 | app.db.add_op(&s.ws.id, "sync", &before)?; |
| 706 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 707 | let mut r = Report::new(); |
| 708 | r.line("synced", format!("{} onto {label} (was {was})", app.short(&s.project, &c.id))); |
| 709 | for x in &m.conflicts { |
| 710 | r.line("conflict", x.path.clone()); |
| 711 | } |
| 712 | for n in &m.notes { |
| 713 | r.line("note", n.message.clone()); |
| 714 | } |
| 715 | r.set("change", change_json(app, &s.project, &c)) |
| 716 | .set("conflicts", m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>()) |
| 717 | .set("notes", m.notes.iter().map(|n| n.message.clone()).collect::<Vec<_>>()); |
| 718 | if m.conflicts.is_empty() { |
| 719 | r.next("vcs land"); |
| 720 | } else { |
| 721 | r.exit = 3; |
| 722 | r.next(format!("fix the marked lines in {}, then vcs land", m.conflicts.iter().map(|x| x.path.as_str()).collect::<Vec<_>>().join(", "))); |
| 723 | } |
| 724 | Ok(r) |
| 725 | } |
| 726 |
| 727 | pub fn land(app: &App, target: Option<String>, messages: Vec<String>, no_wait: bool, allow_secrets: bool) -> Out { |
| 728 | let mut s = app.session()?; |
| 729 | let current = app.save(&s)?; |
| 730 | let mut c = match target { |
| 731 | Some(t) => app.find_change(&s.project, &t)?, |
| 732 | None => current.clone(), |
| 733 | }; |
| 734 | let _ = no_wait; |
| 735 | if !messages.is_empty() { |
| 736 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 737 | set_description(&mut c, &messages); |
| 738 | app.db.put_change(&c)?; |
| 739 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 740 | } |
| 741 | if c.state == "landed" { |
| 742 | return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))).state("nothing changed")); |
| 743 | } |
| 744 | if c.state == "dropped" { |
| 745 | return Err(Fail::new("bad_usage", format!("change {} was dropped", c.id)).state("nothing changed").next("vcs undo (if you just dropped it)")); |
| 746 | } |
| 747 | if c.is_empty() { |
| 748 | let mut f = Fail::new("empty_change", format!("change {} has nothing to land", app.short(&s.project, &c.id))).state("nothing changed"); |
| 749 | if c.after_change.is_some() { |
| 750 | f = f.next("you're on a fresh change after a landing; edit files first"); |
| 751 | } else { |
| 752 | f = f.next("edit files first"); |
| 753 | } |
| 754 | return Err(f); |
| 755 | } |
| 756 | if !c.conflicts.is_empty() { |
| 757 | return Err(Fail::new("conflict", format!("change {} still has conflict markers", app.short(&s.project, &c.id))) |
| 758 | .detail(c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 759 | .state("main didn't change; your change is saved") |
| 760 | .next("fix the marked lines, then vcs land")); |
| 761 | } |
| 762 | require_title(&c)?; |
| 763 |
| 764 | // Land what it's stacked on first, in order. |
| 765 | let mut stack = vec![c.clone()]; |
| 766 | let mut parent = c.on_change.clone(); |
| 767 | while let Some(p) = parent { |
| 768 | let pc = app.change(&p)?; |
| 769 | if pc.state != "open" && pc.state != "waiting" { |
| 770 | break; |
| 771 | } |
| 772 | require_title(&pc)?; |
| 773 | parent = pc.on_change.clone(); |
| 774 | stack.push(pc); |
| 775 | } |
| 776 | stack.reverse(); |
| 777 |
| 778 | let mut r = Report::new(); |
| 779 | let mut landed_versions = Vec::new(); |
| 780 | for (i, item) in stack.iter().enumerate() { |
| 781 | let mut item = app.change(&item.id)?; |
| 782 | if !allow_secrets { |
| 783 | let found = secrets::scan(&app.store, &item.base_tree, &item.tree())?; |
| 784 | if let Some(hit) = found.first() { |
| 785 | 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)) |
| 786 | .detail(format!("{}:{}", hit.path, hit.line)) |
| 787 | .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()) }) |
| 788 | .next(format!("remove it from {} (put real secrets in .env, which stays yours), then vcs land", hit.path)) |
| 789 | .set("secrets", serde_json::to_value(&found).unwrap_or_default())); |
| 790 | } |
| 791 | } |
| 792 | let host = app.host(&s.project); |
| 793 | host.fetch_tree(&app.store, &s.project, &item.tree(), None)?; |
| 794 | let request = LandRequest { |
| 795 | change: item.id.clone(), |
| 796 | base_tree: item.base_tree, |
| 797 | tree: item.tree(), |
| 798 | title: item.title.clone(), |
| 799 | body: item.body.clone(), |
| 800 | author: item.author.clone(), |
| 801 | allow_secrets, |
| 802 | }; |
| 803 | let outcome = host.land(&app.db, &app.store, &s.project, &request)?; |
| 804 | match outcome { |
| 805 | Landed::Landed { version } => { |
| 806 | item.state = "landed".into(); |
| 807 | item.version = Some(version.n); |
| 808 | app.db.put_change(&item)?; |
| 809 | app.db.put_version(&s.project.id, &version)?; |
| 810 | let _ = host.publish_change(&app.db, &app.store, &s.project, &item, &s.ws.id); |
| 811 | landed_versions.push((item.id.clone(), version.clone())); |
| 812 | r.line("landed", format!("{} as main {} \"{}\"", app.short(&s.project, &item.id), version.n, version.title)); |
| 813 | } |
| 814 | Landed::Conflict { main, conflicts } => { |
| 815 | let state = if landed_versions.is_empty() { |
| 816 | "main didn't change; your change is saved".to_string() |
| 817 | } else { |
| 818 | 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(", ")) |
| 819 | }; |
| 820 | 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" })); |
| 821 | for x in &conflicts { |
| 822 | f = f.detail(format!("{}{}", x.path, if x.kind == "text" { String::new() } else { format!(" ({})", x.kind) })); |
| 823 | } |
| 824 | return Err(f.state(state).next("vcs sync, fix the conflicts in those files, then vcs land") |
| 825 | .set("conflicts", serde_json::to_value(&conflicts).unwrap_or_default()) |
| 826 | .set("main", main)); |
| 827 | } |
| 828 | Landed::Waiting { asked, reason } => { |
| 829 | item.state = "waiting".into(); |
| 830 | app.db.put_change(&item)?; |
| 831 | r.line("waiting", format!("{} {reason}", app.short(&s.project, &item.id))); |
| 832 | if !asked.is_empty() { |
| 833 | r.line("asked", asked.join(", ")); |
| 834 | } |
| 835 | r.exit = 5; |
| 836 | r.set("waiting", json!({ "change": item.id, "asked": asked })); |
| 837 | r.next(format!("vcs status {} later", app.short(&s.project, &item.id))); |
| 838 | // The workspace moves on, so later edits don't change what's waiting. |
| 839 | if item.id == current.id { |
| 840 | let fresh = continue_after(app, &mut s, &item)?; |
| 841 | r.line("change", format!("{} new, on top of the waiting change", app.short(&s.project, &fresh.id))); |
| 842 | } |
| 843 | return Ok(r); |
| 844 | } |
| 845 | Landed::ChecksFailed { check, log } => { |
| 846 | return Err(Fail::new("checks_failed", format!("can't land {}: check \"{check}\" failed on the merged result", app.short(&s.project, &item.id))) |
| 847 | .detail(log.map(|l| format!("log: {l}")).unwrap_or_default()) |
| 848 | .state("main didn't change; your change is saved") |
| 849 | .next("fix it, then vcs land again")); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | let (last_id, last_version) = landed_versions.last().cloned().unwrap(); |
| 854 | if let Some(prev) = app.db.version(&s.project.id, last_version.n.saturating_sub(1))? |
| 855 | && let Some(first) = stack.first() |
| 856 | && let Some(b) = first.base_version |
| 857 | && prev.n > b |
| 858 | { |
| 859 | r.line("merged", format!("with {} versions that landed since main {b}", prev.n - b)); |
| 860 | } |
| 861 | 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<_>>() }))?; |
| 862 | if stack.iter().any(|x| x.id == current.id) { |
| 863 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 864 | r.line("change", format!("{} new, empty, on top of what you just landed", app.short(&s.project, &fresh.id))); |
| 865 | r.set("change", change_json(app, &s.project, &fresh)); |
| 866 | } |
| 867 | r.set("landed", landed_versions.iter().map(|(id, v)| json!({ "change": id, "version": v.n, "title": v.title })).collect::<Vec<_>>()) |
| 868 | .set("main", last_version.n); |
| 869 | r.next("keep working, or vcs sync to bring in others' work"); |
| 870 | Ok(r) |
| 871 | } |
| 872 |
| 873 | /// After a landing (or a land that's waiting), the workspace continues on a |
| 874 | /// fresh change on top of what it had, without touching files. |
| 875 | fn continue_after(app: &App, s: &mut Session, done: &Change) -> Result<Change, Fail> { |
| 876 | let mut fresh = Change::new(ids::new_change_id(), &s.project.id, done.tree(), None, &app.author(&s.project)); |
| 877 | if done.state == "waiting" { |
| 878 | fresh.on_change = Some(done.id.clone()); |
| 879 | } else { |
| 880 | fresh.after_change = Some(done.id.clone()); |
| 881 | } |
| 882 | app.db.put_change(&fresh)?; |
| 883 | app.put_workspace_change(s, &fresh.id)?; |
| 884 | Ok(fresh) |
| 885 | } |
| 886 |
| 887 | // Fix. |
| 888 |
| 889 | pub fn undo(app: &App, version_n: Option<u64>) -> Out { |
| 890 | let mut s = app.session()?; |
| 891 | let current = app.save(&s)?; |
| 892 | if let Some(n) = version_n { |
| 893 | let (v, revert) = take_back(app, &s, n)?; |
| 894 | let mut r = Report::new(); |
| 895 | r.line("undid", format!("main {} (\"{}\"): main {} takes it back out", v.n, v.title, revert.n)); |
| 896 | if let Some(mut c) = app.db.change(&v.change)? { |
| 897 | c.state = "open".into(); |
| 898 | c.version = None; |
| 899 | app.db.put_change(&c)?; |
| 900 | 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))); |
| 901 | } |
| 902 | app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back main {}", v.n) }))?; |
| 903 | r.set("undid", v.n).set("main", revert.n); |
| 904 | return Ok(r); |
| 905 | } |
| 906 | 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"))?; |
| 907 | let d = op.data.clone(); |
| 908 | let text = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 909 | let mut r = Report::new(); |
| 910 | match op.kind.as_str() { |
| 911 | "new" | "switch" => { |
| 912 | let back = app.change(&text("from"))?; |
| 913 | app.show_tree(&s, &back.tree())?; |
| 914 | app.put_workspace_change(&mut s, &back.id)?; |
| 915 | r.line("undid", format!("{}: back on change {}", op.kind, app.short(&s.project, &back.id))); |
| 916 | if current.is_empty() && op.kind == "new" { |
| 917 | let mut gone = current.clone(); |
| 918 | gone.state = "dropped".into(); |
| 919 | app.db.put_change(&gone)?; |
| 920 | } else { |
| 921 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 922 | } |
| 923 | } |
| 924 | "drop" => { |
| 925 | let mut c = app.change(&text("change"))?; |
| 926 | c.state = "open".into(); |
| 927 | app.db.put_change(&c)?; |
| 928 | if d.get("current").and_then(|v| v.as_bool()) == Some(true) { |
| 929 | app.show_tree(&s, &c.tree())?; |
| 930 | app.put_workspace_change(&mut s, &c.id)?; |
| 931 | if let Some(rep) = d.get("replacement").and_then(|v| v.as_str()) { |
| 932 | if let Some(mut x) = app.db.change(rep)? && x.is_empty() { |
| 933 | x.state = "dropped".into(); |
| 934 | app.db.put_change(&x)?; |
| 935 | } |
| 936 | } |
| 937 | } |
| 938 | r.line("undid", format!("drop: change {} is back", app.short(&s.project, &c.id))); |
| 939 | } |
| 940 | "describe" => { |
| 941 | let mut c = app.change(&text("change"))?; |
| 942 | c.title = text("title"); |
| 943 | c.body = text("body"); |
| 944 | app.db.put_change(&c)?; |
| 945 | r.line("undid", format!("describe: change {} has its old description", app.short(&s.project, &c.id))); |
| 946 | } |
| 947 | "sync" => { |
| 948 | let mut c = app.change(&text("change"))?; |
| 949 | let id = |k: &str| d.get(k).and_then(|v| v.as_str()).and_then(Id::parse); |
| 950 | c.base_tree = id("base_tree").unwrap_or(c.base_tree); |
| 951 | c.base_version = d.get("base_version").and_then(|v| v.as_u64()); |
| 952 | c.on_change = d.get("on_change").and_then(|v| v.as_str()).map(str::to_string); |
| 953 | c.after_change = d.get("after_change").and_then(|v| v.as_str()).map(str::to_string); |
| 954 | c.head_tree = id("head_tree"); |
| 955 | c.conflicts = serde_json::from_value(d.get("conflicts").cloned().unwrap_or_default()).unwrap_or_default(); |
| 956 | c.saves += 1; |
| 957 | 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)?; |
| 958 | app.db.put_change(&c)?; |
| 959 | app.show_tree(&s, &c.tree())?; |
| 960 | r.line("undid", format!("sync: change {} is back on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 961 | } |
| 962 | "restore" => { |
| 963 | 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"))?; |
| 964 | app.show_tree(&s, &tree)?; |
| 965 | app.save(&s)?; |
| 966 | r.line("undid", format!("restore of {}", text("paths"))); |
| 967 | } |
| 968 | "land" => { |
| 969 | let n = d.get("version").and_then(|v| v.as_u64()).unwrap_or(0); |
| 970 | let (v, revert) = take_back(app, &s, n)?; |
| 971 | let mut c = app.change(&text("change"))?; |
| 972 | c.state = "open".into(); |
| 973 | c.version = None; |
| 974 | // Edits made since the land come along. |
| 975 | let after = current; |
| 976 | c.head_tree = Some(after.tree()); |
| 977 | if after.id != c.id { |
| 978 | let mut x = after.clone(); |
| 979 | x.state = "dropped".into(); |
| 980 | app.db.put_change(&x)?; |
| 981 | } |
| 982 | c.saves += 1; |
| 983 | 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)?; |
| 984 | app.db.put_change(&c)?; |
| 985 | app.put_workspace_change(&mut s, &c.id)?; |
| 986 | r.line("undid", format!("land of {}: main {} takes main {} back out", app.short(&s.project, &c.id), revert.n, v.n)) |
| 987 | .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); |
| 988 | r.next("fix it, then vcs land"); |
| 989 | } |
| 990 | "access" => { |
| 991 | crate::access::undo(app, &s, &d)?; |
| 992 | r.line("undid", format!("access change for {}", text("target"))); |
| 993 | } |
| 994 | "undo" => { |
| 995 | 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")); |
| 996 | } |
| 997 | other => return Err(Fail::new("failed", format!("can't undo {other}")).state("nothing changed")), |
| 998 | } |
| 999 | app.db.mark_undone(op.id)?; |
| 1000 | r.set("undid", op.kind.clone()).set("data", d); |
| 1001 | Ok(r) |
| 1002 | } |
| 1003 |
| 1004 | /// Lands a change that reverses version `n` on the latest main. |
| 1005 | fn take_back(app: &App, s: &Session, n: u64) -> Result<(Version, Version), Fail> { |
| 1006 | let v = version(app, &s.project, n)?; |
| 1007 | let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; |
| 1008 | let main = app.refresh(&s.project)?.ok_or_else(|| Fail::new("not_found", "main has no versions"))?; |
| 1009 | let host = app.host(&s.project); |
| 1010 | for t in [&v.tree, &before, &main.tree] { |
| 1011 | host.fetch_tree(&app.store, &s.project, t, None)?; |
| 1012 | } |
| 1013 | // Merge "version → version before it" onto main. |
| 1014 | let m = merge::trees(&app.store, Some(&v.tree), &main.tree, &before, Mode::Land, ("main", "the undo"))?; |
| 1015 | if !m.clean() { |
| 1016 | return Err(Fail::new("conflict", format!("can't take back main {n}: later versions changed the same lines")) |
| 1017 | .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 1018 | .state("main didn't change") |
| 1019 | .next("make a new change that undoes it by hand, then vcs land")); |
| 1020 | } |
| 1021 | for o in m.objects.objects.values() { |
| 1022 | app.store.put(o)?; |
| 1023 | } |
| 1024 | let request = LandRequest { |
| 1025 | change: ids::new_change_id(), |
| 1026 | base_tree: main.tree, |
| 1027 | tree: m.tree, |
| 1028 | title: format!("Take back main {n}: {}", v.title), |
| 1029 | body: format!("Undoes main {n}."), |
| 1030 | author: app.author(&s.project), |
| 1031 | allow_secrets: true, |
| 1032 | }; |
| 1033 | match host.land(&app.db, &app.store, &s.project, &request)? { |
| 1034 | Landed::Landed { version } => { |
| 1035 | app.db.put_version(&s.project.id, &version)?; |
| 1036 | Ok((v, version)) |
| 1037 | } |
| 1038 | Landed::Conflict { .. } => Err(Fail::new("conflict", format!("main moved while taking back main {n}")).state("main didn't change").next("vcs undo again")), |
| 1039 | Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state("main didn't change")), |
| 1040 | Landed::ChecksFailed { check, .. } => Err(Fail::new("checks_failed", format!("check \"{check}\" failed on the undo")).state("main didn't change")), |
| 1041 | } |
| 1042 | } |
| 1043 |
| 1044 | pub fn restore(app: &App, paths: Vec<String>, at: Option<String>, from: Option<String>) -> Out { |
| 1045 | let s = app.session()?; |
| 1046 | let c = app.save(&s)?; |
| 1047 | if paths.is_empty() { |
| 1048 | return Err(Fail::new("bad_usage", "say which files to restore (. for all)").state("nothing changed").next("vcs restore <file>")); |
| 1049 | } |
| 1050 | let (source, label) = match (&at, &from) { |
| 1051 | (Some(_), Some(_)) => return Err(Fail::new("bad_usage", "use --at or --from, not both").state("nothing changed")), |
| 1052 | (Some(when), None) => { |
| 1053 | 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"))?; |
| 1054 | let sv = app.db.save_at(&s.ws.id, t)?.ok_or_else(|| { |
| 1055 | Fail::new("not_found", format!("nothing was saved in this workspace by {}", ids::clock(t))).state("nothing changed") |
| 1056 | })?; |
| 1057 | (sv.tree, format!("save {} ({})", sv.n, ids::ago(sv.at))) |
| 1058 | } |
| 1059 | (None, Some(r)) => resolve_tree(app, &s.project, r)?, |
| 1060 | (None, None) => (c.base_tree, "the change's base".to_string()), |
| 1061 | }; |
| 1062 | let src = app.files(&source)?; |
| 1063 | let mut now = app.files(&c.tree())?; |
| 1064 | let wants: Vec<String> = paths.iter().map(|p| { |
| 1065 | let abs = app.cwd.join(p); |
| 1066 | abs.strip_prefix(&s.root).map(|r| r.to_string_lossy().into_owned()).unwrap_or_else(|_| p.clone()) |
| 1067 | }).map(|p| p.trim_matches('/').to_string()).map(|p| if p == "." { String::new() } else { p }).collect(); |
| 1068 | let mut touched = 0; |
| 1069 | for want in &wants { |
| 1070 | let before: Vec<String> = now.keys().filter(|p| tree::under(p, want)).cloned().collect(); |
| 1071 | for p in before { |
| 1072 | now.remove(&p); |
| 1073 | touched += 1; |
| 1074 | } |
| 1075 | for (p, e) in src.iter().filter(|(p, _)| tree::under(p, want)) { |
| 1076 | now.insert(p.clone(), *e); |
| 1077 | touched += 1; |
| 1078 | } |
| 1079 | } |
| 1080 | if touched == 0 { |
| 1081 | return Err(Fail::new("not_found", format!("no files match {}", paths.join(", "))).state("nothing changed")); |
| 1082 | } |
| 1083 | let (tree_id, objects) = tree::build(&now); |
| 1084 | for o in &objects { |
| 1085 | app.store.put(o)?; |
| 1086 | } |
| 1087 | let before_tree = c.tree(); |
| 1088 | app.show_tree(&s, &tree_id)?; |
| 1089 | let saved = app.save(&s)?; |
| 1090 | app.db.add_op(&s.ws.id, "restore", &json!({ "change": c.id, "before": before_tree, "paths": paths.join(" "), "source": label }))?; |
| 1091 | let mut r = Report::new(); |
| 1092 | r.line("restored", format!("{} from {label}", paths.join(", "))); |
| 1093 | r.set("restored", paths.clone()).set("source", label).set("change", change_json(app, &s.project, &saved)); |
| 1094 | r.next(format!("vcs diff {} to check", paths.join(" "))); |
| 1095 | Ok(r) |
| 1096 | } |
| 1097 |
| 1098 | pub fn guide() -> Out { |
| 1099 | let mut r = Report::new(); |
| 1100 | r.raw(include_str!("../../GUIDE.md")); |
| 1101 | r.set("guide", include_str!("../../GUIDE.md")); |
| 1102 | Ok(r) |
| 1103 | } |
| 1104 |
| 1105 | /// Files a workspace tracks, by path, for helpers. |
| 1106 | pub fn tracked(root: &Path) -> BTreeMap<String, ()> { |
| 1107 | Index::load(root).entries.keys().map(|k| (k.clone(), ())).collect() |
| 1108 | } |
| 1109 |
| 1110 | #[allow(dead_code)] |
| 1111 | fn files_to_vec(files: &Files) -> Vec<String> { |
| 1112 | files.keys().cloned().collect() |
| 1113 | } |
| 1114 |