navid/veins / commit
bc0b02d957b7
Navid M <navidmomtahen@gmail.com> · 2026-11-29
parents: a987695cdcf0
Browse files at this commit · Download source
--- a/veinsrs/src/cli/commands/bookmark.rs+++ b/veinsrs/src/cli/commands/bookmark.rs@@ -3,11 +3,11 @@ use crate::cli::args; use crate::error::{Error, Result}; use crate::object::view::Bookmark;+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::snapshot; pub fn run(arguments: &[String]) -> Result<u8> {@@ -38,10 +38,7 @@ if *byte == 0 || *byte == b' ' || *byte < 32 || *byte == 127 { return false; }- if matches!(- *byte,- b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\'- ) {+ if matches!(*byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\') { return false; } }@@ -143,8 +140,8 @@ let root = layout::discover(Path::new("."))?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let working_copy = ops::working_copy_id(&view); let mut name_width = 8; for bookmark in &view.bookmarks {@@ -175,7 +172,11 @@ Some(commit) => graph::base32_encode(commit.change_id)[..8].to_string(), None => String::new(), };- let marker = if working_copy == Some(target) { "@" } else { "" };+ let marker = if working_copy == Some(target) {+ "@"+ } else {+ ""+ }; println!( "{:<name_width$} {:<12} {:<8} {marker}", name,--- a/veinsrs/src/cli/commands/commit.rs+++ b/veinsrs/src/cli/commands/commit.rs@@ -3,14 +3,14 @@ use crate::cli::args; use crate::error::{Error, Result}; use crate::identity;+use crate::object::TYPE_COMMIT; use crate::object::commit::{self, Commit}; use crate::object::id::Id;-use crate::object::TYPE_COMMIT;+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::snapshot; enum Outcome {@@ -37,7 +37,12 @@ Ok(0) } -fn describe(root: &Path, store: &mut Store, message: &str, require_changes: bool) -> Result<Outcome> {+fn describe(+ root: &Path,+ store: &mut Store,+ message: &str,+ require_changes: bool,+) -> Result<Outcome> { snapshot::run_with(root, store)?; let mut txn = Txn::begin(root, store)?; let working_copy =--- a/veinsrs/src/cli/commands/init.rs+++ b/veinsrs/src/cli/commands/init.rs@@ -1,22 +1,66 @@ use std::path::Path; -use crate::cli::args;-use crate::error::Result;+use crate::core;+use crate::error::{Error, Result}; use crate::store::layout; pub fn run(arguments: &[String]) -> Result<u8> {- let mut path = ".";+ let mut path = ".".to_string();+ let mut source = None;+ let mut remote_url = String::new();+ let mut remote_name = "o".to_string();+ let mut remote_name_given = false; let mut end_flags = false; for argument in arguments { if !end_flags && argument == "--" { end_flags = true;- } else if !end_flags && args::is_flag(argument) {- return Err(crate::Error::new(format!("unknown flag: {argument}")));+ } else if !end_flags && let Some(value) = argument.strip_prefix("-git-import:") {+ if value.is_empty() {+ return Err(Error::new("-git-import: requires a path"));+ }+ source = Some(value.to_string());+ } else if !end_flags && let Some(value) = argument.strip_prefix("-remote:") {+ if value.is_empty() {+ return Err(Error::new("-remote: requires a URL"));+ }+ remote_url = value.to_string();+ } else if !end_flags && let Some(value) = argument.strip_prefix("-remote-name:") {+ if value.is_empty() {+ return Err(Error::new("-remote-name: requires a name"));+ }+ remote_name = value.to_string();+ remote_name_given = true;+ } else if !end_flags && core::is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}"))); } else {- path = argument;+ path = argument.clone(); } }- let root = layout::init(Path::new(path))?;+ if remote_name_given && remote_url.is_empty() {+ return Err(Error::new("-remote-name: requires -remote:<url>"));+ }+ if source.is_none() && !remote_url.is_empty() {+ return Err(Error::new("-remote: requires -git-import:<path>"));+ }+ let root = layout::init(Path::new(&path)).map_err(|_| Error::new("init failed"))?; println!("info: initialized veins repository at {}", root.display());+ if let Some(source) = source {+ let prepared = crate::git::prepare_mirror(&root, &source);+ if prepared != 0 {+ if prepared == 2 {+ return Err(Error::new(format!(+ "-git-import: {source} is not a git repository root (expected the directory containing .git)"+ )));+ }+ return Err(Error::new(format!(+ "cannot prepare git mirror from {source} (code {prepared})"+ )));+ }+ let imported = crate::git::import(&root);+ if imported != 0 {+ return Ok(1);+ }+ crate::git::configure_remote(&root, &remote_url, &remote_name);+ } Ok(0) }--- a/veinsrs/src/cli/commands/log.rs+++ b/veinsrs/src/cli/commands/log.rs@@ -74,10 +74,7 @@ } records.sort_by(|left, right| right.seconds.cmp(&left.seconds)); - let change_ids: Vec<String> = records- .iter()- .map(|record| record.change.clone())- .collect();+ let change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect(); let mut change_width = 6; let mut author_width = 6; for (index, record) in records.iter().enumerate() {--- a/veinsrs/src/cli/commands/selftest.rs+++ b/veinsrs/src/cli/commands/selftest.rs@@ -2,7 +2,7 @@ use crate::object::blob::{self, BlobForm}; use crate::object::chunker::{gear_table, next_chunk}; use crate::object::commit::{self, Commit, Sig};-use crate::object::id::{hash_bytes, object_id, Id};+use crate::object::id::{Id, hash_bytes, object_id}; use crate::object::tree; use crate::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef}; use crate::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};@@ -47,10 +47,14 @@ let empty_tree_body = vec![0u8]; let empty_tree_id = object_id(TYPE_TREE, &empty_tree_body); expect(- empty_tree_id.to_hex() == "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",+ empty_tree_id.to_hex()+ == "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb", "empty tree id", )?;- expect(tree::decode(&empty_tree_body)?.entries.is_empty(), "empty tree decode")?;+ expect(+ tree::decode(&empty_tree_body)?.entries.is_empty(),+ "empty tree decode",+ )?; let inline = blob::encode_inline(b"hello"); expect(@@ -60,8 +64,8 @@ )?; let change_id: [u8; 16] = [- 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,- 0x19, 0x1a,+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,+ 0x1a, ]; let signature = Sig { name: b"Alice".to_vec(),--- a/veinsrs/src/cli/commands/status.rs+++ b/veinsrs/src/cli/commands/status.rs@@ -12,8 +12,8 @@ let root = layout::discover(Path::new("."))?; let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let Some(working_copy) = ops::working_copy_id(&view) else { println!("info: working copy clean"); return Ok(0);--- a/veinsrs/src/cli/config_cmd.rs+++ b/veinsrs/src/cli/config_cmd.rs@@ -4,8 +4,6 @@ use crate::core; use crate::error::{Error, Result}; use crate::store::layout;--use super::output; pub fn run(arguments: &[String]) -> Result<u8> { if arguments.len() == 1 && matches!(arguments[0].as_str(), "help" | "-h" | "-help") {@@ -54,9 +52,7 @@ positional.remove(0); } else if positional.len() == 3 && positional[0] == "set" { positional.remove(0);- } else if positional.len() == 2- && matches!(positional[0].as_str(), "unset" | "rm" | "remove")- {+ } else if positional.len() == 2 && matches!(positional[0].as_str(), "unset" | "rm" | "remove") { unset = true; positional.remove(0); }@@ -184,7 +180,11 @@ let ok = if global { core::user_config_set(key, value) } else {- core::repo_config_set(root.ok_or_else(|| Error::new("not a veins repository"))?, key, value)+ core::repo_config_set(+ root.ok_or_else(|| Error::new("not a veins repository"))?,+ key,+ value,+ ) }; if !ok { return Err(Error::new(format!(@@ -199,7 +199,10 @@ let ok = if global { core::user_config_remove(key) } else {- core::repo_config_remove(root.ok_or_else(|| Error::new("not a veins repository"))?, key)+ core::repo_config_remove(+ root.ok_or_else(|| Error::new("not a veins repository"))?,+ key,+ ) }; if !ok { return Err(Error::new(format!(--- a/veinsrs/src/cli/diff.rs+++ b/veinsrs/src/cli/diff.rs@@ -89,8 +89,7 @@ let mut k = -d; while k <= d { let mut x = if k == -d- || (k != d- && v[(offset + k - 1) as usize] < v[(offset + k + 1) as usize])+ || (k != d && v[(offset + k - 1) as usize] < v[(offset + k + 1) as usize]) { v[(offset + k + 1) as usize] } else {@@ -123,8 +122,7 @@ let previous = &trace[d as usize]; let k = x - y; let previous_k = if k == -d- || (k != d- && previous[(offset + k - 1) as usize] < previous[(offset + k + 1) as usize])+ || (k != d && previous[(offset + k - 1) as usize] < previous[(offset + k + 1) as usize]) { k + 1 } else {@@ -344,9 +342,7 @@ (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(), }; if contains_nul(&old_data) || contains_nul(&new_data) {- output.push_str(&format!(- "Binary files a/{path} and b/{path} differ\n"- ));+ output.push_str(&format!("Binary files a/{path} and b/{path} differ\n")); continue; } output.push_str(&super::output::red("--- "));@@ -363,7 +359,11 @@ output.push_str(&super::output::green(&format!("b/{path}"))); } output.push('\n');- render_unified(&split_lines(&old_data), &split_lines(&new_data), &mut output);+ render_unified(+ &split_lines(&old_data),+ &split_lines(&new_data),+ &mut output,+ ); } if announce && changes.is_empty() { super::output::info_prefix();--- a/veinsrs/src/cli/history.rs+++ b/veinsrs/src/cli/history.rs@@ -8,11 +8,11 @@ use crate::object::id::Id; use crate::object::tree::{self, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE}; use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn; use crate::store::graph::{self, LogNode}; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::snapshot; use super::{diff, output};@@ -33,7 +33,6 @@ seconds: i64, message: String, author: String,- has_changes: bool, conflicted: bool, } @@ -85,9 +84,7 @@ ); first = argument.as_bytes()[1] == b'f'; explicit_limit = true;- } else if !end_flags- && argument.len() > 1- && matches!(argument.as_bytes()[0], b'l' | b'f')+ } else if !end_flags && argument.len() > 1 && matches!(argument.as_bytes()[0], b'l' | b'f') { if let Some(count) = parse_count(&argument[1..]) { limit = Some(count);@@ -115,8 +112,8 @@ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let working_copy = ops::working_copy_id(&view); let start = if revision.is_empty() || revision == "all()" { graph::view_roots(&view)@@ -131,11 +128,6 @@ while let Some(id) = stack.pop() { let Some(commit) = graph::load_commit(&mut store, id)? else { continue;- };- let has_changes = if working_copy == Some(id) {- graph::has_changes(&mut store, &commit)?- } else {- false }; let message = first_line(&commit.message); records.push(LogRecord {@@ -146,7 +138,6 @@ seconds: commit.committer.seconds, message, author: String::from_utf8_lossy(&commit.author.name).into_owned(),- has_changes, conflicted: false, }); for parent in commit.parents {@@ -288,16 +279,17 @@ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; snapshot::run(&root)?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;- let target = graph::resolve_revision(&mut store, &view, &revision)?- .ok_or_else(|| Error::new(if revision.is_empty() {+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+ let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+ Error::new(if revision.is_empty() { "no working-copy commit" } else { "unknown revision"- }))?;- let commit = graph::load_commit(&mut store, target)?- .ok_or_else(|| Error::new("cannot read commit"))?;+ })+ })?;+ let commit =+ graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?; let mut rendered = String::new(); if titles { rendered.push_str(&format!("commit {}\n", target.to_hex()));@@ -347,13 +339,12 @@ Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree), None => None, };- let mut difference = String::new();- {+ let difference = { let mut buffer = Vec::new(); let mut collector = Collector::new(&mut buffer); collector.render(&mut store, old_tree, Some(commit.root_tree), false, b"")?;- difference = String::from_utf8_lossy(&buffer).into_owned();- }+ String::from_utf8_lossy(&buffer).into_owned()+ }; rendered.push_str(&difference); let diff_count = !difference.is_empty(); output::pager_output(&root, &rendered, diff_count && !all);@@ -466,14 +457,15 @@ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; snapshot::run(&root)?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;- let target = graph::resolve_revision(&mut store, &view, &revision)?- .ok_or_else(|| Error::new(if revision.is_empty() {+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+ let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+ Error::new(if revision.is_empty() { "no working-copy commit" } else { "unknown revision"- }))?;+ })+ })?; let hex = target.to_hex(); println!("{}", if short { &hex[..12] } else { &hex }); Ok(0)@@ -538,16 +530,17 @@ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; snapshot::run(&root)?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;- let target = graph::resolve_revision(&mut store, &view, &revision)?- .ok_or_else(|| Error::new(if revision.is_empty() {+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+ let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+ Error::new(if revision.is_empty() { "no working-copy commit" } else { "unknown revision"- }))?;- let commit = graph::load_commit(&mut store, target)?- .ok_or_else(|| Error::new("cannot read commit"))?;+ })+ })?;+ let commit =+ graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?; if plain { for entry in tree::flatten(&mut store, commit.root_tree)? { println!("{}", String::from_utf8_lossy(&entry.path));@@ -634,15 +627,12 @@ .is_none_or(|view| !view_ref_named(view, &operands[0])) { path_filter = Some(operands[0].clone());- } else if view- .as_ref()- .is_some_and(|view| {- graph::resolve_revision(&mut store, view, &operands[0])- .ok()- .flatten()- .is_some()- })- {+ } else if view.as_ref().is_some_and(|view| {+ graph::resolve_revision(&mut store, view, &operands[0])+ .ok()+ .flatten()+ .is_some()+ }) { revisions.push(operands[0].clone()); } else { path_filter = Some(operands[0].clone());@@ -656,7 +646,9 @@ .ok_or_else(|| Error::new("cannot determine current directory"))?; let normalized = crate::worktree::pathspec::pathspec_normalize(&root, &cwd, &path); if normalized.as_ref().is_none_or(|value| value.is_empty()) {- return Err(Error::new(format!("path is outside the repository: {path}")));+ return Err(Error::new(format!(+ "path is outside the repository: {path}"+ ))); } path_filter = normalized; }@@ -779,7 +771,8 @@ .ok_or_else(|| Error::new("unknown revision"))?; parents.push(resolved); if root_tree.is_none() {- root_tree = graph::load_commit(&mut store, resolved)?.map(|commit| commit.root_tree);+ root_tree =+ graph::load_commit(&mut store, resolved)?.map(|commit| commit.root_tree); } } let old_root = match working_copy {@@ -834,8 +827,8 @@ ) -> Result<u8> { snapshot::run_with(root, store)?; let mut txn = Txn::begin(root, store)?;- let working_copy = ops::working_copy_id(txn.view())- .ok_or_else(|| Error::new("no working-copy commit"))?;+ let working_copy =+ ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?; let loaded = graph::load_commit(store, working_copy)? .ok_or_else(|| Error::new("cannot read working-copy commit"))?; let changed = graph::has_changes(store, &loaded)?;@@ -885,7 +878,10 @@ ops::set_workspace(txn.view_mut(), next_id); ops::rebuild_heads(txn.view_mut()); let next_view = txn.view().clone();- txn.finish_chain(vec![(view, "describe".to_string()), (next_view, "new".to_string())])?;+ txn.finish_chain(vec![+ (view, "describe".to_string()),+ (next_view, "new".to_string()),+ ])?; store.refresh()?; mark_native(root, new_id); mark_native(root, next_id);@@ -1110,7 +1106,9 @@ pub fn op(arguments: &[String]) -> Result<u8> { let Some(sub) = arguments.first() else {- return Err(Error::new("expected an op subcommand (log, restore, revert)"));+ return Err(Error::new(+ "expected an op subcommand (log, restore, revert)",+ )); }; match sub.as_str() { "log" => op_log(),@@ -1193,10 +1191,7 @@ Ok(0) } -fn working_tree(- store: &mut Store,- view: &crate::object::view::View,-) -> Result<Option<Id>> {+fn working_tree(store: &mut Store, view: &crate::object::view::View) -> Result<Option<Id>> { let Some(working) = ops::working_copy_id(view) else { return Ok(None); };--- a/veinsrs/src/cli/info.rs+++ b/veinsrs/src/cli/info.rs@@ -14,10 +14,7 @@ use super::output; pub fn version() -> Result<u8> {- println!(- "veins v{} (store v1)",- env!("CARGO_PKG_VERSION")- );+ println!("veins v{} (store v1)", env!("CARGO_PKG_VERSION")); Ok(0) } @@ -71,10 +68,33 @@ "op" => "usage: vn op <log|restore|revert> ...\n\noperation log commands\n", "undo" => "usage: vn undo\n\nrestore the previous operation view\n", "fsck" => "usage: vn fsck [path] [-verbose]\n\nverify repository integrity\n",- "repack" => "usage: vn repack [path] [-level:N] [-verbose]\n\nrewrite packs\n", "inf" => "usage: vn inf [-inc-gen]\n\nshow a repository breakdown\n", "self-test" => "usage: vn self-test\n\nrun the format self-tests\n", "version" => "usage: vn version\n\nprint version information\n",+ "git" => {+ "usage: vn git <import|materialize|export|fetch|push|mirror|remote> ...\n\nimport from or export to git\n"+ }+ "remote" => "usage: vn remote <add|set-url|list|remove> ...\n\nmanage native remotes\n",+ "clone" => {+ "usage: vn clone <url> [-blobs:head|none|all] [-key:<name>] [path]\n\nclone a repository\n"+ }+ "fetch" => "usage: vn fetch [<remote>] [path]\n\nfetch from a native remote\n",+ "pull" => {+ "usage: vn pull [<remote>] [path]\n\nfetch and fast-forward the current bookmark\n"+ }+ "push" | "psh" => {+ "usage: vn push [<remote>] [<bookmark>] [path]\n\npush a bookmark to a native remote\n"+ }+ "serve" => "usage: vn serve [-stdio] [path]\n\nrun the native server\n",+ "key" => "usage: vn key <generate|show|list> ...\n\nmanage local Ed25519 keys\n",+ "auth" => {+ "usage: vn auth <use|list|remove> ...\n\nremember keys for hosts and set a default\n"+ }+ "access" => {+ "usage: vn access <add|remove|anonymous|list> ...\n\nmanage a served repository's access file\n"+ }+ "whoami" => "usage: vn whoami [<remote>]\n\nreport the role granted by a server\n",+ "repack" | "gc" => "usage: vn repack [path] [-level:N] [-verbose]\n\nrewrite packs\n", other => { return Err(Error::new(format!("unknown command: {other}"))); }@@ -144,7 +164,8 @@ }; let stem = &text[..text.len() - 6]; let index_path = packs.join(format!("{stem}.vidx"));- let Some(index_data) = core::read_file_opt(&index_path, crate::object::MAX_STORE_PACK_BYTES)+ let Some(index_data) =+ core::read_file_opt(&index_path, crate::object::MAX_STORE_PACK_BYTES) else { output::error_prefix(); println!("fsck: {}: pack has no index", path.display());@@ -162,7 +183,10 @@ }; if index.entries.len() != pack.records.len() { output::error_prefix();- println!("fsck: {}: pack and index object counts differ", path.display());+ println!(+ "fsck: {}: pack and index object counts differ",+ path.display()+ ); errors += 1; continue; }@@ -232,7 +256,14 @@ if seen_objects.insert(record.id, ()).is_some() { warnings += 1; }- check_object_refs(&mut store, &body, record.kind, promisor, &mut errors, &mut warnings)?;+ check_object_refs(+ &mut store,+ &body,+ record.kind,+ promisor,+ &mut errors,+ &mut warnings,+ )?; } } let heads = ops::read_heads(root)?;@@ -408,7 +439,11 @@ println!("cannot read object {}", record.id.to_hex()); return Ok(1); };- objects.push(crate::object::RawObject::known(record.kind, record.id, body));+ objects.push(crate::object::RawObject::known(+ record.kind,+ record.id,+ body,+ )); } } if objects.is_empty() {@@ -521,10 +556,15 @@ println!(); println!("{}", output::bold_cyan("Repository overview")); println!();- println!("Project {}", root.file_name().unwrap_or_default().to_string_lossy());+ println!(+ "Project {}",+ root.file_name().unwrap_or_default().to_string_lossy()+ ); println!( "HEAD {}",- working.map(|id| id.short()).unwrap_or_else(|| "<none>".to_string())+ working+ .map(|id| id.short())+ .unwrap_or_else(|| "<none>".to_string()) ); println!("Changes {commits}"); println!("Bookmarks {}", view.bookmarks.len());@@ -533,7 +573,9 @@ println!("Lines {total_lines}"); println!("Authors {}", authors.len()); if generated_files > 0 {- print!("Generated {generated_files} files {generated_lines} lines {generated_bytes} B");+ print!(+ "Generated {generated_files} files {generated_lines} lines {generated_bytes} B"+ ); if !include_generated { print!(" (excluded; use -inc-gen)"); }@@ -546,13 +588,7 @@ println!(" no tracked files"); } else { let mut entries: Vec<_> = by_ext.into_iter().collect();- entries.sort_by(|left, right| {- right- .1- .1- .cmp(&left.1.1)- .then_with(|| left.0.cmp(&right.0))- });+ entries.sort_by(|left, right| right.1.1.cmp(&left.1.1).then_with(|| left.0.cmp(&right.0))); for (ext, (files, lines, _)) in entries { println!("{ext:<8} {lines} lines {files} files"); }@@ -561,12 +597,7 @@ println!("{}", output::bold_cyan("Authors")); println!(); let mut authors: Vec<_> = authors.into_iter().collect();- authors.sort_by(|left, right| {- right- .1- .cmp(&left.1)- .then_with(|| left.0.cmp(&right.0))- });+ authors.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0))); for (name, count) in authors { println!("{name:<12} {count} commits"); }--- a/veinsrs/src/cli/merge_cmd.rs+++ b/veinsrs/src/cli/merge_cmd.rs@@ -6,13 +6,13 @@ use crate::merge::engine; use crate::object::conflict::{self, Conflict, ConflictValue}; use crate::object::id::Id;-use crate::object::tree::{self, FlatEntry};+use crate::object::tree; use crate::object::{TYPE_COMMIT, TYPE_CONFLICT};+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::checkout; use crate::worktree::pathspec; use crate::worktree::snapshot;@@ -182,9 +182,8 @@ for (position, parent) in loaded.parents.iter().enumerate() { if position == 0 && chosen == source_id { new_parents.push(destination_id);- new_parent_trees.push(- engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default(),- );+ new_parent_trees+ .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default()); continue; } if let Some(mapped) = old_ids.iter().position(|value| value == parent) {@@ -198,9 +197,8 @@ } if loaded.parents.is_empty() { new_parents.push(destination_id);- new_parent_trees.push(- engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default(),- );+ new_parent_trees+ .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default()); } let outcome = engine::rewrite_tree( &root,@@ -258,18 +256,15 @@ && let Some(index) = old_ids.iter().position(|value| *value == working_copy) { let mut refreshed = Store::open(&root)?;- checkout::materialize(- &root,- &mut refreshed,- old_working_tree,- new_trees[index],- )?;+ checkout::materialize(&root, &mut refreshed, old_working_tree, new_trees[index])?; } Ok(0) } fn map_id(old: &[Id], new: &[Id], id: Id) -> Option<Id> {- old.iter().position(|value| *value == id).map(|index| new[index])+ old.iter()+ .position(|value| *value == id)+ .map(|index| new[index]) } fn remap(old: &[Id], new: &[Id], ids: &mut [Option<Id>]) {@@ -324,8 +319,8 @@ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; snapshot::run(&root)?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let Some(working_copy) = ops::working_copy_id(&view) else { output::info_prefix(); println!("no conflicts");@@ -475,7 +470,9 @@ } else if !end_flags && (argument == "-take" || argument == "-t") { index += 1; if index >= arguments.len() {- return Err(Error::new(format!("{argument} requires ours, theirs, or base")));+ return Err(Error::new(format!(+ "{argument} requires ours, theirs, or base"+ ))); } take = arguments[index].clone(); } else if !end_flags && argument == "-tool" {@@ -501,8 +498,8 @@ snapshot::run(&root)?; let mut store = Store::open(&root)?; let mut txn = Txn::begin(&root, &mut store)?;- let working_copy = ops::working_copy_id(txn.view())- .ok_or_else(|| Error::new("no working-copy commit"))?;+ let working_copy =+ ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?; let loaded = graph::load_commit(&mut store, working_copy)? .ok_or_else(|| Error::new("cannot read working-copy commit"))?; let old_root = loaded.root_tree;@@ -526,7 +523,10 @@ } normalized_paths.push(normalized.clone()); let flat = tree::flatten(&mut store, root_tree)?;- let Some(entry) = flat.iter().find(|entry| entry.path == normalized.as_bytes()) else {+ let Some(entry) = flat+ .iter()+ .find(|entry| entry.path == normalized.as_bytes())+ else { output::error_prefix(); println!("not a conflicted path: {normalized}"); continue;@@ -613,5 +613,3 @@ } Ok(0) }--pub fn _unused(_entry: &FlatEntry, _store: &mut Store) {}--- a/veinsrs/src/cli/mod.rs+++ b/veinsrs/src/cli/mod.rs@@ -53,13 +53,13 @@ "attr" => worktree_cmd::attr(rest), "edit" => worktree_cmd::edit(rest), "fsck" => info::fsck(rest),- "repack" => info::repack(rest),+ "repack" | "gc" => info::repack(rest), "inf" => info::inf(rest), "self-test" => commands::selftest::run(), "version" | "-version" | "-v" => info::version(), "merge" | "rebase" | "xs" | "resolve" => merge_cmd::run(command, rest),- "remote" | "clone" | "fetch" | "pull" | "pl" | "push" | "psh" | "gg" | "serve"- | "key" | "auth" | "access" | "whoami" => net_cmd::run(command, rest),+ "remote" | "clone" | "fetch" | "pull" | "pl" | "push" | "psh" | "gg" | "serve" | "key"+ | "auth" | "access" | "whoami" => net_cmd::run(command, rest), "git" => net_cmd::git(rest), "help" | "-help" | "-h" => info::help(rest), _ => Err(crate::Error::new(format!("unknown command: {command}"))),--- a/veinsrs/src/cli/net_cmd.rs+++ b/veinsrs/src/cli/net_cmd.rs@@ -6,17 +6,16 @@ use crate::error::{Error, Result}; use crate::object::blob::{self, BlobForm}; use crate::object::commit::{self, Commit};-use crate::object::conflict; use crate::object::id::Id; use crate::object::tree::{self, KIND_SUBTREE};-use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_TREE}; use crate::protocol::client::Client; use crate::protocol::messages::{self, RefInfo, UpdateRef};+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::checkout; use crate::worktree::snapshot; @@ -143,8 +142,8 @@ } "list" | "ls" => { for name in list_remote_names(&root) {- let url = core::repo_config_value(&root, &remote_key(&name, "url"))- .unwrap_or_default();+ let url =+ core::repo_config_value(&root, &remote_key(&name, "url")).unwrap_or_default(); println!("{name}\t{url}"); } Ok(0)@@ -240,11 +239,9 @@ } fn set_remote_ref(view: &mut crate::object::view::View, remote: &str, name: &str, target: Id) {- if let Some(reference) = view- .remote_refs- .iter_mut()- .find(|reference| reference.remote == remote.as_bytes() && reference.name == name.as_bytes())- {+ if let Some(reference) = view.remote_refs.iter_mut().find(|reference| {+ reference.remote == remote.as_bytes() && reference.name == name.as_bytes()+ }) { reference.target = target; } else { view.remote_refs.push(crate::object::view::RemoteRef {@@ -271,9 +268,7 @@ } } ops::rebuild_heads(txn.view_mut());- if clone- && let Some(target) = default_target(refs)- {+ if clone && let Some(target) = default_target(refs) { let child = create_working_copy(&mut txn, &mut store, target)?; ops::set_workspace(txn.view_mut(), child); ops::rebuild_heads(txn.view_mut());@@ -283,7 +278,7 @@ if let Some(name) = default_ref_name(refs) { core::set_current_bookmark(root, &name); } else {- core::clear_current_bookmark(root);+ core::clear_current_bookmark(root); } } Ok(())@@ -408,7 +403,8 @@ path = argument.clone(); } }- let root = layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+ let root =+ layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?; if !have_remote { remote_name = active_remote(&root); }@@ -460,9 +456,9 @@ if path != "." { forward.push(path.clone()); }- // The fetch call is inlined so pull sees the updated view. fetch(&forward)?;- let root = layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+ let root =+ layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?; if !have_remote { remote_name = active_remote(&root); }@@ -470,10 +466,12 @@ snapshot::run_with(&root, &mut store)?; let bookmark_name = core::current_bookmark_name(&root) .ok_or_else(|| Error::new("no current bookmark; check out a bookmark before pulling"))?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let Some(index) = ops::find_bookmark(&view, bookmark_name.as_bytes()) else {- return Err(Error::new(format!("current bookmark is missing: {bookmark_name}")));+ return Err(Error::new(format!(+ "current bookmark is missing: {bookmark_name}"+ ))); }; let bookmark = &view.bookmarks[index]; let Some(local_target) = bookmark.targets.adds.first().copied().flatten() else {@@ -633,7 +631,8 @@ path = argument.clone(); } }- let root = layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+ let root =+ layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?; if !have_remote { remote_name = active_remote(&root); }@@ -640,13 +639,20 @@ let url = remote_url(&root, &remote_name).ok_or_else(|| Error::new("unknown remote"))?; let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; if bookmark.is_empty() { bookmark = core::current_bookmark_name(&root).unwrap_or_else(|| "master".to_string()); } let bookmark_target = ops::find_bookmark(&view, bookmark.as_bytes())- .and_then(|index| view.bookmarks[index].targets.adds.first().copied().flatten())+ .and_then(|index| {+ view.bookmarks[index]+ .targets+ .adds+ .first()+ .copied()+ .flatten()+ }) .ok_or_else(|| Error::new(format!("no such bookmark: {bookmark}")))?; let key = remote_key_name(&root, &remote_name); let repo_name = messages::url_repo_name(&url);@@ -728,7 +734,8 @@ if !stdio { return Err(Error::new("serve requires -stdio")); }- let root = layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;+ let root =+ layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?; crate::server::serve_stdio(&root, 0)?; Ok(0) }@@ -743,8 +750,8 @@ .get(1) .cloned() .unwrap_or_else(|| "default".to_string());- let key = crypto::generate_key(&name)- .ok_or_else(|| Error::new("cannot generate key"))?;+ let key =+ crypto::generate_key(&name).ok_or_else(|| Error::new("cannot generate key"))?; println!("name: {}", key.name); println!("public key: {}", crypto::format_public_key(&key.public_key)); println!("fingerprint: {}", key.fingerprint);@@ -870,7 +877,8 @@ } index += 1; }- let public_key = read_public_key(&key).ok_or_else(|| Error::new("invalid public key"))?;+ let public_key =+ read_public_key(&key).ok_or_else(|| Error::new("invalid public key"))?; if !crypto::add_access(&root, role, &public_key, &name) { return Err(Error::new("cannot add access entry")); }@@ -940,12 +948,146 @@ let (role, _) = client.whoami()?; println!("role: {}", messages::role_name(role)); Ok(0)-}--pub fn git(_arguments: &[String]) -> Result<u8> {- Err(Error::new("git bridge is not implemented yet")) } -pub fn _unused(_path: &PathBuf, _blob: u8) {- let _ = (TYPE_COMMIT, TYPE_CONFLICT);+pub fn git(arguments: &[String]) -> Result<u8> {+ let Some(sub) = arguments.first() else {+ return Err(Error::new("git requires a subcommand"));+ };+ match sub.as_str() {+ "import" => {+ let mut source = None;+ let mut remote = String::new();+ let mut path = ".".to_string();+ for argument in &arguments[1..] {+ if let Some(value) = argument.strip_prefix("-source:") {+ source = Some(value.to_string());+ } else if let Some(value) = argument.strip_prefix("-remote:") {+ remote = value.to_string();+ } else if !core::is_flag(argument) {+ path = argument.clone();+ }+ }+ let root = layout::discover(Path::new(&path))+ .map_err(|_| Error::new("not a veins repository"))?;+ if let Some(source) = source {+ let prepared = crate::git::prepare_mirror(&root, &source);+ if prepared != 0 {+ return Err(Error::new("cannot prepare git mirror"));+ }+ }+ let status = crate::git::import(&root);+ if status != 0 {+ return Ok(1);+ }+ if !remote.is_empty() {+ crate::git::configure_remote(&root, &remote, "o");+ }+ Ok(0)+ }+ "materialize" => {+ let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+ let root = layout::discover(Path::new(&path))+ .map_err(|_| Error::new("not a veins repository"))?;+ Ok(crate::git::materialize(&root) as u8)+ }+ "export" => {+ let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+ let root = layout::discover(Path::new(&path))+ .map_err(|_| Error::new("not a veins repository"))?;+ Ok(crate::git::export(&root) as u8)+ }+ "fetch" => {+ let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+ let root = layout::discover(Path::new(&path))+ .map_err(|_| Error::new("not a veins repository"))?;+ Ok(crate::git::fetch(&root, "origin") as u8)+ }+ "remote" => {+ let sub = arguments.get(1).map(|value| value.as_str()).unwrap_or("");+ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+ match sub {+ "add" => {+ let name = arguments.get(2).cloned().unwrap_or_default();+ let url = arguments.get(3).cloned().unwrap_or_default();+ Ok(crate::git::mirror_remote(&root, "add", &name, &url) as u8)+ }+ "remove" | "rm" => {+ let name = arguments.get(2).cloned().unwrap_or_default();+ Ok(crate::git::mirror_remote(&root, "remove", &name, "") as u8)+ }+ "list" | "ls" => {+ for name in crate::git::mirror_remote_list(&root) {+ println!("{name}");+ }+ Ok(0)+ }+ _ => Err(Error::new("unknown git remote subcommand")),+ }+ }+ "mirror" => {+ let action = arguments.get(1).map(|value| value.as_str()).unwrap_or("");+ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+ let force = !arguments.iter().any(|argument| argument == "-no-force");+ let prune = arguments.iter().any(|argument| argument == "-prune");+ let dry_run = arguments.iter().any(|argument| argument == "-dry-run");+ let options = crate::git::MirrorOptions {+ force,+ prune,+ dry_run,+ };+ match action {+ "push" | "psh" => {+ let remote = arguments+ .iter()+ .skip(2)+ .find(|argument| !core::is_flag(argument))+ .cloned()+ .or_else(|| crate::git::mirror_remote_list(&root).into_iter().next())+ .unwrap_or_else(|| "origin".to_string());+ let status = crate::git::mirror_push(&root, &remote, &options);+ if status == 0+ && !dry_run+ && let Some(view) = crate::store::ops::current_view(+ &root,+ &mut crate::store::Store::open(&root)?,+ )+ .ok()+ .flatten()+ {+ println!("info: mirrored {} bookmark(s)", view.bookmarks.len());+ }+ Ok(status as u8)+ }+ "pt" | "tag" => {+ let tag = arguments.get(2).cloned().unwrap_or_default();+ let remote = arguments+ .get(3)+ .cloned()+ .unwrap_or_else(|| "origin".to_string());+ let mut store = Store::open(&root)?;+ let view = ops::current_view(&root, &mut store)?.unwrap_or_default();+ if ops::find_tag(&view, tag.as_bytes()).is_none() {+ return Err(Error::new(format!("unknown tag: {tag}")));+ }+ let status = crate::git::mirror_tag(&root, &remote, &tag, &options);+ Ok(status as u8)+ }+ _ => Err(Error::new("unknown git mirror subcommand")),+ }+ }+ "push" => {+ let remote = arguments+ .get(1)+ .cloned()+ .unwrap_or_else(|| "origin".to_string());+ let bookmark = arguments+ .get(2)+ .cloned()+ .unwrap_or_else(|| "master".to_string());+ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+ Ok(crate::git::push(&root, &remote, &bookmark) as u8)+ }+ _ => Err(Error::new(format!("unknown git subcommand: {sub}"))),+ } }--- a/veinsrs/src/cli/output.rs+++ b/veinsrs/src/cli/output.rs@@ -69,7 +69,10 @@ if cwd_rel.is_empty() { return path.into_owned(); }- let current: Vec<&str> = cwd_rel.split('/').filter(|value| !value.is_empty()).collect();+ let current: Vec<&str> = cwd_rel+ .split('/')+ .filter(|value| !value.is_empty())+ .collect(); let target: Vec<&str> = path.split('/').collect(); let mut common = 0; while common < current.len() && common < target.len() && current[common] == target[common] {--- a/veinsrs/src/cli/refs.rs+++ b/veinsrs/src/cli/refs.rs@@ -3,10 +3,10 @@ use crate::core; use crate::error::{Error, Result}; use crate::object::view::{Bookmark, TagRef};+use crate::store::Txn; use crate::store::graph; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::snapshot; use super::output;@@ -110,12 +110,13 @@ let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?; let mut txn = Txn::begin(&root, &mut store)?;- let target = graph::resolve_revision(&mut store, txn.view(), &revision)?- .ok_or_else(|| Error::new(if revision.is_empty() {+ let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {+ Error::new(if revision.is_empty() { "no working-copy commit" } else { "unknown revision"- }))?;+ })+ })?; let mut changed = true; if let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) { let bookmark = &mut txn.view_mut().bookmarks[existing];@@ -198,8 +199,8 @@ } let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let working_copy = ops::working_copy_id(&view); let mut name_width = 8; for bookmark in &view.bookmarks {@@ -320,12 +321,13 @@ let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?; let mut txn = Txn::begin(&root, &mut store)?;- let target = graph::resolve_revision(&mut store, txn.view(), &revision)?- .ok_or_else(|| Error::new(if revision.is_empty() {+ let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {+ Error::new(if revision.is_empty() { "no working-copy commit" } else { "unknown revision"- }))?;+ })+ })?; let mut changed = true; if let Some(existing) = ops::find_tag(txn.view(), name.as_bytes()) { let tag = &mut txn.view_mut().tags[existing];@@ -399,8 +401,8 @@ } let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let working_copy = ops::working_copy_id(&view); let mut name_width = 3; for tag in &view.tags {@@ -452,8 +454,16 @@ while j < right.len() && right[j].is_ascii_digit() { j += 1; }- let an = left[ai..i].iter().position(|byte| *byte != b'0').map(|offset| ai + offset).unwrap_or(i);- let bn = right[bj..j].iter().position(|byte| *byte != b'0').map(|offset| bj + offset).unwrap_or(j);+ let an = left[ai..i]+ .iter()+ .position(|byte| *byte != b'0')+ .map(|offset| ai + offset)+ .unwrap_or(i);+ let bn = right[bj..j]+ .iter()+ .position(|byte| *byte != b'0')+ .map(|offset| bj + offset)+ .unwrap_or(j); let alen = i - an; let blen = j - bn; if alen != blen {@@ -487,8 +497,8 @@ } let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?; let mut store = Store::open(&root)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; if view.tags.is_empty() { return Err(Error::new("no tags")); }--- a/veinsrs/src/cli/status.rs+++ b/veinsrs/src/cli/status.rs@@ -1,6 +1,5 @@ use std::collections::HashSet; -use crate::core; use crate::error::{Error, Result}; use crate::object::tree::KIND_CONFLICT; use crate::store::graph;@@ -16,8 +15,8 @@ let cwd = pathspec::cwd_relative(&root).unwrap_or_default(); let mut store = Store::open(&root)?; snapshot::run_with(&root, &mut store)?;- let view = ops::current_view(&root, &mut store)?- .ok_or_else(|| Error::new("no operation state"))?;+ let view =+ ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?; let Some(working_copy) = ops::working_copy_id(&view) else { output::info_prefix(); println!("working copy clean");@@ -74,8 +73,4 @@ println!("{conflicted_commits} conflicted commit(s) in ancestry"); } Ok(0)-}--pub fn _unused() {- let _ = core::is_flag("-a"); }--- a/veinsrs/src/cli/worktree_cmd.rs+++ b/veinsrs/src/cli/worktree_cmd.rs@@ -1,19 +1,19 @@ use std::collections::HashSet; use std::fs;-use std::path::{Path, PathBuf};+use std::path::Path; use crate::core; use crate::error::{Error, Result}; use crate::identity;-use crate::object::commit::{self, Commit};+use crate::object::commit; use crate::object::path::valid_path;-use crate::object::tree::{self, TreeEntry, KIND_SUBTREE};+use crate::object::tree::{self, KIND_SUBTREE, TreeEntry}; use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::pathspec; use crate::worktree::snapshot; @@ -44,11 +44,14 @@ } fn normalize_operands(root: &Path, operands: &[String]) -> Result<Vec<String>> {- let cwd = pathspec::cwd_relative(root).ok_or_else(|| Error::new("cannot determine current directory"))?;+ let cwd = pathspec::cwd_relative(root)+ .ok_or_else(|| Error::new("cannot determine current directory"))?; let mut normalized = Vec::new(); for argument in operands { let Some(normalized_path) = pathspec::pathspec_normalize(root, &cwd, argument) else {- return Err(Error::new(format!("path is outside the repository: {argument}")));+ return Err(Error::new(format!(+ "path is outside the repository: {argument}"+ ))); }; if normalized_path.is_empty() || !valid_path(normalized_path.as_bytes()) { return Err(Error::new(format!("invalid path: {argument}")));@@ -182,8 +185,8 @@ fn run_removal(root: &Path, operands: &[String], delete_mode: bool) -> Result<u8> { let mut store = Store::open(root)?; let mut txn = Txn::begin(root, &mut store)?;- let working_copy = ops::working_copy_id(txn.view())- .ok_or_else(|| Error::new("no working-copy commit"))?;+ let working_copy =+ ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?; let loaded = graph::load_commit(&mut store, working_copy)? .ok_or_else(|| Error::new("cannot read working-copy commit"))?; let entries = tree::flatten(&mut store, loaded.root_tree)?;@@ -202,7 +205,10 @@ } for (index, value) in matched.iter().enumerate() { if !value {- return Err(Error::new(format!("path is not tracked: {}", operands[index])));+ return Err(Error::new(format!(+ "path is not tracked: {}",+ operands[index]+ ))); } } if !delete_mode {@@ -278,7 +284,9 @@ return Err(Error::new(format!("not a tracked path: {source}"))); } if core::stat_path(&destination_path).is_some() {- return Err(Error::new(format!("destination already exists: {destination}")));+ return Err(Error::new(format!(+ "destination already exists: {destination}"+ ))); } if let Some((parent, _)) = destination.rsplit_once('/') { if !core::ensure_directory(&root.join(parent)) {@@ -368,7 +376,8 @@ if paths.is_empty() { paths.push(".".to_string()); }- let root = layout::discover(Path::new(".")).unwrap_or_else(|_| std::env::current_dir().unwrap());+ let root =+ layout::discover(Path::new(".")).unwrap_or_else(|_| std::env::current_dir().unwrap()); if !core::run_editor(&root, &paths, None) { return Err(Error::new("editor exited with an error")); }@@ -541,7 +550,9 @@ let mut patterns = Vec::new(); for argument in arguments { let Some(normalized) = pathspec::pathspec_normalize(root, &cwd, argument) else {- return Err(Error::new(format!("{argument}\nnot a valid attribute pattern")));+ return Err(Error::new(format!(+ "{argument}\nnot a valid attribute pattern"+ ))); }; if normalized.is_empty() || !valid_path(normalized.as_bytes())@@ -548,7 +559,9 @@ || normalized.contains([' ', '\t', '\r', '\n']) || normalized.starts_with('#') {- return Err(Error::new(format!("{argument}\nnot a valid attribute pattern")));+ return Err(Error::new(format!(+ "{argument}\nnot a valid attribute pattern"+ ))); } patterns.push(normalized); }@@ -709,5 +722,3 @@ }, } }--pub fn _unused(_path: PathBuf, _commit: Commit) {}--- a/veinsrs/src/core.rs+++ b/veinsrs/src/core.rs@@ -475,10 +475,7 @@ if let Some(value) = value { output.insert(0, format!("{key} = {}", toml_quote(value))); } else {- while output- .last()- .is_some_and(|line| trim_str(line).is_empty())- {+ while output.last().is_some_and(|line| trim_str(line).is_empty()) { output.pop(); } }@@ -820,12 +817,26 @@ } if pc == b'?' { if text[t] != b'/' {- let _ = push(&mut stack, &mut work, GlobState { pi: p + 1, ti: t + 1 });+ let _ = push(+ &mut stack,+ &mut work,+ GlobState {+ pi: p + 1,+ ti: t + 1,+ },+ ); } continue; } if pc == text[t] {- let _ = push(&mut stack, &mut work, GlobState { pi: p + 1, ti: t + 1 });+ let _ = push(+ &mut stack,+ &mut work,+ GlobState {+ pi: p + 1,+ ti: t + 1,+ },+ ); } } false--- a/veinsrs/src/crypto.rs+++ b/veinsrs/src/crypto.rs@@ -78,8 +78,7 @@ } pub fn base64url_encode(raw: &[u8]) -> String {- const ALPHABET: &[u8; 64] =- b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+ const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; let mut output = String::with_capacity(raw.len() * 4 / 3 + 4); let mut accumulator = 0u32; let mut bits = 0usize;@@ -175,9 +174,7 @@ } fn valid_key_name(name: &str) -> bool {- !name.is_empty()- && name.len() <= 128- && !name.contains(['/', '\\', '\0'])+ !name.is_empty() && name.len() <= 128 && !name.contains(['/', '\\', '\0']) } pub fn key_path(name: &str) -> std::path::PathBuf {@@ -367,11 +364,7 @@ fn lookup_credential(directory: &std::path::Path, target: &str) -> Option<String> { let data = crate::core::read_file_opt(&target_path(directory, target), 0)?; let value = String::from_utf8_lossy(&data).trim().to_string();- if value.is_empty() {- None- } else {- Some(value)- }+ if value.is_empty() { None } else { Some(value) } } pub fn key_for_url(url: &str) -> Option<String> {@@ -543,7 +536,12 @@ name: &str, ) -> bool { let mut access = load_access(repo_root);- if !access.valid || access.entries.iter().any(|entry| entry.public_key == *public_key) {+ if !access.valid+ || access+ .entries+ .iter()+ .any(|entry| entry.public_key == *public_key)+ { return false; } access.entries.push(AccessEntry {--- a/veinsrs/src/encoding/reader.rs+++ b/veinsrs/src/encoding/reader.rs@@ -39,9 +39,7 @@ pub fn u32le(&mut self) -> Result<u32> { let bytes = self.take(4)?;- Ok(u32::from_le_bytes([- bytes[0], bytes[1], bytes[2], bytes[3],- ]))+ Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) } pub fn u64le(&mut self) -> Result<u64> {--- /dev/null+++ b/veinsrs/src/git.rs@@ -0,0 +1,837 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::blob;+use crate::object::commit::{self, Commit, Sig};+use crate::object::id::Id;+use crate::object::tree::{self, FlatEntry, TreeEntry};+use crate::object::view::{Bookmark, TagRef};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;++#[derive(Clone, Copy)]+pub struct Oid(pub [u8; 20]);++impl Oid {+ pub fn from_hex(text: &str) -> Option<Self> {+ if text.len() != 40 {+ return None;+ }+ let mut value = [0u8; 20];+ for index in 0..20 {+ let high = hex_value(text.as_bytes()[index * 2])?;+ let low = hex_value(text.as_bytes()[index * 2 + 1])?;+ value[index] = (high << 4) | low;+ }+ Some(Self(value))+ }++ pub fn hex(self) -> String {+ let mut output = String::with_capacity(40);+ for byte in self.0 {+ output.push_str(&format!("{byte:02x}"));+ }+ output+ }+}++fn hex_value(byte: u8) -> Option<u8> {+ match byte {+ b'0'..=b'9' => Some(byte - b'0'),+ b'a'..=b'f' => Some(byte - b'a' + 10),+ b'A'..=b'F' => Some(byte - b'A' + 10),+ _ => None,+ }+}++fn mirror_dir(root: &Path) -> PathBuf {+ layout::git_dir(root)+}++fn run_git(arguments: &[&str], cwd: Option<&Path>, stdin: Option<&[u8]>) -> Result<Vec<u8>> {+ let mut command = Command::new("git");+ command.args(arguments);+ if let Some(cwd) = cwd {+ command.current_dir(cwd);+ }+ command.stdout(Stdio::piped()).stderr(Stdio::piped());+ if stdin.is_some() {+ command.stdin(Stdio::piped());+ } else {+ command.stdin(Stdio::null());+ }+ let mut child = command.spawn().map_err(Error::from)?;+ if let Some(data) = stdin {+ use std::io::Write;+ let mut pipe = child+ .stdin+ .take()+ .ok_or_else(|| Error::new("cannot open git stdin"))?;+ pipe.write_all(data).map_err(Error::from)?;+ }+ let output = child.wait_with_output().map_err(Error::from)?;+ if !output.status.success() {+ return Err(Error::new(+ String::from_utf8_lossy(&output.stderr).into_owned(),+ ));+ }+ Ok(output.stdout)+}++fn git_dir_command(arguments: &[&str], mirror: &Path, stdin: Option<&[u8]>) -> Result<Vec<u8>> {+ let mut full = vec!["--git-dir", mirror.to_str().unwrap_or("")];+ full.extend_from_slice(arguments);+ run_git(&full, None, stdin)+}++pub fn prepare_mirror(root: &Path, source: &str) -> i32 {+ let source_path = Path::new(source);+ if !source_path.join(".git").exists() {+ return 2;+ }+ let mirror = mirror_dir(root);+ let _ = std::fs::remove_dir_all(&mirror);+ if let Some(parent) = mirror.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let mirror_text = mirror.to_str().unwrap_or("");+ match run_git(&["clone", "--mirror", source, mirror_text], None, None) {+ Ok(_) => 0,+ Err(_) => 1,+ }+}++pub fn configure_remote(root: &Path, url: &str, name: &str) {+ if url.is_empty() {+ crate::cli::output::warning_prefix();+ println!(+ "no native remote configured; set one with 'vn remote add o <url>' and push with 'vn psh o'"+ );+ return;+ }+ core::repo_config_set(root, &format!("remote.{name}.url"), url);+ core::repo_config_set(root, "remote.default", name);+}++pub fn import(root: &Path) -> i32 {+ match import_inner(root) {+ Ok(()) => 0,+ Err(error) => {+ crate::cli::output::error_prefix();+ println!("git import failed: {error}");+ 1+ }+ }+}++fn import_inner(root: &Path) -> Result<()> {+ let mirror = mirror_dir(root);+ let refs_output = git_dir_command(&["for-each-ref", "--format=%(refname)"], &mirror, None)?;+ let refs_text = String::from_utf8_lossy(&refs_output);+ let mut bookmarks = Vec::new();+ let mut tags = Vec::new();+ for line in refs_text.lines() {+ let name = line.trim();+ if name.is_empty() {+ continue;+ }+ let Some(oid_text) =+ git_dir_command(&["rev-parse", &format!("{name}^{{commit}}")], &mirror, None)+ .ok()+ .and_then(|data| String::from_utf8(data).ok())+ else {+ continue;+ };+ let Some(oid) = Oid::from_hex(oid_text.trim()) else {+ continue;+ };+ if let Some(short) = name.strip_prefix("refs/heads/") {+ bookmarks.push((short.to_string(), oid));+ } else if let Some(short) = name.strip_prefix("refs/tags/") {+ tags.push((short.to_string(), oid));+ }+ }+ let revs = git_dir_command(&["rev-list", "--all", "--reverse"], &mirror, None)?;+ let revs_text = String::from_utf8_lossy(&revs);+ let mut store = Store::open(root)?;+ let mut txn = Txn::begin(root, &mut store)?;+ let mut mapped: HashMap<String, Id> = HashMap::new();+ let mut ordered: Vec<String> = revs_text+ .lines()+ .map(|line| line.trim().to_string())+ .filter(|line| !line.is_empty())+ .collect();+ ordered.reverse();+ ordered.reverse();+ for oid_text in ordered {+ let Some(oid) = Oid::from_hex(&oid_text) else {+ continue;+ };+ import_commit(&mirror, &mut txn, &mut store, oid, &mut mapped)?;+ }+ for (name, oid) in bookmarks {+ if let Some(target) = mapped.get(&oid.hex()) {+ set_bookmark(txn.view_mut(), &name, *target);+ }+ }+ for (name, oid) in tags {+ if let Some(target) = mapped.get(&oid.hex()) {+ set_tag(txn.view_mut(), &name, *target);+ }+ }+ ops::rebuild_heads(txn.view_mut());+ let default = bookmarks_default(&txn.view().bookmarks);+ let default_name = bookmarks_default_name(&txn.view().bookmarks);+ txn.finish("git import")?;+ store.refresh()?;+ if let Some(target) = default {+ let mut checkout_txn = Txn::begin(root, &mut store)?;+ let child = create_working_copy(&mut checkout_txn, &mut store, target)?;+ ops::set_workspace(checkout_txn.view_mut(), child);+ ops::rebuild_heads(checkout_txn.view_mut());+ checkout_txn.finish("checkout")?;+ }+ if let Some(name) = default_name {+ core::set_current_bookmark(root, &name);+ }+ materialize(root);+ Ok(())+}++fn bookmarks_default(bookmarks: &[Bookmark]) -> Option<Id> {+ for bookmark in bookmarks {+ if matches!(bookmark.name.as_slice(), b"main" | b"master") {+ return bookmark.targets.adds.first().copied().flatten();+ }+ }+ bookmarks+ .iter()+ .find_map(|bookmark| bookmark.targets.adds.first().copied().flatten())+}++fn bookmarks_default_name(bookmarks: &[Bookmark]) -> Option<String> {+ for bookmark in bookmarks {+ if matches!(bookmark.name.as_slice(), b"main" | b"master") {+ return Some(String::from_utf8_lossy(&bookmark.name).into_owned());+ }+ }+ bookmarks+ .first()+ .map(|bookmark| String::from_utf8_lossy(&bookmark.name).into_owned())+}++fn set_bookmark(view: &mut crate::object::view::View, name: &str, target: Id) {+ ops::set_bookmark_target(view, name.as_bytes(), target);+}++fn set_tag(view: &mut crate::object::view::View, name: &str, target: Id) {+ view.tags.push(TagRef {+ name: name.as_bytes().to_vec(),+ target,+ });+}++fn create_working_copy(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {+ let loaded = graph::load_commit(store, parent)?+ .ok_or_else(|| Error::new("cannot read parent commit"))?;+ let signature = identity::signature(store.root());+ let commit = Commit {+ version: 1,+ parents: vec![parent],+ root_tree: loaded.root_tree,+ change_id: identity::random_change_id(),+ author: signature.clone(),+ committer: signature,+ message: Vec::new(),+ renames_state: commit::RENAMES_RECORDED,+ renames: Vec::new(),+ extra: Vec::new(),+ };+ Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))+}++struct ParsedCommit {+ parents: Vec<String>,+ author: Sig,+ committer: Sig,+ message: Vec<u8>,+ extra: Vec<(Vec<u8>, Vec<u8>)>,+}++fn parse_sig(text: &str) -> Sig {+ let (name, rest) = text.split_once(" <").unwrap_or((text, "> 0 +0000"));+ let (email, rest) = rest.split_once('>').unwrap_or((rest, " 0 +0000"));+ let mut parts = rest.split_whitespace();+ let seconds = parts+ .next()+ .and_then(|value| value.parse().ok())+ .unwrap_or(0);+ let tz = parts.next().unwrap_or("+0000");+ let tz_min = parse_tz(tz);+ Sig {+ name: name.as_bytes().to_vec(),+ email: email.as_bytes().to_vec(),+ seconds,+ tz_min,+ }+}++fn parse_tz(text: &str) -> i16 {+ if text.len() != 5 {+ return 0;+ }+ let sign = if text.starts_with('-') { -1 } else { 1 };+ let hours: i16 = text[1..3].parse().unwrap_or(0);+ let minutes: i16 = text[3..5].parse().unwrap_or(0);+ sign * (hours * 60 + minutes)+}++fn parse_git_commit(data: &[u8]) -> Option<ParsedCommit> {+ let split = data+ .windows(2)+ .position(|window| window == b"\n\n")+ .unwrap_or(data.len());+ let header = String::from_utf8_lossy(&data[..split]);+ let message = if split + 2 <= data.len() {+ data[split + 2..].to_vec()+ } else {+ Vec::new()+ };+ let mut parents = Vec::new();+ let mut author = Sig::default();+ let mut committer = Sig::default();+ let mut extra = Vec::new();+ for line in header.lines() {+ if let Some(value) = line.strip_prefix("parent ") {+ parents.push(value.to_string());+ } else if let Some(value) = line.strip_prefix("author ") {+ author = parse_sig(value);+ } else if let Some(value) = line.strip_prefix("committer ") {+ committer = parse_sig(value);+ } else if let Some((key, value)) = line.split_once(' ')+ && !line.starts_with(' ')+ && key != "gpgsig"+ {+ extra.push((key.as_bytes().to_vec(), value.as_bytes().to_vec()));+ }+ }+ Some(ParsedCommit {+ parents,+ author,+ committer,+ message,+ extra,+ })+}++fn import_commit(+ mirror: &Path,+ txn: &mut Txn,+ store: &mut Store,+ oid: Oid,+ mapped: &mut HashMap<String, Id>,+) -> Result<()> {+ if mapped.contains_key(&oid.hex()) {+ return Ok(());+ }+ let data = git_dir_command(&["cat-file", "commit", &oid.hex()], mirror, None)?;+ let parsed = parse_git_commit(&data).ok_or_else(|| Error::new("corrupt git commit"))?;+ for parent in &parsed.parents {+ if let Some(parent_oid) = Oid::from_hex(parent)+ && !mapped.contains_key(&oid.hex())+ {+ import_commit(mirror, txn, store, parent_oid, mapped)?;+ }+ }+ let entries = git_flat_entries(mirror, &oid.hex())?;+ let root_tree = build_tree(txn, &entries)?;+ let parents: Vec<Id> = parsed+ .parents+ .iter()+ .filter_map(|parent| mapped.get(parent).copied())+ .collect();+ let change_hash = blake3::hash(oid.hex().as_bytes());+ let mut change_id = [0u8; 16];+ change_id.copy_from_slice(&change_hash.as_bytes()[..16]);+ let commit = Commit {+ version: 1,+ parents,+ root_tree,+ change_id,+ author: parsed.author,+ committer: parsed.committer,+ message: parsed.message,+ renames_state: commit::RENAMES_UNKNOWN,+ renames: Vec::new(),+ extra: parsed.extra,+ };+ let id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));+ mapped.insert(oid.hex(), id);+ Ok(())+}++fn git_flat_entries(mirror: &Path, revision: &str) -> Result<Vec<FlatEntry>> {+ let output = git_dir_command(&["ls-tree", "-r", "-z", revision], mirror, None)?;+ let mut entries = Vec::new();+ for record in output.split(|byte| *byte == 0) {+ if record.is_empty() {+ continue;+ }+ let Some(tab) = record.iter().position(|byte| *byte == b'\t') else {+ continue;+ };+ let meta = String::from_utf8_lossy(&record[..tab]).into_owned();+ let path = record[tab + 1..].to_vec();+ let mut parts = meta.split_whitespace();+ let mode = parts.next().unwrap_or("100644");+ let kind = parts.next().unwrap_or("blob");+ let oid_text = parts.next().unwrap_or("");+ let kind = if kind == "commit" || mode == "160000" {+ tree::KIND_SUBMODULE+ } else if mode == "120000" {+ tree::KIND_SYMLINK+ } else if mode == "100755" {+ tree::KIND_EXECUTABLE+ } else {+ tree::KIND_FILE+ };+ let target = if kind == tree::KIND_SUBMODULE {+ let Some(oid) = Oid::from_hex(oid_text) else {+ continue;+ };+ let mut id = [0u8; 32];+ id[..20].copy_from_slice(&oid.0);+ Id(id)+ } else {+ let data = git_dir_command(&["cat-file", "blob", oid_text], mirror, None)?;+ let build = blob::build(&data);+ for object in build.objects {+ txn_add_later(&object);+ }+ build.root+ };+ entries.push(FlatEntry { path, kind, target });+ }+ Ok(entries)+}++thread_local! {+ static PENDING: std::cell::RefCell<Vec<crate::object::RawObject>> = const { std::cell::RefCell::new(Vec::new()) };+}++fn txn_add_later(object: &crate::object::RawObject) {+ PENDING.with(|pending| pending.borrow_mut().push(object.clone()));+}++fn drain_pending(txn: &mut Txn) {+ PENDING.with(|pending| {+ for object in pending.borrow_mut().drain(..) {+ txn.add_known(object.kind, object.id, object.body);+ }+ });+}++fn build_tree(txn: &mut Txn, entries: &[FlatEntry]) -> Result<Id> {+ drain_pending(txn);+ let mut sorted = entries.to_vec();+ sorted.sort_by(|left, right| left.path.cmp(&right.path));+ build_level(txn, &sorted, 0, sorted.len(), 0)+}++fn build_level(+ txn: &mut Txn,+ entries: &[FlatEntry],+ start: usize,+ end: usize,+ prefix: usize,+) -> Result<Id> {+ let mut output = Vec::new();+ let mut index = start;+ while index < end {+ let entry = &entries[index];+ let cut = entry.path[prefix..]+ .iter()+ .position(|byte| *byte == b'/')+ .map(|offset| prefix + offset)+ .unwrap_or(entry.path.len());+ let name = entry.path[prefix..cut].to_vec();+ if cut == entry.path.len() {+ output.push(TreeEntry {+ name,+ kind: entry.kind,+ target: entry.target,+ });+ index += 1;+ } else {+ let mut next = index + 1;+ while next < end {+ let other = &entries[next];+ let other_cut = other.path[prefix..]+ .iter()+ .position(|byte| *byte == b'/')+ .map(|offset| prefix + offset)+ .unwrap_or(other.path.len());+ if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {+ break;+ }+ next += 1;+ }+ let child = build_level(txn, entries, index, next, cut + 1)?;+ output.push(TreeEntry {+ name,+ kind: tree::KIND_SUBTREE,+ target: child,+ });+ index = next;+ }+ }+ Ok(txn.add_object(TYPE_TREE, tree::encode(&output)?))+}++pub fn materialize(root: &Path) -> i32 {+ let result = (|| -> Result<()> {+ let mut store = Store::open(root)?;+ let view =+ ops::current_view(root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+ if let Some(working) = ops::working_copy_id(&view)+ && let Some(commit) = graph::load_commit(&mut store, working)?+ {+ crate::worktree::checkout::materialize(root, &mut store, None, commit.root_tree)?;+ }+ Ok(())+ })();+ match result {+ Ok(()) => 0,+ Err(error) => {+ crate::cli::output::error_prefix();+ println!("git materialize failed: {error}");+ 1+ }+ }+}++pub fn export(root: &Path) -> i32 {+ match export_inner(root) {+ Ok(()) => 0,+ Err(error) => {+ crate::cli::output::error_prefix();+ println!("git export failed: {error}");+ 1+ }+ }+}++fn export_inner(root: &Path) -> Result<()> {+ let mirror = mirror_dir(root);+ if !mirror.is_dir() {+ std::fs::create_dir_all(&mirror)?;+ run_git(+ &["init", "--bare", mirror.to_str().unwrap_or("")],+ None,+ None,+ )?;+ }+ let mut store = Store::open(root)?;+ let view = ops::current_view(root, &mut store)?.unwrap_or_default();+ let commits = graph::collect_commits(&mut store, &graph::view_roots(&view))?;+ let nodes: Vec<graph::LogNode> = {+ let mut output = Vec::new();+ for id in &commits {+ if let Some(commit) = graph::load_commit(&mut store, *id)? {+ output.push(graph::LogNode {+ id: *id,+ seconds: commit.committer.seconds,+ parents: commit.parents,+ });+ }+ }+ output+ };+ let order = graph::order_log_nodes(&nodes);+ let mut ordered = Vec::new();+ for index in order.into_iter().rev() {+ ordered.push(nodes[index].id);+ }+ let mut stream: Vec<u8> = Vec::new();+ let mut marks: HashMap<Id, usize> = HashMap::new();+ let mut blob_marks: HashMap<Id, usize> = HashMap::new();+ let mut next_mark = 1usize;+ let mut next_blob = 1_000_000usize;+ for id in &ordered {+ let Some(commit) = graph::load_commit(&mut store, *id)? else {+ continue;+ };+ let entries = tree::flatten(&mut store, commit.root_tree)?;+ let mut file_lines = Vec::new();+ for entry in &entries {+ if matches!(entry.kind, tree::KIND_CONFLICT | tree::KIND_SUBMODULE) {+ continue;+ }+ let mark = if let Some(mark) = blob_marks.get(&entry.target) {+ *mark+ } else {+ let Some(data) = graph::read_blob(&mut store, entry.target)? else {+ continue;+ };+ let mark = next_blob;+ next_blob += 1;+ blob_marks.insert(entry.target, mark);+ stream.extend_from_slice(+ format!("blob\nmark :{mark}\ndata {}\n", data.len()).as_bytes(),+ );+ stream.extend_from_slice(&data);+ stream.push(b'\n');+ mark+ };+ let mode = match entry.kind {+ tree::KIND_EXECUTABLE => "100755",+ tree::KIND_SYMLINK => "120000",+ _ => "100644",+ };+ let mut line = format!("M {mode} :{mark} ").into_bytes();+ line.extend_from_slice(&entry.path);+ line.push(b'\n');+ file_lines.push(line);+ }+ let mark = next_mark;+ next_mark += 1;+ marks.insert(*id, mark);+ stream.extend_from_slice(b"commit refs/veins/export\n");+ stream.extend_from_slice(format!("mark :{mark}\n").as_bytes());+ stream.extend_from_slice(+ format!(+ "author {} <{}> {} {}\n",+ String::from_utf8_lossy(&commit.author.name),+ String::from_utf8_lossy(&commit.author.email),+ commit.author.seconds,+ format_tz(commit.author.tz_min)+ )+ .as_bytes(),+ );+ stream.extend_from_slice(+ format!(+ "committer {} <{}> {} {}\n",+ String::from_utf8_lossy(&commit.committer.name),+ String::from_utf8_lossy(&commit.committer.email),+ commit.committer.seconds,+ format_tz(commit.committer.tz_min)+ )+ .as_bytes(),+ );+ stream.extend_from_slice(format!("data {}\n", commit.message.len()).as_bytes());+ stream.extend_from_slice(&commit.message);+ stream.push(b'\n');+ if let Some(parent) = commit.parents.first()+ && let Some(parent_mark) = marks.get(parent)+ {+ stream.extend_from_slice(format!("from :{parent_mark}\n").as_bytes());+ }+ for parent in commit.parents.iter().skip(1) {+ if let Some(parent_mark) = marks.get(parent) {+ stream.extend_from_slice(format!("merge :{parent_mark}\n").as_bytes());+ }+ }+ stream.extend_from_slice(b"deleteall\n");+ for line in file_lines {+ stream.extend_from_slice(&line);+ }+ stream.push(b'\n');+ }+ for bookmark in &view.bookmarks {+ if let Some(target) = bookmark.targets.adds.first().copied().flatten()+ && let Some(mark) = marks.get(&target)+ {+ stream.extend_from_slice(b"reset refs/heads/");+ stream.extend_from_slice(&bookmark.name);+ stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());+ }+ }+ for tag in &view.tags {+ if let Some(mark) = marks.get(&tag.target) {+ stream.extend_from_slice(b"reset refs/tags/");+ stream.extend_from_slice(&tag.name);+ stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());+ }+ }+ git_dir_command(+ &["fast-import", "--quiet", "--force"],+ &mirror,+ Some(&stream),+ )?;+ sync_mirror_refs(&mirror, &view)?;+ Ok(())+}++fn sync_mirror_refs(mirror: &Path, view: &crate::object::view::View) -> Result<()> {+ let output = git_dir_command(&["for-each-ref", "--format=%(refname)"], mirror, None)?;+ let text = String::from_utf8_lossy(&output);+ for line in text.lines() {+ let name = line.trim();+ if let Some(tag) = name.strip_prefix("refs/tags/") {+ if ops::find_tag(view, tag.as_bytes()).is_none() {+ let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);+ }+ } else if let Some(bookmark) = name.strip_prefix("refs/heads/") {+ if ops::find_bookmark(view, bookmark.as_bytes()).is_none() {+ let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);+ }+ }+ }+ Ok(())+}++fn format_tz(minutes: i16) -> String {+ let sign = if minutes < 0 { '-' } else { '+' };+ let value = minutes.abs();+ format!("{sign}{:02}{:02}", value / 60, value % 60)+}++pub fn fetch(root: &Path, remote: &str) -> i32 {+ let mirror = mirror_dir(root);+ if !mirror.is_dir() {+ std::fs::create_dir_all(&mirror).ok();+ let _ = run_git(+ &["init", "--bare", mirror.to_str().unwrap_or("")],+ None,+ None,+ );+ }+ let remote_name = if remote.is_empty() { "origin" } else { remote };+ if run_git(+ &[+ "--git-dir",+ mirror.to_str().unwrap_or(""),+ "config",+ "remote.real.url",+ ],+ None,+ None,+ )+ .is_err()+ {+ let _ = remote_name;+ }+ match git_dir_command(&["fetch", "--prune", remote_name], &mirror, None) {+ Ok(_) => import(root),+ Err(_) => 1,+ }+}++pub fn push(root: &Path, remote: &str, bookmark: &str) -> i32 {+ if export(root) != 0 {+ return 1;+ }+ let mirror = mirror_dir(root);+ let status = run_git(+ &[+ "--git-dir",+ mirror.to_str().unwrap_or(""),+ "push",+ remote,+ &format!("refs/heads/{bookmark}:refs/heads/{bookmark}"),+ ],+ None,+ None,+ );+ if status.is_err() {+ return 1;+ }+ 0+}++pub struct MirrorOptions {+ pub force: bool,+ pub prune: bool,+ pub dry_run: bool,+}++pub fn mirror_push(root: &Path, remote: &str, options: &MirrorOptions) -> i32 {+ if export(root) != 0 {+ return 1;+ }+ let mirror = mirror_dir(root);+ let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];+ if options.prune {+ arguments.push("--mirror");+ arguments.push("--prune");+ }+ if options.force {+ arguments.push("--force");+ }+ if options.dry_run {+ arguments.push("--dry-run");+ }+ arguments.push(remote);+ if !options.prune {+ arguments.push("refs/heads/*:refs/heads/*");+ arguments.push("refs/tags/*:refs/tags/*");+ }+ if run_git(&arguments, None, None).is_err() {+ return 1;+ }+ 0+}++pub fn mirror_tag(root: &Path, remote: &str, tag: &str, options: &MirrorOptions) -> i32 {+ if export(root) != 0 {+ return 1;+ }+ let mirror = mirror_dir(root);+ let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];+ if options.force {+ arguments.push("--force");+ }+ if options.dry_run {+ arguments.push("--dry-run");+ }+ let reference = format!("refs/tags/{tag}:refs/tags/{tag}");+ arguments.push(remote);+ arguments.push(&reference);+ if run_git(&arguments, None, None).is_err() {+ return 1;+ }+ 0+}++pub fn mirror_remote(root: &Path, sub: &str, name: &str, url: &str) -> i32 {+ let mirror = mirror_dir(root);+ if !mirror.is_dir() {+ std::fs::create_dir_all(&mirror).ok();+ let _ = run_git(+ &["init", "--bare", mirror.to_str().unwrap_or("")],+ None,+ None,+ );+ }+ let result = match sub {+ "add" => git_dir_command(&["remote", "add", name, url], &mirror, None),+ "remove" | "rm" => git_dir_command(&["remote", "remove", name], &mirror, None),+ _ => Ok(Vec::new()),+ };+ if result.is_err() { 1 } else { 0 }+}++pub fn mirror_remote_list(root: &Path) -> Vec<String> {+ let mirror = mirror_dir(root);+ git_dir_command(&["remote"], &mirror, None)+ .map(|data| {+ String::from_utf8_lossy(&data)+ .lines()+ .map(|line| line.trim().to_string())+ .filter(|line| !line.is_empty())+ .collect()+ })+ .unwrap_or_default()+}++pub fn read_lazy_blob(_root: &Path, _id: Id) -> Option<Vec<u8>> {+ None+}--- a/veinsrs/src/identity.rs+++ b/veinsrs/src/identity.rs@@ -30,14 +30,7 @@ pub fn signature(root: &Path) -> Sig { Sig { name: first_value(root, "user.name", true, "GIT_AUTHOR_NAME", "USER").into_bytes(),- email: first_value(- root,- "user.email",- false,- "GIT_AUTHOR_EMAIL",- "EMAIL",- )- .into_bytes(),+ email: first_value(root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL").into_bytes(), seconds: time::now_seconds(), tz_min: 0, }--- a/veinsrs/src/lib.rs+++ b/veinsrs/src/lib.rs@@ -3,6 +3,7 @@ pub mod crypto; pub mod encoding; pub mod error;+pub mod git; pub mod identity; pub mod merge; pub mod object;--- a/veinsrs/src/merge/engine.rs+++ b/veinsrs/src/merge/engine.rs@@ -1,4 +1,3 @@-use std::collections::HashMap; use std::path::Path; use crate::core;@@ -7,13 +6,13 @@ use crate::object::blob::{self, BlobForm}; use crate::object::commit::{self, Commit, Rename, Sig}; use crate::object::conflict::{self, Conflict, ConflictValue};-use crate::object::id::{object_id, Id};-use crate::object::tree::{self, FlatEntry, TreeEntry, KIND_CONFLICT, KIND_SUBTREE};+use crate::object::id::{Id, object_id};+use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry}; use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::store::Txn; use crate::store::graph; use crate::store::reader::Store; use crate::store::writer::Writer;-use crate::store::Txn; use crate::worktree::snapshot; fn same(left: Id, right: Id) -> bool {@@ -20,7 +19,12 @@ left == right } -fn read_any(store: &mut Store, writer: Option<&Writer>, kind: u8, id: Id) -> Result<Option<Vec<u8>>> {+fn read_any(+ store: &mut Store,+ writer: Option<&Writer>,+ kind: u8,+ id: Id,+) -> Result<Option<Vec<u8>>> { if let Some(writer) = writer && let Some(body) = writer.find_cached(kind, id) {@@ -171,7 +175,9 @@ fn tree_empty(store: &mut Store, writer: Option<&Writer>, id: Id) -> Result<bool> { match read_any(store, writer, TYPE_TREE, id)? {- Some(body) => Ok(tree::decode(&body).map(|tree| tree.entries.is_empty()).unwrap_or(true)),+ Some(body) => Ok(tree::decode(&body)+ .map(|tree| tree.entries.is_empty())+ .unwrap_or(true)), None => Ok(true), } }@@ -213,8 +219,8 @@ output.sort_unstable(); output }- let mut a = lines(left);- let mut b = lines(right);+ let a = lines(left);+ let b = lines(right); let mut ia = 0; let mut ib = 0; let mut intersection = 0;@@ -259,12 +265,7 @@ }) } -fn similarity(- store: &mut Store,- writer: Option<&Writer>,- a: Id,- b: Id,-) -> Result<u32> {+fn similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> { if same(a, b) { return Ok(100); }@@ -329,9 +330,7 @@ if similar_pct > 0 { let mut pairs = Vec::new(); for (old_index, old) in deleted.iter().enumerate() {- if used_old[old_index]- || !matches!(old.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)- {+ if used_old[old_index] || !matches!(old.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) { continue; } for (new_index, new) in added.iter().enumerate() {@@ -406,7 +405,6 @@ #[derive(Clone, Copy)] struct Op { tag: u8,- ai: usize, bi: usize, } @@ -424,18 +422,23 @@ } let mut output = Vec::new(); for index in 0..prefix {- output.push(Op { tag: b' ', ai: index, bi: index });+ output.push(Op {+ tag: b' ',+ bi: index,+ }); }- for index in prefix..a.len() - suffix {- output.push(Op { tag: b'-', ai: index, bi: 0 });+ for _index in prefix..a.len() - suffix {+ output.push(Op { tag: b'-', bi: 0 }); } for index in prefix..b.len() - suffix {- output.push(Op { tag: b'+', ai: 0, bi: index });+ output.push(Op {+ tag: b'+',+ bi: index,+ }); } for index in 0..suffix { output.push(Op { tag: b' ',- ai: a.len() - suffix + index, bi: b.len() - suffix + index, }); }@@ -463,14 +466,20 @@ let mut j = b.len(); while i > 0 || j > 0 { if i > 0 && j > 0 && a[i - 1] == b[j - 1] {- output.push(Op { tag: b' ', ai: i - 1, bi: j - 1 });+ output.push(Op {+ tag: b' ',+ bi: j - 1,+ }); i -= 1; j -= 1; } else if j > 0 && (i == 0 || dp[i * columns + j - 1] >= dp[(i - 1) * columns + j]) {- output.push(Op { tag: b'+', ai: 0, bi: j - 1 });+ output.push(Op {+ tag: b'+',+ bi: j - 1,+ }); j -= 1; } else {- output.push(Op { tag: b'-', ai: i - 1, bi: 0 });+ output.push(Op { tag: b'-', bi: 0 }); i -= 1; } }@@ -578,14 +587,7 @@ output.max(0) as usize } -fn same_hunks(- ours: &[Hunk],- of: usize,- ol: usize,- theirs: &[Hunk],- tf: usize,- tl: usize,-) -> bool {+fn same_hunks(ours: &[Hunk], of: usize, ol: usize, theirs: &[Hunk], tf: usize, tl: usize) -> bool { let mut left = Vec::new(); let mut right = Vec::new(); for hunk in &ours[of..ol] {@@ -601,12 +603,7 @@ left == right } -pub fn merge_lines(- base: &[u8],- ours: &[u8],- theirs: &[u8],- adjacent: bool,-) -> EditResult {+pub fn merge_lines(base: &[u8], ours: &[u8], theirs: &[u8], adjacent: bool) -> EditResult { let base = split_lines(base); let ours = split_lines(ours); let theirs = split_lines(theirs);@@ -624,7 +621,11 @@ let have_ours = oi < ours_hunks.len(); let have_theirs = ti < theirs_hunks.len(); let ours_start = if have_ours { ours_hunks[oi].start } else { 0 };- let theirs_start = if have_theirs { theirs_hunks[ti].start } else { 0 };+ let theirs_start = if have_theirs {+ theirs_hunks[ti].start+ } else {+ 0+ }; let take_ours = have_ours && (!have_theirs || ours_start <= theirs_start); let cluster_start = if take_ours { ours_start } else { theirs_start }; let of = oi;@@ -674,7 +675,15 @@ } end = end.max(cluster_start); if seen_ours && !seen_theirs {- apply_hunks(&mut result.data, &base, position, end, &ours_hunks, of, o_last);+ apply_hunks(+ &mut result.data,+ &base,+ position,+ end,+ &ours_hunks,+ of,+ o_last,+ ); position = end; oi = o_last; ti = t_last;@@ -693,11 +702,27 @@ ti = t_last; } else { if same_hunks(&ours_hunks, of, o_last, &theirs_hunks, tf, t_last) {- apply_hunks(&mut result.data, &base, position, end, &ours_hunks, of, o_last);+ apply_hunks(+ &mut result.data,+ &base,+ position,+ end,+ &ours_hunks,+ of,+ o_last,+ ); position = end; } else { result.conflicted = true;- apply_hunks(&mut result.data, &base, position, end, &ours_hunks, of, o_last);+ apply_hunks(+ &mut result.data,+ &base,+ position,+ end,+ &ours_hunks,+ of,+ o_last,+ ); result.ranges.push(MergeRange { base_start: cluster_start, base_end: end,@@ -872,8 +897,7 @@ continue; }; let base = glob.rsplit('/').next().unwrap_or(glob);- if !core::glob_match(glob, &path)- && !(!glob.contains('/') && core::glob_match(base, &path))+ if !core::glob_match(glob, &path) && !(!glob.contains('/') && core::glob_match(base, &path)) { continue; }@@ -892,7 +916,10 @@ fn resolution_lookup(repo: &Path, body: &[u8]) -> Option<Id> { let key = crate::object::id::hash_bytes(body);- let data = core::read_file_opt(&crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()), 0)?;+ let data = core::read_file_opt(+ &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),+ 0,+ )?; if data.len() < 64 { return None; }@@ -1077,12 +1104,7 @@ build_level(txn, entries, 0, entries.len(), 0) } -fn build_subtree(- txn: &mut Txn,- canon: &[OrigEntry],- term: usize,- prefix: &[u8],-) -> Result<Id> {+fn build_subtree(txn: &mut Txn, canon: &[OrigEntry], term: usize, prefix: &[u8]) -> Result<Id> { let mut entries = Vec::new(); for entry in canon { if entry.term == term && has_prefix(&entry.path, prefix) {@@ -1130,7 +1152,9 @@ return Ok(Some(OutEntry { path: path.to_vec(), kind: value.kind,- target: value.target.ok_or_else(|| Error::new("missing conflict target"))?,+ target: value+ .target+ .ok_or_else(|| Error::new("missing conflict target"))?, })); } if all_files(&sum)@@ -1144,7 +1168,8 @@ let base = sum.removes[0].target.unwrap(); let ours = sum.adds[0].target.unwrap(); let theirs = sum.adds[1].target.unwrap();- if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)? {+ if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)?+ { if !merged.conflicted { let blob = add_blob(txn, &merged.data); let mode = merge_mode(&sum);@@ -1235,10 +1260,13 @@ }); } let find_orig = |term: usize, path: &[u8]| -> Option<&OrigEntry> {- orig.iter().find(|entry| entry.term == term && entry.path == path)+ orig.iter()+ .find(|entry| entry.term == term && entry.path == path) }; let find_canon = |term: usize, path: &[u8]| -> Option<&OrigEntry> {- canon.iter().find(|entry| entry.term == term && entry.path == path)+ canon+ .iter()+ .find(|entry| entry.term == term && entry.path == path) }; let mut output = Vec::new(); let mut rerere = 0;@@ -1276,7 +1304,8 @@ } entries.push(value); }- if let Some(merged) = merge_entry(repo, txn, store, path, &entries, adjacent, &mut rerere)? {+ if let Some(merged) = merge_entry(repo, txn, store, path, &entries, adjacent, &mut rerere)?+ { output.push(merged); } if !consumed.contains(path) {@@ -1334,7 +1363,8 @@ } entries.push(value); }- if let Some(merged) = merge_entry(repo, txn, store, &path, &entries, adjacent, &mut rerere)? {+ if let Some(merged) = merge_entry(repo, txn, store, &path, &entries, adjacent, &mut rerere)?+ { output.push(merged); } if mixed {@@ -1399,8 +1429,16 @@ let t1 = tree_of(store, bases[1])?; let lcas = merge_bases(store, bases[0], bases[1])?; let mut terms = vec![- TreeTerm { positive: true, present: t0.is_some(), id: t0.unwrap_or_default() },- TreeTerm { positive: true, present: t1.is_some(), id: t1.unwrap_or_default() },+ TreeTerm {+ positive: true,+ present: t0.is_some(),+ id: t0.unwrap_or_default(),+ },+ TreeTerm {+ positive: true,+ present: t1.is_some(),+ id: t1.unwrap_or_default(),+ }, ]; if let Some(first) = lcas.first() { let tree = tree_of(store, *first)?;@@ -1410,11 +1448,22 @@ id: tree.unwrap_or_default(), }); } else {- terms.push(TreeTerm { positive: false, present: false, id: Id::default() });+ terms.push(TreeTerm {+ positive: false,+ present: false,+ id: Id::default(),+ }); } Ok(Some(- treemerge(repo, txn, store, &terms, &[RenameMap::new(), RenameMap::new(), RenameMap::new()], adjacent)?- .tree,+ treemerge(+ repo,+ txn,+ store,+ &terms,+ &[RenameMap::new(), RenameMap::new(), RenameMap::new()],+ adjacent,+ )?+ .tree, )) } @@ -1483,7 +1532,11 @@ new_parent_trees: &[Id], adjacent: bool, ) -> Result<MergeOutcome> {- let mut terms = vec![TreeTerm { positive: true, present: true, id: commit_tree }];+ let mut terms = vec![TreeTerm {+ positive: true,+ present: true,+ id: commit_tree,+ }]; let mut maps = Vec::new(); maps.push(if let Some(parent) = old_parents.first() { map_from(store, *parent, old_commit)?@@ -1492,16 +1545,28 @@ }); if old_parents.is_empty() { for tree in new_parent_trees {- terms.push(TreeTerm { positive: true, present: true, id: *tree });+ terms.push(TreeTerm {+ positive: true,+ present: true,+ id: *tree,+ }); maps.push(RenameMap::new()); }- terms.push(TreeTerm { positive: false, present: false, id: Id::default() });+ terms.push(TreeTerm {+ positive: false,+ present: false,+ id: Id::default(),+ }); maps.push(RenameMap::new()); } else { for (index, parent) in old_parents.iter().enumerate() { let old_tree = tree_of(store, *parent)?; let new_tree = new_parent_trees.get(index).copied().unwrap_or_default();- terms.push(TreeTerm { positive: true, present: true, id: new_tree });+ terms.push(TreeTerm {+ positive: true,+ present: true,+ id: new_tree,+ }); terms.push(TreeTerm { positive: false, present: old_tree.is_some(),@@ -1534,7 +1599,14 @@ if renames_state == commit::RENAMES_RECORDED { for (index, parent) in parents.iter().enumerate() { let parent_tree = tree_of(store, *parent)?;- let detected = detect(store, Some(txn.writer()), parent_tree, Some(root), 0, index as u64)?;+ let detected = detect(+ store,+ Some(txn.writer()),+ parent_tree,+ Some(root),+ 0,+ index as u64,+ )?; renames.extend(detected); } }@@ -1633,7 +1705,10 @@ return Ok(None); }; let tree = tree::decode(&body)?;- let cut = path.iter().position(|byte| *byte == b'/').unwrap_or(path.len());+ let cut = path+ .iter()+ .position(|byte| *byte == b'/')+ .unwrap_or(path.len()); let name = &path[..cut]; let mut entries = Vec::new(); let mut found = false;@@ -1645,7 +1720,11 @@ found = true; if cut == path.len() { if present {- entries.push(TreeEntry { name: entry.name, kind, target });+ entries.push(TreeEntry {+ name: entry.name,+ kind,+ target,+ }); } } else if entry.kind == KIND_SUBTREE { if let Some(child) = edit_tree_into(@@ -1673,7 +1752,11 @@ } } if !found && cut == path.len() && present {- entries.push(TreeEntry { name: name.to_vec(), kind, target });+ entries.push(TreeEntry {+ name: name.to_vec(),+ kind,+ target,+ }); } Ok(Some(add_tree(txn, &entries)?)) }@@ -1722,5 +1805,3 @@ pub fn merge_binary_path(repo: &Path, path: &[u8]) -> bool { merge_binary(repo, path) }--pub fn _unused(_: &mut Store, _: &mut Txn, _: &mut HashMap<Id, Id>) {}--- a/veinsrs/src/object/blob.rs+++ b/veinsrs/src/object/blob.rs@@ -1,9 +1,9 @@ use crate::encoding::{Reader, Writer}; use crate::error::{Error, Result}; use crate::object::chunker::next_chunk;-use crate::object::id::{object_id, Id};+use crate::object::id::{Id, object_id}; use crate::object::{- RawObject, INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, TYPE_BLOB, TYPE_CHUNK,+ INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, RawObject, TYPE_BLOB, TYPE_CHUNK, }; #[derive(Clone, Copy, PartialEq, Eq)]--- a/veinsrs/src/object/commit.rs+++ b/veinsrs/src/object/commit.rs@@ -167,7 +167,8 @@ }); } let extra_count = reader.varint()?;- let extra_count = usize::try_from(extra_count).map_err(|_| Error::new("too many extra headers"))?;+ let extra_count =+ usize::try_from(extra_count).map_err(|_| Error::new("too many extra headers"))?; if extra_count > 1024 { return Err(Error::new("too many extra headers")); }--- a/veinsrs/src/object/conflict.rs+++ b/veinsrs/src/object/conflict.rs@@ -27,10 +27,7 @@ return Err(Error::new("invalid conflict value kind")); } if kind == 0 {- return Ok(ConflictValue {- kind,- target: None,- });+ return Ok(ConflictValue { kind, target: None }); } Ok(ConflictValue { kind,@@ -89,7 +86,8 @@ } pub fn encode(conflict: &Conflict) -> Vec<u8> {- let mut writer = Writer::with_capacity((conflict.adds.len() + conflict.removes.len()) * 40 + 16);+ let mut writer =+ Writer::with_capacity((conflict.adds.len() + conflict.removes.len()) * 40 + 16); write_values(&mut writer, &conflict.adds); write_values(&mut writer, &conflict.removes); writer.into_vec()--- a/veinsrs/src/object/path.rs+++ b/veinsrs/src/object/path.rs@@ -7,9 +7,7 @@ if component == b"." || component == b".." { return false; }- component- .iter()- .all(|byte| *byte != 0 && *byte != b'/')+ component.iter().all(|byte| *byte != 0 && *byte != b'/') } pub fn valid_name(name: &[u8]) -> bool {--- a/veinsrs/src/object/tree.rs+++ b/veinsrs/src/object/tree.rs@@ -2,7 +2,7 @@ use crate::error::{Error, Result}; use crate::object::id::Id; use crate::object::path::valid_name;-use crate::object::{MAX_NAME_LEN, MAX_TREE_ENTRIES, MAX_TREE_DEPTH, TYPE_TREE};+use crate::object::{MAX_NAME_LEN, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, TYPE_TREE}; use crate::store::reader::Store; pub const KIND_FILE: u8 = 1;@@ -151,4 +151,3 @@ .binary_search_by(|entry| entry.name.as_slice().cmp(name)) .ok() }---- a/veinsrs/src/object/view.rs+++ b/veinsrs/src/object/view.rs@@ -183,7 +183,10 @@ return Err(Error::new("bookmarks are not sorted")); } let targets = read_target_set(&mut reader)?;- bookmarks.push(Bookmark { name: name.clone(), targets });+ bookmarks.push(Bookmark {+ name: name.clone(),+ targets,+ }); previous_name = Some(name); } @@ -200,12 +203,16 @@ return Err(Error::new("tags are not sorted")); } let target = reader.id()?;- tags.push(TagRef { name: name.clone(), target });+ tags.push(TagRef {+ name: name.clone(),+ target,+ }); previous_name = Some(name); } let remote_count = reader.varint()?;- let remote_count = usize::try_from(remote_count).map_err(|_| Error::new("too many remote refs"))?;+ let remote_count =+ usize::try_from(remote_count).map_err(|_| Error::new("too many remote refs"))?; if remote_count > 1_000_000 { return Err(Error::new("remote ref limit exceeded")); }@@ -219,7 +226,11 @@ return Err(Error::new("remote refs are not sorted")); } let target = reader.id()?;- remote_refs.push(RemoteRef { remote, name, target });+ remote_refs.push(RemoteRef {+ remote,+ name,+ target,+ }); previous_pair = Some(key); } @@ -233,7 +244,10 @@ let mut previous_name: Option<Vec<u8>> = None; for _ in 0..workspace_count { let workspace = read_name(&mut reader)?;- if previous_name.as_ref().is_some_and(|value| value >= &workspace) {+ if previous_name+ .as_ref()+ .is_some_and(|value| value >= &workspace)+ { return Err(Error::new("workspaces are not sorted")); } let target = reader.id()?;--- a/veinsrs/src/protocol/client.rs+++ b/veinsrs/src/protocol/client.rs@@ -1,10 +1,8 @@ use std::path::Path; -use crate::core; use crate::crypto; use crate::error::{Error, Result};-use crate::object::id::{object_id, Id};-use crate::object::TYPE_CHUNK;+use crate::object::id::{Id, object_id}; use crate::store::reader::Store; use crate::store::writer::Writer; use crate::time;@@ -200,10 +198,11 @@ pub fn fetch_skeleton(&mut self, repo: &Path, wants: &[Id]) -> Result<()> { let request_id = (time::now_millis() & 0x7fff_ffff) as u32;- if !self- .stream- .write_frame(wire::kind::FETCH_SKELETON, request_id, &messages::encode_ids(wants))- {+ if !self.stream.write_frame(+ wire::kind::FETCH_SKELETON,+ request_id,+ &messages::encode_ids(wants),+ ) { return Err(Error::new("connection closed while requesting objects")); } self.receive_stream(repo)@@ -214,10 +213,11 @@ return Ok(()); } let request_id = (time::now_millis() & 0x7fff_ffff) as u32;- if !self- .stream- .write_frame(wire::kind::GET_CHUNKS, request_id, &messages::encode_ids(ids))- {+ if !self.stream.write_frame(+ wire::kind::GET_CHUNKS,+ request_id,+ &messages::encode_ids(ids),+ ) { return Err(Error::new("connection closed while requesting chunks")); } self.receive_stream(repo)@@ -233,7 +233,10 @@ pub fn push_objects(&mut self, repo: &Path, ids: &[Id]) -> Result<()> { let request_id = (time::now_millis() & 0x7fff_ffff) as u32;- if !self.stream.write_frame(wire::kind::PUT_RECORDS, request_id, &[]) {+ if !self+ .stream+ .write_frame(wire::kind::PUT_RECORDS, request_id, &[])+ { return Err(Error::new("connection closed while starting push")); } let mut store = Store::open(repo)?;@@ -272,7 +275,10 @@ } pub fn update_refs(&mut self, updates: &[UpdateRef]) -> Result<()> {- let frame = self.request(wire::kind::UPDATE_REFS, &messages::encode_update_refs(updates))?;+ let frame = self.request(+ wire::kind::UPDATE_REFS,+ &messages::encode_update_refs(updates),+ )?; if frame.kind != wire::kind::UPDATE_REFS_OK { return Err(Error::new("unexpected response to ref update")); }@@ -297,8 +303,4 @@ pub fn same_id(left: Id, right: Id) -> bool { left == right-}--pub fn _unused(_core: &core::StatInfo, _chunk: u8) {- let _ = TYPE_CHUNK; }--- a/veinsrs/src/protocol/wire.rs+++ b/veinsrs/src/protocol/wire.rs@@ -1,8 +1,8 @@ use std::io::{Read, Write}; use crate::error::{Error, Result};-use crate::object::id::Id; use crate::object::MAX_OBJECT_BODY;+use crate::object::id::Id; pub const MAX_FRAME: usize = 16 * 1024 * 1024; --- a/veinsrs/src/server.rs+++ b/veinsrs/src/server.rs@@ -1,21 +1,20 @@ use std::path::{Path, PathBuf}; -use crate::core; use crate::crypto; use crate::error::Result; use crate::object::blob::{self, BlobForm}; use crate::object::conflict;-use crate::object::id::{object_id, Id};+use crate::object::id::{Id, object_id}; use crate::object::tree::{self, KIND_SUBTREE}; use crate::object::view::{Bookmark, TagRef}; use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE}; use crate::protocol::messages::{self, RefInfo}; use crate::protocol::wire::{self, Stream};+use crate::store::Txn; use crate::store::graph; use crate::store::ops; use crate::store::reader::Store; use crate::store::writer::Writer;-use crate::store::Txn; const MAX_CHUNKS: usize = 4096; @@ -33,14 +32,6 @@ public_key: Option<crypto::PublicKey>, fingerprint: Vec<u8>, haves: Vec<Id>,-}--fn role_text(role: u8) -> &'static str {- match role {- 2 => "write",- 1 => "read",- _ => "anonymous",- } } fn deny(session: &mut Session, request_id: u32, write: bool) -> bool {@@ -54,7 +45,9 @@ } else { wire::error_code::UNAUTHENTICATED };- session.stream.write_error(request_id, code, "permission denied");+ session+ .stream+ .write_error(request_id, code, "permission denied"); return true; } if role == 1 || role == 2 {@@ -65,7 +58,9 @@ } else { wire::error_code::UNAUTHENTICATED };- session.stream.write_error(request_id, code, "permission denied");+ session+ .stream+ .write_error(request_id, code, "permission denied"); true } @@ -108,7 +103,14 @@ let Some(body) = session.store.body(id, TYPE_TREE)? else { return Err(crate::error::Error::new("missing tree")); };- if !send_record(&mut session.stream, request_id, hasher, id, TYPE_TREE, &body) {+ if !send_record(+ &mut session.stream,+ request_id,+ hasher,+ id,+ TYPE_TREE,+ &body,+ ) { return Err(crate::error::Error::new("write failed")); } let tree = tree::decode(&body)?;@@ -115,9 +117,14 @@ for entry in tree.entries { match entry.kind { KIND_SUBTREE => send_tree(session, request_id, hasher, entry.target, seen)?,- tree::KIND_CONFLICT => {- send_object(session, request_id, hasher, entry.target, TYPE_CONFLICT, seen)?- }+ tree::KIND_CONFLICT => send_object(+ session,+ request_id,+ hasher,+ entry.target,+ TYPE_CONFLICT,+ seen,+ )?, tree::KIND_SUBMODULE => {} _ => send_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen)?, }@@ -255,9 +262,11 @@ server_nonce: session.server_nonce.clone(), auth_required: u8::from(!session.access.anonymous_read), };- session- .stream- .write_frame(wire::kind::HELLO_OK, frame.request_id, &messages::encode_hello_ok(&hello_ok))+ session.stream.write_frame(+ wire::kind::HELLO_OK,+ frame.request_id,+ &messages::encode_hello_ok(&hello_ok),+ ) } fn handle_auth(session: &mut Session, frame: &wire::Frame) -> bool {@@ -285,9 +294,7 @@ &[], ); let valid = role != 255- && public_key.is_some_and(|key| {- crypto::ed25519_verify(&key, &message, &auth.signature)- });+ && public_key.is_some_and(|key| crypto::ed25519_verify(&key, &message, &auth.signature)); if !valid { session.stream.write_error( frame.request_id,@@ -305,9 +312,11 @@ role, fingerprint: session.fingerprint.clone(), };- session- .stream- .write_frame(wire::kind::AUTH_OK, frame.request_id, &messages::encode_auth_ok(&ok))+ session.stream.write_frame(+ wire::kind::AUTH_OK,+ frame.request_id,+ &messages::encode_auth_ok(&ok),+ ) } fn handle_list_refs(session: &mut Session, frame: &wire::Frame) -> Result<bool> {@@ -338,9 +347,11 @@ kind: 1, }); }- Ok(session- .stream- .write_frame(wire::kind::REFS, frame.request_id, &messages::encode_refs(&refs)))+ Ok(session.stream.write_frame(+ wire::kind::REFS,+ frame.request_id,+ &messages::encode_refs(&refs),+ )) } fn handle_fetch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {@@ -370,10 +381,23 @@ continue; }; let body = crate::object::commit::encode(&commit);- if !send_record(&mut session.stream, frame.request_id, &mut hasher, id, TYPE_COMMIT, &body) {+ if !send_record(+ &mut session.stream,+ frame.request_id,+ &mut hasher,+ id,+ TYPE_COMMIT,+ &body,+ ) { return Ok(false); }- send_tree(session, frame.request_id, &mut hasher, commit.root_tree, &mut seen)?;+ send_tree(+ session,+ frame.request_id,+ &mut hasher,+ commit.root_tree,+ &mut seen,+ )?; } send_end(&mut session.stream, frame.request_id, &hasher); Ok(true)@@ -401,7 +425,14 @@ ); return Ok(true); };- if !send_record(&mut session.stream, frame.request_id, &mut hasher, id, TYPE_CHUNK, &body) {+ if !send_record(+ &mut session.stream,+ frame.request_id,+ &mut hasher,+ id,+ TYPE_CHUNK,+ &body,+ ) { return Ok(false); } }@@ -485,11 +516,9 @@ } hasher.update(&incoming.payload); let Some(record) = wire::parse_record(&incoming.payload) else {- session.stream.write_error(- frame.request_id,- wire::error_code::BAD_FRAME,- "bad record",- );+ session+ .stream+ .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record"); return Ok(true); }; if object_id(record.kind, &record.body) != record.id {@@ -521,7 +550,14 @@ ops::find_tag(view, tag.as_bytes()).map(|index| view.tags[index].target) } else { ops::find_bookmark(view, name.as_bytes())- .and_then(|index| view.bookmarks[index].targets.adds.first().copied().flatten())+ .and_then(|index| {+ view.bookmarks[index]+ .targets+ .adds+ .first()+ .copied()+ .flatten()+ }) .or_else(|| ops::find_tag(view, name.as_bytes()).map(|index| view.tags[index].target)) }; match expected {@@ -599,10 +635,9 @@ ops::rebuild_heads(txn.view_mut()); txn.finish("remote push")?; session.store.refresh()?;- Ok(session.stream.write_simple(- wire::kind::UPDATE_REFS_OK,- frame.request_id,- ))+ Ok(session+ .stream+ .write_simple(wire::kind::UPDATE_REFS_OK, frame.request_id)) } fn dispatch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {@@ -662,16 +697,4 @@ } } Ok(())-}--pub fn log_line(session: &Session, outcome: &str) {- let path = crate::store::layout::veins_dir(&session.repo).join("server.log");- let line = format!(- "{} {} {} {}\n",- crate::time::now_millis(),- role_text(session.role),- outcome,- session.hello_repo- );- core::append_file(&path, line.as_bytes()); }--- a/veinsrs/src/store/graph.rs+++ b/veinsrs/src/store/graph.rs@@ -3,7 +3,7 @@ use crate::error::{Error, Result}; use crate::object::blob::{self, BlobForm}; use crate::object::commit::{self, Commit};-use crate::object::id::{is_hex_prefix, prefix_matches, Id};+use crate::object::id::{Id, is_hex_prefix, prefix_matches}; use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE}; use crate::object::view::View; use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT};--- a/veinsrs/src/store/index.rs+++ b/veinsrs/src/store/index.rs@@ -1,6 +1,6 @@ use crate::encoding::Reader; use crate::error::{Error, Result};-use crate::object::id::{hash_bytes, Id};+use crate::object::id::{Id, hash_bytes}; #[derive(Clone)] pub struct IndexEntry {--- a/veinsrs/src/store/layout.rs+++ b/veinsrs/src/store/layout.rs@@ -19,6 +19,10 @@ pub fn op_heads_dir(root: &Path) -> PathBuf { veins_dir(root).join("op-heads")+}++pub fn git_dir(root: &Path) -> PathBuf {+ veins_dir(root).join("git") } pub fn git_map_dir(root: &Path) -> PathBuf {--- a/veinsrs/src/store/mod.rs+++ b/veinsrs/src/store/mod.rs@@ -7,5 +7,5 @@ pub mod transaction; pub mod writer; -pub use reader::{set_promisor_fetcher, Location, Store};+pub use reader::{Location, Store, set_promisor_fetcher}; pub use transaction::Txn;--- a/veinsrs/src/store/ops.rs+++ b/veinsrs/src/store/ops.rs@@ -48,8 +48,8 @@ let Some(first) = heads.first() else { return Ok(None); };- let mut view = load_view_for_head(store, *first)?- .ok_or_else(|| Error::new("missing operation state"))?;+ let mut view =+ load_view_for_head(store, *first)?.ok_or_else(|| Error::new("missing operation state"))?; for head in &heads[1..] { if let Some(extra) = load_view_for_head(store, *head)? { merge_view_into(&mut view, &extra);--- a/veinsrs/src/store/pack.rs+++ b/veinsrs/src/store/pack.rs@@ -8,10 +8,10 @@ use crate::encoding::{Reader, Writer}; use crate::error::{Error, Result}; use crate::object::blob::{self, BlobEntry, BlobForm};-use crate::object::id::{hash_bytes, Id};+use crate::object::id::{Id, hash_bytes}; use crate::object::{- type_valid, RawObject, MAX_CHUNK_LEN, MAX_OBJECT_BODY, MAX_STORE_PACK_BYTES, TYPE_BLOB,- TYPE_CHUNK,+ MAX_CHUNK_LEN, MAX_OBJECT_BODY, MAX_STORE_PACK_BYTES, RawObject, TYPE_BLOB, TYPE_CHUNK,+ type_valid, }; use crate::store::index::{self, IndexEntry}; @@ -219,7 +219,6 @@ } struct BlobRoot {- pending_index: usize, entries: Vec<BlobEntry>, offsets: Vec<u64>, length: u64,@@ -317,7 +316,6 @@ offset = offset.saturating_add(entry.length); } roots.push(BlobRoot {- pending_index: index, entries, offsets, length: offset,@@ -360,9 +358,7 @@ solo_sum += solo; let mut best = solo; let position = target_root.offsets[selected];- let near = base- .offsets- .partition_point(|value| *value < position);+ let near = base.offsets.partition_point(|value| *value < position); for delta in -1i64..=1 { let candidate = near as i64 + delta; if candidate < 0 || candidate as usize >= base.entries.len() {@@ -369,9 +365,7 @@ continue; } let candidate = candidate as usize;- let Some(base_index) = chunk_index- .get(&base.entries[candidate].id)- .copied()+ let Some(base_index) = chunk_index.get(&base.entries[candidate].id).copied() else { continue; };@@ -378,9 +372,7 @@ if base_index >= chunk { continue; }- if let Some(frame) =- compress_dict(&bodies[chunk], &bodies[base_index], level)- {+ if let Some(frame) = compress_dict(&bodies[chunk], &bodies[base_index], level) { best = best.min(frame.len() + 10); } }@@ -404,8 +396,7 @@ if roots[candidate].length == 0 || roots[root_index].length == 0 { continue; }- let ratio =- roots[candidate].length as f64 / roots[root_index].length as f64;+ let ratio = roots[candidate].length as f64 / roots[root_index].length as f64; if ratio < 0.4 || ratio > 2.5 { continue; }@@ -447,13 +438,11 @@ } bucket += 1; }- let mut ranked: Vec<(u64, usize)> =- nearby.into_iter().map(|(candidate, difference)| (difference, candidate)).collect();- ranked.sort_by(|left, right| {- left.0- .cmp(&right.0)- .then_with(|| right.1.cmp(&left.1))- });+ let mut ranked: Vec<(u64, usize)> = nearby+ .into_iter()+ .map(|(candidate, difference)| (difference, candidate))+ .collect();+ ranked.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| right.1.cmp(&left.1))); for (_, candidate) in ranked { candidates.push(candidate); }@@ -538,9 +527,7 @@ continue; } let candidate = candidate as usize;- let Some(base_index) = chunk_index- .get(&base_root.entries[candidate].id)- .copied()+ let Some(base_index) = chunk_index.get(&base_root.entries[candidate].id).copied() else { continue; };@@ -640,11 +627,7 @@ level, ); - let estimate = bodies- .iter()- .map(|body| body.len() + 64)- .sum::<usize>()- + 16;+ let estimate = bodies.iter().map(|body| body.len() + 64).sum::<usize>() + 16; let mut writer = Writer::with_capacity(estimate); writer.raw(b"VPK1"); writer.u32le(1);--- a/veinsrs/src/store/reader.rs+++ b/veinsrs/src/store/reader.rs@@ -5,12 +5,12 @@ use crate::encoding::Reader; use crate::error::{Error, Result};-use crate::object::id::{object_id, Id};+use crate::object::id::{Id, object_id}; use crate::object::view::{self, Operation, View};-use crate::object::{type_valid, MAX_STORE_PACK_BYTES, TYPE_CHUNK};+use crate::object::{MAX_STORE_PACK_BYTES, TYPE_CHUNK, type_valid}; use crate::store::index::{self, Index}; use crate::store::layout;-use crate::store::pack::{self, record_limit, Pack};+use crate::store::pack::{self, Pack, record_limit}; type PromisorFetcher = Box<dyn Fn(&Path, Id) -> bool + Send + Sync>; @@ -148,29 +148,7 @@ true } Err(_) => false,- }- }-- fn read_range(&mut self, index: usize, offset: u64, length: usize) -> Option<Vec<u8>> {- if length as u64 > MAX_STORE_PACK_BYTES {- return None;- }- if !self.open_file(index) {- return None;- }- let file = self.packs[index].file.as_ref()?;- let mut data = vec![0u8; length];- let mut done = 0;- while done < length {- match file.read_at(&mut data[done..], offset + done as u64) {- Ok(0) => break,- Ok(count) => done += count,- Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,- Err(_) => return None,- } }- data.truncate(done);- Some(data) } fn read_at_shared(&self, index: usize, offset: u64, length: usize) -> Option<Vec<u8>> {--- a/veinsrs/src/store/transaction.rs+++ b/veinsrs/src/store/transaction.rs@@ -2,9 +2,7 @@ use crate::error::{Error, Result}; use crate::object::id::Id;-use crate::object::view::{- encode_operation, encode_view, Operation, TimeMs, View,-};+use crate::object::view::{Operation, TimeMs, View, encode_operation, encode_view}; use crate::object::{TYPE_OPERATION, TYPE_VIEW}; use crate::store::ops; use crate::store::reader::Store;--- a/veinsrs/src/store/writer.rs+++ b/veinsrs/src/store/writer.rs@@ -1,7 +1,7 @@ use std::collections::HashSet; use std::path::Path; -use crate::object::id::{object_id, Id};+use crate::object::id::{Id, object_id}; use crate::object::{RawObject, TYPE_CHUNK}; use crate::store::pack::{self, PackOutput}; @@ -37,12 +37,7 @@ if self.quota_hit || !self.seen.insert(id) { return false; }- if self.limit > 0- && self- .raw_bytes- .saturating_add(body.len() as u64)- > self.limit- {+ if self.limit > 0 && self.raw_bytes.saturating_add(body.len() as u64) > self.limit { self.quota_hit = true; return false; }--- a/veinsrs/src/worktree/attributes.rs+++ b/veinsrs/src/worktree/attributes.rs@@ -53,15 +53,11 @@ } fn next_token<'a>(text: &'a str, position: &mut usize) -> &'a str {- while *position < text.len()- && matches!(text.as_bytes()[*position], b' ' | b'\t')- {+ while *position < text.len() && matches!(text.as_bytes()[*position], b' ' | b'\t') { *position += 1; } let start = *position;- while *position < text.len()- && !matches!(text.as_bytes()[*position], b' ' | b'\t')- {+ while *position < text.len() && !matches!(text.as_bytes()[*position], b' ' | b'\t') { *position += 1; } &text[start..*position]--- a/veinsrs/src/worktree/checkout.rs+++ b/veinsrs/src/worktree/checkout.rs@@ -10,11 +10,11 @@ use crate::object::id::Id; use crate::object::path::valid_checkout_path; use crate::object::tree::{self, FlatEntry};+use crate::store::Txn; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store;-use crate::store::Txn; use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText}; use crate::worktree::snapshot; use crate::worktree::stat_cache::{self, CacheEntry};@@ -27,8 +27,8 @@ .ok_or_else(|| Error::new("no operation state; import a repository first"))?; let target = graph::resolve_revision(&mut store, &view, revision)? .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;- let target_commit = graph::load_commit(&mut store, target)?- .ok_or_else(|| Error::new("cannot read commit"))?;+ let target_commit =+ graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?; let bookmark_checkout = !revision.is_empty() && revision != "@"@@ -97,7 +97,11 @@ } fn sidecar_suffixes() -> Vec<String> {- let mut suffixes = vec![".base".to_string(), ".ours".to_string(), ".theirs".to_string()];+ let mut suffixes = vec![+ ".base".to_string(),+ ".ours".to_string(),+ ".theirs".to_string(),+ ]; for number in 2..=64 { suffixes.push(format!(".base{number}")); suffixes.push(format!(".theirs{number}"));@@ -253,8 +257,8 @@ entry: &FlatEntry, attributes: &AttributeRules, ) -> Result<()> {- let data = graph::read_blob_loaded(store, entry.target)?- .ok_or_else(|| Error::new("missing blob"))?;+ let data =+ graph::read_blob_loaded(store, entry.target)?.ok_or_else(|| Error::new("missing blob"))?; if entry.kind == tree::KIND_SYMLINK { return write_symlink(root, &entry.path, &data); }@@ -277,11 +281,7 @@ } } -fn delete_stale(- root: &Path,- old_entries: &[FlatEntry],- new_entries: &[FlatEntry],-) -> Result<()> {+fn delete_stale(root: &Path, old_entries: &[FlatEntry], new_entries: &[FlatEntry]) -> Result<()> { for entry in old_entries { if entry.kind == tree::KIND_SUBMODULE { continue;@@ -358,8 +358,8 @@ target: Id, attributes: &AttributeRules, ) -> Result<()> {- let conflict = load_conflict(store, target)?- .ok_or_else(|| Error::new("cannot read conflict value"))?;+ let conflict =+ load_conflict(store, target)?.ok_or_else(|| Error::new("cannot read conflict value"))?; for (index, value) in conflict.removes.iter().enumerate() { let suffix = if index == 0 { ".base".to_string()@@ -450,7 +450,9 @@ } match entry.kind { tree::KIND_CONFLICT => conflicts.push(entry.clone()),- tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => files.push(entry.clone()),+ tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {+ files.push(entry.clone())+ } _ => {} } }@@ -482,7 +484,9 @@ ensure_safe_dirs(root, b"")?; store.preload()?;- files.par_iter().try_for_each(|entry| write_entry(store, root, entry, &attributes))?;+ files+ .par_iter()+ .try_for_each(|entry| write_entry(store, root, entry, &attributes))?; for conflict in &conflicts { materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)?; }--- a/veinsrs/src/worktree/snapshot.rs+++ b/veinsrs/src/worktree/snapshot.rs@@ -10,13 +10,13 @@ use crate::object::commit::{self, Commit, Rename}; use crate::object::id::Id; use crate::object::path;-use crate::object::tree::{self, FlatEntry, TreeEntry, KIND_CONFLICT, KIND_SUBTREE};+use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry}; use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn; use crate::store::graph; use crate::store::ops; use crate::store::reader::Store; use crate::store::writer::Writer;-use crate::store::Txn; use crate::time; use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText}; use crate::worktree::stat_cache::{self, Cache, CacheEntry};@@ -111,15 +111,13 @@ let old_tree = match old_tree_id { Some(id) => {- let body = store- .body(id, TYPE_TREE)?- .ok_or_else(|| {- Error::new(format!(- "missing tree {} at {}",- id.to_hex(),- String::from_utf8_lossy(base)- ))- })?;+ let body = store.body(id, TYPE_TREE)?.ok_or_else(|| {+ Error::new(format!(+ "missing tree {} at {}",+ id.to_hex(),+ String::from_utf8_lossy(base)+ ))+ })?; match tree::decode(&body).ok() { Some(tree) => Some(tree), None => {@@ -371,12 +369,14 @@ Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?))) } -fn read_build(path: &Path, relative: &[u8], attributes: &AttributeRules) -> Option<blob::BlobBuild> {+fn read_build(+ path: &Path,+ relative: &[u8],+ attributes: &AttributeRules,+) -> Option<blob::BlobBuild> { let data = core::read_file_opt(path, 0)?; let path_attributes = attributes.lookup(&String::from_utf8_lossy(relative));- if path_attributes.eol != AttributeEol::None- && path_attributes.text != AttributeText::Binary- {+ if path_attributes.eol != AttributeEol::None && path_attributes.text != AttributeText::Binary { Some(blob::build(&attributes::normalize_eol( &data, path_attributes.eol,--- a/veinsrs/src/worktree/stat_cache.rs+++ b/veinsrs/src/worktree/stat_cache.rs@@ -85,7 +85,9 @@ trusted, }); }- cache.entries.sort_by(|left, right| left.path.cmp(&right.path));+ cache+ .entries+ .sort_by(|left, right| left.path.cmp(&right.path)); cache } --- a/veinsrs/tests/end_to_end.rs+++ b/veinsrs/tests/end_to_end.rs@@ -11,7 +11,8 @@ .duration_since(UNIX_EPOCH) .unwrap() .as_nanos();- let path = std::env::temp_dir().join(format!("veins-rust-test-{}-{stamp}", std::process::id()));+ let path =+ std::env::temp_dir().join(format!("veins-rust-test-{}-{stamp}", std::process::id())); fs::create_dir_all(&path).unwrap(); Self(path) }@@ -70,8 +71,9 @@ .lines() .find(|line| line.contains("first")) .and_then(|line| {- line.split_whitespace()- .find(|token| token.len() == 12 && token.bytes().all(|byte| byte.is_ascii_hexdigit()))+ line.split_whitespace().find(|token| {+ token.len() == 12 && token.bytes().all(|byte| byte.is_ascii_hexdigit())+ }) }) .expect("first commit id"); ok(root, &["co", first]);--- a/veinsrs/tests/format_vectors.rs+++ b/veinsrs/tests/format_vectors.rs@@ -1,7 +1,7 @@ use veins_rust::object::blob; use veins_rust::object::chunker::{gear_table, next_chunk}; use veins_rust::object::commit::{self, Commit, Sig};-use veins_rust::object::id::{hash_bytes, object_id, Id};+use veins_rust::object::id::{Id, hash_bytes, object_id}; use veins_rust::object::tree; use veins_rust::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef}; use veins_rust::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};@@ -57,8 +57,8 @@ #[test] fn objects_round_trip_and_pack_is_canonical() { let change_id = [- 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,- 0x19, 0x1a,+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,+ 0x1a, ]; let signature = Sig { name: b"Alice".to_vec(),@@ -66,10 +66,8 @@ seconds: 1_700_000_000, tz_min: 0, };- let empty_tree_id = Id::from_hex(- "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",- )- .unwrap();+ let empty_tree_id =+ Id::from_hex("8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb").unwrap(); let commit = Commit { version: 1, parents: Vec::new(),@@ -88,7 +86,10 @@ commit_id.to_hex(), "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299" );- assert_eq!(commit::decode(&commit_body).unwrap().message, b"initial commit");+ assert_eq!(+ commit::decode(&commit_body).unwrap().message,+ b"initial commit"+ ); let view = View { heads: vec![commit_id],@@ -112,7 +113,10 @@ view_id.to_hex(), "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11" );- assert_eq!(view::decode_view(&view_body).unwrap().heads, vec![commit_id]);+ assert_eq!(+ view::decode_view(&view_body).unwrap().heads,+ vec![commit_id]+ ); let operation = Operation { parents: Vec::new(),--- /dev/null+++ b/veinsrs/tests/integration.rs@@ -0,0 +1,717 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Output};+use std::time::{SystemTime, UNIX_EPOCH};++struct Fixture {+ root: PathBuf,+ home: PathBuf,+ repo: PathBuf,+}++impl Fixture {+ fn new() -> Self {+ let stamp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let root = std::env::temp_dir().join(format!(+ "veins-rust-integration-{}-{stamp}",+ std::process::id()+ ));+ let home = root.join("home");+ let repo = root.join("repo");+ fs::create_dir_all(home.join(".config")).unwrap();+ fs::create_dir_all(&repo).unwrap();+ Self { root, home, repo }+ }++ fn command(&self, arguments: &[&str], cwd: &Path) -> Output {+ Command::new(env!("CARGO_BIN_EXE_vn"))+ .args(arguments)+ .current_dir(cwd)+ .env("HOME", &self.home)+ .env("XDG_CONFIG_HOME", self.home.join(".config"))+ .env("USER", "tester")+ .env("GIT_AUTHOR_NAME", "Tester")+ .env("GIT_AUTHOR_EMAIL", "tester@example.com")+ .env("GIT_COMMITTER_NAME", "Tester")+ .env("GIT_COMMITTER_EMAIL", "tester@example.com")+ .env("NO_COLOR", "1")+ .env("TZ", "UTC")+ .env("VN_EDITOR", "/bin/true")+ .output()+ .unwrap()+ }++ fn vn(&self, arguments: &[&str]) -> String {+ self.vn_in(&self.repo, arguments)+ }++ fn vn_in(&self, cwd: &Path, arguments: &[&str]) -> String {+ let output = self.command(arguments, cwd);+ assert!(+ output.status.success(),+ "{arguments:?} failed: {}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).into_owned()+ }++ fn fail(&self, arguments: &[&str]) -> String {+ let output = self.command(arguments, &self.repo);+ assert!(+ !output.status.success(),+ "{arguments:?} unexpectedly passed"+ );+ format!(+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ }++ fn init(&self) {+ self.vn(&["init", "."]);+ }++ fn write(&self, path: &str, content: &str) {+ self.write_in(&self.repo, path, content);+ }++ fn write_in(&self, root: &Path, path: &str, content: &str) {+ let path = root.join(path);+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent).unwrap();+ }+ fs::write(path, content).unwrap();+ }++ fn read(&self, path: &str) -> String {+ self.read_in(&self.repo, path)+ }++ fn read_in(&self, root: &Path, path: &str) -> String {+ fs::read_to_string(root.join(path)).unwrap()+ }++ fn exists(&self, path: &str) -> bool {+ self.repo.join(path).exists()+ }++ fn commit(&self, message: &str) {+ self.vn(&["go", "-m", message]);+ }++ fn hash(&self, revision: &str) -> String {+ self.vn(&["hash", revision]).trim().to_string()+ }++ fn log_lines(&self) -> Vec<String> {+ self.vn(&["log", "-a", "-no-col-titles"])+ .lines()+ .map(|line| line.to_string())+ .collect()+ }+}++impl Drop for Fixture {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.root);+ }+}++#[test]+fn init_status_list_and_diff() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "alpha\n");+ f.write("dir/b.txt", "beta\n");+ let status = f.vn(&["stat"]);+ assert!(status.contains("A a.txt"));+ assert!(status.contains("A dir/b.txt"));+ let plain = f.vn(&["ls", "-plain"]);+ assert_eq!(+ plain.lines().collect::<Vec<_>>(),+ vec!["a.txt", "dir/b.txt"]+ );+ let diff = f.vn(&["diff"]);+ assert!(diff.contains("+alpha"));+ assert!(diff.contains("+beta"));+}++#[test]+fn status_paths_are_relative_to_cwd() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "alpha\n");+ f.write("dir/b.txt", "beta\n");+ f.write("dir/sub/c.txt", "gamma\n");+ let sub = f.repo.join("dir/sub");+ let status = f.vn_in(&sub, &["stat"]);+ assert!(status.contains("A ../../a.txt"));+ assert!(status.contains("A ../b.txt"));+ assert!(status.contains("A c.txt"));+}++#[test]+fn commit_log_show_and_hash() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "one\n");+ f.commit("first commit");+ assert!(f.vn(&["stat"]).contains("working copy clean"));+ let rows = f.log_lines();+ assert!(rows.len() >= 2);+ assert!(rows[0].trim_start().starts_with('@'));+ let commit = f+ .log_lines()+ .iter()+ .find(|line| line.contains("first commit"))+ .and_then(|line| line.split_whitespace().nth(1))+ .unwrap()+ .to_string();+ let shown = f.vn(&["show", &commit]);+ assert!(shown.contains("first commit"));+ assert!(shown.contains("+one"));+ assert_eq!(f.hash(&commit).len(), 64);+ let short = f.vn(&["hash", "-short", &commit]).trim().to_string();+ assert_eq!(short, &f.hash(&commit)[..12]);+}++#[test]+fn log_limits_and_revisions() {+ let f = Fixture::new();+ f.init();+ for index in 0..4 {+ f.write("a.txt", &format!("value {index}\n"));+ f.commit(&format!("commit {index}"));+ }+ assert_eq!(f.log_lines().len(), 5);+ assert_eq!(f.vn(&["log", "-l2", "-no-col-titles"]).lines().count(), 2);+ let oldest: Vec<String> = f+ .vn(&["log", "-f2", "-no-col-titles"])+ .lines()+ .map(|line| line.to_string())+ .collect();+ assert!(oldest[0].contains("commit 0"));+ assert!(oldest[1].contains("commit 1"));+ assert_eq!(f.vn(&["log", "l2", "-no-col-titles"]).lines().count(), 2);+ assert!(f.fail(&["log", "-l0"]).contains("error"));+ assert!(f.fail(&["log", "-bad"]).contains("unknown flag"));+}++#[test]+fn checkout_materializes_and_new() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "one\n");+ f.vn(&["bmk", "set", "main"]);+ f.commit("first");+ let first = f.hash("main");+ f.write("a.txt", "two\n");+ f.write("later.txt", "later\n");+ f.commit("second");+ let second = f.hash("main");+ f.vn(&["bmk", "set", "main", "-rev", &first]);+ f.vn(&["bmk", "set", "feature", "-rev", &second]);+ f.vn(&["co", "main"]);+ assert_eq!(f.read("a.txt"), "one\n");+ assert!(!f.exists("later.txt"));+ assert!(f.vn(&["stat"]).contains("working copy clean"));+ f.vn(&["co", "feature"]);+ assert_eq!(f.read("a.txt"), "two\n");+ assert!(f.exists("later.txt"));+ f.vn(&["new"]);+ assert!(f.vn(&["stat"]).contains("working copy clean"));+}++#[test]+fn worktree_rename_delete_exclude_remove() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "alpha\n");+ f.write("b.txt", "beta\n");+ f.commit("base");+ f.vn(&["mv", "a.txt", "renamed.txt"]);+ assert!(!f.exists("a.txt"));+ assert_eq!(f.read("renamed.txt"), "alpha\n");+ let status = f.vn(&["stat"]);+ assert!(status.contains("D a.txt"));+ assert!(status.contains("A renamed.txt"));+ f.commit("rename");+ fs::remove_file(f.repo.join("b.txt")).unwrap();+ assert!(f.vn(&["stat"]).contains("D b.txt"));+ f.commit("delete");+ f.write("src/a.c", "a\n");+ f.write("src/b.c", "b\n");+ f.write("docs/readme.md", "docs\n");+ assert!(f.vn(&["rm", "src/*.c"]).contains("will be re-added"));+ f.vn(&["ex", "src/*.c"]);+ assert!(f.read(".vnexclude").contains("src/*.c"));+ f.vn(&["rm", "-delete", "docs/readme.md"]);+ assert!(!f.exists("docs/readme.md"));+}++#[test]+fn ignore_rules_and_attributes() {+ let f = Fixture::new();+ f.init();+ f.write(".gitignore", "*.log\nbuild/\n");+ f.write("debug.log", "ignored\n");+ f.write("build/out.bin", "ignored\n");+ f.write("src/.gitignore", "*.tmp\n");+ f.write("src/notes.tmp", "ignored\n");+ f.write("src/main.c", "kept\n");+ let listing = f.vn(&["ls", "-plain"]);+ let tracked: Vec<&str> = listing.lines().collect();+ assert_eq!(tracked, vec![".gitignore", "src/.gitignore", "src/main.c"]);+ f.write(".vnattribs", "*.txt txt eol:lf\n*.cmd txt eol:crlf\n");+ f.write("a.txt", "a\r\nb\r\n");+ f.write("b.cmd", "x\ny\n");+ f.commit("base");+ fs::remove_file(f.repo.join("a.txt")).unwrap();+ fs::remove_file(f.repo.join("b.cmd")).unwrap();+ let base = f+ .vn(&["log", "-a", "-no-col-titles"])+ .lines()+ .find(|line| line.contains("base"))+ .and_then(|line| line.split_whitespace().nth(1))+ .unwrap()+ .to_string();+ f.vn(&["co", &base]);+ assert_eq!(f.read("a.txt"), "a\nb\n");+ assert_eq!(f.read("b.cmd"), "x\r\ny\r\n");+}++#[test]+fn attributes_command() {+ let f = Fixture::new();+ f.init();+ assert!(+ f.vn(&["attr", "gen", "*.ssa", "*.bin"])+ .contains("updated 2")+ );+ assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n");+ f.vn(&["attr", "txt", "*.c"]);+ f.vn(&["attr", "crlf", "*.c"]);+ assert_eq!(+ f.read(".vnattribs"),+ "*.ssa gen\n*.bin gen\n*.c txt eol:crlf\n"+ );+ f.vn(&["attr", "rm", "crlf", "*.c"]);+ assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n*.c txt\n");+ assert!(+ f.fail(&["attr", "gen", "bad pattern"])+ .contains("not a valid attribute pattern")+ );+ assert!(f.vn(&["attr", "ls"]).contains("*.c txt"));+}++#[test]+fn bookmarks_and_tags() {+ let f = Fixture::new();+ f.init();+ f.write("f.txt", "one\n");+ f.commit("one");+ f.vn(&["bmk", "set", "main"]);+ f.write("f.txt", "two\n");+ f.commit("two");+ let listing = f.vn(&["bmk", "ls"]);+ assert!(listing.contains("main"));+ f.vn(&["tag", "set", "v0.0.9"]);+ f.vn(&["tag", "set", "v0.0.10"]);+ assert_eq!(f.vn(&["tag", "latest"]).trim(), "v0.0.10");+ f.vn(&["tag", "rm", "v0.0.9"]);+ assert!(f.fail(&["tag", "rm", "missing"]).contains("no such tag"));+}++#[test]+fn config_local_global_and_defaults() {+ let f = Fixture::new();+ f.init();+ f.vn(&["cfg", "test.key", "value"]);+ assert_eq!(f.vn(&["cfg", "test.key"]).trim(), "value");+ f.vn(&["cfg", "-global", "user.name", "Global Tester"]);+ f.vn(&["cfg", "-global", "user.email", "global@example.com"]);+ f.write("f.txt", "content\n");+ f.commit("global identity");+ assert!(f.vn(&["show", "@"]).contains("Global Tester"));+ assert!(f.home.join(".local/config/veins/veins.toml").exists());+ let defaults = f.vn(&["cfg", "-d"]);+ assert!(defaults.contains("log.default_amount = 20"));+ assert!(defaults.contains("rename.autodetect = similar"));+}++#[test]+fn amend_and_undo() {+ let f = Fixture::new();+ f.init();+ f.write("f.txt", "one\n");+ f.commit("one");+ let one = f+ .vn(&["log", "-a", "-no-col-titles"])+ .lines()+ .find(|line| line.contains("one"))+ .and_then(|line| line.split_whitespace().nth(1))+ .unwrap()+ .to_string();+ f.write("f.txt", "two\n");+ f.commit("two");+ f.vn(&["amend", &one, "-m", "one renamed"]);+ assert!(f.vn(&["log"]).contains("one renamed"));+ f.vn(&["undo"]);+ assert!(!f.vn(&["log"]).contains("one renamed"));+}++#[test]+fn merge_clean_and_conflict() {+ let f = Fixture::new();+ f.init();+ f.write("f.txt", "base\n");+ f.vn(&["bmk", "set", "master"]);+ f.commit("base");+ f.vn(&["bmk", "set", "left"]);+ f.vn(&["new", "left"]);+ f.write("f.txt", "left\n");+ f.write("left.txt", "left\n");+ f.commit("left");+ f.vn(&["bmk", "set", "right"]);+ f.vn(&["new", "master"]);+ f.write("f.txt", "right\n");+ f.write("right.txt", "right\n");+ f.commit("right");+ f.vn(&["merge", "left"]);+ assert!(f.vn(&["stat"]).contains("C f.txt"));+ assert!(f.exists("f.txt.base"));+ assert!(f.vn(&["xs", "-porcelain"]).contains("f.txt\ttext\t"));+ f.vn(&["resolve", "-take", "theirs", "f.txt"]);+ assert_eq!(f.read("f.txt"), "left\n");+ assert!(f.vn(&["xs"]).contains("no conflicts"));+ f.commit("resolved");+ assert!(f.vn(&["stat"]).contains("working copy clean"));+ assert!(f.vn(&["fsck"]).contains("fsck: clean"));+}++#[test]+fn rebase_changes_parent_and_rewrites_descendants() {+ let f = Fixture::new();+ f.init();+ f.write("base.txt", "base\n");+ f.vn(&["bmk", "set", "master"]);+ f.commit("base");+ f.vn(&["bmk", "set", "side"]);+ f.vn(&["new", "side"]);+ f.write("one.txt", "one\n");+ f.commit("one");+ f.write("two.txt", "two\n");+ f.commit("two");+ f.vn(&["bmk", "set", "target"]);+ f.vn(&["new", "master"]);+ f.write("target.txt", "target\n");+ f.commit("target");+ let target = f.hash("target");+ f.vn(&["rebase", "-s", "side", "-d", "target"]);+ assert!(f.vn(&["log", "-a"]).contains("two"));+ let _ = target;+}++#[test]+fn error_handling_never_panics() {+ let f = Fixture::new();+ f.init();+ f.write("tracked.txt", "one\n");+ f.commit("initial");+ for command in ["stat", "log", "ls", "diff", "show", "hash", "inf", "fsck"] {+ for token in ["", "-", "--", "-x", "..", "/", "999999999999999999999999"] {+ let output = f.command(&[command, token], &f.repo);+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!text.contains("panic"), "{command} {token}: {text}");+ }+ }+}++#[test]+fn protocol_clone_push_fetch_pull() {+ let f = Fixture::new();+ let source = f.root.join("source");+ fs::create_dir_all(&source).unwrap();+ f.vn_in(&source, &["init", "."]);+ f.write_in(&source, "a.txt", "hello\n");+ f.vn_in(&source, &["bmk", "set", "master"]);+ f.vn_in(&source, &["go", "-m", "initial"]);+ f.vn_in(&source, &["access", "anonymous", "on"]);+ let key_output = f.vn_in(&source, &["key", "generate", "integration"]);+ let public_key = key_output+ .lines()+ .find_map(|line| line.strip_prefix("public key: "))+ .unwrap()+ .to_string();+ f.vn_in(+ &source,+ &[+ "access",+ "add",+ "-role",+ "write",+ "-key",+ &public_key,+ "-name",+ "integration",+ ],+ );+ let clone_a = f.root.join("clone-a");+ let clone_b = f.root.join("clone-b");+ let url = format!("file://{}", source.display());+ f.vn_in(&f.root, &["clone", &url, clone_a.to_str().unwrap()]);+ f.vn_in(&f.root, &["clone", &url, clone_b.to_str().unwrap()]);+ assert_eq!(f.read_in(&clone_a, "a.txt"), "hello\n");+ f.vn_in(&clone_a, &["cfg", "remote.o.key", "integration"]);+ f.vn_in(&clone_b, &["cfg", "remote.o.key", "integration"]);+ f.write_in(&clone_a, "b.txt", "from a\n");+ f.vn_in(&clone_a, &["go", "-m", "a change"]);+ f.vn_in(&clone_a, &["push", "o", "master"]);+ f.vn_in(&clone_b, &["pull"]);+ assert_eq!(f.read_in(&clone_b, "b.txt"), "from a\n");+ assert!(f.vn_in(&clone_b, &["whoami", "o"]).contains("role: write"));+}++#[test]+fn git_import_materialize_export() {+ if Command::new("git").arg("--version").output().is_err() {+ return;+ }+ let f = Fixture::new();+ let git_repo = f.root.join("gitrepo");+ fs::create_dir_all(&git_repo).unwrap();+ for arguments in [+ vec!["init", "-q"],+ vec!["config", "user.name", "Tester"],+ vec!["config", "user.email", "tester@example.com"],+ ] {+ assert!(+ Command::new("git")+ .args(&arguments)+ .current_dir(&git_repo)+ .status()+ .unwrap()+ .success()+ );+ }+ fs::write(git_repo.join("a.txt"), "one\ntwo\n").unwrap();+ for arguments in [vec!["add", "a.txt"], vec!["commit", "-qm", "git one"]] {+ assert!(+ Command::new("git")+ .args(&arguments)+ .current_dir(&git_repo)+ .status()+ .unwrap()+ .success()+ );+ }+ let vn_repo = f.root.join("vnrepo");+ f.vn_in(+ &f.root,+ &[+ "init",+ vn_repo.to_str().unwrap(),+ &format!("-git-import:{}", git_repo.display()),+ ],+ );+ assert!(f.vn_in(&vn_repo, &["log", "-a"]).contains("git one"));+ assert_eq!(f.read_in(&vn_repo, "a.txt"), "one\ntwo\n");+ f.write_in(&vn_repo, "b.txt", "native\n");+ f.vn_in(&vn_repo, &["go", "-m", "native commit"]);+ f.vn_in(&vn_repo, &["git", "export"]);+ let output = Command::new("git")+ .args([+ "--git-dir",+ vn_repo.join(".veins/git").to_str().unwrap(),+ "log",+ "--format=%s",+ "--all",+ ])+ .output()+ .unwrap();+ assert!(String::from_utf8_lossy(&output.stdout).contains("native commit"));+}++#[test]+fn merge_multiple_parents_and_resolve_current() {+ let f = Fixture::new();+ f.init();+ f.write("f.txt", "base\n");+ f.vn(&["bmk", "set", "master"]);+ f.commit("base");+ f.vn(&["bmk", "set", "left"]);+ f.vn(&["new", "left"]);+ f.write("left.txt", "left\n");+ f.commit("left");+ f.vn(&["bmk", "set", "right"]);+ f.vn(&["new", "master"]);+ f.write("right.txt", "right\n");+ f.commit("right");+ f.vn(&["merge", "left", "right"]);+ let metadata = f.vn(&["show", "@"]);+ let parents = metadata+ .lines()+ .find_map(|line| line.strip_prefix("parents "))+ .unwrap();+ assert_eq!(parents.split_whitespace().count(), 3);+}++#[test]+fn rebase_conflict_produces_conflicted_commit() {+ let f = Fixture::new();+ f.init();+ f.write("f.txt", "base\n");+ f.vn(&["bmk", "set", "master"]);+ f.commit("base");+ f.vn(&["bmk", "set", "left"]);+ f.vn(&["new", "left"]);+ f.write("f.txt", "left\n");+ f.commit("left");+ f.vn(&["bmk", "set", "right"]);+ f.vn(&["new", "master"]);+ f.write("f.txt", "right\n");+ f.commit("right");+ f.vn(&["rebase", "-s", "left", "-d", "right"]);+ assert!(+ f.log_lines()+ .iter()+ .any(|line| line.contains("(conflicted)"))+ );+ f.vn(&["co", "left"]);+ assert!(f.vn(&["xs"]).contains("f.txt"));+ assert!(f.exists("f.txt.base"));+}++#[test]+fn git_mirror_push_and_tag_prune() {+ if Command::new("git").arg("--version").output().is_err() {+ return;+ }+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "one\n");+ f.vn(&["bmk", "set", "master"]);+ f.commit("first");+ let mirror = f.root.join("mirror.git");+ fs::create_dir_all(&mirror).unwrap();+ assert!(+ Command::new("git")+ .args(["init", "-q", "--bare", mirror.to_str().unwrap()])+ .status()+ .unwrap()+ .success()+ );+ f.vn(&["git", "remote", "add", "mirror", mirror.to_str().unwrap()]);+ assert!(+ f.vn(&["git", "mirror", "psh"])+ .contains("mirrored 1 bookmark(s)")+ );+ f.vn(&["tag", "set", "v0.0.1"]);+ f.vn(&["tag", "set", "v0.0.2"]);+ f.vn(&["git", "mirror", "pt", "v0.0.1", "mirror"]);+ let tags = Command::new("git")+ .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+ .output()+ .unwrap();+ let tags = String::from_utf8_lossy(&tags.stdout);+ assert!(tags.contains("refs/tags/v0.0.1"));+ assert!(!tags.contains("refs/tags/v0.0.2"));+ f.vn(&["git", "mirror", "push", "mirror"]);+ f.vn(&["tag", "rm", "v0.0.2"]);+ f.vn(&["git", "mirror", "push", "mirror"]);+ let tags = Command::new("git")+ .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+ .output()+ .unwrap();+ assert!(String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));+ f.vn(&["git", "mirror", "push", "mirror", "-prune"]);+ let tags = Command::new("git")+ .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+ .output()+ .unwrap();+ assert!(!String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));+ assert!(+ f.fail(&["git", "mirror", "pt", "missing", "mirror"])+ .contains("unknown tag")+ );+}++#[test]+fn lazy_checkout_of_old_commit() {+ let f = Fixture::new();+ let source = f.root.join("source");+ fs::create_dir_all(&source).unwrap();+ f.vn_in(&source, &["init", "."]);+ for index in 1..=20 {+ f.write_in(&source, &format!("f{index}.txt"), &format!("old {index}\n"));+ }+ f.write_in(&source, "a.txt", "hello\n");+ f.vn_in(&source, &["bmk", "set", "master"]);+ f.vn_in(&source, &["go", "-m", "initial"]);+ f.vn_in(&source, &["access", "anonymous", "on"]);+ for index in 1..=20 {+ f.write_in(&source, &format!("f{index}.txt"), &format!("new {index}\n"));+ }+ f.write_in(&source, "a.txt", "updated\n");+ f.vn_in(&source, &["go", "-m", "second"]);+ let first = f+ .vn_in(&source, &["log", "-a", "-no-col-titles"])+ .lines()+ .find(|line| line.contains("initial"))+ .and_then(|line| line.split_whitespace().nth(1))+ .map(|value| value.trim_start_matches('@').to_string())+ .unwrap();+ let clone = f.root.join("clone");+ f.vn_in(+ &f.root,+ &[+ "clone",+ &format!("file://{}", source.display()),+ clone.to_str().unwrap(),+ ],+ );+ f.vn_in(&clone, &["co", &first]);+ assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");+ assert_eq!(f.read_in(&clone, "f1.txt"), "old 1\n");+ assert!(f.vn_in(&clone, &["stat"]).contains("working copy clean"));+}++#[test]+fn corrupt_repository_does_not_panic() {+ let f = Fixture::new();+ f.init();+ f.write("a.txt", "one\n");+ f.commit("first");+ fs::write(f.repo.join(".veins/config"), b"bad\0line\n").unwrap();+ let pack = fs::read_dir(f.repo.join(".veins/store/packs"))+ .unwrap()+ .flatten()+ .map(|entry| entry.path())+ .find(|path| path.extension().and_then(|value| value.to_str()) == Some("vpack"));+ if let Some(pack) = pack {+ let mut data = fs::read(&pack).unwrap();+ if !data.is_empty() {+ let middle = data.len() / 2;+ data[middle] ^= 0xff;+ fs::write(&pack, data).unwrap();+ }+ }+ for command in [&["stat"][..], &["log"], &["fsck"], &["show"], &["ls"]] {+ let output = f.command(command, &f.repo);+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!text.contains("panic"), "{command:?}: {text}");+ }+}