//! The commands. Each returns a [`Report`] or a [`Fail`] that says whether //! anything changed and what to do next. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use serde_json::json; use vcs_core::merge::{self, Mode}; use vcs_core::tree::{self, Files}; use vcs_core::version::Version; use vcs_core::{Id, diff}; use crate::app::{App, Session, ensure_dir_empty}; use crate::db::{Change, Conflict, Project, Save, Workspace}; use crate::host::{LandRequest, Landed}; use crate::ids; use crate::out::{Fail, Out, Report}; use crate::secrets; use crate::ws::{self, CowSource, Index}; // Labels people see. fn main_label(n: Option) -> String { match n { Some(n) => format!("main {n}"), None => "an empty main".into(), } } fn base_text(app: &App, project: &Project, c: &Change) -> String { if let Some(on) = &c.on_change { return format!("change {} (not landed yet)", app.short(project, on)); } if let Some(after) = &c.after_change { let landed = app.db.change(after).ok().flatten().and_then(|a| a.version); return match landed { Some(n) => format!("what you landed as main {n} (change {})", app.short(project, after)), None => format!("change {}", app.short(project, after)), }; } main_label(c.base_version) } fn change_json(app: &App, project: &Project, c: &Change) -> serde_json::Value { json!({ "id": c.id, "short": app.short(project, &c.id), "title": c.title, "body": c.body, "state": c.state, "base": c.base_version, "on": c.on_change, "saves": c.saves, "version": c.version, "author": c.author, "conflicts": c.conflicts.iter().map(|x| &x.path).collect::>(), }) } fn require_title(c: &Change) -> Result<(), Fail> { if c.title.trim().is_empty() { return Err(Fail::new("no_description", format!("change {} has no description", c.id)) .state("nothing changed; your change is saved") .next(format!("vcs land -m \"what you did\""))); } Ok(()) } // Start. pub fn init(app: &App, folder: Option) -> Out { let root = folder.map(|f| app.cwd.join(f)).unwrap_or_else(|| app.cwd.clone()); std::fs::create_dir_all(&root)?; let root = root.canonicalize()?; if ws::find(&root).is_some() { return Err(Fail::new("bad_usage", format!("{} is already in a vcs workspace", root.display())).state("nothing changed")); } let project = Project { id: format!("local-{}", ids::new_workspace_id()), address: root.to_string_lossy().into_owned(), kind: "local".into(), api: None, checked: ids::now(), }; app.db.put_project(&project)?; let empty = app.store.put(&tree::empty())?; let author = app.author(&project); let change = Change::new(ids::new_change_id(), &project.id, empty, None, &author); app.db.put_change(&change)?; let workspace = Workspace { id: ids::new_workspace_id(), project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: vec![] }; ws::write_id(&root, &workspace.id)?; app.db.put_workspace(&workspace)?; let mut s = app.session_at(&root)?; let saved = app.save(&mut s)?; let mut r = Report::new(); r.line("project", format!("{} (on this machine only)", project.address)) .line("workspace", root.display().to_string()) .line("change", format!("{} new{}", app.short(&project, &change.id), if saved.is_empty() { ", empty" } else { ", holds the files already here" })) .set("project", project.address.clone()) .set("workspace", root.display().to_string()) .set("change", change_json(app, &project, &saved)) .next("add or edit files, then vcs land -m \"First version\""); Ok(r) } /// `vcs get`. pub fn get(app: &App, target: &str, folder: Option, change_id: Option, only: Vec) -> Out { let project = resolve_project(app, target)?; let name = project.address.trim_end_matches('/').rsplit('/').next().unwrap_or("project").to_string(); let root = app.cwd.join(folder.unwrap_or_else(|| PathBuf::from(&name))); ensure_dir_empty(&root)?; let main = app.refresh(&project)?; let only: Vec = only.into_iter().map(|o| o.trim_matches('/').to_string()).filter(|o| !o.is_empty()).collect(); let author = app.author(&project); let workspace_id = ids::new_workspace_id(); let mut took_from = None; let (change, tree) = match change_id { Some(text) => { let mut c = app.find_change(&project, &text)?; if c.state == "landed" || c.state == "dropped" { return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); } took_from = take_over(app, &project, &mut c, &workspace_id, &root)?; let t = c.tree(); (c, t) } None => { let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); let c = Change::new(ids::new_change_id(), &project.id, base, main.as_ref().map(|v| v.n), &author); app.db.put_change(&c)?; (c, base) } }; std::fs::create_dir_all(&root)?; let root = root.canonicalize()?; let workspace = Workspace { id: workspace_id, project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: only.clone() }; ws::write_id(&root, &workspace.id)?; // Copy unchanged files from the most recent workspace of this project. let source = app.db.project_workspaces(&project.id)?.into_iter().find(|w| w.path.join(ws::DIR).is_dir() && w.path != root); let source_index = source.as_ref().map(|w| Index::load(&w.path)); app.host(&project).fetch_tree(&app.store, &project, &tree, None)?; let files = app.files(&tree)?; let cow = match (&source, &source_index) { (Some(w), Some(i)) => Some(CowSource { root: &w.path, index: i }), _ => None, }; let mut index = ws::materialize(&root, &app.store, &Index::default(), &files, &only, cow)?; index.save(&root)?; app.db.put_workspace(&workspace)?; let mut copied = Vec::new(); if let Some(w) = &source { for folder in ws::config(&root).workspace.copy { let folder = folder.trim_matches('/'); if folder.is_empty() || folder.contains("..") { continue; } let n = ws::copy_folder(&w.path.join(folder), &root.join(folder))?; if n > 0 { copied.push(format!("{folder} from {} ({n} files)", w.path.display())); } } } let _ = crate::remote::pull_mine(app, &project); let mine = app.place_mine(&project, &root)?; // One save now: it records the tree in the index and reads every new // folder once, so the first command after this one is quick. let mut fresh = app.session_at(&root)?; app.save(&mut fresh)?; let mut r = Report::new(); r.line("workspace", format!("{} ({})", root.display(), project.address)); if let Some(from) = &took_from { r.line("took over", format!("from {from}")); } let state = if change.is_empty() { "new, empty".to_string() } else { format!("{} saves", change.saves) }; r.line("change", format!("{} {}, on {}", app.short(&project, &change.id), state, base_text(app, &project, &change))); if !only.is_empty() { r.line("only", only.join(", ")); } for c in &copied { r.line("copied", c.clone()); } if mine > 0 { r.line("yours", format!("{mine} private files (like .env) placed")); } r.set("workspace", root.display().to_string()) .set("project", project.address.clone()) .set("main", main.as_ref().map(|v| v.n)) .set("change", change_json(app, &project, &change)) .next("edit files, then vcs land -m \"what you did\""); Ok(r) } /// A project by address: a hosted `host/owner/name`, or a local folder. fn resolve_project(app: &App, target: &str) -> Result { let path = app.cwd.join(target); if target.starts_with('/') || target.starts_with('.') || target.starts_with('~') || path.join(ws::DIR).is_dir() { let root = ws::find(&path).ok_or_else(|| { Fail::new("not_found", format!("{target} isn't a vcs workspace")).state("nothing changed").next("vcs init to start a project there") })?; let id = ws::read_id(&root)?; let w = app.db.workspace(&id)?.ok_or_else(|| Fail::new("not_found", "that workspace isn't known on this machine"))?; return app.db.project(&w.project)?.ok_or_else(|| Fail::new("not_found", "that workspace's project is missing")); } crate::remote::project(app, target) } /// Makes `workspace` the one holding `change`: on the host (the other /// workspace finds out on its next save) and on this machine. fn take_over(app: &App, project: &Project, change: &mut Change, workspace: &str, path: &Path) -> Result, Fail> { let mut previous = None; if project.hosted() { let remote = crate::remote::Remote::for_project(project); remote.fetch_saves(&app.db, &app.store, project, change)?; previous = remote.hold(&change.id, workspace, &crate::remote::label(path))?; *change = app.change(&change.id)?; } if let Some(holder) = app.db.workspace_holding(&change.id)? && holder.id != workspace { previous = Some(holder.path.display().to_string()); release(app, project, holder)?; } Ok(previous) } // See. pub fn status(app: &App, which: Option) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let c = match which { Some(text) => app.find_change(&s.project, &text)?, None => current, }; app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; let main = app.main(&s.project)?; let mut r = Report::new(); r.line("project", s.project.address.clone()).line("workspace", s.root.display().to_string()); let who = if c.author == app.author(&s.project) { "yours".to_string() } else { c.author.clone() }; let title = if c.title.is_empty() { "(no description yet)".to_string() } else { format!("\"{}\"", c.title) }; r.line("change", format!("{} {} {}, {}", app.short(&s.project, &c.id), title, c.state, who)); match c.state.as_str() { "landed" => { r.line("landed", format!("as main {}", c.version.map(|v| v.to_string()).unwrap_or("?".into()))); } "waiting" => { r.line("waiting", "for someone with landing rights to land it"); } _ => { let behind = match (c.base_version, &main) { (Some(b), Some(m)) if m.n > b && c.on_change.is_none() => format!(" (main is at {}; land merges the difference)", m.n), _ => String::new(), }; r.line("based on", format!("{}{behind}", base_text(app, &s.project, &c))); } } if c.saves > 0 { let last = app.db.save(&c.id, c.saves)?.map(|sv| sv.at).unwrap_or(c.updated); r.line("saved", format!("{} (save {})", ids::ago(last), c.saves)); } let changes = tree::diff_trees(&app.store, &c.base_tree, &c.tree())?; let mut list = Vec::new(); for (path, change) in &changes { let mark = match change { tree::Change::Added(_) => "A", tree::Change::Removed(_) => "D", tree::Change::Modified(..) => "M", }; list.push(format!("{mark} {path}")); } if list.is_empty() { r.line("files", "no changes yet"); } else { let shown: Vec = list.iter().take(50).cloned().collect(); let more = if list.len() > 50 { format!("\n… and {} more", list.len() - 50) } else { String::new() }; r.line("files", format!("{}{more}", shown.join("\n"))); } if !c.conflicts.is_empty() { r.line("conflicts", c.conflicts.iter().map(|x| x.path.clone()).collect::>().join("\n")); } r.set("project", s.project.address.clone()) .set("workspace", s.root.display().to_string()) .set("change", change_json(app, &s.project, &c)) .set("main", main.as_ref().map(|v| v.n)) .set("files", list.clone()); if c.state == "open" { if !c.conflicts.is_empty() { r.next(format!("fix the marked lines in {}, then vcs land", c.conflicts[0].path)); } else if list.is_empty() { r.next("edit files, then vcs land -m \"what you did\""); } else if c.title.is_empty() { r.next("vcs land -m \"what you did\""); } else { r.next("vcs land"); } } Ok(r) } /// Resolves a reference: a version number, `main`, a change, or change:save. fn resolve_tree(app: &App, project: &Project, text: &str) -> Result<(Id, String), Fail> { if text == "main" { let v = app.refresh(project)?.ok_or_else(|| Fail::new("not_found", "main has no versions yet"))?; app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; return Ok((v.tree, format!("main {}", v.n))); } if let Ok(n) = text.parse::() { let v = version(app, project, n)?; app.host(project).fetch_tree(&app.store, project, &v.tree, None)?; return Ok((v.tree, format!("main {n}"))); } if let Some((id, save)) = text.split_once(':') { let c = app.find_change(project, id)?; let n: i64 = save.parse().map_err(|_| Fail::new("bad_usage", format!("{text}: save numbers are whole numbers")))?; let sv = app.db.save(&c.id, n)?.ok_or_else(|| Fail::new("not_found", format!("change {} has no save {n}", c.id)))?; return Ok((sv.tree, format!("save {n} of {}", app.short(project, &c.id)))); } let c = app.find_change(project, text)?; Ok((c.tree(), format!("change {}", app.short(project, &c.id)))) } fn version(app: &App, project: &Project, n: u64) -> Result { if let Some(v) = app.db.version(&project.id, n)? { return Ok(v); } app.refresh(project)?; app.db.version(&project.id, n)?.ok_or_else(|| Fail::new("not_found", format!("main has no version {n}")).state("nothing changed")) } pub fn diff_cmd(app: &App, paths: Vec, change: Option, from: Option, to: Option, stat: bool) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let c = match change { Some(t) => app.find_change(&s.project, &t)?, None => current, }; app.host(&s.project).fetch_tree(&app.store, &s.project, &c.base_tree, None)?; app.host(&s.project).fetch_tree(&app.store, &s.project, &c.tree(), Some(&c.base_tree))?; let (a, a_label) = match &from { Some(t) => resolve_tree(app, &s.project, t)?, None => (c.base_tree, "base".to_string()), }; let (b, b_label) = match &to { Some(t) => resolve_tree(app, &s.project, t)?, None => (c.tree(), "change".to_string()), }; let paths: Vec = paths.into_iter().map(|p| p.trim_matches('/').to_string()).collect(); let mut text = String::new(); let mut stats = Vec::new(); let (mut adds, mut dels) = (0usize, 0usize); for (path, ch) in tree::diff_trees(&app.store, &a, &b)? { if !paths.is_empty() && !paths.iter().any(|p| p == "." || tree::under(&path, p)) { continue; } let (old, new) = match ch { tree::Change::Added(e) => (None, Some(e)), tree::Change::Removed(e) => (Some(e), None), tree::Change::Modified(o, n) => (Some(o), Some(n)), }; let read = |e: Option| -> Result, Fail> { match e { Some(e) => Ok(app.store.read_file(&e.id)?), None => Ok(Vec::new()), } }; let (ob, nb) = (read(old)?, read(new)?); if diff::is_binary(&ob) || diff::is_binary(&nb) { text.push_str(&format!("Binary file {path} changed\n")); stats.push(json!({ "path": path, "binary": true })); continue; } let (added, removed) = diff::counts(&ob, &nb); adds += added; dels += removed; stats.push(json!({ "path": path, "added": added, "removed": removed })); if !stat { 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() })); if old.is_some() && new.is_some() && old.unwrap().kind != new.unwrap().kind { text.push_str(&format!("kind {} → {}\n", old.unwrap().kind.name(), new.unwrap().kind.name())); } text.push_str(&diff::unified(&ob, &nb, 3)); } else { text.push_str(&format!("{path} | +{added} -{removed}\n")); } } let mut r = Report::new(); if text.is_empty() { r.line("diff", format!("no differences between {a_label} and {b_label}")); } else { r.raw(text); if stat { r.raw(format!("{} files, +{adds} -{dels}\n", stats.len())); } } r.set("from", a_label).set("to", b_label).set("files", stats).set("added", adds).set("removed", dels); Ok(r) } pub fn log(app: &App, what: Option, changes: bool, saves: bool, ops: bool, limit: i64) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let mut r = Report::new(); if changes { let list = crate::remote::visible_changes(app, &s.project)?; let mut rows = Vec::new(); for c in &list { if c.state != "open" && c.state != "waiting" { continue; } if c.is_empty() && c.id != current.id { continue; } let held = app.db.workspace_holding(&c.id)?.map(|w| w.path.display().to_string()).unwrap_or_else(|| "no workspace here".into()); let title = if c.title.is_empty() { "(no description)".to_string() } else { c.title.clone() }; let here = if c.id == current.id { " ← this workspace" } else { "" }; r.raw(format!("{} {:<8} {} {} [{}]{here}\n", app.short(&s.project, &c.id), c.state, title, c.author, held)); rows.push(json!({ "change": change_json(app, &s.project, c), "workspace": held })); } if rows.is_empty() { r.line("changes", "no open changes"); } r.set("changes", rows); return Ok(r); } if saves { let list = app.db.saves(¤t.id)?; for sv in &list { r.raw(format!("{}:{} {} ({})\n", app.short(&s.project, ¤t.id), sv.n, ids::clock(sv.at), ids::ago(sv.at))); } if list.is_empty() { r.line("saves", "nothing saved yet in this change"); } r.set("saves", list.iter().map(|sv| json!({ "n": sv.n, "at": sv.at, "tree": sv.tree })).collect::>()); return Ok(r); } if ops { let list = app.db.ops(&s.ws.id, limit)?; for (op, undone) in &list { r.raw(format!("{} {:<9} {}{}\n", ids::clock(op.at), op.kind, op_summary(op), if *undone { " (undone)" } else { "" })); } if list.is_empty() { r.line("operations", "none yet in this workspace"); } r.set("ops", list.iter().map(|(op, undone)| json!({ "kind": op.kind, "at": op.at, "undone": undone, "data": op.data })).collect::>()); return Ok(r); } if let Some(what) = what { if let Ok(n) = what.parse::() { let v = version(app, &s.project, n)?; let prev_tree = match n { 1 => tree::empty_id(), _ => version(app, &s.project, n - 1)?.tree, }; app.host(&s.project).fetch_tree(&app.store, &s.project, &v.tree, None)?; app.host(&s.project).fetch_tree(&app.store, &s.project, &prev_tree, None)?; let changed = tree::diff_trees(&app.store, &prev_tree, &v.tree)?; r.line("version", format!("main {}", v.n)) .line("title", v.title.clone()) .line("author", v.author.clone()) .line("landed", format!("{} ({})", ids::clock(v.time), ids::ago(v.time))); if !v.change.is_empty() { r.line("change", v.change.clone()); } if !v.body.is_empty() { r.line("about", v.body.clone()); } if let Some(g) = &v.git { r.line("git", g.clone()); } r.line("files", changed.keys().take(50).cloned().collect::>().join("\n")); r.set("version", serde_json::to_value(&v).unwrap_or_default()).set("files", changed.keys().cloned().collect::>()); return Ok(r); } let c = app.find_change(&s.project, &what)?; r.line("change", app.short(&s.project, &c.id)) .line("title", if c.title.is_empty() { "(no description)".into() } else { c.title.clone() }) .line("state", c.state.clone()) .line("author", c.author.clone()) .line("saves", c.saves.to_string()); if let Some(v) = c.version { r.line("landed", format!("as main {v}")); } r.set("change", change_json(app, &s.project, &c)); return Ok(r); } app.refresh(&s.project)?; let list = app.db.versions(&s.project.id, limit)?; for v in &list { r.raw(format!("{:>6} {} {} {}\n", v.n, v.title, short_author(&v.author), ids::ago(v.time))); } if list.is_empty() { r.line("main", "no versions yet"); r.next("vcs land -m \"First version\""); } 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::>()); Ok(r) } fn short_author(author: &str) -> String { author.split(" <").next().unwrap_or(author).to_string() } fn op_summary(op: &crate::db::Op) -> String { let d = &op.data; let s = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); match op.kind.as_str() { "land" => format!("change {} as main {}", s("change"), d.get("version").and_then(|v| v.as_u64()).unwrap_or(0)), "sync" => format!("change {} onto {}", s("change"), s("onto")), "new" | "switch" => format!("from {} to {}", s("from"), s("to")), "drop" => format!("change {}", s("change")), "describe" => format!("change {}", s("change")), "restore" => format!("{} from {}", s("paths"), s("source")), "access" => format!("{} → {}", s("target"), s("who")), "undo" => s("what"), _ => String::new(), } } // Work. pub fn new(app: &App, title: Option, on: Option) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let author = app.author(&s.project); let mut c = match &on { Some(text) => { let parent = app.find_change(&s.project, text)?; if parent.state == "landed" || parent.state == "dropped" { return Err(Fail::new("bad_usage", format!("change {} is {}; start from main instead", parent.id, parent.state)) .state("nothing changed") .next("vcs new")); } if s.project.hosted() { crate::remote::Remote::for_project(&s.project).fetch_saves(&app.db, &app.store, &s.project, &parent)?; } let mut c = Change::new(ids::new_change_id(), &s.project.id, parent.tree(), None, &author); c.on_change = Some(parent.id.clone()); c } None => { let main = app.refresh(&s.project)?; let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &author) } }; if let Some(t) = title { set_description(&mut c, &[t]); } app.db.put_change(&c)?; app.show_tree(&s, &c.base_tree)?; app.put_workspace_change(&mut s, &c.id)?; app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": c.id }))?; let mut r = Report::new(); r.line("change", format!("{} new, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); let kept = if current.is_empty() { "(it was empty)".to_string() } else { "is saved; vcs switch goes back to it".to_string() }; r.line("kept", format!("{} {kept}", app.short(&s.project, ¤t.id))); r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); r.next("edit files, then vcs land"); Ok(r) } fn set_description(c: &mut Change, parts: &[String]) { let text = parts.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).collect::>().join("\n\n"); let mut lines = text.splitn(2, '\n'); c.title = lines.next().unwrap_or("").trim().to_string(); c.body = lines.next().unwrap_or("").trim().to_string(); } pub fn describe(app: &App, parts: Vec) -> Out { let mut s = app.session()?; let mut c = app.save(&mut s)?; if parts.iter().all(|p| p.trim().is_empty()) { return Err(Fail::new("bad_usage", "give a description").state("nothing changed").next("vcs describe \"Title\" \"More detail\"")); } let before = json!({ "change": c.id, "title": c.title, "body": c.body }); set_description(&mut c, &parts); app.db.put_change(&c)?; app.db.add_op(&s.ws.id, "describe", &before)?; let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); let mut r = Report::new(); r.line("change", format!("{} \"{}\"", app.short(&s.project, &c.id), c.title)).set("change", change_json(app, &s.project, &c)); r.next("vcs land"); Ok(r) } pub fn switch(app: &App, target: &str) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let mut c = app.find_change(&s.project, target)?; if c.id == current.id { let mut r = Report::new(); r.line("change", format!("{} is already this workspace's change", app.short(&s.project, &c.id))); return Ok(r); } if c.state == "landed" || c.state == "dropped" { return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)) .state("nothing changed") .next(if c.state == "dropped" { "vcs undo (if you just dropped it)" } else { "vcs new" })); } let took_from = take_over(app, &s.project, &mut c, &s.ws.id.clone(), &s.root.clone())?; if let Some(from) = &took_from { app.notes.borrow_mut().push(format!("took change {} over from {from}", c.id)); } app.show_tree(&s, &c.tree())?; app.put_workspace_change(&mut s, &c.id)?; app.db.add_op(&s.ws.id, "switch", &json!({ "from": current.id, "to": c.id }))?; let mut r = Report::new(); let title = if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) }; r.line("change", format!("{}{title}, on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); r.set("change", change_json(app, &s.project, &c)).set("previous", current.id.clone()); r.next("keep working, then vcs land"); Ok(r) } /// Moves another workspace on this machine off a change someone took over: /// it gets a fresh change on the same base, so its next save can't touch the /// taken change. fn release(app: &App, project: &Project, mut holder: Workspace) -> Result<(), Fail> { let taken = app.change(&holder.change)?; let mut fresh = Change::new(ids::new_change_id(), &project.id, taken.tree(), None, &taken.author); fresh.title = format!("Rescued from {}", taken.id); fresh.after_change = Some(taken.id.clone()); app.db.put_change(&fresh)?; holder.change = fresh.id; app.db.put_workspace(&holder)?; Ok(()) } pub fn drop(app: &App, target: Option) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let mut c = match target { Some(t) => app.find_change(&s.project, &t)?, None => current.clone(), }; if c.state == "landed" { return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))) .state("nothing changed") .next(format!("vcs undo {}", c.version.unwrap_or(0)))); } c.state = "dropped".into(); app.db.put_change(&c)?; let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); let mut r = Report::new(); let mut data = json!({ "change": c.id, "current": c.id == current.id }); r.line("dropped", format!("{}{}", app.short(&s.project, &c.id), if c.title.is_empty() { String::new() } else { format!(" \"{}\"", c.title) })); if c.id == current.id { let main = app.refresh(&s.project)?; let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); let fresh = Change::new(ids::new_change_id(), &s.project.id, base, main.as_ref().map(|v| v.n), &app.author(&s.project)); app.db.put_change(&fresh)?; app.show_tree(&s, &base)?; app.put_workspace_change(&mut s, &fresh.id)?; data["replacement"] = json!(fresh.id); r.line("change", format!("{} new, on {}", app.short(&s.project, &fresh.id), main_label(main.map(|v| v.n)))); } app.db.add_op(&s.ws.id, "drop", &data)?; r.set("dropped", c.id.clone()); r.next("vcs undo brings it back"); Ok(r) } // Finish. pub fn sync(app: &App) -> Out { let mut s = app.session()?; let mut c = app.save(&mut s)?; if c.state != "open" { return Err(Fail::new("bad_usage", format!("change {} is {}", c.id, c.state)).state("nothing changed")); } // Onto the change it's stacked on while that hasn't landed, else main. let parent = match &c.on_change { Some(p) => Some(app.change(p)?), None => None, }; let (target_tree, target_version, label, still_on) = match parent.as_ref().filter(|p| p.state == "open" || p.state == "waiting") { Some(p) => (p.tree(), None, format!("change {}", app.short(&s.project, &p.id)), Some(p.id.clone())), None => { let main = app.refresh(&s.project)?; let t = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); app.host(&s.project).fetch_tree(&app.store, &s.project, &t, Some(&c.base_tree))?; (t, main.as_ref().map(|v| v.n), main_label(main.as_ref().map(|v| v.n)), None) } }; if target_tree == c.base_tree { let mut r = Report::new(); r.line("synced", format!("{} is already on {label}", app.short(&s.project, &c.id))).set("change", change_json(app, &s.project, &c)); r.next("vcs land"); return Ok(r); } let ours_label = label.clone(); let theirs_label = format!("your change {}", app.short(&s.project, &c.id)); let m = merge::trees(&app.store, Some(&c.base_tree), &target_tree, &c.tree(), Mode::Sync, (&ours_label, &theirs_label))?; for o in m.objects.objects.values() { app.store.put(o)?; } let before = json!({ "change": c.id, "onto": label, "base_tree": c.base_tree, "base_version": c.base_version, "on_change": c.on_change, "after_change": c.after_change, "head_tree": c.head_tree, "conflicts": c.conflicts, }); let was = base_text(app, &s.project, &c); c.base_tree = target_tree; c.base_version = target_version; c.on_change = still_on; c.after_change = None; c.head_tree = Some(m.tree); c.saves += 1; c.conflicts = m.conflicts.iter().map(|x| Conflict { path: x.path.clone(), version: target_version }).collect(); 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)?; app.db.put_change(&c)?; app.show_tree(&s, &m.tree)?; app.db.add_op(&s.ws.id, "sync", &before)?; let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); let mut r = Report::new(); r.line("synced", format!("{} onto {label} (was {was})", app.short(&s.project, &c.id))); for x in &m.conflicts { r.line("conflict", x.path.clone()); } for n in &m.notes { r.line("note", n.message.clone()); } r.set("change", change_json(app, &s.project, &c)) .set("conflicts", m.conflicts.iter().map(|x| x.path.clone()).collect::>()) .set("notes", m.notes.iter().map(|n| n.message.clone()).collect::>()); if m.conflicts.is_empty() { r.next("vcs land"); } else { r.exit = 3; r.next(format!("fix the marked lines in {}, then vcs land", m.conflicts.iter().map(|x| x.path.as_str()).collect::>().join(", "))); } Ok(r) } pub fn land(app: &App, target: Option, messages: Vec, allow_secrets: bool) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; let mut c = match target { Some(t) => { let found = app.find_change(&s.project, &t)?; // Someone else's change: take the host's newest state and content. if s.project.hosted() && found.id != current.id { crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, &found.id)?.unwrap_or(found) } else { found } } None => current.clone(), }; if !messages.is_empty() { let before = json!({ "change": c.id, "title": c.title, "body": c.body }); set_description(&mut c, &messages); app.db.put_change(&c)?; app.db.add_op(&s.ws.id, "describe", &before)?; } if c.state == "landed" { return Err(Fail::new("bad_usage", format!("change {} already landed as main {}", c.id, c.version.unwrap_or(0))).state("nothing changed")); } if c.state == "dropped" { return Err(Fail::new("bad_usage", format!("change {} was dropped", c.id)).state("nothing changed").next("vcs undo (if you just dropped it)")); } if c.is_empty() { let mut f = Fail::new("empty_change", format!("change {} has nothing to land", app.short(&s.project, &c.id))).state("nothing changed"); if c.after_change.is_some() { f = f.next("you're on a fresh change after a landing; edit files first"); } else { f = f.next("edit files first"); } return Err(f); } if !c.conflicts.is_empty() { return Err(Fail::new("conflict", format!("change {} still has conflict markers", app.short(&s.project, &c.id))) .detail(c.conflicts.iter().map(|x| x.path.clone()).collect::>().join(", ")) .state("main didn't change; your change is saved") .next("fix the marked lines, then vcs land")); } require_title(&c)?; // Land what it's stacked on first, in order. let mut stack = vec![c.clone()]; let mut parent = c.on_change.clone(); while let Some(p) = parent { let pc = app.change(&p)?; if pc.state != "open" && pc.state != "waiting" { break; } require_title(&pc)?; parent = pc.on_change.clone(); stack.push(pc); } stack.reverse(); let mut r = Report::new(); let mut landed_versions = Vec::new(); for (i, item) in stack.iter().enumerate() { let mut item = app.change(&item.id)?; let host = app.host(&s.project); host.fetch_tree(&app.store, &s.project, &item.base_tree, None)?; host.fetch_tree(&app.store, &s.project, &item.tree(), Some(&item.base_tree))?; if !allow_secrets { let found = secrets::scan(&app.store, &item.base_tree, &item.tree())?; if let Some(hit) = found.first() { 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)) .detail(format!("{}:{}", hit.path, hit.line)) .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()) }) .next(format!("remove it from {} (put real secrets in .env, which stays yours), then vcs land", hit.path)) .set("secrets", serde_json::to_value(&found).unwrap_or_default())); } } let request = LandRequest { change: item.id.clone(), base_tree: item.base_tree, tree: item.tree(), title: item.title.clone(), body: item.body.clone(), author: item.author.clone(), allow_secrets, }; let outcome = host.land(&app.db, &app.store, &s.project, &request)?; match outcome { Landed::Landed { version } => { item.state = "landed".into(); item.version = Some(version.n); app.db.put_change(&item)?; app.db.put_version(&s.project.id, &version)?; let _ = host.publish_change(&app.db, &app.store, &s.project, &item, &s.ws.id); landed_versions.push((item.id.clone(), version.clone())); r.line("landed", format!("{} as main {} \"{}\"", app.short(&s.project, &item.id), version.n, version.title)); } Landed::Conflict { main, conflicts } => { let state = if landed_versions.is_empty() { "main didn't change; your change is saved".to_string() } else { 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::>().join(", ")) }; 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" })); for x in &conflicts { f = f.detail(format!("{}{}", x.path, if x.kind == "text" { String::new() } else { format!(" ({})", x.kind) })); } 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()) .set("main", main)); } Landed::Waiting { asked, reason } => { item.state = "waiting".into(); app.db.put_change(&item)?; r.line("waiting", format!("{} {reason}", app.short(&s.project, &item.id))); if !asked.is_empty() { r.line("asked", asked.join(", ")); } r.exit = 5; r.set("waiting", json!({ "change": item.id, "asked": asked })); r.next(format!("vcs status {} later", app.short(&s.project, &item.id))); // The workspace moves on, so later edits don't change what's waiting. if item.id == current.id { let fresh = continue_after(app, &mut s, &item)?; r.line("change", format!("{} new, on top of the waiting change", app.short(&s.project, &fresh.id))); } return Ok(r); } Landed::ChecksFailed { check, log } => { return Err(Fail::new("checks_failed", format!("can't land {}: check \"{check}\" failed on the merged result", app.short(&s.project, &item.id))) .detail(log.map(|l| format!("log: {l}")).unwrap_or_default()) .state("main didn't change; your change is saved") .next("fix it, then vcs land again")); } } } let (last_id, last_version) = landed_versions.last().cloned().unwrap(); if let Some(prev) = app.db.version(&s.project.id, last_version.n.saturating_sub(1))? && let Some(first) = stack.first() && let Some(b) = first.base_version && prev.n > b { r.line("merged", format!("with {} versions that landed since main {b}", prev.n - b)); } 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::>() }))?; if stack.iter().any(|x| x.id == current.id) { let fresh = continue_after(app, &mut s, &app.change(¤t.id)?)?; r.line("change", format!("{} new, empty, on top of what you just landed", app.short(&s.project, &fresh.id))); r.set("change", change_json(app, &s.project, &fresh)); } r.set("landed", landed_versions.iter().map(|(id, v)| json!({ "change": id, "version": v.n, "title": v.title })).collect::>()) .set("main", last_version.n); r.next("keep working, or vcs sync to bring in others' work"); Ok(r) } /// After a landing (or a land that's waiting), the workspace continues on a /// fresh change on top of what it had, without touching files. fn continue_after(app: &App, s: &mut Session, done: &Change) -> Result { let mut fresh = Change::new(ids::new_change_id(), &s.project.id, done.tree(), None, &app.author(&s.project)); if done.state == "waiting" { fresh.on_change = Some(done.id.clone()); } else { fresh.after_change = Some(done.id.clone()); } app.db.put_change(&fresh)?; app.put_workspace_change(s, &fresh.id)?; Ok(fresh) } // Fix. pub fn undo(app: &App, version_n: Option) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; if let Some(n) = version_n { let (v, revert) = take_back(app, &s, n)?; let mut r = Report::new(); r.line("undid", format!("main {} (\"{}\"): main {} takes it back out", v.n, v.title, revert.n)); if let Some(mut c) = app.db.change(&v.change)? { c.state = "open".into(); c.version = None; app.db.put_change(&c)?; 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))); } app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back main {}", v.n) }))?; r.set("undid", v.n).set("main", revert.n); return Ok(r); } 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"))?; let d = op.data.clone(); let text = |k: &str| d.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); let mut r = Report::new(); match op.kind.as_str() { "new" | "switch" => { let back = app.change(&text("from"))?; app.show_tree(&s, &back.tree())?; app.put_workspace_change(&mut s, &back.id)?; r.line("undid", format!("{}: back on change {}", op.kind, app.short(&s.project, &back.id))); if current.is_empty() && op.kind == "new" { let mut gone = current.clone(); gone.state = "dropped".into(); app.db.put_change(&gone)?; } else { r.line("kept", format!("{} is saved", app.short(&s.project, ¤t.id))); } } "drop" => { let mut c = app.change(&text("change"))?; c.state = "open".into(); app.db.put_change(&c)?; if d.get("current").and_then(|v| v.as_bool()) == Some(true) { app.show_tree(&s, &c.tree())?; app.put_workspace_change(&mut s, &c.id)?; if let Some(rep) = d.get("replacement").and_then(|v| v.as_str()) { if let Some(mut x) = app.db.change(rep)? && x.is_empty() { x.state = "dropped".into(); app.db.put_change(&x)?; } } } r.line("undid", format!("drop: change {} is back", app.short(&s.project, &c.id))); } "describe" => { let mut c = app.change(&text("change"))?; c.title = text("title"); c.body = text("body"); app.db.put_change(&c)?; r.line("undid", format!("describe: change {} has its old description", app.short(&s.project, &c.id))); } "sync" => { let mut c = app.change(&text("change"))?; let id = |k: &str| d.get(k).and_then(|v| v.as_str()).and_then(Id::parse); c.base_tree = id("base_tree").unwrap_or(c.base_tree); c.base_version = d.get("base_version").and_then(|v| v.as_u64()); c.on_change = d.get("on_change").and_then(|v| v.as_str()).map(str::to_string); c.after_change = d.get("after_change").and_then(|v| v.as_str()).map(str::to_string); c.head_tree = id("head_tree"); c.conflicts = serde_json::from_value(d.get("conflicts").cloned().unwrap_or_default()).unwrap_or_default(); c.saves += 1; 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)?; app.db.put_change(&c)?; app.show_tree(&s, &c.tree())?; r.line("undid", format!("sync: change {} is back on {}", app.short(&s.project, &c.id), base_text(app, &s.project, &c))); } "restore" => { 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"))?; app.show_tree(&s, &tree)?; app.save(&mut s)?; r.line("undid", format!("restore of {}", text("paths"))); } "land" => { let n = d.get("version").and_then(|v| v.as_u64()).unwrap_or(0); let (v, revert) = take_back(app, &s, n)?; let mut c = app.change(&text("change"))?; c.state = "open".into(); c.version = None; // Edits made since the land come along. let after = current; c.head_tree = Some(after.tree()); if after.id != c.id { let mut x = after.clone(); x.state = "dropped".into(); app.db.put_change(&x)?; } c.saves += 1; 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)?; app.db.put_change(&c)?; app.put_workspace_change(&mut s, &c.id)?; r.line("undid", format!("land of {}: main {} takes main {} back out", app.short(&s.project, &c.id), revert.n, v.n)) .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); r.next("fix it, then vcs land"); } "access" => { crate::access::undo(app, &s, &d)?; r.line("undid", format!("access change for {}", text("target"))); } "undo" => { 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")); } other => return Err(Fail::new("failed", format!("can't undo {other}")).state("nothing changed")), } app.db.mark_undone(op.id)?; r.set("undid", op.kind.clone()).set("data", d); Ok(r) } /// Lands a change that reverses version `n` on the latest main. fn take_back(app: &App, s: &Session, n: u64) -> Result<(Version, Version), Fail> { let v = version(app, &s.project, n)?; let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; let main = app.refresh(&s.project)?.ok_or_else(|| Fail::new("not_found", "main has no versions"))?; let host = app.host(&s.project); for t in [&v.tree, &before, &main.tree] { host.fetch_tree(&app.store, &s.project, t, None)?; } // Merge "version → version before it" onto main. let m = merge::trees(&app.store, Some(&v.tree), &main.tree, &before, Mode::Land, ("main", "the undo"))?; if !m.clean() { return Err(Fail::new("conflict", format!("can't take back main {n}: later versions changed the same lines")) .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::>().join(", ")) .state("main didn't change") .next("make a new change that undoes it by hand, then vcs land")); } for o in m.objects.objects.values() { app.store.put(o)?; } let request = LandRequest { change: ids::new_change_id(), base_tree: main.tree, tree: m.tree, title: format!("Take back main {n}: {}", v.title), body: format!("Undoes main {n}."), author: app.author(&s.project), allow_secrets: true, }; match host.land(&app.db, &app.store, &s.project, &request)? { Landed::Landed { version } => { app.db.put_version(&s.project.id, &version)?; Ok((v, version)) } Landed::Conflict { .. } => Err(Fail::new("conflict", format!("main moved while taking back main {n}")).state("main didn't change").next("vcs undo again")), Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state("main didn't change")), Landed::ChecksFailed { check, .. } => Err(Fail::new("checks_failed", format!("check \"{check}\" failed on the undo")).state("main didn't change")), } } pub fn restore(app: &App, paths: Vec, at: Option, from: Option) -> Out { let mut s = app.session()?; let c = app.save(&mut s)?; if paths.is_empty() { return Err(Fail::new("bad_usage", "say which files to restore (. for all)").state("nothing changed").next("vcs restore ")); } let (source, label) = match (&at, &from) { (Some(_), Some(_)) => return Err(Fail::new("bad_usage", "use --at or --from, not both").state("nothing changed")), (Some(when), None) => { 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"))?; let sv = app.db.save_at(&s.ws.id, t)?.ok_or_else(|| { Fail::new("not_found", format!("nothing was saved in this workspace by {}", ids::clock(t))).state("nothing changed") })?; (sv.tree, format!("save {} ({})", sv.n, ids::ago(sv.at))) } (None, Some(r)) => resolve_tree(app, &s.project, r)?, (None, None) => (c.base_tree, "the change's base".to_string()), }; let src = app.files(&source)?; let mut now = app.files(&c.tree())?; let wants: Vec = paths.iter().map(|p| { let abs = app.cwd.join(p); abs.strip_prefix(&s.root).map(|r| r.to_string_lossy().into_owned()).unwrap_or_else(|_| p.clone()) }).map(|p| p.trim_matches('/').to_string()).map(|p| if p == "." { String::new() } else { p }).collect(); let mut touched = 0; for want in &wants { let before: Vec = now.keys().filter(|p| tree::under(p, want)).cloned().collect(); for p in before { now.remove(&p); touched += 1; } for (p, e) in src.iter().filter(|(p, _)| tree::under(p, want)) { now.insert(p.clone(), *e); touched += 1; } } if touched == 0 { return Err(Fail::new("not_found", format!("no files match {}", paths.join(", "))).state("nothing changed")); } let (tree_id, objects) = tree::build(&now); for o in &objects { app.store.put(o)?; } let before_tree = c.tree(); app.show_tree(&s, &tree_id)?; let saved = app.save(&mut s)?; app.db.add_op(&s.ws.id, "restore", &json!({ "change": c.id, "before": before_tree, "paths": paths.join(" "), "source": label }))?; let mut r = Report::new(); r.line("restored", format!("{} from {label}", paths.join(", "))); r.set("restored", paths.clone()).set("source", label).set("change", change_json(app, &s.project, &saved)); r.next(format!("vcs diff {} to check", paths.join(" "))); Ok(r) } pub fn guide() -> Out { let mut r = Report::new(); r.raw(include_str!("../../GUIDE.md")); r.set("guide", include_str!("../../GUIDE.md")); Ok(r) } /// Files a workspace tracks, by path, for helpers. pub fn tracked(root: &Path) -> BTreeMap { Index::load(root).entries.keys().map(|k| (k.clone(), ())).collect() } #[allow(dead_code)] fn files_to_vec(files: &Files) -> Vec { files.keys().cloned().collect() }