//! What every command shares: the database, the object store, the open //! workspace, and saving. use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use vcs_core::tree::{self, Entry, Files}; use vcs_core::version::Version; use vcs_core::Id; use crate::db::{Change, Db, Project, Save, Workspace}; use crate::host::{Host, Local}; use crate::ids; use crate::objects::Store; use crate::out::Fail; use crate::paths; use crate::remote::Remote; use crate::ws::{self, Index, Lock}; pub struct App { pub db: Db, pub store: Store, pub json: bool, pub cwd: PathBuf, /// Things that happened on the side, printed after the answer. pub notes: std::cell::RefCell>, } /// An open workspace, locked for the command's lifetime. pub struct Session { pub root: PathBuf, pub ws: Workspace, pub project: Project, _lock: Lock, } impl App { pub fn open(json: bool, cwd: PathBuf) -> Result { let home = paths::home(); Ok(App { db: Db::open(&home)?, store: Store::open(&paths::objects())?, json, cwd, notes: Default::default() }) } pub fn host(&self, project: &Project) -> Box { if project.hosted() { Box::new(Remote::for_project(project)) } else { Box::new(Local) } } /// The workspace containing the current folder. pub fn session(&self) -> Result { let root = ws::find(&self.cwd).ok_or_else(|| { Fail::new("not_found", "this folder isn't in a vcs workspace") .state("nothing changed") .next("cd into a workspace, or vcs get ") })?; self.session_at(&root) } pub fn session_at(&self, root: &Path) -> Result { let id = ws::read_id(root)?; let lock = ws::lock(root)?; let mut workspace = self.db.workspace(&id)?.ok_or_else(|| { Fail::new("not_found", format!("{} is a workspace this machine doesn't know", root.display())) .state("nothing changed") .next("vcs get to make a new workspace") })?; let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); if workspace.path != canonical { // The folder moved; follow it. workspace.path = canonical.clone(); self.db.put_workspace(&workspace)?; } let project = self.db.project(&workspace.project)?.ok_or_else(|| Fail::new("not_found", "this workspace's project is missing"))?; Ok(Session { root: canonical, ws: workspace, project, _lock: lock }) } pub fn change(&self, id: &str) -> Result { self.db.change(id)?.ok_or_else(|| Fail::new("not_found", format!("no change {id}")).state("nothing changed")) } /// A change named by its ID or a unique prefix of four letters or more. pub fn find_change(&self, project: &Project, text: &str) -> Result { if !ids::looks_like_change(text) { return Err(Fail::new("bad_usage", format!("{text} isn't a change ID (changes are 4 or more letters)")) .state("nothing changed") .next("vcs log --changes to see change IDs")); } let mut found = self.db.changes_by_prefix(&project.id, text)?; if found.is_empty() && project.hosted() { // Someone else's change, or one from another machine. if let Some(c) = Remote::for_project(project).fetch_change(&self.db, &self.store, project, text)? { found.push(c); } } match found.len() { 0 => Err(Fail::new("not_found", format!("no change {text} in this project")) .state("nothing changed") .next("vcs log --changes")), 1 => Ok(found.remove(0)), _ => Err(Fail::new("bad_usage", format!("{text} matches {} changes; use more letters", found.len())) .state("nothing changed") .next("vcs log --changes")), } } pub fn short(&self, project: &Project, id: &str) -> String { let others = self.db.change_ids(&project.id).unwrap_or_default(); ids::short(id, &others) } pub fn author(&self, project: &Project) -> String { let me = identity(project, &self.db); match std::env::var("VCS_AGENT").ok().filter(|a| !a.is_empty()) { Some(agent) => format!("{} (via {agent}) <{}>", me.0, me.1), None => format!("{} <{}>", me.0, me.1), } } pub fn main(&self, project: &Project) -> Result> { self.db.latest_version(&project.id) } /// The latest main, asking the host when the project is hosted. pub fn refresh(&self, project: &Project) -> Result> { let v = self.host(project).refresh(&self.db, &self.store, project)?; self.db.set_checked(&project.id, ids::now())?; Ok(v) } pub fn files(&self, tree: &Id) -> Result { Ok(tree::flatten(&self.store, tree)?) } /// Saves the workspace into its change. Returns the change as saved /// (a new one if another workspace took the change over meanwhile). pub fn save(&self, s: &mut Session) -> Result { self.save_with(s, true) } /// Saves without telling the host (a landing carries the change itself). pub fn save_local(&self, s: &mut Session) -> Result { self.save_with(s, false) } fn save_with(&self, s: &mut Session, publish: bool) -> Result { let mut change = self.change(&s.ws.change).map_err(|f| f.into_anyhow())?; let index = Index::load(&s.root); let known: Files = if s.ws.only.is_empty() { index.entries.iter().map(|(p, e)| (p.clone(), e.entry)).collect() } else { self.files(&change.tree())? }; let personal = crate::access::personal(self, &s.project.id)?; let main_paths = self.base_paths(s, &change.base_tree)?; let snap = ws::snapshot(&s.root, &self.store, &known, &s.ws.only, &index, &personal, &main_paths)?; let mut next = snap.index; if !index.same_as(&next) { next.save(&s.root)?; } let saved_mine = self.db.mine(&s.project.id)?; let mut mine_changed = false; for (path, id, exec) in &snap.mine { if !saved_mine.iter().any(|(p, i, x)| p == path && i == id && x == exec) { self.db.put_mine(&s.project.id, path, id, *exec)?; mine_changed = true; } } let _ = self.db.conn.execute("INSERT OR IGNORE INTO complete (tree) VALUES (?1)", [snap.tree.hex()]); let mut dirty = false; if snap.tree != change.tree() { change.head_tree = Some(snap.tree); change.saves += 1; self.db.add_save( &Save { change: change.id.clone(), n: change.saves, tree: snap.tree, base_tree: change.base_tree, at: ids::now(), uploaded: false }, &s.ws.id, )?; dirty = true; } if !change.conflicts.is_empty() { let before = change.conflicts.len(); change.conflicts.retain(|c| std::fs::read(s.root.join(&c.path)).is_ok_and(|b| ws::has_markers(&b))); dirty |= change.conflicts.len() != before; } if dirty { self.db.put_change(&change)?; } if s.project.hosted() && publish { if mine_changed { let _ = crate::remote::push_mine(self, &s.project); } if dirty || !self.db.unuploaded_saves(&change.id)?.is_empty() { // The change follows you to other machines. Offline, it // uploads on a later command. if let Err(e) = self.host(&s.project).publish_change(&self.db, &self.store, &s.project, &change, &s.ws.id) { let fail = Fail::from(e); if fail.code == "held_elsewhere" { return self.rescue(s, &change, fail.message.clone()); } } } } Ok(change) } /// Another workspace took this workspace's change over. What this one /// has goes into a new change, so nothing is lost. fn rescue(&self, s: &mut Session, taken: &Change, why: String) -> Result { let mut fresh = Change::new(ids::new_change_id(), &s.project.id, taken.base_tree, taken.base_version, &self.author(&s.project)); fresh.head_tree = taken.head_tree; fresh.saves = 1; fresh.on_change = taken.on_change.clone(); fresh.title = format!("Rescued from {}", taken.id); self.db.put_change(&fresh)?; self.db.add_save(&Save { change: fresh.id.clone(), n: 1, tree: fresh.tree(), base_tree: fresh.base_tree, at: ids::now(), uploaded: false }, &s.ws.id)?; // The taken change's newest state is the host's. if let Some(remote) = Some(crate::remote::Remote::for_project(&s.project)) { let _ = remote.fetch_change(&self.db, &self.store, &s.project, &taken.id); } s.ws.change = fresh.id.clone(); self.db.put_workspace(&s.ws)?; let _ = self.host(&s.project).publish_change(&self.db, &self.store, &s.project, &fresh, &s.ws.id); self.notes.borrow_mut().push(format!("{why}; what this workspace had is in new change {}", fresh.id)); Ok(fresh) } /// The paths a base tree holds, cached in the workspace (bases change /// only on sync, new and land). pub fn base_paths(&self, s: &Session, base: &Id) -> Result> { let cache = s.root.join(ws::DIR).join("base"); if let Ok(text) = std::fs::read_to_string(&cache) && let Some((id, rest)) = text.split_once('\n') && id == base.hex() { return Ok(rest.lines().map(str::to_string).collect()); } let files = self.files(base)?; let mut text = format!("{}\n", base.hex()); for p in files.keys() { text.push_str(p); text.push('\n'); } std::fs::write(&cache, text)?; Ok(files.into_keys().collect()) } /// Makes the workspace folder hold `tree`. pub fn show_tree(&self, s: &Session, tree: &Id) -> Result<()> { self.host(&s.project).fetch_tree(&self.store, &s.project, tree, None)?; let index = Index::load(&s.root); let files = self.files(tree)?; let mut next = ws::materialize(&s.root, &self.store, &index, &files, &s.ws.only, None)?; next.save(&s.root)?; Ok(()) } /// Writes the user's own files (like .env) into a workspace if missing. pub fn place_mine(&self, project: &Project, root: &Path) -> Result { let mut n = 0; for (path, id, exec) in self.db.mine(&project.id)? { let abs = root.join(&path); if abs.exists() { continue; } if let Some(parent) = abs.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&abs, self.store.read_file(&id)?)?; use std::os::unix::fs::PermissionsExt; let mode = if exec { 0o700 } else { 0o600 }; std::fs::set_permissions(&abs, std::fs::Permissions::from_mode(mode))?; n += 1; } Ok(n) } pub fn put_workspace_change(&self, s: &mut Session, change: &str) -> Result<()> { s.ws.change = change.to_string(); self.db.put_workspace(&s.ws)?; Ok(()) } /// Files under `only` for a tree, as a [`Files`] map (for workspaces /// limited to some folders). pub fn scoped(&self, only: &[String], files: &Files) -> Files { if only.is_empty() { return files.clone(); } files.iter().filter(|(p, _)| only.iter().any(|o| tree::under(p, o))).map(|(p, e)| (p.clone(), *e)).collect() } } /// Who's working: VCS_NAME and VCS_EMAIL, then the host's account, then /// ~/.gitconfig's user, then the login name. pub fn identity(project: &Project, db: &Db) -> (String, String) { let _ = (project, db); let mut name = std::env::var("VCS_NAME").ok().filter(|s| !s.is_empty()); let mut email = std::env::var("VCS_EMAIL").ok().filter(|s| !s.is_empty()); if (name.is_none() || email.is_none()) && project.hosted() && let Some(account) = crate::remote::account(project) { name = name.or(Some(account.0)); email = email.or(Some(account.1)); } if name.is_none() || email.is_none() { let (n, e) = gitconfig_user(); name = name.or(n); email = email.or(e); } let name = name.unwrap_or_else(|| std::env::var("USER").unwrap_or_else(|_| "someone".into())); let email = email.unwrap_or_else(|| format!("{}@localhost", name.to_lowercase().replace(' ', "."))); (name, email) } fn gitconfig_user() -> (Option, Option) { let Some(home) = std::env::var_os("HOME") else { return (None, None) }; let Ok(text) = std::fs::read_to_string(PathBuf::from(home).join(".gitconfig")) else { return (None, None) }; let mut in_user = false; let (mut name, mut email) = (None, None); for line in text.lines() { let line = line.trim(); if line.starts_with('[') { in_user = line == "[user]"; continue; } if in_user && let Some((k, v)) = line.split_once('=') { match k.trim() { "name" => name = Some(v.trim().to_string()), "email" => email = Some(v.trim().to_string()), _ => {} } } } (name, email) } /// Index entries as a [`Files`] map. pub fn index_files(index: &Index) -> Files { index.entries.iter().map(|(p, e)| (p.clone(), e.entry)).collect::() } pub fn entry_map(files: &Files) -> Vec<(String, Entry)> { files.iter().map(|(p, e)| (p.clone(), *e)).collect() } pub fn ensure_dir_empty(path: &Path) -> Result<(), Fail> { if path.exists() { let empty = std::fs::read_dir(path).with_context(|| format!("reading {}", path.display()))?.next().is_none(); if !empty { return Err(Fail::new("bad_usage", format!("{} already exists and isn't empty", path.display())) .state("nothing changed") .next("pick a new folder name")); } } Ok(()) }