//! 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 onset_core::merge::{self, Mode}; use onset_core::tree::{self, Files}; use onset_core::version::Version; use onset_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(line) = &c.line { return format!("{line}/{}", c.base_version.unwrap_or(0)); } 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, "line": c.line, "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!("on 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 = crate::sys::canonical(&root)?; if ws::find(&root).is_some() { return Err(Fail::new("bad_usage", format!("{} is already in an Onset 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 on land -m \"First version\""); Ok(r) } /// `on get`: a new workspace on a new change (on main, on a release line, /// or on the change `on` when it's given), or on an existing change. #[allow(clippy::too_many_arguments)] pub fn get(app: &App, target: &str, folder: Option, change_id: Option, only: Vec, on: Option, line: Option, lazy: bool) -> Out { if line.is_some() && (change_id.is_some() || on.is_some()) { 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")); } if lazy && !only.is_empty() { return Err(Fail::new("bad_usage", "--lazy fetches files as they're opened, so --only isn't needed with it").state("nothing changed")); } let project = resolve_project(app, target)?; if lazy && !project.hosted() { return Err(Fail::new("bad_usage", "--lazy is for hosted projects; a local one is all on this machine already").state("nothing changed")); } 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)?; if project.hosted() { crate::seal::register_machine(&project); } // Just switched on in Upstream for a repository with git history: main's history comes in first. if project.hosted() && main.is_none() && change_id.is_none() && on.is_none() && line.is_none() { let remote = crate::remote::Remote::for_project(&project); let view = remote.view()?; if view.import_pending && let Some(git) = &view.git { // The import publishes to this address itself. app.db.forget_project(&project.id)?; match crate::bridge::import_as(app, git, Some(project.address.clone()), Some(root.clone()), remote.token.as_deref()) { Ok(mut r) => { r.line("note", "Onset was just turned on for this repository: main's git history came in with this get"); return Ok(r); } // Nothing in git after all: an empty project, as any other. Err(f) if f.message.contains("no commits") => app.db.put_project(&project)?, Err(f) => return Err(f), } } } 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 parent = match &on { Some(text) => { let parent = app.find_change(&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")); } if project.hosted() { crate::remote::Remote::for_project(&project).fetch_saves(&app.db, &app.store, &project, &parent)?; } Some(parent) } None => None, }; let mut c = match (&parent, &line) { (Some(p), _) => { let mut c = Change::new(ids::new_change_id(), &project.id, p.tree(), None, &author); c.line = p.line.clone(); c } (None, Some(name)) => on_line(app, &project, name, &author)?, (None, None) => { let base = main.as_ref().map(|v| v.tree).unwrap_or_else(tree::empty_id); Change::new(ids::new_change_id(), &project.id, base, main.as_ref().map(|v| v.n), &author) } }; c.on_change = parent.map(|p| p.id); app.db.put_change(&c)?; let base = c.base_tree; (c, base) } }; std::fs::create_dir_all(&root)?; let root = crate::sys::canonical(&root)?; let workspace = Workspace { id: workspace_id, project: project.id.clone(), path: root.clone(), change: change.id.clone(), only: only.clone() }; let source = app.db.project_workspaces(&project.id)?.into_iter().find(|w| ws::is_workspace(&w.path) && w.path != root); // Where the workspace's own files go: the folder, or a lazy one's backing (the mount shows it). let home = if lazy { crate::lazy::backing(&workspace.id) } else { root.clone() }; ws::write_id(&home, &workspace.id)?; if lazy { // Folders and sizes now; each file when it's first opened. let mut index = crate::lazy::prepare(app, &project, &workspace.id, &tree)?; index.save(&home)?; } else { // Copy unchanged files from the most recent workspace of this project. 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, &crate::seal::Seals::load(&app.db, &project.id)?.unreadable(), cow)?; index.save(&root)?; } app.db.put_workspace(&workspace)?; let mut copied = Vec::new(); if let Some(w) = &source { for folder in ws::config(if lazy { &w.path } else { &root }).workspace.copy { let folder = folder.trim_matches('/'); if folder.is_empty() || folder.contains("..") { continue; } let n = ws::copy_folder(&w.path.join(folder), &home.join(folder))?; if n > 0 { copied.push(format!("{folder} from {} ({n} files)", w.path.display())); } } } if lazy { crate::lazy::mount(&workspace)?; } 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 lazy { r.line("lazy", "every file is there; each comes from the host the first time it's opened"); } 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 on land -m \"what you did\""); Ok(r) } /// A new change on a release line's latest version. fn on_line(app: &App, project: &Project, name: &str, author: &str) -> Result { let (l, tree) = crate::lines::head(app, project, name)?; let mut c = Change::new(ids::new_change_id(), &project.id, tree, Some(l.head), author); c.line = Some(l.name); Ok(c) } /// 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('~') || ws::is_workspace(&path) { let root = ws::find(&path).ok_or_else(|| { Fail::new("not_found", format!("{target} isn't an Onset workspace")).state("nothing changed").next("on 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 named = which.is_some(); let mut c = match which { Some(text) => app.find_change(&s.project, &text)?, None => current, }; let asked = c.id.clone(); c = settle_review(app, &mut s, c)?; // A named change that landed meanwhile moved the workspace on; show the named one. if named && c.id != asked { c = app.change(&asked)?; } let review = if c.state == "open" { app.db.review(&c.id)? } else { None }; 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" => { let n = c.version.map(|v| v.to_string()).unwrap_or("?".into()); r.line("landed", match &c.line { Some(line) => format!("as {line}/{n}"), None => format!("as main {n}"), }); } "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() && c.line.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 let Some(link) = &review { r.line("review", format!("change request {link}; it lands when its approvals and checks pass")); r.set("review", link.clone()); } 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 moved = onset_core::rename::renames(&app.store, &changes)?; let mut list = Vec::new(); for (from, to) in &moved { list.push(format!("R {from} -> {to}")); } for (path, change) in &changes { if moved.iter().any(|(from, to)| from == path || to == path) { continue; } 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 on land", c.conflicts[0].path)); } else if list.is_empty() { r.next("edit files, then on land -m \"what you did\""); } else if c.title.is_empty() { r.next("on land -m \"what you did\""); } else { r.next("on 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 Some(n) = text.parse::().ok().or(crate::tags::find(app, project, text)?) { 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)))); } match app.find_change(project, text) { Ok(c) => Ok((c.tree(), format!("change {}", app.short(project, &c.id)))), // A release line ("1.x", its latest version) or one of its versions ("1.x/3"). Err(f) => crate::lines::tree_at(app, project, text)?.ok_or(f), } } fn version(app: &App, project: &Project, n: u64) -> Result { app.version(project, 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 Some(n) = what.parse::().ok().or(crate::tags::find(app, &s.project, &what)?) { 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); } if crate::history::is_path(&app.cwd, &what) { let path = crate::history::workspace_path(app, &s.root, &what); return crate::history::log_path(app, &s.project, &path, limit.max(1) as usize); } 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 mut list = app.db.versions(&s.project.id, limit)?; let start = app.db.history_from(&s.project.id)?; if (list.len() as i64) < limit && start > 1 { // Older than this machine keeps: fetch them now. app.history(&s.project, start.saturating_sub((limit - list.len() as i64) as u64))?; 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("on 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, line: Option) -> Out { if line.is_some() && on.is_some() { return Err(Fail::new("bad_usage", "--line starts on that line's latest version; it doesn't go with --on").state("nothing changed")); } let mut s = app.session()?; let current = app.save(&mut s)?; let author = app.author(&s.project); let mut c = match &on { None if line.is_some() => on_line(app, &s.project, line.as_deref().unwrap_or_default(), &author)?, 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("on 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.line = parent.line.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; on 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 on 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("on 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("on 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" { "on undo (if you just dropped it)" } else { "on 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 on 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!("on 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("on undo brings it back"); Ok(r) } // Finish. pub fn sync(app: &App) -> Out { let mut s = app.session()?; let saved = app.save(&mut s)?; let mut c = settle_review(app, &mut s, saved)?; 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 { // A scheduled change lands on the host on its own: ask whether it has. Some(p) => Some(match app.change(p)? { 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), pc => pc, }), None => None, }; let (target_tree, target_version, label, still_on) = match parent.as_ref().filter(|p| p.state == "open" || p.state == "waiting" || p.state == "scheduled") { Some(p) => (p.tree(), None, format!("change {}", app.short(&s.project, &p.id)), Some(p.id.clone())), None if c.line.is_some() => { let (l, t) = crate::lines::head(app, &s.project, c.line.as_deref().unwrap_or_default())?; (t, Some(l.head), format!("{}/{}", l.name, l.head), None) } 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("on land"); return Ok(r); } let ours_label = label.clone(); let theirs_label = format!("your change {}", app.short(&s.project, &c.id)); let mut 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)?; } // Sealed files the host couldn't merge are merged here. 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))?; 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("on land"); } else { r.exit = 3; r.next(format!("fix the marked lines in {}, then on land", m.conflicts.iter().map(|x| x.path.as_str()).collect::>().join(", "))); } Ok(r) } /// Runs onset.toml's `[land] run` commands in the workspace, in order, their /// output on stderr; the first that fails stops the landing. fn run_before_land(root: &Path) -> Result<(), Fail> { for command in ws::config(root).land.run { let mut shell = if cfg!(windows) { std::process::Command::new("cmd") } else { std::process::Command::new("sh") }; shell.args(if cfg!(windows) { ["/C", command.as_str()] } else { ["-c", command.as_str()] }); let status = shell .current_dir(root) .stdin(std::process::Stdio::null()) .stdout(std::io::stderr()) .status() .map_err(|e| Fail::new("checks_failed", format!("couldn't run \"{command}\" from onset.toml: {e}")).state("main didn't change; your change is saved"))?; if !status.success() { return Err(Fail::new("checks_failed", format!("\"{command}\" (onset.toml [land] run) failed, so nothing landed")) .state("main didn't change; your change is saved") .next("fix what it found, then on land (on land --no-run lands without running it)")); } } Ok(()) } #[allow(clippy::too_many_arguments)] pub fn land(app: &App, target: Option, messages: Vec, allow_secrets: bool, run: bool, at: Option, with: Vec, to: Option) -> Out { let mut s = app.session()?; if to.is_some() && (at.is_some() || !with.is_empty()) { 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")); } let at = match at.as_deref() { None => None, Some(words) => { let t = ids::parse_future(words) .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"))?; if !s.project.hosted() { return Err(Fail::new("bad_usage", "landing at a set time needs a host, which lands it then").state("nothing changed").next("on publish ")); } Some(t) } }; if !with.is_empty() { return land_together(app, &mut s, &with, messages, allow_secrets, run, at); } // Saved here only: the landing itself carries the change to the host. let current = app.save_local(&mut s)?; let current = settle_review(app, &mut s, current)?; // This workspace's change and what it's stacked on are its own; a change // named on the command line is someone else's unless it's the current one. let own_stack = target.is_none(); 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(), }; // Another line's change (or main's, landed or not) brought over to a line. if let Some(name) = to.as_deref().filter(|name| c.line.as_deref() != Some(*name)) { return bring_over(app, &mut s, &c, name, &messages, allow_secrets); } 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" { let what = match &c.line { Some(line) => format!("{line}/{}", c.version.unwrap_or(0)), None => format!("main {}", c.version.unwrap_or(0)), }; return Err(Fail::new("bad_usage", format!("change {} already landed as {what}", c.id)).state("nothing changed").next(format!("on land {} --to brings it over to a release line", app.short(&s.project, &c.id)))); } if c.state == "dropped" { return Err(Fail::new("bad_usage", format!("change {} was dropped", c.id)).state("nothing changed").next("on 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 on land")); } require_title(&c)?; // The workspace's files are this change's: its own checks run on them. if run && own_stack { run_before_land(&s.root)?; } // The agent's session, kept with the change it lands (only its owner sees it). let kept = if own_stack { crate::sessions::keep_for(app, &s, &c) } else { None }; // 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(); if let Some(line) = kept { r.line("session", line); } let mut landed_versions = Vec::new(); let mut on_line = 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 on land", hit.path)) .set("secrets", serde_json::to_value(&found).unwrap_or_default())); } } // A change of this workspace's goes up with its landing, in one call. let own = s.project.hosted() && (own_stack || item.id == current.id); let pending = if own { app.db.unuploaded_saves(&item.id)? } else { Vec::new() }; 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, at, 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 }, line: item.line.clone(), undoes: None, record: own.then(|| crate::wire::PutChange { change: crate::remote::Remote::record(&item), workspace: s.ws.id.clone(), label: crate::remote::label(&s.root), 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() }), }), }; let outcome = match host.land(&app.db, &app.store, &s.project, &request) { Ok(o) => o, Err(e) => { let fail = Fail::from(e); if fail.code == "held_elsewhere" { // Another workspace took the change over: a normal save // moves this one's work to a new change. let rescued = app.save(&mut s)?; return Err(Fail::new("held_elsewhere", format!("{}; this workspace's work is in change {}", fail.message, app.short(&s.project, &rescued.id))) .state("main didn't change") .next("on land")); } return Err(fail); } }; for sv in &pending { app.db.mark_uploaded(&item.id, sv.n)?; } 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)?; 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("on sync, fix the conflicts in those files, then on 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!("on 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 on land again")); } Landed::Review { number, url, blockers, at: when } => { // The workspace stays on the change: landing again after more // edits updates the same change request. app.db.set_review(&item.id, Some(&format!("#{number} {url}")))?; r.line("review", format!("{} is change request #{number}, {url}", app.short(&s.project, &item.id))); for b in &blockers { r.line("waiting on", b.clone()); } match when { Some(t) => r.line("lands", format!("at {} or after, once its approvals and checks pass", ids::clock(t))), None => r.line("lands", "when its approvals and checks pass (Upstream merges it, and it comes into main)"), }; r.exit = 5; r.set("review", json!({ "change": item.id, "number": number, "url": url, "blockers": blockers })); r.next("keep working; on land again updates it, and on status shows where it is"); return Ok(r); } Landed::Scheduled { at } => { item.state = "scheduled".into(); app.db.put_change(&item)?; r.line("scheduled", format!("{} lands at {}", app.short(&s.project, &item.id), ids::clock(at))); r.set("scheduled", json!({ "change": item.id, "at": at })); } Landed::OnLine { line, n, title } => { item.state = "landed".into(); item.version = Some(n); item.line = Some(line.clone()); app.db.put_change(&item)?; r.line("landed", format!("{} as {line}/{n} \"{title}\"", app.short(&s.project, &item.id))); on_line.push(json!({ "change": item.id, "line": line, "version": n, "title": title })); } Landed::LineConflict { line, n, conflicts } => { 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()) }; 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" })); for x in &conflicts { f = f.detail(x.path.clone()); } return Err(f.state(state).next("on sync, fix the conflicts in those files, then on land").set("conflicts", serde_json::to_value(&conflicts).unwrap_or_default())); } } } if !on_line.is_empty() { let last = on_line.last().cloned().unwrap_or_default(); app.db.add_op(&s.ws.id, "land_line", &json!({ "change": last["change"], "line": last["line"], "n": last["version"] }))?; 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", on_line); r.next("keep working on the line; on land puts the next version on it"); return Ok(r); } if landed_versions.is_empty() { // All of it is scheduled: the workspace goes on on top of it. 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, on top of the scheduled change", app.short(&s.project, &fresh.id))); } r.next("keep working; the host lands it then, as it is now"); return Ok(r); } 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 on sync to bring in others' work"); Ok(r) } /// `on land --to `: a change's edits brought over to a /// release line as its next version: what a landed change did (main's /// version against the one before it), or an open change's own edits. The /// change itself stays as it is. When the edits conflict with the line, this /// workspace goes on a new change on the line with the conflicts marked. fn bring_over(app: &App, s: &mut Session, c: &Change, name: &str, messages: &[String], allow_secrets: bool) -> Out { let short = app.short(&s.project, &c.id); let (line, head) = crate::lines::head(app, &s.project, name)?; let at = |text: String| -> Result { 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")) }; let (base, tree) = match (c.state.as_str(), &c.line, c.version) { ("landed", None, Some(n)) => { let before = if n > 1 { version(app, &s.project, n - 1)?.tree } else { tree::empty_id() }; (before, version(app, &s.project, n)?.tree) } ("landed", Some(from), Some(n)) => (at(format!("{from}/{}", n - 1))?, at(format!("{from}/{n}"))?), ("dropped", ..) => return Err(Fail::new("bad_usage", format!("change {short} was dropped")).state("nothing changed")), _ => { if c.is_empty() { return Err(Fail::new("empty_change", format!("change {short} has nothing to bring over")).state("nothing changed")); } if !c.conflicts.is_empty() { return Err(Fail::new("conflict", format!("change {short} still has conflict markers")).state("nothing changed").next("fix the marked lines first")); } (c.base_tree, c.tree()) } }; let mut described = c.clone(); if !messages.is_empty() { set_description(&mut described, messages); } require_title(&described)?; let host = app.host(&s.project); host.fetch_tree(&app.store, &s.project, &base, None)?; host.fetch_tree(&app.store, &s.project, &tree, Some(&base))?; if !allow_secrets && let Some(hit) = secrets::scan(&app.store, &base, &tree)?.first() { return Err(Fail::new("secret", format!("change {short} looks like it has a secret: {} line {} ({})", hit.path, hit.line, hit.kind)) .state(format!("{name} didn't change")) .next("on land --allow-secrets if it isn't one")); } let (title, body) = (described.title, described.body); let request = LandRequest { change: c.id.clone(), base_tree: base, tree, title: title.clone(), body: body.clone(), author: c.author.clone(), allow_secrets, record: None, at: None, signature: if s.project.hosted() { crate::host::LandSignature::for_land(&s.project.address, &c.id, &base, &tree, &title, &body, &c.author) } else { None }, line: Some(line.name.clone()), undoes: None, }; let mut r = Report::new(); match host.land(&app.db, &app.store, &s.project, &request)? { Landed::OnLine { line, n, title } => { app.db.add_op(&s.ws.id, "land_line", &json!({ "change": c.id, "line": line, "n": n, "brought": true }))?; r.line("brought over", format!("{short} to {line} as {line}/{n} \"{title}\"")); r.set("line", line.clone()).set("version", n).set("change", c.id.clone()); r.next(format!("on log --line {line} shows it")); } Landed::LineConflict { line: _, n, conflicts: _ } => { let ours = format!("{name}/{n}"); let m = merge::trees(&app.store, Some(&base), &head, &tree, Mode::Sync, (&ours, &format!("change {short}")))?; for o in m.objects.objects.values() { app.store.put(o)?; } let current = app.save(s)?; let mut x = Change::new(ids::new_change_id(), &s.project.id, head, Some(line.head), &app.author(&s.project)); x.line = Some(line.name.clone()); x.title = title; x.body = body; x.head_tree = Some(m.tree); x.saves = 1; x.conflicts = m.conflicts.iter().map(|k| Conflict { path: k.path.clone(), version: Some(line.head) }).collect(); 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)?; app.db.put_change(&x)?; app.show_tree(s, &m.tree)?; app.put_workspace_change(s, &x.id)?; app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": x.id }))?; r.line("conflict", format!("{short}'s edits conflict with {ours}, so this workspace is on a new change on {name} with them marked")); for k in &m.conflicts { r.line("conflict", k.path.clone()); } r.line("change", format!("{} on {ours}", app.short(&s.project, &x.id))); if !current.is_empty() { r.line("kept", format!("{} is saved; on switch goes back to it", app.short(&s.project, ¤t.id))); } r.exit = 3; r.set("change", change_json(app, &s.project, &x)).set("conflicts", m.conflicts.iter().map(|k| k.path.clone()).collect::>()); r.next(format!("fix the marked lines, then on land (it lands on {name})")); } Landed::Waiting { reason, .. } => return Err(Fail::new("waiting", format!("{name}: {reason}")).state(format!("{name} didn't change"))), Landed::ChecksFailed { check, .. } => return Err(Fail::new("checks_failed", format!("check \"{check}\" failed on {name}")).state(format!("{name} didn't change"))), other => return Err(Fail::new("failed", format!("the host answered {other:?} for a landing on {name}")).state(format!("{name} didn't change"))), } Ok(r) } /// One workspace's part of a landing together: its change, checked and /// uploaded, and the host's landing request for it. fn together_part(app: &App, s: &mut Session, messages: &[String], allow_secrets: bool, run: bool) -> Result<(Change, serde_json::Value), Fail> { let saved = app.save_local(s)?; let mut c = settle_review(app, s, saved)?; let short = app.short(&s.project, &c.id); if !messages.is_empty() { set_description(&mut c, messages); app.db.put_change(&c)?; } let place = s.root.display().to_string(); if c.state != "open" { return Err(Fail::new("bad_usage", format!("{place}: change {short} is {}", c.state)).state("nothing landed")); } if c.is_empty() { return Err(Fail::new("empty_change", format!("{place}: change {short} has nothing to land")).state("nothing landed").next("edit files there first")); } if !c.conflicts.is_empty() { 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"))); } if let Some(p) = &c.on_change { // One held or in review may have landed on the host meanwhile. let mut parent = app.change(p)?; if parent.state != "landed" && s.project.hosted() { parent = crate::remote::Remote::for_project(&s.project).fetch_change(&app.db, &app.store, &s.project, p)?.unwrap_or(parent); } if parent.state != "landed" { 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 (on -C {place} land)"))); } } require_title(&c)?; if run { run_before_land(&s.root)?; } if !allow_secrets && let Some(hit) = secrets::scan(&app.store, &c.base_tree, &c.tree())?.first() { 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))); } let remote = crate::remote::Remote::for_project(&s.project); remote.upload_change(&app.db, &app.store, &s.project, &c.base_tree, Some(&c.tree()))?; let pending = app.db.unuploaded_saves(&c.id)?; let request = LandRequest { change: c.id.clone(), base_tree: c.base_tree, tree: c.tree(), title: c.title.clone(), body: c.body.clone(), author: c.author.clone(), allow_secrets, at: None, signature: crate::host::LandSignature::for_land(&s.project.address, &c.id, &c.base_tree, &c.tree(), &c.title, &c.body, &c.author), line: c.line.clone(), undoes: None, record: Some(crate::wire::PutChange { change: crate::remote::Remote::record(&c), workspace: s.ws.id.clone(), label: crate::remote::label(&s.root), 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() }), }), }; for sv in &pending { app.db.mark_uploaded(&c.id, sv.n)?; } let (_, owner, name) = crate::remote::split_address(&s.project.address)?; Ok((c, json!({ "project": format!("{owner}/{name}"), "land": request }))) } /// `on land --with ...`: this workspace's change and the other /// workspaces' (in other projects on the same host) land together, all of /// them or none. Under review rules, or with --at, each waits (in review, or /// held as it is) and the host lands them all once every one is ready. fn land_together(app: &App, s: &mut Session, with: &[PathBuf], messages: Vec, allow_secrets: bool, run: bool, at: Option) -> Out { if !s.project.hosted() { return Err(Fail::new("bad_usage", "landing together needs a host, which lands every part at once").state("nothing changed").next("on publish ")); } let mut others = Vec::new(); for path in with { let root = ws::find(&app.cwd.join(path)).ok_or_else(|| Fail::new("not_found", format!("{} isn't in an Onset workspace", path.display())).state("nothing changed"))?; let other = app.session_at(&root)?; if other.project.api != s.project.api { return Err(Fail::new("bad_usage", format!("{} is on another host; landing together is on one host", root.display())).state("nothing changed")); } if other.project.id == s.project.id || others.iter().any(|o: &Session| o.project.id == other.project.id) { 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")); } others.push(other); } let mut changes = Vec::new(); let mut parts = Vec::new(); for i in 0..=others.len() { let session: &mut Session = if i == 0 { &mut *s } else { &mut others[i - 1] }; let (c, part) = together_part(app, session, if i == 0 { &messages } else { &[] }, allow_secrets, run)?; changes.push(c); parts.push(part); } let mut body = json!({ "parts": parts }); if let Some(t) = at { body["at"] = json!(t); } let answer: serde_json::Value = crate::remote::Remote::for_project(&s.project).post_host("/land-together", &body)?; let mut r = Report::new(); let sessions: Vec<&mut Session> = std::iter::once(&mut *s).chain(others.iter_mut()).collect(); let mut sessions = sessions; match answer["outcome"].as_str() { Some("landed") => { for (session, c) in sessions.iter_mut().zip(&changes) { let (_, owner, name) = crate::remote::split_address(&session.project.address)?; let project = format!("{owner}/{name}"); let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); let mut done = c.clone(); done.state = "landed".into(); if let (Some(line), Some(n)) = (part["line"]["line"].as_str(), part["line"]["n"].as_u64()) { // A part on a release line. done.version = Some(n); done.line = Some(line.to_string()); app.db.put_change(&done)?; r.line("landed", format!("{} as {line}/{n} of {project} \"{}\"", app.short(&session.project, &c.id), c.title)); } else { 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}")))?; done.version = Some(version.n); app.db.put_change(&done)?; app.db.put_version(&session.project.id, &version)?; r.line("landed", format!("{} as main {} of {project} \"{}\"", app.short(&session.project, &c.id), version.n, version.title)); } continue_after(app, session, &done)?; } r.set("landed", answer["parts"].clone()); r.next("keep working; each workspace is on a fresh change"); } Some("together") => { let mut reviews = 0; for (session, c) in sessions.iter_mut().zip(&changes) { let (_, owner, name) = crate::remote::split_address(&session.project.address)?; let project = format!("{owner}/{name}"); let part = answer["parts"].as_array().and_then(|ps| ps.iter().find(|p| p["project"] == project.as_str())).cloned().unwrap_or_default(); let short = app.short(&session.project, &c.id); if let (Some(number), Some(url)) = (part["review"]["number"].as_u64(), part["review"]["url"].as_str()) { reviews += 1; app.db.set_review(&c.id, Some(&format!("#{number} {url}")))?; r.line("review", format!("{short} in {project} is change request #{number}, {url}")); } else { let mut held = c.clone(); held.state = "scheduled".into(); app.db.put_change(&held)?; r.line("held", format!("{short} in {project}, as it is now")); continue_after(app, session, &held)?; } } let when = answer["at"].as_i64().map(|t| format!(" at {} or after", ids::clock(t))).unwrap_or_default(); r.line("lands", format!("all together{when}, once every change request's approvals and checks pass")); if reviews > 0 { r.exit = 5; } r.set("together", answer.clone()); r.next("keep working; the host lands them all when every part is ready"); } Some("refused") => { let project = answer["project"].as_str().unwrap_or("a project"); let landed: Landed = serde_json::from_value(answer["landed"].clone()).map_err(|e| Fail::new("failed", format!("the host's answer was off: {e}")))?; let (code, why) = match &landed { Landed::Conflict { main, conflicts } => ("conflict", format!("conflicts with main {main} of {project} in {}", conflicts.iter().map(|x| x.path.clone()).collect::>().join(", "))), Landed::Waiting { reason, .. } => ("waiting", format!("{project}: {reason}")), _ => ("failed", format!("{project} couldn't land its part")), }; 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: on sync, fix it, then land together again"))); } _ => return Err(Fail::new("failed", format!("the host answered {answer}"))), } Ok(r) } /// A change in review: the host says whether its change request merged /// meanwhile, and if it did and it's the workspace's change, the workspace /// moves on to a fresh change on top of it, as after a land. fn settle_review(app: &App, s: &mut Session, c: Change) -> Result { if !s.project.hosted() || app.db.review(&c.id)?.is_none() { return Ok(c); } let found: Result = crate::remote::Remote::for_project(&s.project).get_json(&format!("/changes/{}", c.id)); let Ok(found) = found else { return Ok(c) }; let Ok(record) = serde_json::from_value::(found["change"].clone()) else { return Ok(c) }; let adopted = crate::remote::Remote::adopt(&app.db, &s.project, &record)?; if adopted.state == "landed" && s.ws.change == adopted.id { // On from what the workspace has (a sync may have moved it since). let mut done = c; done.state = "landed".into(); done.version = adopted.version; return continue_after(app, s, &done); } Ok(adopted) } /// 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" || done.state == "scheduled" { fresh.on_change = Some(done.id.clone()); } else { fresh.after_change = Some(done.id.clone()); } // On a release line, the workspace stays on it. fresh.line = done.line.clone(); if done.line.is_some() && done.state == "landed" { fresh.base_version = done.version; } app.db.put_change(&fresh)?; app.put_workspace_change(s, &fresh.id)?; Ok(fresh) } // Fix. pub fn undo(app: &App, which: Option) -> Out { let mut s = app.session()?; let current = app.save(&mut s)?; // A release line's version: a version of the line takes it back out. if let Some((name, n)) = which.as_deref().and_then(|w| w.rsplit_once('/')).and_then(|(l, n)| n.parse::().ok().map(|n| (l.to_string(), n))) { let (title, taken) = take_back_line(app, &s, &name, n)?; app.db.add_op(&s.ws.id, "undo", &json!({ "what": format!("took back {name}/{n}") }))?; let mut r = Report::new(); r.line("undid", format!("{name}/{n} (\"{title}\"): {name}/{taken} takes it back out")); r.set("undid", format!("{name}/{n}")).set("line", name.clone()).set("version", taken); return Ok(r); } let version_n = match which.as_deref() { None => None, Some(text) => Some(text.parse::().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"))?), }; 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; on 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 on 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")); } "land_line" => { let (line, n) = (text("line"), d.get("n").and_then(|v| v.as_u64()).unwrap_or(0)); if line.is_empty() || n == 0 { return Err(Fail::new("nothing_to_undo", "that landing on a release line was made by an older version of Onset, which didn't note its version").state("nothing changed").next("on log --line , then on undo /")); } let (_, taken) = take_back_line(app, &s, &line, n)?; if d.get("brought").and_then(|v| v.as_bool()) == Some(true) { r.line("undid", format!("bringing {} over: {line}/{taken} takes {line}/{n} back out", app.short(&s.project, &text("change")))); } else { // The change made on the line opens again here, with what was done since. let mut c = app.change(&text("change"))?; c.state = "open".into(); c.version = None; 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 {}: {line}/{taken} takes {line}/{n} back out", app.short(&s.project, &c.id))) .line("change", format!("{} is open again in this workspace", app.short(&s.project, &c.id))); r.next("fix it, then on land"); } } 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 version on release line `name` that reverses its version `n`; /// answers that version's title and the new version's number. fn take_back_line(app: &App, s: &Session, name: &str, n: u64) -> Result<(String, u64), Fail> { let at = |k: u64| -> Result { 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")) }; let (line, head) = crate::lines::head(app, &s.project, name)?; if n == 0 || n > line.head { return Err(Fail::new("not_found", format!("line {name} has no version {n}")).state("nothing changed")); } let (taken, before) = (at(n)?, at(n - 1)?); 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(); // Merge "version → version before it" onto the line's latest. let m = merge::trees(&app.store, Some(&taken), &head, &before, Mode::Land, (&format!("{name}/{}", line.head), "the undo"))?; if !m.clean() { return Err(Fail::new("conflict", format!("can't take back {name}/{n}: later versions of {name} changed the same lines")) .detail(m.conflicts.iter().map(|x| x.path.clone()).collect::>().join(", ")) .state(format!("{name} didn't change")) .next(format!("on new --line {name}, undo it by hand, then on land"))); } for o in m.objects.objects.values() { app.store.put(o)?; } let request = LandRequest { change: ids::new_change_id(), base_tree: head, tree: m.tree, title: format!("Take back {name}/{n}: {title}"), body: format!("Undoes {name}/{n}."), author: app.author(&s.project), allow_secrets: true, record: None, at: None, signature: None, line: Some(name.to_string()), undoes: Some(format!("{name}/{n}")), }; match app.host(&s.project).land(&app.db, &app.store, &s.project, &request)? { Landed::OnLine { n: made, .. } => Ok((title, made)), Landed::LineConflict { .. } => Err(Fail::new("conflict", format!("{name} moved while taking back {name}/{n}")).state(format!("{name} didn't change")).next("on undo again")), Landed::Review { number, url, .. } => Err(Fail::new("waiting", format!("the repository's rules send the undo through review: #{number}, {url}")) .state(format!("{name} didn't change yet; it lands once the change request's approvals and checks pass")) .set("review", json!({ "number": number, "url": url }))), Landed::Waiting { .. } => Err(Fail::new("waiting", "you can't land on this project on your own").state(format!("{name} didn't change"))), other => Err(Fail::new("failed", format!("the host answered {other:?} for the undo")).state(format!("{name} didn't change"))), } } /// Lands a change that reverses version `n` on the latest main. fn take_back(app: &App, s: &Session, n: u64) -> Result<(Version, Version), Fail> { take_back_why(app, s, n, None) } /// [`take_back`], with why in the new version's description (on watch: the check that failed). pub fn take_back_why(app: &App, s: &Session, n: u64, why: Option<&str>) -> 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 on 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: match why { Some(w) => format!("Undoes main {n}.\n\n{w}"), None => format!("Undoes main {n}."), }, author: app.author(&s.project), allow_secrets: true, record: None, at: None, signature: None, line: None, undoes: Some(n.to_string()), }; 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("on 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")), Landed::Review { number, url, .. } => Err(Fail::new("waiting", format!("the repository's rules send the undo through review: #{number}, {url}")) .state("main didn't change yet; it lands once the change request's approvals and checks pass") .set("review", json!({ "number": number, "url": url }))), Landed::Scheduled { .. } => Err(Fail::new("failed", "the host kept the undo for later, which it shouldn't").state("main didn't change")), 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")), } } /// `on show [--from ]`: the file as it /// is in main's latest version (or in --from), printed as it is. /// `on bisect --run ""`: finds the first version of /// main where the command fails. Main's versions are numbered, so it's a /// binary search between them: each version it tries is written to a folder /// of its own (the workspace's files never change) and the command runs /// there. Exit 0 means good, 125 means it can't tell (that version is /// skipped), anything else means bad. pub fn bisect(app: &App, good: String, bad: String, run: String, folder: Option) -> Out { let s = app.session()?; let number = |text: &str| -> Result { match text.parse::().ok().or(crate::tags::find(app, &s.project, text)?) { Some(n) => Ok(n), None if text == "main" => Ok(app.refresh(&s.project)?.map(|v| v.n).unwrap_or(0)), None => Err(Fail::new("bad_usage", format!("{text} isn't a version of main or a tag")).state("nothing changed")), } }; let (good_n, bad_n) = (number(&good)?, number(&bad)?); if good_n >= bad_n { return Err(Fail::new("bad_usage", format!("the good version ({good_n}) has to come before the bad one ({bad_n})")).state("nothing changed")); } let keep = folder.is_some(); let root = match folder { Some(f) => app.cwd.join(f), None => crate::paths::home().join("tmp").join(format!("bisect-{}", ids::new_workspace_id())), }; std::fs::create_dir_all(&root)?; let mut index = Index::default(); let mut tried: Vec<(u64, &'static str)> = Vec::new(); let mut skipped: std::collections::BTreeSet = Default::default(); let (mut lo, mut hi) = (good_n, bad_n); let result = (|| -> Result<(), Fail> { loop { // The middle untried version, or the nearest one that isn't skipped. let mid = (lo + 1..hi).filter(|n| !skipped.contains(n)).min_by_key(|n| n.abs_diff((lo + hi) / 2)); let Some(mid) = mid else { return Ok(()) }; let (tree, _) = resolve_tree(app, &s.project, &mid.to_string())?; index = ws::materialize(&root, &app.store, &index, &app.files(&tree)?, &[], &crate::seal::Seals::load(&app.db, &s.project.id)?.unreadable(), None)?; let mut shell = if cfg!(windows) { std::process::Command::new("cmd") } else { std::process::Command::new("sh") }; shell.args(if cfg!(windows) { ["/C", run.as_str()] } else { ["-c", run.as_str()] }); let status = shell .current_dir(&root) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .map_err(|e| Fail::new("bad_usage", format!("couldn't run {run:?}: {e}")).state("nothing changed"))?; match status.code() { Some(0) => { tried.push((mid, "good")); lo = mid; } Some(125) => { tried.push((mid, "skip")); skipped.insert(mid); } _ => { tried.push((mid, "bad")); hi = mid; } } } })(); if !keep { let _ = std::fs::remove_dir_all(&root); } result?; let v = version(app, &s.project, hi)?; let mut r = Report::new(); let left: Vec = (lo + 1..hi).collect(); if left.is_empty() { r.line("first bad", format!("main {} \"{}\" {}, {}", v.n, v.title, v.author, ids::clock(v.time))); } else { // Only skipped versions sit between the last good and the first bad. r.line("first bad", format!("one of main {}, {}", left.iter().map(|n| n.to_string()).collect::>().join(", "), v.n)); } r.line("tried", tried.iter().map(|(n, how)| format!("{n} {how}")).collect::>().join(", ")); if keep { r.line("folder", format!("{} has main {} as the last one tried", root.display(), tried.last().map(|t| t.0).unwrap_or(hi))); } r.set("first_bad", v.n) .set("candidates", left.iter().copied().chain([v.n]).collect::>()) .set("tried", tried.iter().map(|(n, how)| json!({ "version": n, "result": how })).collect::>()); r.next(format!("on log {} to see what it changed, or on undo {} to take it back out", v.n, v.n)); Ok(r) } pub fn show(app: &App, path: String, from: Option) -> Out { use base64::Engine; use std::io::Write; let s = app.session()?; let path = crate::history::workspace_path(app, &s.root, &path); let from = from.unwrap_or_else(|| "main".to_string()); // A tag is the version it names. let from = match crate::tags::find(app, &s.project, &from)? { Some(n) => n.to_string(), None => from, }; // A version of a hosted project is read where it is, not fetched whole. let mut found: Option<(Vec, String)> = None; if s.project.hosted() && (from == "main" || from.parse::().is_ok()) { #[derive(serde::Deserialize)] struct HostFile { version: u64, base64: Option, } let version = if from == "main" { String::new() } else { format!("&version={from}") }; let f: HostFile = crate::remote::Remote::for_project(&s.project).get_json(&format!("/file?path={}{version}", crate::history::encode(&path)))?; // Over 1 MB (or a submodule): below, from the version's objects. if let Some(b) = f.base64 { let content = base64::engine::general_purpose::STANDARD.decode(b).map_err(|e| anyhow::anyhow!("the host sent a bad file: {e}"))?; found = Some((content, format!("main {}", f.version))); } } let (content, label) = match found { Some(f) => f, None => { let (tree, label) = resolve_tree(app, &s.project, &from)?; match tree::lookup(&app.store, &tree, &path)? { Some(e) if e.kind == tree::EntryKind::Tree => return Err(Fail::new("bad_usage", format!("{path} is a folder in {label}")).state("nothing changed")), 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")), Some(e) => (app.store.read_file(&e.id)?, label), None => return Err(Fail::new("not_found", format!("there's no {path} in {label}")).state("nothing changed")), } } }; if !app.json { std::io::stdout().write_all(&content).map_err(anyhow::Error::from)?; } let mut r = Report::new(); r.set("path", path).set("from", label).set("base64", base64::engine::general_purpose::STANDARD.encode(&content)); Ok(r) } 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("on 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).ok().and_then(crate::sys::tree_path).unwrap_or_else(|| p.replace('\\', "/")) }).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!("on 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() }