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