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