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