Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 5 |
| 6 | use anyhow::{Context, Result}; |
| 7 | use vcs_core::tree::{self, Entry, Files}; |
| 8 | use vcs_core::version::Version; |
| 9 | use vcs_core::Id; |
| 10 |
| 11 | use crate::db::{Change, Db, Project, Save, Workspace}; |
| 12 | use crate::host::{Host, Local}; |
| 13 | use crate::ids; |
| 14 | use crate::objects::Store; |
| 15 | use crate::out::Fail; |
| 16 | use crate::paths; |
| 17 | use crate::remote::Remote; |
| 18 | use crate::ws::{self, Index, Lock}; |
| 19 |
| 20 | pub struct App { |
| 21 | pub db: Db, |
| 22 | pub store: Store, |
| 23 | pub json: bool, |
| 24 | pub cwd: PathBuf, |
| 25 | /// Things that happened on the side, printed after the answer. |
| 26 | pub notes: std::cell::RefCell<Vec<String>>, |
| 27 | } |
| 28 |
| 29 | /// An open workspace, locked for the command's lifetime. |
| 30 | pub struct Session { |
| 31 | pub root: PathBuf, |
| 32 | pub ws: Workspace, |
| 33 | pub project: Project, |
| 34 | _lock: Lock, |
| 35 | } |
| 36 |
| 37 | impl App { |
| 38 | pub fn open(json: bool, cwd: PathBuf) -> Result<App> { |
| 39 | let home = paths::home(); |
| 40 | Ok(App { db: Db::open(&home)?, store: Store::open(&paths::objects())?, json, cwd, notes: Default::default() }) |
| 41 | } |
| 42 |
| 43 | pub fn host(&self, project: &Project) -> Box<dyn Host> { |
| 44 | if project.hosted() { Box::new(Remote::for_project(project)) } else { Box::new(Local) } |
| 45 | } |
| 46 |
| 47 | /// The workspace containing the current folder. |
| 48 | pub fn session(&self) -> Result<Session, Fail> { |
| 49 | let root = ws::find(&self.cwd).ok_or_else(|| { |
| 50 | Fail::new("not_found", "this folder isn't in a vcs workspace") |
| 51 | .state("nothing changed") |
| 52 | .next("cd into a workspace, or vcs get <project> <folder>") |
| 53 | })?; |
| 54 | self.session_at(&root) |
| 55 | } |
| 56 |
| 57 | pub fn session_at(&self, root: &Path) -> Result<Session, Fail> { |
| 58 | let id = ws::read_id(root)?; |
| 59 | let lock = ws::lock(root)?; |
| 60 | let mut workspace = self.db.workspace(&id)?.ok_or_else(|| { |
| 61 | Fail::new("not_found", format!("{} is a workspace this machine doesn't know", root.display())) |
| 62 | .state("nothing changed") |
| 63 | .next("vcs get <project> <new-folder> to make a new workspace") |
| 64 | })?; |
| 65 | let canonical = crate::sys::canonical(root).unwrap_or_else(|_| root.to_path_buf()); |
| 66 | if workspace.path != canonical { |
| 67 | // The folder moved; follow it. |
| 68 | workspace.path = canonical.clone(); |
| 69 | self.db.put_workspace(&workspace)?; |
| 70 | } |
| 71 | let project = self.db.project(&workspace.project)?.ok_or_else(|| Fail::new("not_found", "this workspace's project is missing"))?; |
| 72 | Ok(Session { root: canonical, ws: workspace, project, _lock: lock }) |
| 73 | } |
| 74 |
| 75 | pub fn change(&self, id: &str) -> Result<Change, Fail> { |
| 76 | self.db.change(id)?.ok_or_else(|| Fail::new("not_found", format!("no change {id}")).state("nothing changed")) |
| 77 | } |
| 78 |
| 79 | /// A change named by its ID or a unique prefix of four letters or more. |
| 80 | pub fn find_change(&self, project: &Project, text: &str) -> Result<Change, Fail> { |
| 81 | if !ids::looks_like_change(text) { |
| 82 | return Err(Fail::new("bad_usage", format!("{text} isn't a change ID (changes are 4 or more letters)")) |
| 83 | .state("nothing changed") |
| 84 | .next("vcs log --changes to see change IDs")); |
| 85 | } |
| 86 | let mut found = self.db.changes_by_prefix(&project.id, text)?; |
| 87 | if found.is_empty() && project.hosted() { |
| 88 | // Someone else's change, or one from another machine. |
| 89 | if let Some(c) = Remote::for_project(project).fetch_change(&self.db, &self.store, project, text)? { |
| 90 | found.push(c); |
| 91 | } |
| 92 | } |
| 93 | match found.len() { |
| 94 | 0 => Err(Fail::new("not_found", format!("no change {text} in this project")) |
| 95 | .state("nothing changed") |
| 96 | .next("vcs log --changes")), |
| 97 | 1 => Ok(found.remove(0)), |
| 98 | _ => Err(Fail::new("bad_usage", format!("{text} matches {} changes; use more letters", found.len())) |
| 99 | .state("nothing changed") |
| 100 | .next("vcs log --changes")), |
| 101 | } |
| 102 | } |
| 103 |
| 104 | pub fn short(&self, project: &Project, id: &str) -> String { |
| 105 | let others = self.db.change_ids(&project.id).unwrap_or_default(); |
| 106 | ids::short(id, &others) |
| 107 | } |
| 108 |
| 109 | pub fn author(&self, project: &Project) -> String { |
| 110 | let me = identity(project, &self.db); |
| 111 | match std::env::var("VCS_AGENT").ok().filter(|a| !a.is_empty()) { |
| 112 | Some(agent) => format!("{} (via {agent}) <{}>", me.0, me.1), |
| 113 | None => format!("{} <{}>", me.0, me.1), |
| 114 | } |
| 115 | } |
| 116 |
| 117 | pub fn main(&self, project: &Project) -> Result<Option<Version>> { |
| 118 | self.db.latest_version(&project.id) |
| 119 | } |
| 120 |
| 121 | /// The latest main, asking the host when the project is hosted. |
| 122 | pub fn refresh(&self, project: &Project) -> Result<Option<Version>> { |
| 123 | let mut v = self.host(project).refresh(&self.db, &self.store, project)?; |
| 124 | // Someone purged paths from the host's history: out of this machine's too. |
| 125 | let (seen, host) = self.db.purges(&project.id)?; |
| 126 | if host > seen { |
| 127 | crate::purge::catch_up(self, project)?; |
| 128 | v = self.host(project).refresh(&self.db, &self.store, project)?; |
| 129 | } |
| 130 | self.db.set_checked(&project.id, ids::now())?; |
| 131 | Ok(v) |
| 132 | } |
| 133 |
| 134 | /// Version `n` of main, fetching history this machine doesn't keep yet |
| 135 | /// (older than it started with, or newer than it last looked). |
| 136 | pub fn version(&self, project: &Project, n: u64) -> Result<Option<Version>> { |
| 137 | if let Some(v) = self.db.version(&project.id, n)? { |
| 138 | return Ok(Some(v)); |
| 139 | } |
| 140 | if n < self.db.history_from(&project.id)? { |
| 141 | self.host(project).fetch_version(&self.db, project, n)?; |
| 142 | } else { |
| 143 | self.refresh(project)?; |
| 144 | } |
| 145 | self.db.version(&project.id, n) |
| 146 | } |
| 147 |
| 148 | /// Makes sure this machine keeps main's history from `n` on. |
| 149 | pub fn history(&self, project: &Project, n: u64) -> Result<()> { |
| 150 | self.host(project).fetch_history(&self.db, project, n) |
| 151 | } |
| 152 |
| 153 | pub fn files(&self, tree: &Id) -> Result<Files> { |
| 154 | Ok(tree::flatten(&self.store, tree)?) |
| 155 | } |
| 156 |
| 157 | /// Saves the workspace into its change. Returns the change as saved |
| 158 | /// (a new one if another workspace took the change over meanwhile). |
| 159 | pub fn save(&self, s: &mut Session) -> Result<Change> { |
| 160 | self.save_with(s, true) |
| 161 | } |
| 162 |
| 163 | /// Saves without telling the host (a landing carries the change itself). |
| 164 | pub fn save_local(&self, s: &mut Session) -> Result<Change> { |
| 165 | self.save_with(s, false) |
| 166 | } |
| 167 |
| 168 | fn save_with(&self, s: &mut Session, publish: bool) -> Result<Change> { |
| 169 | let mut change = self.change(&s.ws.change).map_err(|f| f.into_anyhow())?; |
| 170 | let index = Index::load(&s.root); |
| 171 | // A whole workspace's files are its index's; with --only, the |
| 172 | // change's tree gives the rest. |
| 173 | let known: Files = if s.ws.only.is_empty() { Files::new() } else { self.files(&change.tree())? }; |
| 174 | let personal = crate::access::personal(self, &s.project.id)?; |
| 175 | let base_tree = change.base_tree; |
| 176 | let mut snap = ws::snapshot(&s.root, &self.store, &known, &s.ws.only, &index, &personal, &|| self.base_paths(s, &base_tree))?; |
| 177 | if let Some(next) = &mut snap.index |
| 178 | && !index.same_as(next) |
| 179 | { |
| 180 | next.save(&s.root)?; |
| 181 | } |
| 182 | let saved_mine = self.db.mine(&s.project.id)?; |
| 183 | let mut mine_changed = false; |
| 184 | for (path, id, exec) in &snap.mine { |
| 185 | if !saved_mine.iter().any(|(p, i, x)| p == path && i == id && x == exec) { |
| 186 | self.db.put_mine(&s.project.id, path, id, *exec)?; |
| 187 | mine_changed = true; |
| 188 | } |
| 189 | } |
| 190 | let _ = self.db.conn.execute("INSERT OR IGNORE INTO complete (tree) VALUES (?1)", [snap.tree.hex()]); |
| 191 | let mut dirty = false; |
| 192 | if snap.tree != change.tree() { |
| 193 | change.head_tree = Some(snap.tree); |
| 194 | change.saves += 1; |
| 195 | self.db.add_save( |
| 196 | &Save { change: change.id.clone(), n: change.saves, tree: snap.tree, base_tree: change.base_tree, at: ids::now(), uploaded: false }, |
| 197 | &s.ws.id, |
| 198 | )?; |
| 199 | dirty = true; |
| 200 | } |
| 201 | if !change.conflicts.is_empty() { |
| 202 | let before = change.conflicts.len(); |
| 203 | change.conflicts.retain(|c| std::fs::read(s.root.join(&c.path)).is_ok_and(|b| ws::has_markers(&b))); |
| 204 | dirty |= change.conflicts.len() != before; |
| 205 | } |
| 206 | if dirty { |
| 207 | self.db.put_change(&change)?; |
| 208 | } |
| 209 | if s.project.hosted() && publish { |
| 210 | if mine_changed { |
| 211 | let _ = crate::remote::push_mine(self, &s.project); |
| 212 | } |
| 213 | if dirty || !self.db.unuploaded_saves(&change.id)?.is_empty() { |
| 214 | // The change follows you to other machines. Offline, it |
| 215 | // uploads on a later command. |
| 216 | if let Err(e) = self.host(&s.project).publish_change(&self.db, &self.store, &s.project, &change, &s.ws.id) { |
| 217 | let fail = Fail::from(e); |
| 218 | if fail.code == "held_elsewhere" { |
| 219 | return self.rescue(s, &change, fail.message.clone()); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | Ok(change) |
| 225 | } |
| 226 |
| 227 | /// Another workspace took this workspace's change over. What this one |
| 228 | /// has goes into a new change, so nothing is lost. |
| 229 | fn rescue(&self, s: &mut Session, taken: &Change, why: String) -> Result<Change> { |
| 230 | let mut fresh = Change::new(ids::new_change_id(), &s.project.id, taken.base_tree, taken.base_version, &self.author(&s.project)); |
| 231 | fresh.head_tree = taken.head_tree; |
| 232 | fresh.saves = 1; |
| 233 | fresh.on_change = taken.on_change.clone(); |
| 234 | fresh.title = format!("Rescued from {}", taken.id); |
| 235 | self.db.put_change(&fresh)?; |
| 236 | 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)?; |
| 237 | // The taken change's newest state is the host's. |
| 238 | if let Some(remote) = Some(crate::remote::Remote::for_project(&s.project)) { |
| 239 | let _ = remote.fetch_change(&self.db, &self.store, &s.project, &taken.id); |
| 240 | } |
| 241 | s.ws.change = fresh.id.clone(); |
| 242 | self.db.put_workspace(&s.ws)?; |
| 243 | let _ = self.host(&s.project).publish_change(&self.db, &self.store, &s.project, &fresh, &s.ws.id); |
| 244 | self.notes.borrow_mut().push(format!("{why}; what this workspace had is in new change {}", fresh.id)); |
| 245 | Ok(fresh) |
| 246 | } |
| 247 |
| 248 | /// The paths a base tree holds, cached in the workspace (bases change |
| 249 | /// only on sync, new and land). |
| 250 | pub fn base_paths(&self, s: &Session, base: &Id) -> Result<std::collections::HashSet<String>> { |
| 251 | let cache = s.root.join(ws::DIR).join("base"); |
| 252 | if let Ok(text) = std::fs::read_to_string(&cache) |
| 253 | && let Some((id, rest)) = text.split_once('\n') |
| 254 | && id == base.hex() |
| 255 | { |
| 256 | return Ok(rest.lines().map(str::to_string).collect()); |
| 257 | } |
| 258 | let files = self.files(base)?; |
| 259 | let mut text = format!("{}\n", base.hex()); |
| 260 | for p in files.keys() { |
| 261 | text.push_str(p); |
| 262 | text.push('\n'); |
| 263 | } |
| 264 | std::fs::write(&cache, text)?; |
| 265 | Ok(files.into_keys().collect()) |
| 266 | } |
| 267 |
| 268 | /// Makes the workspace folder hold `tree`. |
| 269 | pub fn show_tree(&self, s: &Session, tree: &Id) -> Result<()> { |
| 270 | self.host(&s.project).fetch_tree(&self.store, &s.project, tree, None)?; |
| 271 | let index = Index::load(&s.root); |
| 272 | let files = self.files(tree)?; |
| 273 | let mut next = ws::materialize(&s.root, &self.store, &index, &files, &s.ws.only, None)?; |
| 274 | next.save(&s.root)?; |
| 275 | Ok(()) |
| 276 | } |
| 277 |
| 278 | /// Writes the user's own files (like .env) into a workspace if missing. |
| 279 | pub fn place_mine(&self, project: &Project, root: &Path) -> Result<usize> { |
| 280 | let mut n = 0; |
| 281 | for (path, id, exec) in self.db.mine(&project.id)? { |
| 282 | let abs = root.join(&path); |
| 283 | if abs.exists() { |
| 284 | continue; |
| 285 | } |
| 286 | if let Some(parent) = abs.parent() { |
| 287 | std::fs::create_dir_all(parent)?; |
| 288 | } |
| 289 | std::fs::write(&abs, self.store.read_file(&id)?)?; |
| 290 | crate::sys::owner_only(&abs, exec)?; |
| 291 | n += 1; |
| 292 | } |
| 293 | Ok(n) |
| 294 | } |
| 295 |
| 296 | pub fn put_workspace_change(&self, s: &mut Session, change: &str) -> Result<()> { |
| 297 | s.ws.change = change.to_string(); |
| 298 | self.db.put_workspace(&s.ws)?; |
| 299 | Ok(()) |
| 300 | } |
| 301 |
| 302 | /// Files under `only` for a tree, as a [`Files`] map (for workspaces |
| 303 | /// limited to some folders). |
| 304 | pub fn scoped(&self, only: &[String], files: &Files) -> Files { |
| 305 | if only.is_empty() { |
| 306 | return files.clone(); |
| 307 | } |
| 308 | files.iter().filter(|(p, _)| only.iter().any(|o| tree::under(p, o))).map(|(p, e)| (p.clone(), *e)).collect() |
| 309 | } |
| 310 | } |
| 311 |
| 312 | /// Who's working: VCS_NAME and VCS_EMAIL, then the host's account, then |
| 313 | /// ~/.gitconfig's user, then the login name. |
| 314 | pub fn identity(project: &Project, db: &Db) -> (String, String) { |
| 315 | let _ = (project, db); |
| 316 | let mut name = std::env::var("VCS_NAME").ok().filter(|s| !s.is_empty()); |
| 317 | let mut email = std::env::var("VCS_EMAIL").ok().filter(|s| !s.is_empty()); |
| 318 | if (name.is_none() || email.is_none()) |
| 319 | && project.hosted() |
| 320 | && let Some(account) = crate::remote::account(project) |
| 321 | { |
| 322 | name = name.or(Some(account.0)); |
| 323 | email = email.or(Some(account.1)); |
| 324 | } |
| 325 | if name.is_none() || email.is_none() { |
| 326 | let (n, e) = gitconfig_user(); |
| 327 | name = name.or(n); |
| 328 | email = email.or(e); |
| 329 | } |
| 330 | let name = name.unwrap_or_else(|| crate::sys::user_name().unwrap_or_else(|| "someone".into())); |
| 331 | let email = email.unwrap_or_else(|| format!("{}@localhost", name.to_lowercase().replace(' ', "."))); |
| 332 | (name, email) |
| 333 | } |
| 334 |
| 335 | fn gitconfig_user() -> (Option<String>, Option<String>) { |
| 336 | let Some(home) = crate::sys::user_home() else { return (None, None) }; |
| 337 | let Ok(text) = std::fs::read_to_string(home.join(".gitconfig")) else { return (None, None) }; |
| 338 | let mut in_user = false; |
| 339 | let (mut name, mut email) = (None, None); |
| 340 | for line in text.lines() { |
| 341 | let line = line.trim(); |
| 342 | if line.starts_with('[') { |
| 343 | in_user = line == "[user]"; |
| 344 | continue; |
| 345 | } |
| 346 | if in_user && let Some((k, v)) = line.split_once('=') { |
| 347 | match k.trim() { |
| 348 | "name" => name = Some(v.trim().to_string()), |
| 349 | "email" => email = Some(v.trim().to_string()), |
| 350 | _ => {} |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | (name, email) |
| 355 | } |
| 356 |
| 357 | /// Index entries as a [`Files`] map. |
| 358 | pub fn index_files(index: &Index) -> Files { |
| 359 | index.entries.iter().map(|(p, e)| (p.clone(), e.entry)).collect::<Files>() |
| 360 | } |
| 361 |
| 362 | pub fn entry_map(files: &Files) -> Vec<(String, Entry)> { |
| 363 | files.iter().map(|(p, e)| (p.clone(), *e)).collect() |
| 364 | } |
| 365 |
| 366 | pub fn ensure_dir_empty(path: &Path) -> Result<(), Fail> { |
| 367 | if path.exists() { |
| 368 | let empty = std::fs::read_dir(path).with_context(|| format!("reading {}", path.display()))?.next().is_none(); |
| 369 | if !empty { |
| 370 | return Err(Fail::new("bad_usage", format!("{} already exists and isn't empty", path.display())) |
| 371 | .state("nothing changed") |
| 372 | .next("pick a new folder name")); |
| 373 | } |
| 374 | } |
| 375 | Ok(()) |
| 376 | } |
| 377 |