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(line) = &c.line { |
| 35 | return format!("{line}/{}", c.base_version.unwrap_or(0)); |
| 36 | } |
| 37 | if let Some(after) = &c.after_change { |
| 38 | let landed = app.db.change(after).ok().flatten().and_then(|a| a.version); |
| 39 | return match landed { |
| 40 | Some(n) => format!("what you landed as main {n} (change {})", app.short(project, after)), |
| 41 | None => format!("change {}", app.short(project, after)), |
| 42 | }; |
| 43 | } |
| 44 | main_label(c.base_version) |
| 45 | } |
| 46 |
| 47 | fn change_json(app: &App, project: &Project, c: &Change) -> serde_json::Value { |
| 48 | json!({ |
| 49 | "id": c.id, |
| 50 | "short": app.short(project, &c.id), |
| 51 | "title": c.title, |
| 52 | "body": c.body, |
| 53 | "state": c.state, |
| 54 | "base": c.base_version, |
| 55 | "on": c.on_change, |
| 56 | "saves": c.saves, |
| 57 | "version": c.version, |
| 58 | "line": c.line, |
| 59 | "author": c.author, |
| 60 | "conflicts": c.conflicts.iter().map(|x| &x.path).collect::<Vec<_>>(), |
| 61 | }) |
| 62 | } |
| 63 |
| 64 | fn require_title(c: &Change) -> Result<(), Fail> { |
| 65 | if c.title.trim().is_empty() { |
| 66 | return Err(Fail::new("no_description", format!("change {} has no description", c.id)) |
| 67 | .state("nothing changed; your change is saved") |
| 68 | .next(format!("vcs land -m \"what you did\""))); |
| 69 | } |
| 70 | Ok(()) |
| 71 | } |
| 72 |
| 73 | // Start. |
| 74 |
| 75 | pub fn init(app: &App, folder: Option<PathBuf>) -> Out { |
| 76 | let root = folder.map(|f| app.cwd.join(f)).unwrap_or_else(|| app.cwd.clone()); |
| 77 | std::fs::create_dir_all(&root)?; |
| 78 | let root = crate::sys::canonical(&root)?; |
| 79 | if ws::find(&root).is_some() { |
| 80 | return Err(Fail::new("bad_usage", format!("{} is already in a vcs workspace", root.display())).state("nothing changed")); |
| 81 | } |
| 82 | let project = Project { |
| 83 | id: format!("local-{}", ids::new_workspace_id()), |
| 84 | address: root.to_string_lossy().into_owned(), |
| 85 | kind: "local".into(), |
| 86 | api: None, |
| 87 | checked: ids::now(), |
| 88 | }; |
| 89 | app.db.put_project(&project)?; |
| 90 | let empty = app.store.put(&tree::empty())?; |
| 91 | let author = app.author(&project); |
| 92 | let change = Change::new(ids::new_change_id(), &project.id, empty, None, &author); |
| 93 | app.db.put_change(&change)?; |
| 94 | let workspace = Workspace { id: ids::new_workspace_id(), project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: vec![] }; |
| 95 | ws::write_id(&root, &workspace.id)?; |
| 96 | app.db.put_workspace(&workspace)?; |
| 97 | let mut s = app.session_at(&root)?; |
| 98 | let saved = app.save(&mut s)?; |
| 99 | let mut r = Report::new(); |
| 100 | r.line("project", format!("{} (on this machine only)", project.address)) |
| 101 | .line("workspace", root.display().to_string()) |
| 102 | .line("change", format!("{} new{}", app.short(&project, &change.id), if saved.is_empty() { ", empty" } else { ", holds the files already here" })) |
| 103 | .set("project", project.address.clone()) |
| 104 | .set("workspace", root.display().to_string()) |
| 105 | .set("change", change_json(app, &project, &saved)) |
| 106 | .next("add or edit files, then vcs land -m \"First version\""); |
| 107 | Ok(r) |
| 108 | } |
| 109 |
| 110 | /// `vcs get`: a new workspace on a new change (on main, on a release line, |
| 111 | /// or on the change `on` when it's given), or on an existing change. |
| 112 | #[allow(clippy::too_many_arguments)] |
| 113 | pub fn get(app: &App, target: &str, folder: Option<PathBuf>, change_id: Option<String>, only: Vec<String>, on: Option<String>, line: Option<String>, lazy: bool) -> Out { |
| 114 | if line.is_some() && (change_id.is_some() || on.is_some()) { |
| 115 | return Err(Fail::new("bad_usage", "--line starts a new change on that line; it doesn't go with --change or --on").state("nothing changed")); |
| 116 | } |
| 117 | if lazy && !only.is_empty() { |
| 118 | return Err(Fail::new("bad_usage", "--lazy fetches files as they're opened, so --only isn't needed with it").state("nothing changed")); |
| 119 | } |
| 120 | let project = resolve_project(app, target)?; |
| 121 | if lazy && !project.hosted() { |
| 122 | return Err(Fail::new("bad_usage", "--lazy is for hosted projects; a local one is all on this machine already").state("nothing changed")); |
| 123 | } |
| 124 | let name = project.address.trim_end_matches('/').rsplit('/').next().unwrap_or("project").to_string(); |
| 125 | let root = app.cwd.join(folder.unwrap_or_else(|| PathBuf::from(&name))); |
| 126 | ensure_dir_empty(&root)?; |
| 127 | let main = app.refresh(&project)?; |
| 128 | // Just switched on in Upstream for a repository with git history: main's history comes in first. |
| 129 | if project.hosted() && main.is_none() && change_id.is_none() && on.is_none() && line.is_none() { |
| 130 | let remote = crate::remote::Remote::for_project(&project); |
| 131 | let view = remote.view()?; |
| 132 | if view.import_pending |
| 133 | && let Some(git) = &view.git |
| 134 | { |
| 135 | // The import publishes to this address itself. |
| 136 | app.db.forget_project(&project.id)?; |
| 137 | match crate::bridge::import_as(app, git, Some(project.address.clone()), Some(root.clone()), remote.token.as_deref()) { |
| 138 | Ok(mut r) => { |
| 139 | r.line("note", "vcs was just turned on for this repository: main's git history came in with this get"); |
| 140 | return Ok(r); |
| 141 | } |
| 142 | // Nothing in git after all: an empty project, as any other. |
| 143 | Err(f) if f.message.contains("no commits") => app.db.put_project(&project)?, |
| 144 | Err(f) => return Err(f), |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | let only: Vec<String> = only.into_iter().map(|o| o.trim_matches('/').to_string()).filter(|o| !o.is_empty()).collect(); |
| 149 |
| 150 | let author = app.author(&project); |
| 151 | let workspace_id = ids::new_workspace_id(); |
| 152 | let mut took_from = None; |
| 153 | let (change, tree) = match change_id { |
| 154 | Some(text) => { |
| 155 | let mut c = app.find_change(&project, &text)?; |
| 156 | if c.state == "landed" || c.state == "dropped" { |
| 157 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 158 | } |
| 159 | took_from = take_over(app, &project, &mut c, &workspace_id, &root)?; |
| 160 | let t = c.tree(); |
| 161 | (c, t) |
| 162 | } |
| 163 | None => { |
| 164 | let parent = match &on { |
| 165 | Some(text) => { |
| 166 | let parent = app.find_change(&project, text)?; |
| 167 | if parent.state == "landed" || parent.state == "dropped" { |
| 168 | return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)).state("nothing changed")); |
| 169 | } |
| 170 | if project.hosted() { |
| 171 | crate::remote::Remote::for_project(&project).fetch_saves(&app.db, &app.store, &project, &parent)?; |
| 172 | } |
| 173 | Some(parent) |
| 174 | } |
| 175 | None => None, |
| 176 | }; |
| 177 | let mut c = match (&parent, &line) { |
| 178 | (Some(p), _) => { |
| 179 | let mut c = Change::new(ids::new_change_id(), &project.id, p.tree(), None, &author); |
| 180 | c.line = p.line.clone(); |
| 181 | c |
| 182 | } |
| 183 | (None, Some(name)) => on_line(app, &project, name, &author)?, |
| 184 | (None, None) => { |
| 185 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 186 | Change::new(ids::new_change_id(), &project.id, base, main.as_ref().map(|v| v.n), &author) |
| 187 | } |
| 188 | }; |
| 189 | c.on_change = parent.map(|p| p.id); |
| 190 | app.db.put_change(&c)?; |
| 191 | let base = c.base_tree; |
| 192 | (c, base) |
| 193 | } |
| 194 | }; |
| 195 |
| 196 | std::fs::create_dir_all(&root)?; |
| 197 | let root = crate::sys::canonical(&root)?; |
| 198 | let workspace = Workspace { id: workspace_id, project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: only.clone() }; |
| 199 | let source = app.db.project_workspaces(&project.id)?.into_iter().find(|w| w.path.join(ws::DIR).is_dir() && w.path != root); |
| 200 | // Where the workspace's own files go: the folder, or a lazy one's backing (the mount shows it). |
| 201 | let home = if lazy { crate::lazy::backing(&workspace.id) } else { root.clone() }; |
| 202 | ws::write_id(&home, &workspace.id)?; |
| 203 | if lazy { |
| 204 | // Folders and sizes now; each file when it's first opened. |
| 205 | let mut index = crate::lazy::prepare(app, &project, &workspace.id, &tree)?; |
| 206 | index.save(&home)?; |
| 207 | } else { |
| 208 | // Copy unchanged files from the most recent workspace of this project. |
| 209 | let source_index = source.as_ref().map(|w| Index::load(&w.path)); |
| 210 | app.host(&project).fetch_tree(&app.store, &project, &tree, None)?; |
| 211 | let files = app.files(&tree)?; |
| 212 | let cow = match (&source, &source_index) { |
| 213 | (Some(w), Some(i)) => Some(CowSource { root: &w.path, index: i }), |
| 214 | _ => None, |
| 215 | }; |
| 216 | let mut index = ws::materialize(&root, &app.store, &Index::default(), &files, &only, &crate::seal::Seals::load(&app.db, &project.id)?.unreadable(), cow)?; |
| 217 | index.save(&root)?; |
| 218 | } |
| 219 | app.db.put_workspace(&workspace)?; |
| 220 | let mut copied = Vec::new(); |
| 221 | if let Some(w) = &source { |
| 222 | for folder in ws::config(if lazy { &w.path } else { &root }).workspace.copy { |
| 223 | let folder = folder.trim_matches('/'); |
| 224 | if folder.is_empty() || folder.contains("..") { |
| 225 | continue; |
| 226 | } |
| 227 | let n = ws::copy_folder(&w.path.join(folder), &home.join(folder))?; |
| 228 | if n > 0 { |
| 229 | copied.push(format!("{folder} from {} ({n} files)", w.path.display())); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | if lazy { |
| 234 | crate::lazy::mount(&workspace)?; |
| 235 | } |
| 236 | let _ = crate::remote::pull_mine(app, &project); |
| 237 | let mine = app.place_mine(&project, &root)?; |
| 238 | // One save now: it records the tree in the index and reads every new |
| 239 | // folder once, so the first command after this one is quick. |
| 240 | let mut fresh = app.session_at(&root)?; |
| 241 | app.save(&mut fresh)?; |
| 242 |
| 243 | let mut r = Report::new(); |
| 244 | r.line("workspace", format!("{} ({})", root.display(), project.address)); |
| 245 | if lazy { |
| 246 | r.line("lazy", "every file is there; each comes from the host the first time it's opened"); |
| 247 | } |
| 248 | if let Some(from) = &took_from { |
| 249 | r.line("took over", format!("from {from}")); |
| 250 | } |
| 251 | let state = if change.is_empty() { "new, empty".to_string() } else { format!("{} saves", change.saves) }; |
| 252 | r.line("change", format!("{} {}, on {}", app.short(&project, &change.id), state, base_text(app, &project, &change))); |
| 253 | if !only.is_empty() { |
| 254 | r.line("only", only.join(", ")); |
| 255 | } |
| 256 | for c in &copied { |
| 257 | r.line("copied", c.clone()); |
| 258 | } |
| 259 | if mine > 0 { |
| 260 | r.line("yours", format!("{mine} private files (like .env) placed")); |
| 261 | } |
| 262 | r.set("workspace", root.display().to_string()) |
| 263 | .set("project", project.address.clone()) |
| 264 | .set("main", main.as_ref().map(|v| v.n)) |
| 265 | .set("change", change_json(app, &project, &change)) |
| 266 | .next("edit files, then vcs land -m \"what you did\""); |
| 267 | Ok(r) |
| 268 | } |
| 269 |
| 270 | /// A new change on a release line's latest version. |
| 271 | fn on_line(app: &App, project: &Project, name: &str, author: &str) -> Result<Change, Fail> { |
| 272 | let (l, tree) = crate::lines::head(app, project, name)?; |
| 273 | let mut c = Change::new(ids::new_change_id(), &project.id, tree, Some(l.head), author); |
| 274 | c.line = Some(l.name); |
| 275 | Ok(c) |
| 276 | } |
| 277 |
| 278 | /// A project by address: a hosted `host/owner/name`, or a local folder. |
| 279 | fn resolve_project(app: &App, target: &str) -> Result<Project, Fail> { |
| 280 | let path = app.cwd.join(target); |
| 281 | if target.starts_with('/') || target.starts_with('.') || target.starts_with('~') || path.join(ws::DIR).is_dir() { |
| 282 | let root = ws::find(&path).ok_or_else(|| { |
| 283 | Fail::new("not_found", format!("{target} isn't a vcs workspace")).state("nothing changed").next("vcs init <folder> to start a project there") |
| 284 | })?; |
| 285 | let id = ws::read_id(&root)?; |
| 286 | let w = app.db.workspace(&id)?.ok_or_else(|| Fail::new("not_found", "that workspace isn't known on this machine"))?; |
| 287 | return app.db.project(&w.project)?.ok_or_else(|| Fail::new("not_found", "that workspace's project is missing")); |
| 288 | } |
| 289 | crate::remote::project(app, target) |
| 290 | } |
| 291 |
| 292 | /// Makes `workspace` the one holding `change`: on the host (the other |
| 293 | /// workspace finds out on its next save) and on this machine. |
| 294 | fn take_over(app: &App, project: &Project, change: &mut Change, workspace: &str, path: &Path) -> Result<Option<String>, Fail> { |
| 295 | let mut previous = None; |
| 296 | if project.hosted() { |
| 297 | let remote = crate::remote::Remote::for_project(project); |
| 298 | remote.fetch_saves(&app.db, &app.store, project, change)?; |
| 299 | previous = remote.hold(&change.id, workspace, &crate::remote::label(path))?; |
| 300 | *change = app.change(&change.id)?; |
| 301 | } |
| 302 | if let Some(holder) = app.db.workspace_holding(&change.id)? |
| 303 | && holder.id != workspace |
| 304 | { |
| 305 | previous = Some(holder.path.display().to_string()); |
| 306 | release(app, project, holder)?; |
| 307 | } |
| 308 | Ok(previous) |
| 309 | } |
| 310 |
| 311 | // See. |
| 312 |
| 313 | pub fn status(app: &App, which: Option<String>) -> Out { |
| 314 | let mut s = app.session()?; |
| 315 | let current = app.save(&mut s)?; |
| 316 | let named = which.is_some(); |
| 317 | let mut c = match which { |
| 318 | Some(text) => app.find_change(&s.project, &text)?, |
| 319 | None => current, |
| 320 | }; |
| 321 | let asked = c.id.clone(); |
| 322 | c = settle_review(app, &mut s, c)?; |
| 323 | // A named change that landed meanwhile moved the workspace on; show the named one. |
| 324 | if named && c.id != asked { |
| 325 | c = app.change(&asked)?; |
| 326 | } |
| 327 | let review = if c.state == "open" { app.db.review(&c.id)? } else { None }; |
| 328 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; |
| 329 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; |
| 330 | let main = app.main(&s.project)?; |
| 331 | let mut r = Report::new(); |
| 332 | r.line("project", s.project.address.clone()).line("workspace", s.root.display().to_string()); |
| 333 | let who = if c.author == app.author(&s.project) { "yours".to_string() } else { c.author.clone() }; |
| 334 | let title = if c.title.is_empty() { "(no description yet)".to_string() } else { format!("\"{}\"", c.title) }; |
| 335 | r.line("change", format!("{} {} {}, {}", app.short(&s.project, &c.id), title, c.state, who)); |
| 336 | match c.state.as_str() { |
| 337 | "landed" => { |
| 338 | let n = c.version.map(|v| v.to_string()).unwrap_or("?".into()); |
| 339 | r.line("landed", match &c.line { |
| 340 | Some(line) => format!("as {line}/{n}"), |
| 341 | None => format!("as main {n}"), |
| 342 | }); |
| 343 | } |
| 344 | "waiting" => { |
| 345 | r.line("waiting", "for someone with landing rights to land it"); |
| 346 | } |
| 347 | _ => { |
| 348 | let behind = match (c.base_version, &main) { |
| 349 | (Some(b), Some(m)) if m.n > b && c.on_change.is_none() && c.line.is_none() => format!(" (main is at {}; land merges the difference)", m.n), |
| 350 | _ => String::new(), |
| 351 | }; |
| 352 | r.line("based on", format!("{}{behind}", base_text(app, &s.project, &c))); |
| 353 | } |
| 354 | } |
| 355 | if let Some(link) = &review { |
| 356 | r.line("review", format!("change request {link}; it lands when its approvals and checks pass")); |
| 357 | r.set("review", link.clone()); |
| 358 | } |
| 359 | if c.saves > 0 { |
| 360 | let last = app.db.save(&c.id, c.saves)?.map(|sv| sv.at).unwrap_or(c.updated); |
| 361 | r.line("saved", format!("{} (save {})", ids::ago(last), c.saves)); |
| 362 | } |
| 363 | let changes = tree::diff_trees(&app.store, &c.base_tree, &c.tree())?; |
| 364 | let moved = vcs_core::rename::renames(&app.store, &changes)?; |
| 365 | let mut list = Vec::new(); |
| 366 | for (from, to) in &moved { |
| 367 | list.push(format!("R {from} -> {to}")); |
| 368 | } |
| 369 | for (path, change) in &changes { |
| 370 | if moved.iter().any(|(from, to)| from == path || to == path) { |
| 371 | continue; |
| 372 | } |
| 373 | let mark = match change { |
| 374 | tree::Change::Added(_) => "A", |
| 375 | tree::Change::Removed(_) => "D", |
| 376 | tree::Change::Modified(..) => "M", |
| 377 | }; |
| 378 | list.push(format!("{mark} {path}")); |
| 379 | } |
| 380 | if list.is_empty() { |
| 381 | r.line("files", "no changes yet"); |
| 382 | } else { |
| 383 | let shown: Vec<String> = list.iter().take(50).cloned().collect(); |
| 384 | let more = if list.len() > 50 { format!("\n… and {} more", list.len() - 50) } else { String::new() }; |
| 385 | r.line("files", format!("{}{more}", shown.join("\n"))); |
| 386 | } |
| 387 | if !c.conflicts.is_empty() { |
| 388 | r.line("conflicts", c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join("\n")); |
| 389 | } |
| 390 | r.set("project", s.project.address.clone()) |
| 391 | .set("workspace", s.root.display().to_string()) |
| 392 | .set("change", change_json(app, &s.project, &c)) |
| 393 | .set("main", main.as_ref().map(|v| v.n)) |
| 394 | .set("files", list.clone()); |
| 395 | if c.state == "open" { |
| 396 | if !c.conflicts.is_empty() { |
| 397 | r.next(format!("fix the marked lines in {}, then vcs land", c.conflicts[0].path)); |
| 398 | } else if list.is_empty() { |
| 399 | r.next("edit files, then vcs land -m \"what you did\""); |
| 400 | } else if c.title.is_empty() { |
| 401 | r.next("vcs land -m \"what you did\""); |
| 402 | } else { |
| 403 | r.next("vcs land"); |
| 404 | } |
| 405 | } |
| 406 | Ok(r) |
| 407 | } |
| 408 |
| 409 | /// Resolves a reference: a version number, `main`, a change, or change:save. |
| 410 | fn resolve_tree(app: &App, project: &Project, text: &str) -> Result<(Id, String), Fail> { |
| 411 | if text == "main" { |
| 412 | let v = app.refresh(project)?.ok_or_else(|| Fail::new("not_found", "main has no versions yet"))?; |
| 413 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 414 | return Ok((v.tree, format!("main {}", v.n))); |
| 415 | } |
| 416 | if let Some(n) = text.parse::<u64>().ok().or(crate::tags::find(app, project, text)?) { |
| 417 | let v = version(app, project, n)?; |
| 418 | app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; |
| 419 | return Ok((v.tree, format!("main {n}"))); |
| 420 | } |
| 421 | if let Some((id, save)) = text.split_once(':') { |
| 422 | let c = app.find_change(project, id)?; |
| 423 | let n: i64 = save.parse().map_err(|_| Fail::new("bad_usage", format!("{text}: save numbers are whole numbers")))?; |
| 424 | let sv = app.db.save(&c.id, n)?.ok_or_else(|| Fail::new("not_found", format!("change {} has no save {n}", c.id)))?; |
| 425 | return Ok((sv.tree, format!("save {n} of {}", app.short(project, &c.id)))); |
| 426 | } |
| 427 | match app.find_change(project, text) { |
| 428 | Ok(c) => Ok((c.tree(), format!("change {}", app.short(project, &c.id)))), |
| 429 | // A release line ("1.x", its latest version) or one of its versions ("1.x/3"). |
| 430 | Err(f) => crate::lines::tree_at(app, project, text)?.ok_or(f), |
| 431 | } |
| 432 | } |
| 433 |
| 434 | fn version(app: &App, project: &Project, n: u64) -> Result<Version, Fail> { |
| 435 | app.version(project, n)?.ok_or_else(|| Fail::new("not_found", format!("main has no version {n}")).state("nothing changed")) |
| 436 | } |
| 437 |
| 438 | pub fn diff_cmd(app: &App, paths: Vec<String>, change: Option<String>, from: Option<String>, to: Option<String>, stat: bool) -> Out { |
| 439 | let mut s = app.session()?; |
| 440 | let current = app.save(&mut s)?; |
| 441 | let c = match change { |
| 442 | Some(t) => app.find_change(&s.project, &t)?, |
| 443 | None => current, |
| 444 | }; |
| 445 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; |
| 446 | app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; |
| 447 | let (a, a_label) = match &from { |
| 448 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 449 | None => (c.base_tree, "base".to_string()), |
| 450 | }; |
| 451 | let (b, b_label) = match &to { |
| 452 | Some(t) => resolve_tree(app, &s.project, t)?, |
| 453 | None => (c.tree(), "change".to_string()), |
| 454 | }; |
| 455 | let paths: Vec<String> = paths.into_iter().map(|p| p.trim_matches('/').to_string()).collect(); |
| 456 | let mut text = String::new(); |
| 457 | let mut stats = Vec::new(); |
| 458 | let (mut adds, mut dels) = (0usize, 0usize); |
| 459 | for (path, ch) in tree::diff_trees(&app.store, &a, &b)? { |
| 460 | if !paths.is_empty() && !paths.iter().any(|p| p == "." || tree::under(&path, p)) { |
| 461 | continue; |
| 462 | } |
| 463 | let (old, new) = match ch { |
| 464 | tree::Change::Added(e) => (None, Some(e)), |
| 465 | tree::Change::Removed(e) => (Some(e), None), |
| 466 | tree::Change::Modified(o, n) => (Some(o), Some(n)), |
| 467 | }; |
| 468 | let read = |e: Option<tree::Entry>| -> Result<Vec<u8>, Fail> { |
| 469 | match e { |
| 470 | Some(e) => Ok(app.store.read_file(&e.id)?), |
| 471 | None => Ok(Vec::new()), |
| 472 | } |
| 473 | }; |
| 474 | let (ob, nb) = (read(old)?, read(new)?); |
| 475 | if diff::is_binary(&ob) || diff::is_binary(&nb) { |
| 476 | text.push_str(&format!("Binary file {path} changed\n")); |
| 477 | stats.push(json!({ "path": path, "binary": true })); |
| 478 | continue; |
| 479 | } |
| 480 | let (added, removed) = diff::counts(&ob, &nb); |
| 481 | adds += added; |
| 482 | dels += removed; |
| 483 | stats.push(json!({ "path": path, "added": added, "removed": removed })); |
| 484 | if !stat { |
| 485 | 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() })); |
| 486 | if old.is_some() && new.is_some() && old.unwrap().kind != new.unwrap().kind { |
| 487 | text.push_str(&format!("kind {} → {}\n", old.unwrap().kind.name(), new.unwrap().kind.name())); |
| 488 | } |
| 489 | text.push_str(&diff::unified(&ob, &nb, 3)); |
| 490 | } else { |
| 491 | text.push_str(&format!("{path} | +{added} -{removed}\n")); |
| 492 | } |
| 493 | } |
| 494 | let mut r = Report::new(); |
| 495 | if text.is_empty() { |
| 496 | r.line("diff", format!("no differences between {a_label} and {b_label}")); |
| 497 | } else { |
| 498 | r.raw(text); |
| 499 | if stat { |
| 500 | r.raw(format!("{} files, +{adds} -{dels}\n", stats.len())); |
| 501 | } |
| 502 | } |
| 503 | r.set("from", a_label).set("to", b_label).set("files", stats).set("added", adds).set("removed", dels); |
| 504 | Ok(r) |
| 505 | } |
| 506 |
| 507 | pub fn log(app: &App, what: Option<String>, changes: bool, saves: bool, ops: bool, limit: i64) -> Out { |
| 508 | let mut s = app.session()?; |
| 509 | let current = app.save(&mut s)?; |
| 510 | let mut r = Report::new(); |
| 511 | if changes { |
| 512 | let list = crate::remote::visible_changes(app, &s.project)?; |
| 513 | let mut rows = Vec::new(); |
| 514 | for c in &list { |
| 515 | if c.state != "open" && c.state != "waiting" { |
| 516 | continue; |
| 517 | } |
| 518 | if c.is_empty() && c.id != current.id { |
| 519 | continue; |
| 520 | } |
| 521 | let held = app.db.workspace_holding(&c.id)?.map(|w| w.path.display().to_string()).unwrap_or_else(|| "no workspace here".into()); |
| 522 | let title = if c.title.is_empty() { "(no description)".to_string() } else { c.title.clone() }; |
| 523 | let here = if c.id == current.id { " ← this workspace" } else { "" }; |
| 524 | r.raw(format!("{} {:<8} {} {} [{}]{here}\n", app.short(&s.project, &c.id), c.state, title, c.author, held)); |
| 525 | rows.push(json!({ "change": change_json(app, &s.project, c), "workspace": held })); |
| 526 | } |
| 527 | if rows.is_empty() { |
| 528 | r.line("changes", "no open changes"); |
| 529 | } |
| 530 | r.set("changes", rows); |
| 531 | return Ok(r); |
| 532 | } |
| 533 | if saves { |
| 534 | let list = app.db.saves(¤t.id)?; |
| 535 | for sv in &list { |
| 536 | r.raw(format!("{}:{} {} ({})\n", app.short(&s.project, ¤t.id), sv.n, ids::clock(sv.at), ids::ago(sv.at))); |
| 537 | } |
| 538 | if list.is_empty() { |
| 539 | r.line("saves", "nothing saved yet in this change"); |
| 540 | } |
| 541 | r.set("saves", list.iter().map(|sv| json!({ "n": sv.n, "at": sv.at, "tree": sv.tree })).collect::<Vec<_>>()); |
| 542 | return Ok(r); |
| 543 | } |
| 544 | if ops { |
| 545 | let list = app.db.ops(&s.ws.id, limit)?; |
| 546 | for (op, undone) in &list { |
| 547 | r.raw(format!("{} {:<9} {}{}\n", ids::clock(op.at), op.kind, op_summary(op), if *undone { " (undone)" } else { "" })); |
| 548 | } |
| 549 | if list.is_empty() { |
| 550 | r.line("operations", "none yet in this workspace"); |
| 551 | } |
| 552 | r.set("ops", list.iter().map(|(op, undone)| json!({ "kind": op.kind, "at": op.at, "undone": undone, "data": op.data })).collect::<Vec<_>>()); |
| 553 | return Ok(r); |
| 554 | } |
| 555 | if let Some(what) = what { |
| 556 | if let Some(n) = what.parse::<u64>().ok().or(crate::tags::find(app, &s.project, &what)?) { |
| 557 | let v = version(app, &s.project, n)?; |
| 558 | let prev_tree = match n { |
| 559 | 1 => tree::empty_id(), |
| 560 | _ => version(app, &s.project, n - 1)?.tree, |
| 561 | }; |
| 562 | app.host(&s.project).fetch_tree(&app.store, &s.project, &v.tree, None)?; |
| 563 | app.host(&s.project).fetch_tree(&app.store, &s.project, &prev_tree, None)?; |
| 564 | let changed = tree::diff_trees(&app.store, &prev_tree, &v.tree)?; |
| 565 | r.line("version", format!("main {}", v.n)) |
| 566 | .line("title", v.title.clone()) |
| 567 | .line("author", v.author.clone()) |
| 568 | .line("landed", format!("{} ({})", ids::clock(v.time), ids::ago(v.time))); |
| 569 | if !v.change.is_empty() { |
| 570 | r.line("change", v.change.clone()); |
| 571 | } |
| 572 | if !v.body.is_empty() { |
| 573 | r.line("about", v.body.clone()); |
| 574 | } |
| 575 | if let Some(g) = &v.git { |
| 576 | r.line("git", g.clone()); |
| 577 | } |
| 578 | r.line("files", changed.keys().take(50).cloned().collect::<Vec<_>>().join("\n")); |
| 579 | r.set("version", serde_json::to_value(&v).unwrap_or_default()).set("files", changed.keys().cloned().collect::<Vec<_>>()); |
| 580 | return Ok(r); |
| 581 | } |
| 582 | if crate::history::is_path(&app.cwd, &what) { |
| 583 | let path = crate::history::workspace_path(app, &s.root, &what); |
| 584 | return crate::history::log_path(app, &s.project, &path, limit.max(1) as usize); |
| 585 | } |
| 586 | let c = app.find_change(&s.project, &what)?; |
| 587 | r.line("change", app.short(&s.project, &c.id)) |
| 588 | .line("title", if c.title.is_empty() { "(no description)".into() } else { c.title.clone() }) |
| 589 | .line("state", c.state.clone()) |
| 590 | .line("author", c.author.clone()) |
| 591 | .line("saves", c.saves.to_string()); |
| 592 | if let Some(v) = c.version { |
| 593 | r.line("landed", format!("as main {v}")); |
| 594 | } |
| 595 | r.set("change", change_json(app, &s.project, &c)); |
| 596 | return Ok(r); |
| 597 | } |
| 598 | app.refresh(&s.project)?; |
| 599 | let mut list = app.db.versions(&s.project.id, limit)?; |
| 600 | let start = app.db.history_from(&s.project.id)?; |
| 601 | if (list.len() as i64) < limit && start > 1 { |
| 602 | // Older than this machine keeps: fetch them now. |
| 603 | app.history(&s.project, start.saturating_sub((limit - list.len() as i64) as u64))?; |
| 604 | list = app.db.versions(&s.project.id, limit)?; |
| 605 | } |
| 606 | for v in &list { |
| 607 | r.raw(format!("{:>6} {} {} {}\n", v.n, v.title, short_author(&v.author), ids::ago(v.time))); |
| 608 | } |
| 609 | if list.is_empty() { |
| 610 | r.line("main", "no versions yet"); |
| 611 | r.next("vcs land -m \"First version\""); |
| 612 | } |
| 613 | 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<_>>()); |
| 614 | Ok(r) |
| 615 | } |
| 616 |
| 617 | fn short_author(author: &str) -> String { |
| 618 | author.split(" <").next().unwrap_or(author).to_string() |
| 619 | } |
| 620 |
| 621 | fn op_summary(op: &crate::db::Op) -> String { |
| 622 | let d = &op.data; |
| 623 | let s = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 624 | match op.kind.as_str() { |
| 625 | "land" => format!("change {} as main {}", s("change"), d.get("version").and_then(|v| v.as_u64()).unwrap_or(0)), |
| 626 | "sync" => format!("change {} onto {}", s("change"), s("onto")), |
| 627 | "new" | "switch" => format!("from {} to {}", s("from"), s("to")), |
| 628 | "drop" => format!("change {}", s("change")), |
| 629 | "describe" => format!("change {}", s("change")), |
| 630 | "restore" => format!("{} from {}", s("paths"), s("source")), |
| 631 | "access" => format!("{} → {}", s("target"), s("who")), |
| 632 | "undo" => s("what"), |
| 633 | _ => String::new(), |
| 634 | } |
| 635 | } |
| 636 |
| 637 | // Work. |
| 638 |
| 639 | pub fn new(app: &App, title: Option<String>, on: Option<String>, line: Option<String>) -> Out { |
| 640 | if line.is_some() && on.is_some() { |
| 641 | return Err(Fail::new("bad_usage", "--line starts on that line's latest version; it doesn't go with --on").state("nothing changed")); |
| 642 | } |
| 643 | let mut s = app.session()?; |
| 644 | let current = app.save(&mut s)?; |
| 645 | let author = app.author(&s.project); |
| 646 | let mut c = match &on { |
| 647 | None if line.is_some() => on_line(app, &s.project, line.as_deref().unwrap_or_default(), &author)?, |
| 648 | Some(text) => { |
| 649 | let parent = app.find_change(&s.project, text)?; |
| 650 | if parent.state == "landed" || parent.state == "dropped" { |
| 651 | return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)) |
| 652 | .state("nothing changed") |
| 653 | .next("vcs new")); |
| 654 | } |
| 655 | if s.project.hosted() { |
| 656 | crate::remote::Remote::for_project(&s.project).fetch_saves(&app.db, &app.store, &s.project, &parent)?; |
| 657 | } |
| 658 | let mut c = Change::new(ids::new_change_id(), &s.project.id, parent.tree(), None, &author); |
| 659 | c.on_change = Some(parent.id.clone()); |
| 660 | c.line = parent.line.clone(); |
| 661 | c |
| 662 | } |
| 663 | None => { |
| 664 | let main = app.refresh(&s.project)?; |
| 665 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 666 | Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &author) |
| 667 | } |
| 668 | }; |
| 669 | if let Some(t) = title { |
| 670 | set_description(&mut c, &[t]); |
| 671 | } |
| 672 | app.db.put_change(&c)?; |
| 673 | app.show_tree(&s, &c.base_tree)?; |
| 674 | app.put_workspace_change(&mut s, &c.id)?; |
| 675 | app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": c.id }))?; |
| 676 | let mut r = Report::new(); |
| 677 | r.line("change", format!("{} new, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 678 | let kept = if current.is_empty() { "(it was empty)".to_string() } else { "is saved; vcs switch goes back to it".to_string() }; |
| 679 | r.line("kept", format!("{} {kept}", app.short(&s.project, ¤t.id))); |
| 680 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 681 | r.next("edit files, then vcs land"); |
| 682 | Ok(r) |
| 683 | } |
| 684 |
| 685 | fn set_description(c: &mut Change, parts: &[String]) { |
| 686 | let text = parts.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect::<Vec<_>>().join("\n\n"); |
| 687 | let mut lines = text.splitn(2, '\n'); |
| 688 | c.title = lines.next().unwrap_or("").trim().to_string(); |
| 689 | c.body = lines.next().unwrap_or("").trim().to_string(); |
| 690 | } |
| 691 |
| 692 | pub fn describe(app: &App, parts: Vec<String>) -> Out { |
| 693 | let mut s = app.session()?; |
| 694 | let mut c = app.save(&mut s)?; |
| 695 | if parts.iter().all(|p| p.trim().is_empty()) { |
| 696 | return Err(Fail::new("bad_usage", "give a description").state("nothing changed").next("vcs describe \"Title\" \"More detail\"")); |
| 697 | } |
| 698 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 699 | set_description(&mut c, &parts); |
| 700 | app.db.put_change(&c)?; |
| 701 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 702 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 703 | let mut r = Report::new(); |
| 704 | r.line("change", format!("{} \"{}\"", app.short(&s.project, &c.id), c.title)).set("change", change_json(app, &s.project, &c)); |
| 705 | r.next("vcs land"); |
| 706 | Ok(r) |
| 707 | } |
| 708 |
| 709 | pub fn switch(app: &App, target: &str) -> Out { |
| 710 | let mut s = app.session()?; |
| 711 | let current = app.save(&mut s)?; |
| 712 | let mut c = app.find_change(&s.project, target)?; |
| 713 | if c.id == current.id { |
| 714 | let mut r = Report::new(); |
| 715 | r.line("change", format!("{} is already this workspace's change", app.short(&s.project, &c.id))); |
| 716 | return Ok(r); |
| 717 | } |
| 718 | if c.state == "landed" || c.state == "dropped" { |
| 719 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)) |
| 720 | .state("nothing changed") |
| 721 | .next(if c.state == "dropped" { "vcs undo (if you just dropped it)" } else { "vcs new" })); |
| 722 | } |
| 723 | let took_from = take_over(app, &s.project, &mut c, &s.ws.id.clone(), &s.root.clone())?; |
| 724 | if let Some(from) = &took_from { |
| 725 | app.notes.borrow_mut().push(format!("took change {} over from {from}", c.id)); |
| 726 | } |
| 727 | app.show_tree(&s, &c.tree())?; |
| 728 | app.put_workspace_change(&mut s, &c.id)?; |
| 729 | app.db.add_op(&s.ws.id, "switch", &json!({ "from": current.id, "to": c.id }))?; |
| 730 | let mut r = Report::new(); |
| 731 | let title = if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) }; |
| 732 | r.line("change", format!("{}{title}, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 733 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 734 | r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); |
| 735 | r.next("keep working, then vcs land"); |
| 736 | Ok(r) |
| 737 | } |
| 738 |
| 739 | /// Moves another workspace on this machine off a change someone took over: |
| 740 | /// it gets a fresh change on the same base, so its next save can't touch the |
| 741 | /// taken change. |
| 742 | fn release(app: &App, project: &Project, mut holder: Workspace) -> Result<(), Fail> { |
| 743 | let taken = app.change(&holder.change)?; |
| 744 | let mut fresh = Change::new(ids::new_change_id(), &project.id, taken.tree(), None, &taken.author); |
| 745 | fresh.title = format!("Rescued from {}", taken.id); |
| 746 | fresh.after_change = Some(taken.id.clone()); |
| 747 | app.db.put_change(&fresh)?; |
| 748 | holder.change = fresh.id; |
| 749 | app.db.put_workspace(&holder)?; |
| 750 | Ok(()) |
| 751 | } |
| 752 |
| 753 | pub fn drop(app: &App, target: Option<String>) -> Out { |
| 754 | let mut s = app.session()?; |
| 755 | let current = app.save(&mut s)?; |
| 756 | let mut c = match target { |
| 757 | Some(t) => app.find_change(&s.project, &t)?, |
| 758 | None => current.clone(), |
| 759 | }; |
| 760 | if c.state == "landed" { |
| 761 | return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))) |
| 762 | .state("nothing changed") |
| 763 | .next(format!("vcs undo {}", c.version.unwrap_or(0)))); |
| 764 | } |
| 765 | c.state = "dropped".into(); |
| 766 | app.db.put_change(&c)?; |
| 767 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 768 | let mut r = Report::new(); |
| 769 | let mut data = json!({ "change": c.id, "current": c.id == current.id }); |
| 770 | r.line("dropped", format!("{}{}", app.short(&s.project, &c.id), if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) })); |
| 771 | if c.id == current.id { |
| 772 | let main = app.refresh(&s.project)?; |
| 773 | let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 774 | let fresh = Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &app.author(&s.project)); |
| 775 | app.db.put_change(&fresh)?; |
| 776 | app.show_tree(&s, &base)?; |
| 777 | app.put_workspace_change(&mut s, &fresh.id)?; |
| 778 | data["replacement"] = json!(fresh.id); |
| 779 | r.line("change", format!("{} new, on {}", app.short(&s.project, &fresh.id), main_label(main.map(|v| v.n)))); |
| 780 | } |
| 781 | app.db.add_op(&s.ws.id, "drop", &data)?; |
| 782 | r.set("dropped", c.id.clone()); |
| 783 | r.next("vcs undo brings it back"); |
| 784 | Ok(r) |
| 785 | } |
| 786 |
| 787 | // Finish. |
| 788 |
| 789 | pub fn sync(app: &App) -> Out { |
| 790 | let mut s = app.session()?; |
| 791 | let saved = app.save(&mut s)?; |
| 792 | let mut c = settle_review(app, &mut s, saved)?; |
| 793 | if c.state != "open" { |
| 794 | return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); |
| 795 | } |
| 796 | // Onto the change it's stacked on while that hasn't landed, else main. |
| 797 | let parent = match &c.on_change { |
| 798 | // A scheduled change lands on the host on its own: ask whether it has. |
| 799 | Some(p) => Some(match app.change(p)? { |
| 800 | pc if pc.state == "scheduled" && s.project.hosted() => crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, &pc.id)?.unwrap_or(pc), |
| 801 | pc => pc, |
| 802 | }), |
| 803 | None => None, |
| 804 | }; |
| 805 | let (target_tree, target_version, label, still_on) = match parent.as_ref().filter(|p| p.state == "open" || p.state == "waiting" || p.state == "scheduled") { |
| 806 | Some(p) => (p.tree(), None, format!("change {}", app.short(&s.project, &p.id)), Some(p.id.clone())), |
| 807 | None if c.line.is_some() => { |
| 808 | let (l, t) = crate::lines::head(app, &s.project, c.line.as_deref().unwrap_or_default())?; |
| 809 | (t, Some(l.head), format!("{}/{}", l.name, l.head), None) |
| 810 | } |
| 811 | None => { |
| 812 | let main = app.refresh(&s.project)?; |
| 813 | let t = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); |
| 814 | app.host(&s.project).fetch_tree(&app.store, &s.project, &t, Some(&c.base_tree))?; |
| 815 | (t, main.as_ref().map(|v| v.n), main_label(main.as_ref().map(|v| v.n)), None) |
| 816 | } |
| 817 | }; |
| 818 | if target_tree == c.base_tree { |
| 819 | let mut r = Report::new(); |
| 820 | r.line("synced", format!("{} is already on {label}", app.short(&s.project, &c.id))).set("change", change_json(app, &s.project, &c)); |
| 821 | r.next("vcs land"); |
| 822 | return Ok(r); |
| 823 | } |
| 824 | let ours_label = label.clone(); |
| 825 | let theirs_label = format!("your change {}", app.short(&s.project, &c.id)); |
| 826 | let mut m = merge::trees(&app.store, Some(&c.base_tree), &target_tree, &c.tree(), Mode::Sync, (&ours_label, &theirs_label))?; |
| 827 | for o in m.objects.objects.values() { |
| 828 | app.store.put(o)?; |
| 829 | } |
| 830 | // Sealed files the host couldn't merge are merged here. |
| 831 | crate::seal::merge_sealed(&app.store, &crate::seal::Seals::load(&app.db, &s.project.id)?, Some(&c.base_tree), &target_tree, &c.tree(), &mut m, (&ours_label, &theirs_label))?; |
| 832 | let before = json!({ |
| 833 | "change": c.id, "onto": label, |
| 834 | "base_tree": c.base_tree, "base_version": c.base_version, "on_change": c.on_change, |
| 835 | "after_change": c.after_change, "head_tree": c.head_tree, "conflicts": c.conflicts, |
| 836 | }); |
| 837 | let was = base_text(app, &s.project, &c); |
| 838 | c.base_tree = target_tree; |
| 839 | c.base_version = target_version; |
| 840 | c.on_change = still_on; |
| 841 | c.after_change = None; |
| 842 | c.head_tree = Some(m.tree); |
| 843 | c.saves += 1; |
| 844 | c.conflicts = m.conflicts.iter().map(|x| Conflict { path: x.path.clone(), version: target_version }).collect(); |
| 845 | 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)?; |
| 846 | app.db.put_change(&c)?; |
| 847 | app.show_tree(&s, &m.tree)?; |
| 848 | app.db.add_op(&s.ws.id, "sync", &before)?; |
| 849 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 850 | let mut r = Report::new(); |
| 851 | r.line("synced", format!("{} onto {label} (was {was})", app.short(&s.project, &c.id))); |
| 852 | for x in &m.conflicts { |
| 853 | r.line("conflict", x.path.clone()); |
| 854 | } |
| 855 | for n in &m.notes { |
| 856 | r.line("note", n.message.clone()); |
| 857 | } |
| 858 | r.set("change", change_json(app, &s.project, &c)) |
| 859 | .set("conflicts", m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>()) |
| 860 | .set("notes", m.notes.iter().map(|n| n.message.clone()).collect::<Vec<_>>()); |
| 861 | if m.conflicts.is_empty() { |
| 862 | r.next("vcs land"); |
| 863 | } else { |
| 864 | r.exit = 3; |
| 865 | r.next(format!("fix the marked lines in {}, then vcs land", m.conflicts.iter().map(|x| x.path.as_str()).collect::<Vec<_>>().join(", "))); |
| 866 | } |
| 867 | Ok(r) |
| 868 | } |
| 869 |
| 870 | /// Runs vcs.toml's `[land] run` commands in the workspace, in order, their |
| 871 | /// output on stderr; the first that fails stops the landing. |
| 872 | fn run_before_land(root: &Path) -> Result<(), Fail> { |
| 873 | for command in ws::config(root).land.run { |
| 874 | let mut shell = if cfg!(windows) { std::process::Command::new("cmd") } else { std::process::Command::new("sh") }; |
| 875 | shell.args(if cfg!(windows) { ["/C", command.as_str()] } else { ["-c", command.as_str()] }); |
| 876 | let status = shell |
| 877 | .current_dir(root) |
| 878 | .stdin(std::process::Stdio::null()) |
| 879 | .stdout(std::io::stderr()) |
| 880 | .status() |
| 881 | .map_err(|e| Fail::new("checks_failed", format!("couldn't run \"{command}\" from vcs.toml: {e}")).state("main didn't change; your change is saved"))?; |
| 882 | if !status.success() { |
| 883 | return Err(Fail::new("checks_failed", format!("\"{command}\" (vcs.toml [land] run) failed, so nothing landed")) |
| 884 | .state("main didn't change; your change is saved") |
| 885 | .next("fix what it found, then vcs land (vcs land --no-run lands without running it)")); |
| 886 | } |
| 887 | } |
| 888 | Ok(()) |
| 889 | } |
| 890 |
| 891 | #[allow(clippy::too_many_arguments)] |
| 892 | pub fn land(app: &App, target: Option<String>, messages: Vec<String>, allow_secrets: bool, run: bool, at: Option<String>, with: Vec<PathBuf>, to: Option<String>) -> Out { |
| 893 | let mut s = app.session()?; |
| 894 | if to.is_some() && (at.is_some() || !with.is_empty()) { |
| 895 | return Err(Fail::new("bad_usage", "--to brings one change over to a release line now; it doesn't go with --at or --with").state("nothing changed")); |
| 896 | } |
| 897 | let at = match at.as_deref() { |
| 898 | None => None, |
| 899 | Some(words) => { |
| 900 | let t = ids::parse_future(words) |
| 901 | .ok_or_else(|| Fail::new("bad_usage", format!("can't read --at {words:?}; try \"fri 9:00\", \"in 2h\" or \"2026-11-02 09:00\"")).state("nothing changed"))?; |
| 902 | if !s.project.hosted() { |
| 903 | return Err(Fail::new("bad_usage", "landing at a set time needs a host, which lands it then").state("nothing changed").next("vcs publish <host/owner/name>")); |
| 904 | } |
| 905 | Some(t) |
| 906 | } |
| 907 | }; |
| 908 | if !with.is_empty() { |
| 909 | return land_together(app, &mut s, &with, messages, allow_secrets, run, at); |
| 910 | } |
| 911 | // Saved here only: the landing itself carries the change to the host. |
| 912 | let current = app.save_local(&mut s)?; |
| 913 | let current = settle_review(app, &mut s, current)?; |
| 914 | // This workspace's change and what it's stacked on are its own; a change |
| 915 | // named on the command line is someone else's unless it's the current one. |
| 916 | let own_stack = target.is_none(); |
| 917 | let mut c = match target { |
| 918 | Some(t) => { |
| 919 | let found = app.find_change(&s.project, &t)?; |
| 920 | // Someone else's change: take the host's newest state and content. |
| 921 | if s.project.hosted() && found.id != current.id { |
| 922 | crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, &found.id)?.unwrap_or(found) |
| 923 | } else { |
| 924 | found |
| 925 | } |
| 926 | } |
| 927 | None => current.clone(), |
| 928 | }; |
| 929 | // Another line's change (or main's, landed or not) brought over to a line. |
| 930 | if let Some(name) = to.as_deref().filter(|name| c.line.as_deref() != Some(*name)) { |
| 931 | return bring_over(app, &mut s, &c, name, &messages, allow_secrets); |
| 932 | } |
| 933 | if !messages.is_empty() { |
| 934 | let before = json!({ "change": c.id, "title": c.title, "body": c.body }); |
| 935 | set_description(&mut c, &messages); |
| 936 | app.db.put_change(&c)?; |
| 937 | app.db.add_op(&s.ws.id, "describe", &before)?; |
| 938 | } |
| 939 | if c.state == "landed" { |
| 940 | let what = match &c.line { |
| 941 | Some(line) => format!("{line}/{}", c.version.unwrap_or(0)), |
| 942 | None => format!("main {}", c.version.unwrap_or(0)), |
| 943 | }; |
| 944 | return Err(Fail::new("bad_usage", format!("change {} already landed as {what}", c.id)).state("nothing changed").next(format!("vcs land {} --to <line> brings it over to a release line", app.short(&s.project, &c.id)))); |
| 945 | } |
| 946 | if c.state == "dropped" { |
| 947 | return Err(Fail::new("bad_usage", format!("change {} was dropped", c.id)).state("nothing changed").next("vcs undo (if you just dropped it)")); |
| 948 | } |
| 949 | if c.is_empty() { |
| 950 | let mut f = Fail::new("empty_change", format!("change {} has nothing to land", app.short(&s.project, &c.id))).state("nothing changed"); |
| 951 | if c.after_change.is_some() { |
| 952 | f = f.next("you're on a fresh change after a landing; edit files first"); |
| 953 | } else { |
| 954 | f = f.next("edit files first"); |
| 955 | } |
| 956 | return Err(f); |
| 957 | } |
| 958 | if !c.conflicts.is_empty() { |
| 959 | return Err(Fail::new("conflict", format!("change {} still has conflict markers", app.short(&s.project, &c.id))) |
| 960 | .detail(c.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 961 | .state("main didn't change; your change is saved") |
| 962 | .next("fix the marked lines, then vcs land")); |
| 963 | } |
| 964 | require_title(&c)?; |
| 965 | // The workspace's files are this change's: its own checks run on them. |
| 966 | if run && own_stack { |
| 967 | run_before_land(&s.root)?; |
| 968 | } |
| 969 | // The agent's session, kept with the change it lands (only its owner sees it). |
| 970 | let kept = if own_stack { crate::sessions::keep_for(app, &s, &c) } else { None }; |
| 971 |
| 972 | // Land what it's stacked on first, in order. |
| 973 | let mut stack = vec![c.clone()]; |
| 974 | let mut parent = c.on_change.clone(); |
| 975 | while let Some(p) = parent { |
| 976 | let pc = app.change(&p)?; |
| 977 | if pc.state != "open" && pc.state != "waiting" { |
| 978 | break; |
| 979 | } |
| 980 | require_title(&pc)?; |
| 981 | parent = pc.on_change.clone(); |
| 982 | stack.push(pc); |
| 983 | } |
| 984 | stack.reverse(); |
| 985 |
| 986 | let mut r = Report::new(); |
| 987 | if let Some(line) = kept { |
| 988 | r.line("session", line); |
| 989 | } |
| 990 | let mut landed_versions = Vec::new(); |
| 991 | let mut on_line = Vec::new(); |
| 992 | for (i, item) in stack.iter().enumerate() { |
| 993 | let mut item = app.change(&item.id)?; |
| 994 | let host = app.host(&s.project); |
| 995 | host.fetch_tree(&app.store, &s.project, &item.base_tree, None)?; |
| 996 | host.fetch_tree(&app.store, &s.project, &item.tree(), Some(&item.base_tree))?; |
| 997 | if !allow_secrets { |
| 998 | let found = secrets::scan(&app.store, &item.base_tree, &item.tree())?; |
| 999 | if let Some(hit) = found.first() { |
| 1000 | 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)) |
| 1001 | .detail(format!("{}:{}", hit.path, hit.line)) |
| 1002 | .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()) }) |
| 1003 | .next(format!("remove it from {} (put real secrets in .env, which stays yours), then vcs land", hit.path)) |
| 1004 | .set("secrets", serde_json::to_value(&found).unwrap_or_default())); |
| 1005 | } |
| 1006 | } |
| 1007 | // A change of this workspace's goes up with its landing, in one call. |
| 1008 | let own = s.project.hosted() && (own_stack || item.id == current.id); |
| 1009 | let pending = if own { app.db.unuploaded_saves(&item.id)? } else { Vec::new() }; |
| 1010 | let request = LandRequest { |
| 1011 | change: item.id.clone(), |
| 1012 | base_tree: item.base_tree, |
| 1013 | tree: item.tree(), |
| 1014 | title: item.title.clone(), |
| 1015 | body: item.body.clone(), |
| 1016 | author: item.author.clone(), |
| 1017 | allow_secrets, |
| 1018 | at, |
| 1019 | signature: if s.project.hosted() { crate::host::LandSignature::for_land(&s.project.address, &item.id, &item.base_tree, &item.tree(), &item.title, &item.body, &item.author) } else { None }, |
| 1020 | line: item.line.clone(), |
| 1021 | record: own.then(|| crate::wire::PutChange { |
| 1022 | change: crate::remote::Remote::record(&item), |
| 1023 | workspace: s.ws.id.clone(), |
| 1024 | label: crate::remote::label(&s.root), |
| 1025 | 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() }), |
| 1026 | }), |
| 1027 | }; |
| 1028 | let outcome = match host.land(&app.db, &app.store, &s.project, &request) { |
| 1029 | Ok(o) => o, |
| 1030 | Err(e) => { |
| 1031 | let fail = Fail::from(e); |
| 1032 | if fail.code == "held_elsewhere" { |
| 1033 | // Another workspace took the change over: a normal save |
| 1034 | // moves this one's work to a new change. |
| 1035 | let rescued = app.save(&mut s)?; |
| 1036 | return Err(Fail::new("held_elsewhere", format!("{}; this workspace's work is in change {}", fail.message, app.short(&s.project, &rescued.id))) |
| 1037 | .state("main didn't change") |
| 1038 | .next("vcs land")); |
| 1039 | } |
| 1040 | return Err(fail); |
| 1041 | } |
| 1042 | }; |
| 1043 | for sv in &pending { |
| 1044 | app.db.mark_uploaded(&item.id, sv.n)?; |
| 1045 | } |
| 1046 | match outcome { |
| 1047 | Landed::Landed { version } => { |
| 1048 | item.state = "landed".into(); |
| 1049 | item.version = Some(version.n); |
| 1050 | app.db.put_change(&item)?; |
| 1051 | app.db.put_version(&s.project.id, &version)?; |
| 1052 | landed_versions.push((item.id.clone(), version.clone())); |
| 1053 | r.line("landed", format!("{} as main {} \"{}\"", app.short(&s.project, &item.id), version.n, version.title)); |
| 1054 | } |
| 1055 | Landed::Conflict { main, conflicts } => { |
| 1056 | let state = if landed_versions.is_empty() { |
| 1057 | "main didn't change; your change is saved".to_string() |
| 1058 | } else { |
| 1059 | 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(", ")) |
| 1060 | }; |
| 1061 | 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" })); |
| 1062 | for x in &conflicts { |
| 1063 | f = f.detail(format!("{}{}", x.path, if x.kind == "text" { String::new() } else { format!(" ({})", x.kind) })); |
| 1064 | } |
| 1065 | return Err(f.state(state).next("vcs sync, fix the conflicts in those files, then vcs land") |
| 1066 | .set("conflicts", serde_json::to_value(&conflicts).unwrap_or_default()) |
| 1067 | .set("main", main)); |
| 1068 | } |
| 1069 | Landed::Waiting { asked, reason } => { |
| 1070 | item.state = "waiting".into(); |
| 1071 | app.db.put_change(&item)?; |
| 1072 | r.line("waiting", format!("{} {reason}", app.short(&s.project, &item.id))); |
| 1073 | if !asked.is_empty() { |
| 1074 | r.line("asked", asked.join(", ")); |
| 1075 | } |
| 1076 | r.exit = 5; |
| 1077 | r.set("waiting", json!({ "change": item.id, "asked": asked })); |
| 1078 | r.next(format!("vcs status {} later", app.short(&s.project, &item.id))); |
| 1079 | // The workspace moves on, so later edits don't change what's waiting. |
| 1080 | if item.id == current.id { |
| 1081 | let fresh = continue_after(app, &mut s, &item)?; |
| 1082 | r.line("change", format!("{} new, on top of the waiting change", app.short(&s.project, &fresh.id))); |
| 1083 | } |
| 1084 | return Ok(r); |
| 1085 | } |
| 1086 | Landed::ChecksFailed { check, log } => { |
| 1087 | return Err(Fail::new("checks_failed", format!("can't land {}: check \"{check}\" failed on the merged result", app.short(&s.project, &item.id))) |
| 1088 | .detail(log.map(|l| format!("log: {l}")).unwrap_or_default()) |
| 1089 | .state("main didn't change; your change is saved") |
| 1090 | .next("fix it, then vcs land again")); |
| 1091 | } |
| 1092 | Landed::Review { number, url, blockers, at: when } => { |
| 1093 | // The workspace stays on the change: landing again after more |
| 1094 | // edits updates the same change request. |
| 1095 | app.db.set_review(&item.id, Some(&format!("#{number} {url}")))?; |
| 1096 | r.line("review", format!("{} is change request #{number}, {url}", app.short(&s.project, &item.id))); |
| 1097 | for b in &blockers { |
| 1098 | r.line("waiting on", b.clone()); |
| 1099 | } |
| 1100 | match when { |
| 1101 | Some(t) => r.line("lands", format!("at {} or after, once its approvals and checks pass", ids::clock(t))), |
| 1102 | None => r.line("lands", "when its approvals and checks pass (Upstream merges it, and it comes into main)"), |
| 1103 | }; |
| 1104 | r.exit = 5; |
| 1105 | r.set("review", json!({ "change": item.id, "number": number, "url": url, "blockers": blockers })); |
| 1106 | r.next("keep working; vcs land again updates it, and vcs status shows where it is"); |
| 1107 | return Ok(r); |
| 1108 | } |
| 1109 | Landed::Scheduled { at } => { |
| 1110 | item.state = "scheduled".into(); |
| 1111 | app.db.put_change(&item)?; |
| 1112 | r.line("scheduled", format!("{} lands at {}", app.short(&s.project, &item.id), ids::clock(at))); |
| 1113 | r.set("scheduled", json!({ "change": item.id, "at": at })); |
| 1114 | } |
| 1115 | Landed::OnLine { line, n, title } => { |
| 1116 | item.state = "landed".into(); |
| 1117 | item.version = Some(n); |
| 1118 | item.line = Some(line.clone()); |
| 1119 | app.db.put_change(&item)?; |
| 1120 | r.line("landed", format!("{} as {line}/{n} \"{title}\"", app.short(&s.project, &item.id))); |
| 1121 | on_line.push(json!({ "change": item.id, "line": line, "version": n, "title": title })); |
| 1122 | } |
| 1123 | Landed::LineConflict { line, n, conflicts } => { |
| 1124 | let state = if on_line.is_empty() { format!("{line} didn't change; your change is saved") } else { format!("{} landed before it; this one and the rest didn't", on_line.len()) }; |
| 1125 | let mut f = Fail::new("conflict", format!("can't land {}: {} {} conflict with {line}/{n}", app.short(&s.project, &item.id), conflicts.len(), if conflicts.len() == 1 { "file" } else { "files" })); |
| 1126 | for x in &conflicts { |
| 1127 | f = f.detail(x.path.clone()); |
| 1128 | } |
| 1129 | return Err(f.state(state).next("vcs sync, fix the conflicts in those files, then vcs land").set("conflicts", serde_json::to_value(&conflicts).unwrap_or_default())); |
| 1130 | } |
| 1131 | } |
| 1132 | } |
| 1133 | if !on_line.is_empty() { |
| 1134 | let last = on_line.last().cloned().unwrap_or_default(); |
| 1135 | app.db.add_op(&s.ws.id, "land_line", &json!({ "change": last["change"], "line": last["line"], "n": last["version"] }))?; |
| 1136 | if stack.iter().any(|x| x.id == current.id) { |
| 1137 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 1138 | r.line("change", format!("{} new, empty, on top of what you just landed", app.short(&s.project, &fresh.id))); |
| 1139 | r.set("change", change_json(app, &s.project, &fresh)); |
| 1140 | } |
| 1141 | r.set("landed", on_line); |
| 1142 | r.next("keep working on the line; vcs land puts the next version on it"); |
| 1143 | return Ok(r); |
| 1144 | } |
| 1145 | if landed_versions.is_empty() { |
| 1146 | // All of it is scheduled: the workspace goes on on top of it. |
| 1147 | if stack.iter().any(|x| x.id == current.id) { |
| 1148 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 1149 | r.line("change", format!("{} new, on top of the scheduled change", app.short(&s.project, &fresh.id))); |
| 1150 | } |
| 1151 | r.next("keep working; the host lands it then, as it is now"); |
| 1152 | return Ok(r); |
| 1153 | } |
| 1154 | let (last_id, last_version) = landed_versions.last().cloned().unwrap(); |
| 1155 | if let Some(prev) = app.db.version(&s.project.id, last_version.n.saturating_sub(1))? |
| 1156 | && let Some(first) = stack.first() |
| 1157 | && let Some(b) = first.base_version |
| 1158 | && prev.n > b |
| 1159 | { |
| 1160 | r.line("merged", format!("with {} versions that landed since main {b}", prev.n - b)); |
| 1161 | } |
| 1162 | 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<_>>() }))?; |
| 1163 | if stack.iter().any(|x| x.id == current.id) { |
| 1164 | let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; |
| 1165 | r.line("change", format!("{} new, empty, on top of what you just landed", app.short(&s.project, &fresh.id))); |
| 1166 | r.set("change", change_json(app, &s.project, &fresh)); |
| 1167 | } |
| 1168 | r.set("landed", landed_versions.iter().map(|(id, v)| json!({ "change": id, "version": v.n, "title": v.title })).collect::<Vec<_>>()) |
| 1169 | .set("main", last_version.n); |
| 1170 | r.next("keep working, or vcs sync to bring in others' work"); |
| 1171 | Ok(r) |
| 1172 | } |
| 1173 |
| 1174 | /// `vcs land <change> --to <line>`: a change's edits brought over to a |
| 1175 | /// release line as its next version: what a landed change did (main's |
| 1176 | /// version against the one before it), or an open change's own edits. The |
| 1177 | /// change itself stays as it is. When the edits conflict with the line, this |
| 1178 | /// workspace goes on a new change on the line with the conflicts marked. |
| 1179 | fn bring_over(app: &App, s: &mut Session, c: &Change, name: &str, messages: &[String], allow_secrets: bool) -> Out { |
| 1180 | let short = app.short(&s.project, &c.id); |
| 1181 | let (line, head) = crate::lines::head(app, &s.project, name)?; |
| 1182 | let at = |text: String| -> Result<Id, Fail> { |
| 1183 | crate::lines::tree_at(app, &s.project, &text)?.map(|(t, _)| t).ok_or_else(|| Fail::new("not_found", format!("there's no {text}")).state("nothing changed")) |
| 1184 | }; |
| 1185 | let (base, tree) = match (c.state.as_str(), &c.line, c.version) { |
| 1186 | ("landed", None, Some(n)) => { |
| 1187 | let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; |
| 1188 | (before, version(app, &s.project, n)?.tree) |
| 1189 | } |
| 1190 | ("landed", Some(from), Some(n)) => (at(format!("{from}/{}", n - 1))?, at(format!("{from}/{n}"))?), |
| 1191 | ("dropped", ..) => return Err(Fail::new("bad_usage", format!("change {short} was dropped")).state("nothing changed")), |
| 1192 | _ => { |
| 1193 | if c.is_empty() { |
| 1194 | return Err(Fail::new("empty_change", format!("change {short} has nothing to bring over")).state("nothing changed")); |
| 1195 | } |
| 1196 | if !c.conflicts.is_empty() { |
| 1197 | return Err(Fail::new("conflict", format!("change {short} still has conflict markers")).state("nothing changed").next("fix the marked lines first")); |
| 1198 | } |
| 1199 | (c.base_tree, c.tree()) |
| 1200 | } |
| 1201 | }; |
| 1202 | let mut described = c.clone(); |
| 1203 | if !messages.is_empty() { |
| 1204 | set_description(&mut described, messages); |
| 1205 | } |
| 1206 | require_title(&described)?; |
| 1207 | let host = app.host(&s.project); |
| 1208 | host.fetch_tree(&app.store, &s.project, &base, None)?; |
| 1209 | host.fetch_tree(&app.store, &s.project, &tree, Some(&base))?; |
| 1210 | if !allow_secrets && let Some(hit) = secrets::scan(&app.store, &base, &tree)?.first() { |
| 1211 | return Err(Fail::new("secret", format!("change {short} looks like it has a secret: {} line {} ({})", hit.path, hit.line, hit.kind)) |
| 1212 | .state(format!("{name} didn't change")) |
| 1213 | .next("vcs land --allow-secrets if it isn't one")); |
| 1214 | } |
| 1215 | let (title, body) = (described.title, described.body); |
| 1216 | let request = LandRequest { |
| 1217 | change: c.id.clone(), |
| 1218 | base_tree: base, |
| 1219 | tree, |
| 1220 | title: title.clone(), |
| 1221 | body: body.clone(), |
| 1222 | author: c.author.clone(), |
| 1223 | allow_secrets, |
| 1224 | record: None, |
| 1225 | at: None, |
| 1226 | signature: if s.project.hosted() { crate::host::LandSignature::for_land(&s.project.address, &c.id, &base, &tree, &title, &body, &c.author) } else { None }, |
| 1227 | line: Some(line.name.clone()), |
| 1228 | }; |
| 1229 | let mut r = Report::new(); |
| 1230 | match host.land(&app.db, &app.store, &s.project, &request)? { |
| 1231 | Landed::OnLine { line, n, title } => { |
| 1232 | app.db.add_op(&s.ws.id, "land_line", &json!({ "change": c.id, "line": line, "n": n, "brought": true }))?; |
| 1233 | r.line("brought over", format!("{short} to {line} as {line}/{n} \"{title}\"")); |
| 1234 | r.set("line", line.clone()).set("version", n).set("change", c.id.clone()); |
| 1235 | r.next(format!("vcs log --line {line} shows it")); |
| 1236 | } |
| 1237 | Landed::LineConflict { line: _, n, conflicts: _ } => { |
| 1238 | let ours = format!("{name}/{n}"); |
| 1239 | let m = merge::trees(&app.store, Some(&base), &head, &tree, Mode::Sync, (&ours, &format!("change {short}")))?; |
| 1240 | for o in m.objects.objects.values() { |
| 1241 | app.store.put(o)?; |
| 1242 | } |
| 1243 | let current = app.save(s)?; |
| 1244 | let mut x = Change::new(ids::new_change_id(), &s.project.id, head, Some(line.head), &app.author(&s.project)); |
| 1245 | x.line = Some(line.name.clone()); |
| 1246 | x.title = title; |
| 1247 | x.body = body; |
| 1248 | x.head_tree = Some(m.tree); |
| 1249 | x.saves = 1; |
| 1250 | x.conflicts = m.conflicts.iter().map(|k| Conflict { path: k.path.clone(), version: Some(line.head) }).collect(); |
| 1251 | app.db.add_save(&Save { change: x.id.clone(), n: 1, tree: m.tree, base_tree: head, at: ids::now(), uploaded: false }, &s.ws.id)?; |
| 1252 | app.db.put_change(&x)?; |
| 1253 | app.show_tree(s, &m.tree)?; |
| 1254 | app.put_workspace_change(s, &x.id)?; |
| 1255 | app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": x.id }))?; |
| 1256 | r.line("conflict", format!("{short}'s edits conflict with {ours}, so this workspace is on a new change on {name} with them marked")); |
| 1257 | for k in &m.conflicts { |
| 1258 | r.line("conflict", k.path.clone()); |
| 1259 | } |
| 1260 | r.line("change", format!("{} on {ours}", app.short(&s.project, &x.id))); |
| 1261 | if !current.is_empty() { |
| 1262 | r.line("kept", format!("{} is saved; vcs switch goes back to it", app.short(&s.project, ¤t.id))); |
| 1263 | } |
| 1264 | r.exit = 3; |
| 1265 | r.set("change", change_json(app, &s.project, &x)).set("conflicts", m.conflicts.iter().map(|k| k.path.clone()).collect::<Vec<_>>()); |
| 1266 | r.next(format!("fix the marked lines, then vcs land (it lands on {name})")); |
| 1267 | } |
| 1268 | Landed::Waiting { reason, .. } => return Err(Fail::new("waiting", format!("{name}: {reason}")).state(format!("{name} didn't change"))), |
| 1269 | Landed::ChecksFailed { check, .. } => return Err(Fail::new("checks_failed", format!("check \"{check}\" failed on {name}")).state(format!("{name} didn't change"))), |
| 1270 | other => return Err(Fail::new("failed", format!("the host answered {other:?} for a landing on {name}")).state(format!("{name} didn't change"))), |
| 1271 | } |
| 1272 | Ok(r) |
| 1273 | } |
| 1274 |
| 1275 | /// One workspace's part of a landing together: its change, checked and |
| 1276 | /// uploaded, and the host's landing request for it. |
| 1277 | fn together_part(app: &App, s: &mut Session, messages: &[String], allow_secrets: bool, run: bool) -> Result<(Change, serde_json::Value), Fail> { |
| 1278 | let saved = app.save_local(s)?; |
| 1279 | let mut c = settle_review(app, s, saved)?; |
| 1280 | let short = app.short(&s.project, &c.id); |
| 1281 | if !messages.is_empty() { |
| 1282 | set_description(&mut c, messages); |
| 1283 | app.db.put_change(&c)?; |
| 1284 | } |
| 1285 | let place = s.root.display().to_string(); |
| 1286 | if c.state != "open" { |
| 1287 | return Err(Fail::new("bad_usage", format!("{place}: change {short} is {}", c.state)).state("nothing landed")); |
| 1288 | } |
| 1289 | if c.is_empty() { |
| 1290 | return Err(Fail::new("empty_change", format!("{place}: change {short} has nothing to land")).state("nothing landed").next("edit files there first")); |
| 1291 | } |
| 1292 | if !c.conflicts.is_empty() { |
| 1293 | return Err(Fail::new("conflict", format!("{place}: change {short} still has conflict markers")).state("nothing landed").next(format!("fix the marked lines in {place}, then land again"))); |
| 1294 | } |
| 1295 | if let Some(p) = &c.on_change { |
| 1296 | // One held or in review may have landed on the host meanwhile. |
| 1297 | let mut parent = app.change(p)?; |
| 1298 | if parent.state != "landed" && s.project.hosted() { |
| 1299 | parent = crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, p)?.unwrap_or(parent); |
| 1300 | } |
| 1301 | if parent.state != "landed" { |
| 1302 | return Err(Fail::new("bad_usage", format!("{place}: change {short} is on top of a change that hasn't landed")).state("nothing landed").next(format!("land that first (vcs -C {place} land)"))); |
| 1303 | } |
| 1304 | } |
| 1305 | require_title(&c)?; |
| 1306 | if run { |
| 1307 | run_before_land(&s.root)?; |
| 1308 | } |
| 1309 | if !allow_secrets && let Some(hit) = secrets::scan(&app.store, &c.base_tree, &c.tree())?.first() { |
| 1310 | return Err(Fail::new("secret", format!("{place}: {} line {} looks like a {}", hit.path, hit.line, hit.kind)).state("nothing landed").next(format!("remove it from {}, then land again", hit.path))); |
| 1311 | } |
| 1312 | let remote = crate::remote::Remote::for_project(&s.project); |
| 1313 | remote.upload_change(&app.db, &app.store, &s.project, &c.base_tree, Some(&c.tree()))?; |
| 1314 | let pending = app.db.unuploaded_saves(&c.id)?; |
| 1315 | let request = LandRequest { |
| 1316 | change: c.id.clone(), |
| 1317 | base_tree: c.base_tree, |
| 1318 | tree: c.tree(), |
| 1319 | title: c.title.clone(), |
| 1320 | body: c.body.clone(), |
| 1321 | author: c.author.clone(), |
| 1322 | allow_secrets, |
| 1323 | at: None, |
| 1324 | signature: crate::host::LandSignature::for_land(&s.project.address, &c.id, &c.base_tree, &c.tree(), &c.title, &c.body, &c.author), |
| 1325 | line: c.line.clone(), |
| 1326 | record: Some(crate::wire::PutChange { |
| 1327 | change: crate::remote::Remote::record(&c), |
| 1328 | workspace: s.ws.id.clone(), |
| 1329 | label: crate::remote::label(&s.root), |
| 1330 | 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() }), |
| 1331 | }), |
| 1332 | }; |
| 1333 | for sv in &pending { |
| 1334 | app.db.mark_uploaded(&c.id, sv.n)?; |
| 1335 | } |
| 1336 | let (_, owner, name) = crate::remote::split_address(&s.project.address)?; |
| 1337 | Ok((c, json!({ "project": format!("{owner}/{name}"), "land": request }))) |
| 1338 | } |
| 1339 |
| 1340 | /// `vcs land --with <workspace>...`: this workspace's change and the other |
| 1341 | /// workspaces' (in other projects on the same host) land together, all of |
| 1342 | /// them or none. Under review rules, or with --at, each waits (in review, or |
| 1343 | /// held as it is) and the host lands them all once every one is ready. |
| 1344 | fn land_together(app: &App, s: &mut Session, with: &[PathBuf], messages: Vec<String>, allow_secrets: bool, run: bool, at: Option<i64>) -> Out { |
| 1345 | if !s.project.hosted() { |
| 1346 | return Err(Fail::new("bad_usage", "landing together needs a host, which lands every part at once").state("nothing changed").next("vcs publish <host/owner/name>")); |
| 1347 | } |
| 1348 | let mut others = Vec::new(); |
| 1349 | for path in with { |
| 1350 | let root = ws::find(&app.cwd.join(path)).ok_or_else(|| Fail::new("not_found", format!("{} isn't in a vcs workspace", path.display())).state("nothing changed"))?; |
| 1351 | let other = app.session_at(&root)?; |
| 1352 | if other.project.api != s.project.api { |
| 1353 | return Err(Fail::new("bad_usage", format!("{} is on another host; landing together is on one host", root.display())).state("nothing changed")); |
| 1354 | } |
| 1355 | if other.project.id == s.project.id || others.iter().any(|o: &Session| o.project.id == other.project.id) { |
| 1356 | return Err(Fail::new("bad_usage", format!("{} is in a project that's already in this landing: one change per project", root.display())).state("nothing changed")); |
| 1357 | } |
| 1358 | others.push(other); |
| 1359 | } |
| 1360 | let mut changes = Vec::new(); |
| 1361 | let mut parts = Vec::new(); |
| 1362 | for i in 0..=others.len() { |
| 1363 | let session: &mut Session = if i == 0 { &mut *s } else { &mut others[i - 1] }; |
| 1364 | let (c, part) = together_part(app, session, if i == 0 { &messages } else { &[] }, allow_secrets, run)?; |
| 1365 | changes.push(c); |
| 1366 | parts.push(part); |
| 1367 | } |
| 1368 | let mut body = json!({ "parts": parts }); |
| 1369 | if let Some(t) = at { |
| 1370 | body["at"] = json!(t); |
| 1371 | } |
| 1372 | let answer: serde_json::Value = crate::remote::Remote::for_project(&s.project).post_host("/land-together", &body)?; |
| 1373 | let mut r = Report::new(); |
| 1374 | let sessions: Vec<&mut Session> = std::iter::once(&mut *s).chain(others.iter_mut()).collect(); |
| 1375 | let mut sessions = sessions; |
| 1376 | match answer["outcome"].as_str() { |
| 1377 | Some("landed") => { |
| 1378 | for (session, c) in sessions.iter_mut().zip(&changes) { |
| 1379 | let (_, owner, name) = crate::remote::split_address(&session.project.address)?; |
| 1380 | let project = format!("{owner}/{name}"); |
| 1381 | let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); |
| 1382 | let mut done = c.clone(); |
| 1383 | done.state = "landed".into(); |
| 1384 | if let (Some(line), Some(n)) = (part["line"]["line"].as_str(), part["line"]["n"].as_u64()) { |
| 1385 | // A part on a release line. |
| 1386 | done.version = Some(n); |
| 1387 | done.line = Some(line.to_string()); |
| 1388 | app.db.put_change(&done)?; |
| 1389 | r.line("landed", format!("{} as {line}/{n} of {project} \"{}\"", app.short(&session.project, &c.id), c.title)); |
| 1390 | } else { |
| 1391 | let version: Version = serde_json::from_value(part["version"].clone()).map_err(|e| Fail::new("failed", format!("the host's answer for {project} was off: {e}")))?; |
| 1392 | done.version = Some(version.n); |
| 1393 | app.db.put_change(&done)?; |
| 1394 | app.db.put_version(&session.project.id, &version)?; |
| 1395 | r.line("landed", format!("{} as main {} of {project} \"{}\"", app.short(&session.project, &c.id), version.n, version.title)); |
| 1396 | } |
| 1397 | continue_after(app, session, &done)?; |
| 1398 | } |
| 1399 | r.set("landed", answer["parts"].clone()); |
| 1400 | r.next("keep working; each workspace is on a fresh change"); |
| 1401 | } |
| 1402 | Some("together") => { |
| 1403 | let mut reviews = 0; |
| 1404 | for (session, c) in sessions.iter_mut().zip(&changes) { |
| 1405 | let (_, owner, name) = crate::remote::split_address(&session.project.address)?; |
| 1406 | let project = format!("{owner}/{name}"); |
| 1407 | let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); |
| 1408 | let short = app.short(&session.project, &c.id); |
| 1409 | if let (Some(number), Some(url)) = (part["review"]["number"].as_u64(), part["review"]["url"].as_str()) { |
| 1410 | reviews += 1; |
| 1411 | app.db.set_review(&c.id, Some(&format!("#{number} {url}")))?; |
| 1412 | r.line("review", format!("{short} in {project} is change request #{number}, {url}")); |
| 1413 | } else { |
| 1414 | let mut held = c.clone(); |
| 1415 | held.state = "scheduled".into(); |
| 1416 | app.db.put_change(&held)?; |
| 1417 | r.line("held", format!("{short} in {project}, as it is now")); |
| 1418 | continue_after(app, session, &held)?; |
| 1419 | } |
| 1420 | } |
| 1421 | let when = answer["at"].as_i64().map(|t| format!(" at {} or after", ids::clock(t))).unwrap_or_default(); |
| 1422 | r.line("lands", format!("all together{when}, once every change request's approvals and checks pass")); |
| 1423 | if reviews > 0 { |
| 1424 | r.exit = 5; |
| 1425 | } |
| 1426 | r.set("together", answer.clone()); |
| 1427 | r.next("keep working; the host lands them all when every part is ready"); |
| 1428 | } |
| 1429 | Some("refused") => { |
| 1430 | let project = answer["project"].as_str().unwrap_or("a project"); |
| 1431 | let landed: Landed = serde_json::from_value(answer["landed"].clone()).map_err(|e| Fail::new("failed", format!("the host's answer was off: {e}")))?; |
| 1432 | let (code, why) = match &landed { |
| 1433 | Landed::Conflict { main, conflicts } => ("conflict", format!("conflicts with main {main} of {project} in {}", conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", "))), |
| 1434 | Landed::Waiting { reason, .. } => ("waiting", format!("{project}: {reason}")), |
| 1435 | _ => ("failed", format!("{project} couldn't land its part")), |
| 1436 | }; |
| 1437 | return Err(Fail::new(code, format!("nothing landed: {why}")).state("main didn't change in any of them; every change is saved").next(format!("in {project}'s workspace: vcs sync, fix it, then land together again"))); |
| 1438 | } |
| 1439 | _ => return Err(Fail::new("failed", format!("the host answered {answer}"))), |
| 1440 | } |
| 1441 | Ok(r) |
| 1442 | } |
| 1443 |
| 1444 | /// A change in review: the host says whether its change request merged |
| 1445 | /// meanwhile, and if it did and it's the workspace's change, the workspace |
| 1446 | /// moves on to a fresh change on top of it, as after a land. |
| 1447 | fn settle_review(app: &App, s: &mut Session, c: Change) -> Result<Change, Fail> { |
| 1448 | if !s.project.hosted() || app.db.review(&c.id)?.is_none() { |
| 1449 | return Ok(c); |
| 1450 | } |
| 1451 | let found: Result<serde_json::Value, _> = crate::remote::Remote::for_project(&s.project).get_json(&format!("/changes/{}", c.id)); |
| 1452 | let Ok(found) = found else { return Ok(c) }; |
| 1453 | let Ok(record) = serde_json::from_value::<crate::wire::ChangeRecord>(found["change"].clone()) else { return Ok(c) }; |
| 1454 | let adopted = crate::remote::Remote::adopt(&app.db, &s.project, &record)?; |
| 1455 | if adopted.state == "landed" && s.ws.change == adopted.id { |
| 1456 | // On from what the workspace has (a sync may have moved it since). |
| 1457 | let mut done = c; |
| 1458 | done.state = "landed".into(); |
| 1459 | done.version = adopted.version; |
| 1460 | return continue_after(app, s, &done); |
| 1461 | } |
| 1462 | Ok(adopted) |
| 1463 | } |
| 1464 |
| 1465 | /// After a landing (or a land that's waiting), the workspace continues on a |
| 1466 | /// fresh change on top of what it had, without touching files. |
| 1467 | fn continue_after(app: &App, s: &mut Session, done: &Change) -> Result<Change, Fail> { |
| 1468 | let mut fresh = Change::new(ids::new_change_id(), &s.project.id, done.tree(), None, &app.author(&s.project)); |
| 1469 | if done.state == "waiting" || done.state == "scheduled" { |
| 1470 | fresh.on_change = Some(done.id.clone()); |
| 1471 | } else { |
| 1472 | fresh.after_change = Some(done.id.clone()); |
| 1473 | } |
| 1474 | // On a release line, the workspace stays on it. |
| 1475 | fresh.line = done.line.clone(); |
| 1476 | if done.line.is_some() && done.state == "landed" { |
| 1477 | fresh.base_version = done.version; |
| 1478 | } |
| 1479 | app.db.put_change(&fresh)?; |
| 1480 | app.put_workspace_change(s, &fresh.id)?; |
| 1481 | Ok(fresh) |
| 1482 | } |
| 1483 |
| 1484 | // Fix. |
| 1485 |
| 1486 | pub fn undo(app: &App, which: Option<String>) -> Out { |
| 1487 | let mut s = app.session()?; |
| 1488 | let current = app.save(&mut s)?; |
| 1489 | // A release line's version: a version of the line takes it back out. |
| 1490 | if let Some((name, n)) = which.as_deref().and_then(|w| w.rsplit_once('/')).and_then(|(l, n)| n.parse::<u64>().ok().map(|n| (l.to_string(), n))) { |
| 1491 | let (title, taken) = take_back_line(app, &s, &name, n)?; |
| 1492 | app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back {name}/{n}") }))?; |
| 1493 | let mut r = Report::new(); |
| 1494 | r.line("undid", format!("{name}/{n} (\"{title}\"): {name}/{taken} takes it back out")); |
| 1495 | r.set("undid", format!("{name}/{n}")).set("line", name.clone()).set("version", taken); |
| 1496 | return Ok(r); |
| 1497 | } |
| 1498 | let version_n = match which.as_deref() { |
| 1499 | None => None, |
| 1500 | Some(text) => Some(text.parse::<u64>().map_err(|_| Fail::new("bad_usage", format!("{text} isn't a version of main (48) or of a release line (1.x/3)")).state("nothing changed"))?), |
| 1501 | }; |
| 1502 | if let Some(n) = version_n { |
| 1503 | let (v, revert) = take_back(app, &s, n)?; |
| 1504 | let mut r = Report::new(); |
| 1505 | r.line("undid", format!("main {} (\"{}\"): main {} takes it back out", v.n, v.title, revert.n)); |
| 1506 | if let Some(mut c) = app.db.change(&v.change)? { |
| 1507 | c.state = "open".into(); |
| 1508 | c.version = None; |
| 1509 | app.db.put_change(&c)?; |
| 1510 | 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))); |
| 1511 | } |
| 1512 | app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back main {}", v.n) }))?; |
| 1513 | r.set("undid", v.n).set("main", revert.n); |
| 1514 | return Ok(r); |
| 1515 | } |
| 1516 | 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"))?; |
| 1517 | let d = op.data.clone(); |
| 1518 | let text = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 1519 | let mut r = Report::new(); |
| 1520 | match op.kind.as_str() { |
| 1521 | "new" | "switch" => { |
| 1522 | let back = app.change(&text("from"))?; |
| 1523 | app.show_tree(&s, &back.tree())?; |
| 1524 | app.put_workspace_change(&mut s, &back.id)?; |
| 1525 | r.line("undid", format!("{}: back on change {}", op.kind, app.short(&s.project, &back.id))); |
| 1526 | if current.is_empty() && op.kind == "new" { |
| 1527 | let mut gone = current.clone(); |
| 1528 | gone.state = "dropped".into(); |
| 1529 | app.db.put_change(&gone)?; |
| 1530 | } else { |
| 1531 | r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); |
| 1532 | } |
| 1533 | } |
| 1534 | "drop" => { |
| 1535 | let mut c = app.change(&text("change"))?; |
| 1536 | c.state = "open".into(); |
| 1537 | app.db.put_change(&c)?; |
| 1538 | if d.get("current").and_then(|v| v.as_bool()) == Some(true) { |
| 1539 | app.show_tree(&s, &c.tree())?; |
| 1540 | app.put_workspace_change(&mut s, &c.id)?; |
| 1541 | if let Some(rep) = d.get("replacement").and_then(|v| v.as_str()) { |
| 1542 | if let Some(mut x) = app.db.change(rep)? && x.is_empty() { |
| 1543 | x.state = "dropped".into(); |
| 1544 | app.db.put_change(&x)?; |
| 1545 | } |
| 1546 | } |
| 1547 | } |
| 1548 | r.line("undid", format!("drop: change {} is back", app.short(&s.project, &c.id))); |
| 1549 | } |
| 1550 | "describe" => { |
| 1551 | let mut c = app.change(&text("change"))?; |
| 1552 | c.title = text("title"); |
| 1553 | c.body = text("body"); |
| 1554 | app.db.put_change(&c)?; |
| 1555 | r.line("undid", format!("describe: change {} has its old description", app.short(&s.project, &c.id))); |
| 1556 | } |
| 1557 | "sync" => { |
| 1558 | let mut c = app.change(&text("change"))?; |
| 1559 | let id = |k: &str| d.get(k).and_then(|v| v.as_str()).and_then(Id::parse); |
| 1560 | c.base_tree = id("base_tree").unwrap_or(c.base_tree); |
| 1561 | c.base_version = d.get("base_version").and_then(|v| v.as_u64()); |
| 1562 | c.on_change = d.get("on_change").and_then(|v| v.as_str()).map(str::to_string); |
| 1563 | c.after_change = d.get("after_change").and_then(|v| v.as_str()).map(str::to_string); |
| 1564 | c.head_tree = id("head_tree"); |
| 1565 | c.conflicts = serde_json::from_value(d.get("conflicts").cloned().unwrap_or_default()).unwrap_or_default(); |
| 1566 | c.saves += 1; |
| 1567 | 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)?; |
| 1568 | app.db.put_change(&c)?; |
| 1569 | app.show_tree(&s, &c.tree())?; |
| 1570 | r.line("undid", format!("sync: change {} is back on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); |
| 1571 | } |
| 1572 | "restore" => { |
| 1573 | 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"))?; |
| 1574 | app.show_tree(&s, &tree)?; |
| 1575 | app.save(&mut s)?; |
| 1576 | r.line("undid", format!("restore of {}", text("paths"))); |
| 1577 | } |
| 1578 | "land" => { |
| 1579 | let n = d.get("version").and_then(|v| v.as_u64()).unwrap_or(0); |
| 1580 | let (v, revert) = take_back(app, &s, n)?; |
| 1581 | let mut c = app.change(&text("change"))?; |
| 1582 | c.state = "open".into(); |
| 1583 | c.version = None; |
| 1584 | // Edits made since the land come along. |
| 1585 | let after = current; |
| 1586 | c.head_tree = Some(after.tree()); |
| 1587 | if after.id != c.id { |
| 1588 | let mut x = after.clone(); |
| 1589 | x.state = "dropped".into(); |
| 1590 | app.db.put_change(&x)?; |
| 1591 | } |
| 1592 | c.saves += 1; |
| 1593 | 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)?; |
| 1594 | app.db.put_change(&c)?; |
| 1595 | app.put_workspace_change(&mut s, &c.id)?; |
| 1596 | r.line("undid", format!("land of {}: main {} takes main {} back out", app.short(&s.project, &c.id), revert.n, v.n)) |
| 1597 | .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); |
| 1598 | r.next("fix it, then vcs land"); |
| 1599 | } |
| 1600 | "access" => { |
| 1601 | crate::access::undo(app, &s, &d)?; |
| 1602 | r.line("undid", format!("access change for {}", text("target"))); |
| 1603 | } |
| 1604 | "undo" => { |
| 1605 | 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")); |
| 1606 | } |
| 1607 | "land_line" => { |
| 1608 | let (line, n) = (text("line"), d.get("n").and_then(|v| v.as_u64()).unwrap_or(0)); |
| 1609 | if line.is_empty() || n == 0 { |
| 1610 | return Err(Fail::new("nothing_to_undo", "that landing on a release line was made by an older vcs, which didn't note its version").state("nothing changed").next("vcs log --line <line>, then vcs undo <line>/<n>")); |
| 1611 | } |
| 1612 | let (_, taken) = take_back_line(app, &s, &line, n)?; |
| 1613 | if d.get("brought").and_then(|v| v.as_bool()) == Some(true) { |
| 1614 | r.line("undid", format!("bringing {} over: {line}/{taken} takes {line}/{n} back out", app.short(&s.project, &text("change")))); |
| 1615 | } else { |
| 1616 | // The change made on the line opens again here, with what was done since. |
| 1617 | let mut c = app.change(&text("change"))?; |
| 1618 | c.state = "open".into(); |
| 1619 | c.version = None; |
| 1620 | let after = current; |
| 1621 | c.head_tree = Some(after.tree()); |
| 1622 | if after.id != c.id { |
| 1623 | let mut x = after.clone(); |
| 1624 | x.state = "dropped".into(); |
| 1625 | app.db.put_change(&x)?; |
| 1626 | } |
| 1627 | c.saves += 1; |
| 1628 | 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)?; |
| 1629 | app.db.put_change(&c)?; |
| 1630 | app.put_workspace_change(&mut s, &c.id)?; |
| 1631 | r.line("undid", format!("land of {}: {line}/{taken} takes {line}/{n} back out", app.short(&s.project, &c.id))) |
| 1632 | .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); |
| 1633 | r.next("fix it, then vcs land"); |
| 1634 | } |
| 1635 | } |
| 1636 | other => return Err(Fail::new("failed", format!("can't undo {other}")).state("nothing changed")), |
| 1637 | } |
| 1638 | app.db.mark_undone(op.id)?; |
| 1639 | r.set("undid", op.kind.clone()).set("data", d); |
| 1640 | Ok(r) |
| 1641 | } |
| 1642 |
| 1643 | /// Lands a version on release line `name` that reverses its version `n`; |
| 1644 | /// answers that version's title and the new version's number. |
| 1645 | fn take_back_line(app: &App, s: &Session, name: &str, n: u64) -> Result<(String, u64), Fail> { |
| 1646 | let at = |k: u64| -> Result<Id, Fail> { |
| 1647 | crate::lines::tree_at(app, &s.project, &format!("{name}/{k}"))?.map(|(t, _)| t).ok_or_else(|| Fail::new("not_found", format!("there's no line {name}")).state("nothing changed")) |
| 1648 | }; |
| 1649 | let (line, head) = crate::lines::head(app, &s.project, name)?; |
| 1650 | if n == 0 || n > line.head { |
| 1651 | return Err(Fail::new("not_found", format!("line {name} has no version {n}")).state("nothing changed")); |
| 1652 | } |
| 1653 | let (taken, before) = (at(n)?, at(n - 1)?); |
| 1654 | let title = crate::lines::versions(app, &s.project, name, (line.head - n + 1) as usize)?.into_iter().find(|v| v.n == n).map(|v| v.title).unwrap_or_default(); |
| 1655 | // Merge "version → version before it" onto the line's latest. |
| 1656 | let m = merge::trees(&app.store, Some(&taken), &head, &before, Mode::Land, (&format!("{name}/{}", line.head), "the undo"))?; |
| 1657 | if !m.clean() { |
| 1658 | return Err(Fail::new("conflict", format!("can't take back {name}/{n}: later versions of {name} changed the same lines")) |
| 1659 | .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 1660 | .state(format!("{name} didn't change")) |
| 1661 | .next(format!("vcs new --line {name}, undo it by hand, then vcs land"))); |
| 1662 | } |
| 1663 | for o in m.objects.objects.values() { |
| 1664 | app.store.put(o)?; |
| 1665 | } |
| 1666 | let request = LandRequest { |
| 1667 | change: ids::new_change_id(), |
| 1668 | base_tree: head, |
| 1669 | tree: m.tree, |
| 1670 | title: format!("Take back {name}/{n}: {title}"), |
| 1671 | body: format!("Undoes {name}/{n}."), |
| 1672 | author: app.author(&s.project), |
| 1673 | allow_secrets: true, |
| 1674 | record: None, |
| 1675 | at: None, |
| 1676 | signature: None, |
| 1677 | line: Some(name.to_string()), |
| 1678 | }; |
| 1679 | match app.host(&s.project).land(&app.db, &app.store, &s.project, &request)? { |
| 1680 | Landed::OnLine { n: made, .. } => Ok((title, made)), |
| 1681 | Landed::LineConflict { .. } => Err(Fail::new("conflict", format!("{name} moved while taking back {name}/{n}")).state(format!("{name} didn't change")).next("vcs undo again")), |
| 1682 | Landed::Review { number, url, .. } => Err(Fail::new("waiting", format!("the repository's rules send the undo through review: #{number}, {url}")) |
| 1683 | .state(format!("{name} didn't change yet; it lands once the change request's approvals and checks pass")) |
| 1684 | .set("review", json!({ "number": number, "url": url }))), |
| 1685 | Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state(format!("{name} didn't change"))), |
| 1686 | other => Err(Fail::new("failed", format!("the host answered {other:?} for the undo")).state(format!("{name} didn't change"))), |
| 1687 | } |
| 1688 | } |
| 1689 |
| 1690 | /// Lands a change that reverses version `n` on the latest main. |
| 1691 | fn take_back(app: &App, s: &Session, n: u64) -> Result<(Version, Version), Fail> { |
| 1692 | let v = version(app, &s.project, n)?; |
| 1693 | let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; |
| 1694 | let main = app.refresh(&s.project)?.ok_or_else(|| Fail::new("not_found", "main has no versions"))?; |
| 1695 | let host = app.host(&s.project); |
| 1696 | for t in [&v.tree, &before, &main.tree] { |
| 1697 | host.fetch_tree(&app.store, &s.project, t, None)?; |
| 1698 | } |
| 1699 | // Merge "version → version before it" onto main. |
| 1700 | let m = merge::trees(&app.store, Some(&v.tree), &main.tree, &before, Mode::Land, ("main", "the undo"))?; |
| 1701 | if !m.clean() { |
| 1702 | return Err(Fail::new("conflict", format!("can't take back main {n}: later versions changed the same lines")) |
| 1703 | .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::<Vec<_>>().join(", ")) |
| 1704 | .state("main didn't change") |
| 1705 | .next("make a new change that undoes it by hand, then vcs land")); |
| 1706 | } |
| 1707 | for o in m.objects.objects.values() { |
| 1708 | app.store.put(o)?; |
| 1709 | } |
| 1710 | let request = LandRequest { |
| 1711 | change: ids::new_change_id(), |
| 1712 | base_tree: main.tree, |
| 1713 | tree: m.tree, |
| 1714 | title: format!("Take back main {n}: {}", v.title), |
| 1715 | body: format!("Undoes main {n}."), |
| 1716 | author: app.author(&s.project), |
| 1717 | allow_secrets: true, |
| 1718 | record: None, |
| 1719 | at: None, |
| 1720 | signature: None, |
| 1721 | line: None, |
| 1722 | }; |
| 1723 | match host.land(&app.db, &app.store, &s.project, &request)? { |
| 1724 | Landed::Landed { version } => { |
| 1725 | app.db.put_version(&s.project.id, &version)?; |
| 1726 | Ok((v, version)) |
| 1727 | } |
| 1728 | Landed::Conflict { .. } => Err(Fail::new("conflict", format!("main moved while taking back main {n}")).state("main didn't change").next("vcs undo again")), |
| 1729 | Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state("main didn't change")), |
| 1730 | Landed::ChecksFailed { check, .. } => Err(Fail::new("checks_failed", format!("check \"{check}\" failed on the undo")).state("main didn't change")), |
| 1731 | Landed::Review { number, url, .. } => Err(Fail::new("waiting", format!("the repository's rules send the undo through review: #{number}, {url}")) |
| 1732 | .state("main didn't change yet; it lands once the change request's approvals and checks pass") |
| 1733 | .set("review", json!({ "number": number, "url": url }))), |
| 1734 | Landed::Scheduled { .. } => Err(Fail::new("failed", "the host kept the undo for later, which it shouldn't").state("main didn't change")), |
| 1735 | Landed::OnLine { .. } | Landed::LineConflict { .. } => Err(Fail::new("failed", "the host put the undo on a release line, which it shouldn't").state("main didn't change")), |
| 1736 | } |
| 1737 | } |
| 1738 |
| 1739 | /// `vcs show <file> [--from <version|change|change:save>]`: the file as it |
| 1740 | /// is in main's latest version (or in --from), printed as it is. |
| 1741 | /// `vcs bisect <good> <bad> --run "<command>"`: finds the first version of |
| 1742 | /// main where the command fails. Main's versions are numbered, so it's a |
| 1743 | /// binary search between them: each version it tries is written to a folder |
| 1744 | /// of its own (the workspace's files never change) and the command runs |
| 1745 | /// there. Exit 0 means good, 125 means it can't tell (that version is |
| 1746 | /// skipped), anything else means bad. |
| 1747 | pub fn bisect(app: &App, good: String, bad: String, run: String, folder: Option<PathBuf>) -> Out { |
| 1748 | let s = app.session()?; |
| 1749 | let number = |text: &str| -> Result<u64, Fail> { |
| 1750 | match text.parse::<u64>().ok().or(crate::tags::find(app, &s.project, text)?) { |
| 1751 | Some(n) => Ok(n), |
| 1752 | None if text == "main" => Ok(app.refresh(&s.project)?.map(|v| v.n).unwrap_or(0)), |
| 1753 | None => Err(Fail::new("bad_usage", format!("{text} isn't a version of main or a tag")).state("nothing changed")), |
| 1754 | } |
| 1755 | }; |
| 1756 | let (good_n, bad_n) = (number(&good)?, number(&bad)?); |
| 1757 | if good_n >= bad_n { |
| 1758 | return Err(Fail::new("bad_usage", format!("the good version ({good_n}) has to come before the bad one ({bad_n})")).state("nothing changed")); |
| 1759 | } |
| 1760 | let keep = folder.is_some(); |
| 1761 | let root = match folder { |
| 1762 | Some(f) => app.cwd.join(f), |
| 1763 | None => crate::paths::home().join("tmp").join(format!("bisect-{}", ids::new_workspace_id())), |
| 1764 | }; |
| 1765 | std::fs::create_dir_all(&root)?; |
| 1766 | let mut index = Index::default(); |
| 1767 | let mut tried: Vec<(u64, &'static str)> = Vec::new(); |
| 1768 | let mut skipped: std::collections::BTreeSet<u64> = Default::default(); |
| 1769 | let (mut lo, mut hi) = (good_n, bad_n); |
| 1770 | let result = (|| -> Result<(), Fail> { |
| 1771 | loop { |
| 1772 | // The middle untried version, or the nearest one that isn't skipped. |
| 1773 | let mid = (lo + 1..hi).filter(|n| !skipped.contains(n)).min_by_key(|n| n.abs_diff((lo + hi) / 2)); |
| 1774 | let Some(mid) = mid else { return Ok(()) }; |
| 1775 | let (tree, _) = resolve_tree(app, &s.project, &mid.to_string())?; |
| 1776 | index = ws::materialize(&root, &app.store, &index, &app.files(&tree)?, &[], &crate::seal::Seals::load(&app.db, &s.project.id)?.unreadable(), None)?; |
| 1777 | let mut shell = if cfg!(windows) { std::process::Command::new("cmd") } else { std::process::Command::new("sh") }; |
| 1778 | shell.args(if cfg!(windows) { ["/C", run.as_str()] } else { ["-c", run.as_str()] }); |
| 1779 | let status = shell |
| 1780 | .current_dir(&root) |
| 1781 | .stdout(std::process::Stdio::null()) |
| 1782 | .stderr(std::process::Stdio::null()) |
| 1783 | .status() |
| 1784 | .map_err(|e| Fail::new("bad_usage", format!("couldn't run {run:?}: {e}")).state("nothing changed"))?; |
| 1785 | match status.code() { |
| 1786 | Some(0) => { |
| 1787 | tried.push((mid, "good")); |
| 1788 | lo = mid; |
| 1789 | } |
| 1790 | Some(125) => { |
| 1791 | tried.push((mid, "skip")); |
| 1792 | skipped.insert(mid); |
| 1793 | } |
| 1794 | _ => { |
| 1795 | tried.push((mid, "bad")); |
| 1796 | hi = mid; |
| 1797 | } |
| 1798 | } |
| 1799 | } |
| 1800 | })(); |
| 1801 | if !keep { |
| 1802 | let _ = std::fs::remove_dir_all(&root); |
| 1803 | } |
| 1804 | result?; |
| 1805 | let v = version(app, &s.project, hi)?; |
| 1806 | let mut r = Report::new(); |
| 1807 | let left: Vec<u64> = (lo + 1..hi).collect(); |
| 1808 | if left.is_empty() { |
| 1809 | r.line("first bad", format!("main {} \"{}\" {}, {}", v.n, v.title, v.author, ids::clock(v.time))); |
| 1810 | } else { |
| 1811 | // Only skipped versions sit between the last good and the first bad. |
| 1812 | r.line("first bad", format!("one of main {}, {}", left.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(", "), v.n)); |
| 1813 | } |
| 1814 | r.line("tried", tried.iter().map(|(n, how)| format!("{n} {how}")).collect::<Vec<_>>().join(", ")); |
| 1815 | if keep { |
| 1816 | r.line("folder", format!("{} has main {} as the last one tried", root.display(), tried.last().map(|t| t.0).unwrap_or(hi))); |
| 1817 | } |
| 1818 | r.set("first_bad", v.n) |
| 1819 | .set("candidates", left.iter().copied().chain([v.n]).collect::<Vec<_>>()) |
| 1820 | .set("tried", tried.iter().map(|(n, how)| json!({ "version": n, "result": how })).collect::<Vec<_>>()); |
| 1821 | r.next(format!("vcs log {} to see what it changed, or vcs undo {} to take it back out", v.n, v.n)); |
| 1822 | Ok(r) |
| 1823 | } |
| 1824 |
| 1825 | pub fn show(app: &App, path: String, from: Option<String>) -> Out { |
| 1826 | use base64::Engine; |
| 1827 | use std::io::Write; |
| 1828 | let s = app.session()?; |
| 1829 | let path = crate::history::workspace_path(app, &s.root, &path); |
| 1830 | let from = from.unwrap_or_else(|| "main".to_string()); |
| 1831 | // A tag is the version it names. |
| 1832 | let from = match crate::tags::find(app, &s.project, &from)? { |
| 1833 | Some(n) => n.to_string(), |
| 1834 | None => from, |
| 1835 | }; |
| 1836 | // A version of a hosted project is read where it is, not fetched whole. |
| 1837 | let mut found: Option<(Vec<u8>, String)> = None; |
| 1838 | if s.project.hosted() && (from == "main" || from.parse::<u64>().is_ok()) { |
| 1839 | #[derive(serde::Deserialize)] |
| 1840 | struct HostFile { |
| 1841 | version: u64, |
| 1842 | base64: Option<String>, |
| 1843 | } |
| 1844 | let version = if from == "main" { String::new() } else { format!("&version={from}") }; |
| 1845 | let f: HostFile = crate::remote::Remote::for_project(&s.project).get_json(&format!("/file?path={}{version}", crate::history::encode(&path)))?; |
| 1846 | // Over 1 MB (or a submodule): below, from the version's objects. |
| 1847 | if let Some(b) = f.base64 { |
| 1848 | let content = base64::engine::general_purpose::STANDARD.decode(b).map_err(|e| anyhow::anyhow!("the host sent a bad file: {e}"))?; |
| 1849 | found = Some((content, format!("main {}", f.version))); |
| 1850 | } |
| 1851 | } |
| 1852 | let (content, label) = match found { |
| 1853 | Some(f) => f, |
| 1854 | None => { |
| 1855 | let (tree, label) = resolve_tree(app, &s.project, &from)?; |
| 1856 | match tree::lookup(&app.store, &tree, &path)? { |
| 1857 | Some(e) if e.kind == tree::EntryKind::Tree => return Err(Fail::new("bad_usage", format!("{path} is a folder in {label}")).state("nothing changed")), |
| 1858 | Some(e) if e.kind == tree::EntryKind::Gitlink => return Err(Fail::new("bad_usage", format!("{path} is a git submodule in {label}")).state("nothing changed")), |
| 1859 | Some(e) => (app.store.read_file(&e.id)?, label), |
| 1860 | None => return Err(Fail::new("not_found", format!("there's no {path} in {label}")).state("nothing changed")), |
| 1861 | } |
| 1862 | } |
| 1863 | }; |
| 1864 | if !app.json { |
| 1865 | std::io::stdout().write_all(&content).map_err(anyhow::Error::from)?; |
| 1866 | } |
| 1867 | let mut r = Report::new(); |
| 1868 | r.set("path", path).set("from", label).set("base64", base64::engine::general_purpose::STANDARD.encode(&content)); |
| 1869 | Ok(r) |
| 1870 | } |
| 1871 |
| 1872 | pub fn restore(app: &App, paths: Vec<String>, at: Option<String>, from: Option<String>) -> Out { |
| 1873 | let mut s = app.session()?; |
| 1874 | let c = app.save(&mut s)?; |
| 1875 | if paths.is_empty() { |
| 1876 | return Err(Fail::new("bad_usage", "say which files to restore (. for all)").state("nothing changed").next("vcs restore <file>")); |
| 1877 | } |
| 1878 | let (source, label) = match (&at, &from) { |
| 1879 | (Some(_), Some(_)) => return Err(Fail::new("bad_usage", "use --at or --from, not both").state("nothing changed")), |
| 1880 | (Some(when), None) => { |
| 1881 | 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"))?; |
| 1882 | let sv = app.db.save_at(&s.ws.id, t)?.ok_or_else(|| { |
| 1883 | Fail::new("not_found", format!("nothing was saved in this workspace by {}", ids::clock(t))).state("nothing changed") |
| 1884 | })?; |
| 1885 | (sv.tree, format!("save {} ({})", sv.n, ids::ago(sv.at))) |
| 1886 | } |
| 1887 | (None, Some(r)) => resolve_tree(app, &s.project, r)?, |
| 1888 | (None, None) => (c.base_tree, "the change's base".to_string()), |
| 1889 | }; |
| 1890 | let src = app.files(&source)?; |
| 1891 | let mut now = app.files(&c.tree())?; |
| 1892 | let wants: Vec<String> = paths.iter().map(|p| { |
| 1893 | let abs = app.cwd.join(p); |
| 1894 | abs.strip_prefix(&s.root).ok().and_then(crate::sys::tree_path).unwrap_or_else(|| p.replace('\\', "/")) |
| 1895 | }).map(|p| p.trim_matches('/').to_string()).map(|p| if p == "." { String::new() } else { p }).collect(); |
| 1896 | let mut touched = 0; |
| 1897 | for want in &wants { |
| 1898 | let before: Vec<String> = now.keys().filter(|p| tree::under(p, want)).cloned().collect(); |
| 1899 | for p in before { |
| 1900 | now.remove(&p); |
| 1901 | touched += 1; |
| 1902 | } |
| 1903 | for (p, e) in src.iter().filter(|(p, _)| tree::under(p, want)) { |
| 1904 | now.insert(p.clone(), *e); |
| 1905 | touched += 1; |
| 1906 | } |
| 1907 | } |
| 1908 | if touched == 0 { |
| 1909 | return Err(Fail::new("not_found", format!("no files match {}", paths.join(", "))).state("nothing changed")); |
| 1910 | } |
| 1911 | let (tree_id, objects) = tree::build(&now); |
| 1912 | for o in &objects { |
| 1913 | app.store.put(o)?; |
| 1914 | } |
| 1915 | let before_tree = c.tree(); |
| 1916 | app.show_tree(&s, &tree_id)?; |
| 1917 | let saved = app.save(&mut s)?; |
| 1918 | app.db.add_op(&s.ws.id, "restore", &json!({ "change": c.id, "before": before_tree, "paths": paths.join(" "), "source": label }))?; |
| 1919 | let mut r = Report::new(); |
| 1920 | r.line("restored", format!("{} from {label}", paths.join(", "))); |
| 1921 | r.set("restored", paths.clone()).set("source", label).set("change", change_json(app, &s.project, &saved)); |
| 1922 | r.next(format!("vcs diff {} to check", paths.join(" "))); |
| 1923 | Ok(r) |
| 1924 | } |
| 1925 |
| 1926 | pub fn guide() -> Out { |
| 1927 | let mut r = Report::new(); |
| 1928 | r.raw(include_str!("../../GUIDE.md")); |
| 1929 | r.set("guide", include_str!("../../GUIDE.md")); |
| 1930 | Ok(r) |
| 1931 | } |
| 1932 |
| 1933 | /// Files a workspace tracks, by path, for helpers. |
| 1934 | pub fn tracked(root: &Path) -> BTreeMap<String, ()> { |
| 1935 | Index::load(root).entries.keys().map(|k| (k.clone(), ())).collect() |
| 1936 | } |
| 1937 |
| 1938 | #[allow(dead_code)] |
| 1939 | fn files_to_vec(files: &Files) -> Vec<String> { |
| 1940 | files.keys().cloned().collect() |
| 1941 | } |
| 1942 |