Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 6 | //! many commits share it. A git branch can come in as a change. Publishing |
| 7 | //! an imported project copies its original git history (branches and tags, |
| 8 | //! byte for byte) to the host's git view, which then carries on from it. |
| 9 |
| 10 | use std::collections::HashMap; |
| 11 | use std::io::{BufRead, BufReader, IsTerminal, Read, Write}; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; |
| 14 | use std::time::Instant; |
| 15 |
| 16 | use anyhow::{Result, anyhow, bail}; |
| 17 | use base64::Engine; |
| 18 | use serde_json::json; |
| 19 | use vcs_core::object::{Kind, Object}; |
| 20 | use vcs_core::tree::{self, EntryKind, TreeEntry}; |
| 21 | use vcs_core::version::Version; |
| 22 | use vcs_core::Id; |
| 23 |
| 24 | use crate::app::App; |
| 25 | use crate::db::{Change, Project, Save, Workspace}; |
| 26 | use crate::ids; |
| 27 | use crate::objects::Store; |
| 28 | use crate::out::{Fail, Out, Report}; |
| 29 | use crate::ws::{self, Index}; |
| 30 |
| 31 | /// A git repository to read: one on this machine, or a temporary mirror of |
| 32 | /// a remote one (removed when dropped). |
| 33 | pub struct Repo { |
| 34 | pub dir: PathBuf, |
| 35 | temp: Option<PathBuf>, |
| 36 | } |
| 37 |
| 38 | impl Drop for Repo { |
| 39 | fn drop(&mut self) { |
| 40 | if let Some(t) = &self.temp { |
| 41 | let _ = std::fs::remove_dir_all(t); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 |
| 46 | fn git_missing() -> Fail { |
| 47 | Fail::new("failed", "reading git repositories needs git installed").state("nothing changed") |
| 48 | } |
| 49 |
| 50 | /// Runs git in `dir` and returns what it printed. |
| 51 | fn git(dir: &Path, args: &[&str]) -> Result<String, Fail> { |
| 52 | let out = Command::new("git").arg("--git-dir").arg(dir).args(args).stdin(Stdio::null()).output().map_err(|_| git_missing())?; |
| 53 | if !out.status.success() { |
| 54 | let err = String::from_utf8_lossy(&out.stderr).trim().to_string(); |
| 55 | return Err(Fail::new("failed", format!("git {}: {err}", args.first().unwrap_or(&""))).state("nothing changed")); |
| 56 | } |
| 57 | Ok(String::from_utf8_lossy(&out.stdout).into_owned()) |
| 58 | } |
| 59 |
| 60 | /// The clone URL for a project address or URL (Upstream projects clone from git.coline.app). |
| 61 | fn clone_url(text: &str) -> String { |
| 62 | let t = text.trim().trim_end_matches('/'); |
| 63 | let bare = t.strip_prefix("https://").or_else(|| t.strip_prefix("http://")).unwrap_or(t); |
| 64 | if let Some(rest) = bare.strip_prefix("upstream.codes/") { |
| 65 | let rest = rest.strip_suffix(".git").unwrap_or(rest); |
| 66 | if rest.split('/').count() == 2 { |
| 67 | return format!("https://git.coline.app/{rest}.git"); |
| 68 | } |
| 69 | } |
| 70 | if t.contains("://") || t.contains('@') { t.to_string() } else { format!("https://{t}") } |
| 71 | } |
| 72 |
| 73 | /// Opens a git repository: a folder on this machine, or a URL (mirrored to a temporary folder). |
| 74 | pub fn open(app: &App, source: &str) -> Result<Repo, Fail> { |
| 75 | let local = app.cwd.join(source); |
| 76 | if local.exists() { |
| 77 | let out = Command::new("git").arg("-C").arg(&local).args(["rev-parse", "--absolute-git-dir"]).output().map_err(|_| git_missing())?; |
| 78 | if !out.status.success() { |
| 79 | return Err(Fail::new("bad_usage", format!("{source} isn't a git repository")).state("nothing changed")); |
| 80 | } |
| 81 | return Ok(Repo { dir: PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()), temp: None }); |
| 82 | } |
| 83 | let url = clone_url(source); |
| 84 | let temp = crate::paths::home().join("tmp").join(format!("import-{}", ids::new_workspace_id())); |
| 85 | std::fs::create_dir_all(temp.parent().unwrap())?; |
| 86 | let status = Command::new("git") |
| 87 | .args(["clone", "--mirror", "--quiet", &url]) |
| 88 | .arg(&temp) |
| 89 | .stdin(Stdio::null()) |
| 90 | .status() |
| 91 | .map_err(|_| git_missing())?; |
| 92 | if !status.success() { |
| 93 | let _ = std::fs::remove_dir_all(&temp); |
| 94 | return Err(Fail::new("not_found", format!("couldn't clone {url}")).state("nothing changed")); |
| 95 | } |
| 96 | Ok(Repo { dir: temp.clone(), temp: Some(temp) }) |
| 97 | } |
| 98 |
| 99 | impl Repo { |
| 100 | /// The default branch's name and commit. |
| 101 | fn default_branch(&self) -> Result<(String, String), Fail> { |
| 102 | let head = git(&self.dir, &["symbolic-ref", "-q", "HEAD"]).unwrap_or_default(); |
| 103 | let name = head.trim().strip_prefix("refs/heads/").unwrap_or("HEAD").to_string(); |
| 104 | let sha = git(&self.dir, &["rev-parse", "--verify", "-q", "HEAD^{commit}"]) |
| 105 | .map_err(|_| Fail::new("bad_usage", "the git repository has no commits").state("nothing changed"))?; |
| 106 | Ok((name, sha.trim().to_string())) |
| 107 | } |
| 108 | } |
| 109 |
| 110 | /// `git cat-file --batch`: objects by ID, through one long-running git. |
| 111 | struct Cat { |
| 112 | child: Child, |
| 113 | stdin: ChildStdin, |
| 114 | out: BufReader<ChildStdout>, |
| 115 | } |
| 116 |
| 117 | impl Cat { |
| 118 | fn open(dir: &Path) -> Result<Cat> { |
| 119 | let mut child = Command::new("git") |
| 120 | .arg("--git-dir") |
| 121 | .arg(dir) |
| 122 | .args(["cat-file", "--batch"]) |
| 123 | .stdin(Stdio::piped()) |
| 124 | .stdout(Stdio::piped()) |
| 125 | .stderr(Stdio::null()) |
| 126 | .spawn() |
| 127 | .map_err(|_| git_missing().into_anyhow())?; |
| 128 | let stdin = child.stdin.take().unwrap(); |
| 129 | let out = BufReader::with_capacity(1 << 20, child.stdout.take().unwrap()); |
| 130 | Ok(Cat { child, stdin, out }) |
| 131 | } |
| 132 |
| 133 | fn get(&mut self, sha: &str) -> Result<(String, Vec<u8>)> { |
| 134 | writeln!(self.stdin, "{sha}")?; |
| 135 | self.stdin.flush()?; |
| 136 | let mut header = String::new(); |
| 137 | self.out.read_line(&mut header)?; |
| 138 | let parts: Vec<&str> = header.trim_end().split(' ').collect(); |
| 139 | if parts.len() != 3 { |
| 140 | bail!("git object {sha} is missing"); |
| 141 | } |
| 142 | let size: usize = parts[2].parse()?; |
| 143 | let mut data = vec![0; size]; |
| 144 | self.out.read_exact(&mut data)?; |
| 145 | let mut newline = [0u8; 1]; |
| 146 | self.out.read_exact(&mut newline)?; |
| 147 | Ok((parts[1].to_string(), data)) |
| 148 | } |
| 149 | } |
| 150 |
| 151 | impl Drop for Cat { |
| 152 | fn drop(&mut self) { |
| 153 | let _ = self.child.kill(); |
| 154 | let _ = self.child.wait(); |
| 155 | } |
| 156 | } |
| 157 |
| 158 | fn hex(bytes: &[u8]) -> String { |
| 159 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 160 | } |
| 161 |
| 162 | /// Git trees and files as vcs objects, each converted once. |
| 163 | struct Converter<'a> { |
| 164 | store: &'a Store, |
| 165 | cat: Cat, |
| 166 | trees: HashMap<[u8; 20], Option<Id>>, |
| 167 | files: HashMap<[u8; 20], Id>, |
| 168 | submodules: usize, |
| 169 | odd_names: usize, |
| 170 | } |
| 171 |
| 172 | impl<'a> Converter<'a> { |
| 173 | fn new(store: &'a Store, repo: &Repo) -> Result<Converter<'a>> { |
| 174 | Ok(Converter { store, cat: Cat::open(&repo.dir)?, trees: HashMap::new(), files: HashMap::new(), submodules: 0, odd_names: 0 }) |
| 175 | } |
| 176 |
| 177 | /// Entries of a git tree: (mode, name, id). |
| 178 | fn entries(&mut self, sha: &[u8; 20]) -> Result<Vec<(Vec<u8>, Vec<u8>, [u8; 20])>> { |
| 179 | let (kind, data) = self.cat.get(&hex(sha))?; |
| 180 | if kind != "tree" { |
| 181 | bail!("git object {} isn't a tree", hex(sha)); |
| 182 | } |
| 183 | let mut out = Vec::new(); |
| 184 | let mut at = 0; |
| 185 | while at < data.len() { |
| 186 | let space = data[at..].iter().position(|&b| b == b' ').ok_or_else(|| anyhow!("bad git tree"))? + at; |
| 187 | let nul = data[space + 1..].iter().position(|&b| b == 0).ok_or_else(|| anyhow!("bad git tree"))? + space + 1; |
| 188 | let id: [u8; 20] = data.get(nul + 1..nul + 21).ok_or_else(|| anyhow!("bad git tree"))?.try_into()?; |
| 189 | out.push((data[at..space].to_vec(), data[space + 1..nul].to_vec(), id)); |
| 190 | at = nul + 21; |
| 191 | } |
| 192 | Ok(out) |
| 193 | } |
| 194 |
| 195 | /// A git tree as a vcs tree (None: nothing left in it, for a subfolder). |
| 196 | fn tree(&mut self, sha: [u8; 20], root: bool) -> Result<Option<Id>> { |
| 197 | if let Some(t) = self.trees.get(&sha) { |
| 198 | return Ok(*t); |
| 199 | } |
| 200 | let mut entries = Vec::new(); |
| 201 | for (mode, name, id) in self.entries(&sha)? { |
| 202 | let Ok(name) = String::from_utf8(name) else { |
| 203 | self.odd_names += 1; |
| 204 | continue; |
| 205 | }; |
| 206 | if root && name == ws::DIR { |
| 207 | self.odd_names += 1; |
| 208 | continue; |
| 209 | } |
| 210 | let (kind, id) = match mode.as_slice() { |
| 211 | b"40000" | b"040000" => match self.tree(id, false)? { |
| 212 | Some(t) => (EntryKind::Tree, t), |
| 213 | None => continue, |
| 214 | }, |
| 215 | b"160000" => { |
| 216 | // Submodules stay in the git view only. |
| 217 | self.submodules += 1; |
| 218 | continue; |
| 219 | } |
| 220 | b"120000" => (EntryKind::Link, self.file(id)?), |
| 221 | m if m.ends_with(b"755") => (EntryKind::Exec, self.file(id)?), |
| 222 | _ => (EntryKind::File, self.file(id)?), |
| 223 | }; |
| 224 | entries.push(TreeEntry { name, kind, id }); |
| 225 | } |
| 226 | let out = if entries.is_empty() && !root { None } else { Some(self.store.put(&Object::new(Kind::Tree, tree::encode(&entries)))?) }; |
| 227 | self.trees.insert(sha, out); |
| 228 | Ok(out) |
| 229 | } |
| 230 |
| 231 | fn file(&mut self, sha: [u8; 20]) -> Result<Id> { |
| 232 | if let Some(f) = self.files.get(&sha) { |
| 233 | return Ok(*f); |
| 234 | } |
| 235 | let (_, data) = self.cat.get(&hex(&sha))?; |
| 236 | let id = self.store.put_file(&data)?; |
| 237 | self.files.insert(sha, id); |
| 238 | Ok(id) |
| 239 | } |
| 240 |
| 241 | /// Native ID → git ID for everything under a converted git tree. |
| 242 | fn ids_under(&mut self, sha: [u8; 20], out: &mut Vec<(Id, String)>) -> Result<()> { |
| 243 | let Some(Some(native)) = self.trees.get(&sha).copied() else { return Ok(()) }; |
| 244 | out.push((native, hex(&sha))); |
| 245 | for (mode, _, id) in self.entries(&sha)? { |
| 246 | if mode == b"40000" || mode == b"040000" { |
| 247 | self.ids_under(id, out)?; |
| 248 | } else if let Some(f) = self.files.get(&id) { |
| 249 | out.push((*f, hex(&id))); |
| 250 | } |
| 251 | } |
| 252 | Ok(()) |
| 253 | } |
| 254 | } |
| 255 |
| 256 | fn sha_bytes(text: &str) -> Result<[u8; 20]> { |
| 257 | let t = text.trim(); |
| 258 | if t.len() != 40 { |
| 259 | bail!("{t} isn't a git object ID"); |
| 260 | } |
| 261 | let mut out = [0u8; 20]; |
| 262 | for (i, b) in out.iter_mut().enumerate() { |
| 263 | *b = u8::from_str_radix(&t[i * 2..i * 2 + 2], 16)?; |
| 264 | } |
| 265 | Ok(out) |
| 266 | } |
| 267 |
| 268 | /// A change ID made from a git commit, so importing twice gives the same IDs. |
| 269 | fn change_id(sha: &str) -> String { |
| 270 | sha_bytes(sha).map(|b| b.iter().take(ids::CHANGE_ID_LEN).map(|x| ids::LETTERS[*x as usize % ids::LETTERS.len()] as char).collect()).unwrap_or_else(|_| ids::new_change_id()) |
| 271 | } |
| 272 |
| 273 | struct Commit { |
| 274 | sha: String, |
| 275 | tree: String, |
| 276 | author: String, |
| 277 | time: i64, |
| 278 | title: String, |
| 279 | body: String, |
| 280 | } |
| 281 |
| 282 | fn split_message(message: &str) -> (String, String) { |
| 283 | let mut parts = message.trim().splitn(2, '\n'); |
| 284 | (parts.next().unwrap_or("").trim().to_string(), parts.next().unwrap_or("").trim().to_string()) |
| 285 | } |
| 286 |
| 287 | /// Commits on `rev`'s first-parent line, oldest first. |
| 288 | fn commits(repo: &Repo, rev: &str, limit: Option<usize>) -> Result<Vec<Commit>, Fail> { |
| 289 | let mut args = vec!["log", "--first-parent", "--format=%H%x00%T%x00%an%x00%ae%x00%at%x00%B%x1e"]; |
| 290 | let n; |
| 291 | if let Some(l) = limit { |
| 292 | n = format!("-{l}"); |
| 293 | args.push(&n); |
| 294 | } else { |
| 295 | args.push("--reverse"); |
| 296 | } |
| 297 | args.push(rev); |
| 298 | let text = git(&repo.dir, &args)?; |
| 299 | let mut out = Vec::new(); |
| 300 | for record in text.split('\x1e') { |
| 301 | let record = record.trim_start_matches('\n'); |
| 302 | if record.is_empty() { |
| 303 | continue; |
| 304 | } |
| 305 | let f: Vec<&str> = record.splitn(6, '\0').collect(); |
| 306 | if f.len() != 6 { |
| 307 | continue; |
| 308 | } |
| 309 | let (title, body) = split_message(f[5]); |
| 310 | out.push(Commit { sha: f[0].into(), tree: f[1].into(), author: format!("{} <{}>", f[2], f[3]), time: f[4].parse().unwrap_or(0), title, body }); |
| 311 | } |
| 312 | Ok(out) |
| 313 | } |
| 314 |
| 315 | fn progress(app: &App, text: &str, last: &mut Instant) { |
| 316 | if !app.json && std::io::stderr().is_terminal() && last.elapsed().as_millis() > 500 { |
| 317 | eprint!("\r{text} "); |
| 318 | *last = Instant::now(); |
| 319 | } |
| 320 | } |
| 321 |
| 322 | fn notes_for(app: &App, conv: &Converter) { |
| 323 | if conv.submodules > 0 { |
| 324 | app.notes.borrow_mut().push(format!("{} submodule entries stay in the git view only", conv.submodules)); |
| 325 | } |
| 326 | if conv.odd_names > 0 { |
| 327 | app.notes.borrow_mut().push(format!("{} paths were left out (names that aren't UTF-8, or .vcs)", conv.odd_names)); |
| 328 | } |
| 329 | } |
| 330 |
| 331 | /// `vcs import <repo> [folder] [--to host/owner/name]`: a new project with |
| 332 | /// the repository's history. `--change <ref>` instead brings one git branch |
| 333 | /// into the current workspace's project as a change. |
| 334 | pub fn import(app: &App, source: &str, to: Option<String>, folder: Option<PathBuf>, change: Option<String>) -> Out { |
| 335 | if let Some(rev) = change { |
| 336 | return import_change(app, source, &rev); |
| 337 | } |
| 338 | let repo = open(app, source)?; |
| 339 | let (branch, _) = repo.default_branch()?; |
| 340 | let name = clone_url(source).trim_end_matches('/').rsplit('/').next().unwrap_or("project").trim_end_matches(".git").to_string(); |
| 341 | let root = app.cwd.join(folder.unwrap_or_else(|| PathBuf::from(if name.is_empty() { "project".to_string() } else { name }))); |
| 342 | crate::app::ensure_dir_empty(&root)?; |
| 343 |
| 344 | let list = commits(&repo, "HEAD", None)?; |
| 345 | let project = Project { |
| 346 | id: format!("local-{}", ids::new_workspace_id()), |
| 347 | address: String::new(), |
| 348 | kind: "local".into(), |
| 349 | api: None, |
| 350 | checked: ids::now(), |
| 351 | }; |
| 352 | let mut conv = Converter::new(&app.store, &repo)?; |
| 353 | // What version 1 starts from. |
| 354 | app.store.put(&tree::empty())?; |
| 355 | let mut versions = Vec::with_capacity(list.len()); |
| 356 | let mut prev: Option<Id> = None; |
| 357 | let mut last = Instant::now(); |
| 358 | for (i, c) in list.iter().enumerate() { |
| 359 | progress(app, &format!("reading git history: {} of {} commits", i + 1, list.len()), &mut last); |
| 360 | let tree = conv.tree(sha_bytes(&c.tree)?, true)?.unwrap_or_else(tree::empty_id); |
| 361 | let v = Version { |
| 362 | n: i as u64 + 1, |
| 363 | tree, |
| 364 | prev, |
| 365 | change: change_id(&c.sha), |
| 366 | author: c.author.clone(), |
| 367 | time: c.time, |
| 368 | title: c.title.clone(), |
| 369 | body: c.body.clone(), |
| 370 | git: Some(c.sha.clone()), |
| 371 | }; |
| 372 | prev = Some(v.id(&project.id)); |
| 373 | versions.push(v); |
| 374 | } |
| 375 | if !app.json && std::io::stderr().is_terminal() { |
| 376 | eprint!("\r{}\r", " ".repeat(60)); |
| 377 | } |
| 378 | let main = versions.last().cloned().ok_or_else(|| Fail::new("bad_usage", "the git repository has no commits").state("nothing changed"))?; |
| 379 | let mut git_ids = Vec::new(); |
| 380 | conv.ids_under(sha_bytes(&list.last().unwrap().tree)?, &mut git_ids)?; |
| 381 | notes_for(app, &conv); |
| 382 |
| 383 | // The project, its history and a workspace on main. |
| 384 | std::fs::create_dir_all(&root)?; |
| 385 | let root = root.canonicalize()?; |
| 386 | let project = Project { address: root.to_string_lossy().into_owned(), ..project }; |
| 387 | app.db.put_project(&project)?; |
| 388 | { |
| 389 | let tx = app.db.conn.unchecked_transaction()?; |
| 390 | for v in &versions { |
| 391 | app.db.put_version(&project.id, v)?; |
| 392 | } |
| 393 | tx.commit()?; |
| 394 | } |
| 395 | app.db.put_git_ids(&project.id, &git_ids)?; |
| 396 | let origin = if app.cwd.join(source).exists() { app.cwd.join(source).canonicalize()?.to_string_lossy().into_owned() } else { clone_url(source) }; |
| 397 | app.db.set_import(&project.id, &origin, &branch)?; |
| 398 | let author = app.author(&project); |
| 399 | let c = Change::new(ids::new_change_id(), &project.id, main.tree, Some(main.n), &author); |
| 400 | app.db.put_change(&c)?; |
| 401 | let workspace = Workspace { id: ids::new_workspace_id(), project: project.id.clone(), path: root.clone(), change: c.id.clone(), only: vec![] }; |
| 402 | ws::write_id(&root, &workspace.id)?; |
| 403 | let files = app.files(&main.tree)?; |
| 404 | let mut index = ws::materialize(&root, &app.store, &Index::default(), &files, &[], None)?; |
| 405 | index.save(&root)?; |
| 406 | app.db.put_workspace(&workspace)?; |
| 407 | drop(conv); |
| 408 | drop(repo); |
| 409 |
| 410 | let mut r = Report::new(); |
| 411 | r.line("imported", format!("{} commits from {branch} as versions 1 to {}", versions.len(), main.n)) |
| 412 | .line("workspace", root.display().to_string()) |
| 413 | .set("project", project.address.clone()) |
| 414 | .set("workspace", root.display().to_string()) |
| 415 | .set("versions", versions.len()) |
| 416 | .set("main", main.n); |
| 417 | if let Some(target) = to { |
| 418 | let cwd_app = App::open(app.json, root.clone()).map_err(Fail::from)?; |
| 419 | let published = crate::remote::publish(&cwd_app, &target)?; |
| 420 | for note in cwd_app.notes.borrow().iter() { |
| 421 | app.notes.borrow_mut().push(note.clone()); |
| 422 | } |
| 423 | r.line("published", target.clone()).set("published", serde_json::Value::Object(published.json.clone())); |
| 424 | r.next("keep working; vcs land lands on the host"); |
| 425 | } else { |
| 426 | r.next(format!("cd {} and keep working; vcs publish <host/owner/name> puts it on a host", root.display())); |
| 427 | } |
| 428 | Ok(r) |
| 429 | } |
| 430 |
| 431 | /// `vcs import <repo> --change <ref>`: the git branch `rev`, as a new change |
| 432 | /// in this workspace. It starts from where the branch left main. |
| 433 | fn import_change(app: &App, source: &str, rev: &str) -> Out { |
| 434 | let mut s = app.session()?; |
| 435 | let current = app.save(&mut s)?; |
| 436 | let repo = open(app, source)?; |
| 437 | let tip = git(&repo.dir, &["rev-parse", "--verify", "-q", &format!("{rev}^{{commit}}")]) |
| 438 | .map_err(|_| Fail::new("not_found", format!("{rev} isn't in {source}")).state("nothing changed"))? |
| 439 | .trim() |
| 440 | .to_string(); |
| 441 | // Where the branch left vcs: the newest commit on its first-parent line |
| 442 | // that is a version, named in the commit (the git view writes |
| 443 | // Vcs-Version) or read by an import. |
| 444 | app.refresh(&s.project)?; |
| 445 | let line = commits(&repo, &tip, Some(100_000))?; |
| 446 | let mut found = None; |
| 447 | for c in &line { |
| 448 | let named = c.body.lines().rev().find_map(|l| l.strip_prefix("Vcs-Version: ").and_then(|n| n.trim().parse::<u64>().ok())); |
| 449 | let v = match named { |
| 450 | Some(n) => app.db.version(&s.project.id, n)?, |
| 451 | None => app.db.version_by_git(&s.project.id, &c.sha)?, |
| 452 | }; |
| 453 | if let Some(v) = v { |
| 454 | found = Some((c, v)); |
| 455 | break; |
| 456 | } |
| 457 | } |
| 458 | let (base_commit, version) = found.ok_or_else(|| { |
| 459 | Fail::new("not_found", format!("{rev} doesn't start from any version of this project")) |
| 460 | .state("nothing changed") |
| 461 | .next("vcs import --change works on branches of this project's git view") |
| 462 | })?; |
| 463 | let tip_commit = line.first().ok_or_else(|| Fail::new("failed", "couldn't read the git history"))?; |
| 464 | let mut conv = Converter::new(&app.store, &repo)?; |
| 465 | // The change's base is the git view's tree (without private paths), so |
| 466 | // landing keeps whatever the view left out. |
| 467 | let base_tree = conv.tree(sha_bytes(&base_commit.tree)?, true)?.unwrap_or_else(tree::empty_id); |
| 468 | let head = conv.tree(sha_bytes(&tip_commit.tree)?, true)?.unwrap_or_else(tree::empty_id); |
| 469 | notes_for(app, &conv); |
| 470 | drop(conv); |
| 471 | if head == base_tree { |
| 472 | return Err(Fail::new("empty_change", format!("{rev} changes nothing since version {}", version.n)).state("nothing changed")); |
| 473 | } |
| 474 | let mut c = Change::new(ids::new_change_id(), &s.project.id, base_tree, Some(version.n), &app.author(&s.project)); |
| 475 | let (title, body) = (tip_commit.title.clone(), tip_commit.body.clone()); |
| 476 | c.title = title; |
| 477 | c.body = body; |
| 478 | c.head_tree = Some(head); |
| 479 | c.saves = 1; |
| 480 | app.db.put_change(&c)?; |
| 481 | app.db.add_save(&Save { change: c.id.clone(), n: 1, tree: head, base_tree, at: ids::now(), uploaded: false }, &s.ws.id)?; |
| 482 | app.show_tree(&s, &head)?; |
| 483 | app.put_workspace_change(&mut s, &c.id)?; |
| 484 | app.db.add_op(&s.ws.id, "new", &json!({ "from": current.id, "to": c.id }))?; |
| 485 | let _ = app.host(&s.project).publish_change(&app.db, &app.store, &s.project, &c, &s.ws.id); |
| 486 | let mut r = Report::new(); |
| 487 | r.line("change", format!("{} \"{}\", from git {} on version {}", app.short(&s.project, &c.id), c.title, &tip[..12], version.n)); |
| 488 | r.line("kept", format!("{} is saved; vcs switch goes back to it", app.short(&s.project, ¤t.id))); |
| 489 | r.set("change", json!({ "id": c.id, "title": c.title, "base_version": version.n, "git": tip })); |
| 490 | r.next("vcs land"); |
| 491 | Ok(r) |
| 492 | } |
| 493 |
| 494 | /// Copies an imported project's original git history to the host's git |
| 495 | /// view, so the view carries on from the same commits. Nothing happens if |
| 496 | /// the view's main is already there; a view with other history is left as |
| 497 | /// it is (the host pauses the view and says so). |
| 498 | pub fn push_history(app: &App, project: &Project, git_url: &str, token: &str) -> Result<Option<String>, Fail> { |
| 499 | let Some((source, branch)) = app.db.import_source(&project.id)? else { return Ok(None) }; |
| 500 | // The newest version that came from git (later ones are native). |
| 501 | let Some(last) = app.db.versions(&project.id, i64::MAX)?.into_iter().find_map(|v| v.git) else { return Ok(None) }; |
| 502 | let auth = format!("Authorization: Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("vcs:{token}"))); |
| 503 | // The token goes in git's environment, not its arguments. |
| 504 | let with_auth = |cmd: &mut Command| { |
| 505 | cmd.env("GIT_CONFIG_COUNT", "1").env("GIT_CONFIG_KEY_0", "http.extraHeader").env("GIT_CONFIG_VALUE_0", &auth).env("GIT_TERMINAL_PROMPT", "0"); |
| 506 | }; |
| 507 | let mut ls = Command::new("git"); |
| 508 | ls.args(["ls-remote", git_url, "refs/heads/main"]).stdin(Stdio::null()).stderr(Stdio::null()); |
| 509 | with_auth(&mut ls); |
| 510 | let out = ls.output().map_err(|_| git_missing())?; |
| 511 | if out.status.success() && String::from_utf8_lossy(&out.stdout).split_whitespace().next() == Some(last.as_str()) { |
| 512 | return Ok(None); |
| 513 | } |
| 514 | let repo = open(app, &source)?; |
| 515 | // Every branch and tag as it is, and main at the last imported commit. |
| 516 | let _ = branch; |
| 517 | let mut refspecs = vec!["refs/tags/*:refs/tags/*".to_string(), format!("{last}:refs/heads/main")]; |
| 518 | for name in git(&repo.dir, &["for-each-ref", "--format=%(refname)", "refs/heads"])?.lines() { |
| 519 | if name != "refs/heads/main" && !name.is_empty() { |
| 520 | refspecs.push(format!("{name}:{name}")); |
| 521 | } |
| 522 | } |
| 523 | let mut push = Command::new("git"); |
| 524 | push.arg("--git-dir").arg(&repo.dir).args(["push", "--quiet", git_url]).args(&refspecs).stdin(Stdio::null()); |
| 525 | with_auth(&mut push); |
| 526 | let out = push.output().map_err(|_| git_missing())?; |
| 527 | if !out.status.success() { |
| 528 | return Ok(Some(format!( |
| 529 | "the git view at {git_url} already has other history, so it stays paused: {}", |
| 530 | String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("").trim() |
| 531 | ))); |
| 532 | } |
| 533 | Ok(Some(format!("copied the git history to {git_url}"))) |
| 534 | } |
| 535 |