navid/veins / commit
f82abc262360
Navid M <navidmomtahen@gmail.com> · 2026-11-29
parents: 83508482911f
Browse files at this commit · Download source
--- a/veinsrs/Cargo.lock+++ b/veinsrs/Cargo.lock@@ -7,6 +7,12 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "blake3"@@ -46,7 +52,23 @@ checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" dependencies = [ "rustversion",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc", ]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures"@@ -131,6 +153,18 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "pkg-config"@@ -175,7 +209,53 @@ "getrandom 0.2.17", "libc", "untrusted",- "windows-sys",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustls"+version = "0.23.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted", ] [[package]]@@ -183,6 +263,38 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "schannel"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags",+ "core-foundation",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+] [[package]] name = "shlex"@@ -189,6 +301,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "untrusted"@@ -204,6 +322,10 @@ "libc", "rayon", "ring",+ "rustls",+ "rustls-native-certs",+ "rustls-pki-types",+ "webpki-roots", "zstd", ] @@ -212,6 +334,21 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "webpki-roots"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys"@@ -220,6 +357,15 @@ checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link", ] [[package]]@@ -285,6 +431,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" [[package]] name = "zstd"--- a/veinsrs/Cargo.toml+++ b/veinsrs/Cargo.toml@@ -13,6 +13,10 @@ libc = "0.2" rayon = "1.12" ring = "0.17"+rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }+rustls-native-certs = "0.8"+rustls-pki-types = { version = "1", features = ["std"] }+webpki-roots = "1" zstd = "0.13" [profile.release]--- a/veinsrs/src/cli/info.rs+++ b/veinsrs/src/cli/info.rs@@ -1,5 +1,7 @@ use std::collections::HashMap; use std::path::Path;++use rayon::prelude::*; use crate::core; use crate::error::{Error, Result};@@ -63,7 +65,10 @@ "mv" => "usage: vn mv <source> <destination>\n\nmove a tracked file\n", "ex" => "usage: vn ex <pattern>...\n\nadd exclude rules\n", "edit" => "usage: vn edit [path]...\n\nopen paths in the configured editor\n",- "bmk" => "usage: vn bmk <set|mv|ls|rm> ...\n\nmanage named branch pointers\n",+ "bmk" => {+ "usage: vn bmk <set|rename|ls|rm> ...\n\nmanage named branch pointers\n\+ \nsubcommands:\n set <name> [-rev <rev>] create or move a bookmark\n rename <old> <new> rename a bookmark\n ls list bookmarks\n rm <name> delete a bookmark\n"+ } "tag" => "usage: vn tag <set|ls|rm|latest> ...\n\nmanage named tags\n", "op" => "usage: vn op <log|restore|revert> ...\n\noperation log commands\n", "undo" => "usage: vn undo\n\nrestore the previous operation view\n",@@ -76,7 +81,7 @@ } "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"+ "usage: vn clone <url> [-blobs:head|none|all] [-key:<name>] [-pin:<sha256>] [path]\n\nclone a repository\n" } "fetch" => "usage: vn fetch [<remote>] [path]\n\nfetch from a native remote\n", "pull" => {@@ -85,7 +90,11 @@ "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",+ "serve" => {+ "usage: vn serve -stdio <repo> [-quota <bytes>]\n\+ \x20 vn serve -listen <addr:port> -root <dir> -tls-cert <cert> -tls-key <key> [-quota <bytes>]\n\+ \nrun the native server over standard input/output or TLS 1.3\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"@@ -492,7 +501,12 @@ for argument in arguments { if !end_flags && argument == "--" { end_flags = true;- } else if !end_flags && matches!(argument.as_str(), "-inc-gen" | "-include-generated") {+ } else if !end_flags+ && matches!(+ argument.as_str(),+ "-inc-gen" | "-include-generated" | "--include-generated"+ )+ { include_generated = true; } else if !end_flags && core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}")));@@ -503,49 +517,101 @@ let view = ops::current_view(&root, &mut store)?.unwrap_or_default(); let working = ops::working_copy_id(&view); let rules = AttributeRules::load(&root);- let mut total_files = 0usize;++ let mut total_files = 0u64; let mut total_lines = 0u64;- let mut generated_files = 0usize;+ let mut generated_files = 0u64; let mut generated_lines = 0u64; let mut generated_bytes = 0u64;- let mut by_ext: HashMap<String, (usize, u64, u64)> = HashMap::new();- if let Some(working) = working- && let Some(commit) = graph::load_commit(&mut store, working)?- {- for entry in tree::flatten(&mut store, commit.root_tree)? {- if !matches!(entry.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) {- continue;- }+ let mut by_ext: HashMap<String, (u64, u64, u64)> = HashMap::new();++ let tree = match working {+ Some(working) => graph::load_commit(&mut store, working)?.map(|commit| commit.root_tree),+ None => None,+ };+ if let Some(tree) = tree {+ let entries = tree::flatten(&mut store, tree)?;+ let files: Vec<&tree::FlatEntry> = entries+ .iter()+ .filter(|entry| matches!(entry.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE))+ .collect();+ store.preload()?;++ struct FileResult {+ ext: String,+ lines: u64,+ bytes: u64,+ generated: bool,+ }++ let measure = |entry: &&tree::FlatEntry| -> FileResult { let attributes = rules.lookup(&String::from_utf8_lossy(&entry.path));- let data = graph::read_blob(&mut store, entry.target)?.unwrap_or_default();+ let data = graph::read_blob_loaded(&store, entry.target)+ .ok()+ .flatten()+ .unwrap_or_default(); let binary = attributes.text == AttributeText::Binary || (attributes.text == AttributeText::Auto && data.iter().take(8192).any(|byte| *byte == 0));- let lines = if binary { 0 } else { count_nonblank(&data) };- if attributes.generated {+ FileResult {+ ext: ext_of(&entry.path),+ lines: if binary { 0 } else { count_nonblank(&data) },+ bytes: data.len() as u64,+ generated: attributes.generated,+ }+ };++ let mut workers = std::thread::available_parallelism()+ .map(|value| value.get())+ .unwrap_or(1);+ workers = workers.min(files.len()).min(16);+ let results: Vec<FileResult> = if workers <= 1 {+ files.iter().map(measure).collect()+ } else {+ let pool = rayon::ThreadPoolBuilder::new()+ .num_threads(workers)+ .build()+ .map_err(|error| Error::new(error.to_string()))?;+ pool.install(|| files.par_iter().map(measure).collect())+ };++ for result in results {+ if result.generated { generated_files += 1;- generated_lines += lines;- generated_bytes += data.len() as u64;+ generated_lines += result.lines;+ generated_bytes += result.bytes; if !include_generated { continue; } } total_files += 1;- total_lines += lines;- let ext = extension(&entry.path);- let stat = by_ext.entry(ext).or_insert((0, 0, 0));+ total_lines += result.lines;+ let stat = by_ext.entry(result.ext).or_insert((0, 0, 0)); stat.0 += 1;- stat.1 += lines;- stat.2 += data.len() as u64;+ stat.1 += result.lines;+ stat.2 += result.bytes; } }- let mut commits = 0usize;- let mut authors: HashMap<String, usize> = HashMap::new();++ let mut commits = 0u64;+ let mut has_time = false;+ let mut created = 0i64;+ let mut last = 0i64;+ let mut authors: HashMap<String, u64> = HashMap::new(); for id in graph::collect_commits(&mut store, &graph::view_roots(&view))? { let Some(commit) = graph::load_commit(&mut store, id)? else { continue; }; commits += 1;+ let seconds = commit.committer.seconds;+ if has_time {+ created = created.min(seconds);+ last = last.max(seconds);+ } else {+ created = seconds;+ last = seconds;+ has_time = true;+ } let name = if commit.author.name.is_empty() { "(unknown)".to_string() } else {@@ -553,28 +619,36 @@ }; *authors.entry(name).or_insert(0) += 1; }+ println!(); println!("{}", output::bold_cyan("Repository overview")); println!();- println!(- "Project {}",- root.file_name().unwrap_or_default().to_string_lossy()- );- println!(- "HEAD {}",- working- .map(|id| id.short())- .unwrap_or_else(|| "<none>".to_string())+ row_value(+ "Project",+ &root.file_name().unwrap_or_default().to_string_lossy(), );- println!("Changes {commits}");- println!("Bookmarks {}", view.bookmarks.len());- println!("Tags {}", view.tags.len());- println!("Files {total_files}");- println!("Lines {total_lines}");- println!("Authors {}", authors.len());+ print_left("HEAD", 14, None, true);+ match working {+ Some(id) => println!("{}", id.short()),+ None => println!("<none>"),+ }+ row_number("Changes", commits);+ row_number("Bookmarks", view.bookmarks.len() as u64);+ row_number("Tags", view.tags.len() as u64);+ row_number("Files", total_files);+ row_number("Lines", total_lines);+ row_number("Authors", authors.len() as u64);+ if has_time {+ show_date("Created", created);+ show_date("Last change", last);+ }+ print_left("Size", 14, None, true);+ println!("{}", size_text(dir_size(&layout::veins_dir(&root), 0))); if generated_files > 0 {+ print_left("Generated", 14, None, true); print!(- "Generated {generated_files} files {generated_lines} lines {generated_bytes} B"+ "{generated_files} files {generated_lines} lines {}",+ size_text(generated_bytes) ); if !include_generated { print!(" (excluded; use -inc-gen)");@@ -582,6 +656,7 @@ println!(); } println!();+ println!("{}", output::bold_cyan("Languages")); println!(); if by_ext.is_empty() {@@ -588,21 +663,177 @@ 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)));- for (ext, (files, lines, _)) in entries {- println!("{ext:<8} {lines} lines {files} files");+ entries.sort_by(|left, right| {+ right+ .1+ .1+ .cmp(&left.1.1)+ .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))+ });+ let width = entries+ .iter()+ .fold(6usize, |width, (ext, _)| width.max(ext.len()));+ for (index, (ext, (files, lines, _))) in entries.into_iter().enumerate() {+ print_left(&ext, width, None, false);+ print!(" ");+ print_bar(lines, total_lines, index);+ print!(" ");+ print_percent(percent(lines, total_lines));+ println!("% {lines} lines {files} files"); } } println!();+ 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)));- for (name, count) in authors {- println!("{name:<12} {count} commits");+ if authors.is_empty() {+ println!(" no commits");+ } else {+ let mut entries: Vec<_> = authors.into_iter().collect();+ entries.sort_by(|left, right| {+ right+ .1+ .cmp(&left.1)+ .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))+ });+ let width = entries+ .iter()+ .fold(6usize, |width, (name, _)| width.max(name.len()));+ for (index, (name, count)) in entries.into_iter().enumerate() {+ print_left(&name, width, Some("36"), false);+ print!(" ");+ print_bar(count, commits, index);+ print!(" ");+ print_percent(percent(count, commits));+ println!("% {count} commits");+ } } println!(); Ok(0)+}++fn percent(value: u64, total: u64) -> u64 {+ if total == 0 {+ 0+ } else {+ (value * 100 + total / 2) / total+ }+}++fn print_percent(value: u64) {+ if value < 10 {+ print!(" {value}");+ } else if value < 100 {+ print!(" {value}");+ } else {+ print!("{value}");+ }+}++fn bar_color(index: usize) -> &'static str {+ const COLORS: [&str; 8] = ["96", "92", "93", "95", "94", "91", "36", "32"];+ COLORS[index % COLORS.len()]+}++fn print_bar(value: u64, total: u64, index: usize) {+ let mut filled = 0u64;+ if total > 0 && value > 0 {+ filled = (value * 24 + total / 2) / total;+ if filled == 0 {+ filled = 1;+ }+ if filled > 24 {+ filled = 24;+ }+ }+ for _ in 0..filled {+ output::print_styled(bar_color(index), "\u{2588}");+ }+ for _ in filled..24 {+ output::print_styled("90", "\u{2591}");+ }+}++fn print_left(text: &str, width: usize, color: Option<&str>, dim: bool) {+ if dim {+ output::print_styled("2", text);+ } else if let Some(color) = color {+ output::print_styled(color, text);+ } else {+ print!("{text}");+ }+ for _ in text.len()..width {+ print!(" ");+ }+}++fn row_value(label: &str, value: &str) {+ print_left(label, 14, None, true);+ println!("{value}");+}++fn row_number(label: &str, value: u64) {+ print_left(label, 14, None, true);+ println!("{value}");+}++fn show_date(label: &str, seconds: i64) {+ let stamp = crate::time::format_utc(seconds);+ print_left(label, 14, None, true);+ println!("{}", &stamp[..10.min(stamp.len())]);+}++fn dir_size(path: &Path, depth: usize) -> u64 {+ if depth > 64 {+ return 0;+ }+ let Ok(entries) = std::fs::read_dir(path) else {+ return 0;+ };+ let mut total = 0u64;+ for entry in entries.flatten() {+ let Ok(metadata) = entry.metadata() else {+ continue;+ };+ if metadata.is_file() {+ total += metadata.len();+ } else if metadata.is_dir() {+ total += dir_size(&entry.path(), depth + 1);+ }+ }+ total+}++fn size_text(value: u64) -> String {+ if value >= 1_073_741_824 {+ format!(+ "{}.{} GiB",+ value / 1_073_741_824,+ ((value % 1_073_741_824) * 10) / 1_073_741_824+ )+ } else if value >= 1_048_576 {+ format!(+ "{}.{} MiB",+ value / 1_048_576,+ ((value % 1_048_576) * 10) / 1_048_576+ )+ } else if value >= 1024 {+ format!("{}.{} KiB", value / 1024, ((value % 1024) * 10) / 1024)+ } else {+ format!("{value} B")+ }+}++fn ext_of(path: &[u8]) -> String {+ let text = String::from_utf8_lossy(path);+ let base_start = text.rfind('/').map(|index| index + 1).unwrap_or(0);+ let dot = text.rfind('.');+ match dot {+ Some(position) if position > base_start && position + 1 < text.len() => {+ text[position..].to_ascii_lowercase()+ }+ _ => "(none)".to_string(),+ } } fn count_nonblank(data: &[u8]) -> u64 {@@ -626,15 +857,4 @@ start = end + 1; } count-}--fn extension(path: &[u8]) -> String {- let text = String::from_utf8_lossy(path);- let base = text.rsplit('/').next().unwrap_or(&text);- match base.rfind('.') {- Some(position) if position > 0 && position + 1 < base.len() => {- base[position..].to_lowercase()- }- _ => "(none)".to_string(),- } }--- a/veinsrs/src/cli/mod.rs+++ b/veinsrs/src/cli/mod.rs@@ -17,7 +17,8 @@ match dispatch(arguments) { Ok(code) => code, Err(error) => {- eprintln!("error: {error}");+ output::error_prefix();+ println!("{error}"); 1 } }@@ -96,7 +97,7 @@ println!(" xs list conflicted paths"); println!(" resolve resolve a conflicted path"); println!(" new start a new change");- println!(" bmk manage named branch pointers");+ println!(" bmk manage named branch pointers (set, rename, ls, rm)"); println!(" tag manage named tags"); println!(" cfg read and write configuration"); println!(" edit open paths in the configured text editor");--- a/veinsrs/src/cli/net_cmd.rs+++ b/veinsrs/src/cli/net_cmd.rs@@ -357,7 +357,7 @@ } core::repo_config_set(&root, "remote.default", "o"); let repo_name = messages::url_repo_name(&url);- let mut client = Client::connect(&url, &key_name, &repo_name)?;+ let mut client = Client::connect(&url, &key_name, &repo_name, &pin)?; let refs = client.list_refs()?; let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect(); if wants.is_empty() {@@ -388,12 +388,14 @@ fn fetch(arguments: &[String]) -> Result<u8> { let mut remote_name = String::new(); let mut explicit_key = String::new();+ let mut explicit_pin = String::new(); let mut path = ".".to_string(); let mut have_remote = false; for argument in arguments { if let Some(value) = argument.strip_prefix("-key:") { explicit_key = value.to_string();- } else if argument.starts_with("-pin:") {+ } else if let Some(value) = argument.strip_prefix("-pin:") {+ explicit_pin = value.to_string(); } else if core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}"))); } else if !have_remote {@@ -415,7 +417,12 @@ remote_key_name(&root, &remote_name) }; let repo_name = messages::url_repo_name(&url);- let mut client = Client::connect(&url, &key, &repo_name)?;+ let pin = if !explicit_pin.is_empty() {+ explicit_pin+ } else {+ core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()+ };+ let mut client = Client::connect(&url, &key, &repo_name, &pin)?; let refs = client.list_refs()?; let haves = ops::read_heads(&root)?; let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect();@@ -449,7 +456,11 @@ path = argument.clone(); } }- let mut forward = Vec::new();+ let mut forward: Vec<String> = arguments+ .iter()+ .filter(|argument| argument.starts_with("-key:") || argument.starts_with("-pin:"))+ .cloned()+ .collect(); if have_remote { forward.push(remote_name.clone()); }@@ -541,6 +552,7 @@ commits: &[Id], output: &mut Vec<Id>, seen: &mut HashSet<Id>,+ progress: Option<&crate::core::Progress>, ) -> Result<()> { fn walk_tree( store: &mut Store,@@ -608,6 +620,9 @@ continue; }; walk_tree(store, commit.root_tree, output, seen)?;+ if let Some(progress) = progress {+ progress.advance(1);+ } } Ok(()) }@@ -615,11 +630,15 @@ fn push(arguments: &[String]) -> Result<u8> { let mut remote_name = String::new(); let mut bookmark = String::new();+ let mut explicit_key = String::new();+ let mut explicit_pin = String::new(); let mut path = ".".to_string(); let mut have_remote = false; for argument in arguments {- if argument.starts_with("-key:") || argument.starts_with("-pin:") {- continue;+ if let Some(value) = argument.strip_prefix("-key:") {+ explicit_key = value.to_string();+ } else if let Some(value) = argument.strip_prefix("-pin:") {+ explicit_pin = value.to_string(); } else if core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}"))); } else if !have_remote {@@ -654,9 +673,18 @@ .flatten() }) .ok_or_else(|| Error::new(format!("no such bookmark: {bookmark}")))?;- let key = remote_key_name(&root, &remote_name);+ let key = if !explicit_key.is_empty() {+ explicit_key+ } else {+ remote_key_name(&root, &remote_name)+ }; let repo_name = messages::url_repo_name(&url);- let mut client = Client::connect(&url, &key, &repo_name)?;+ let pin = if !explicit_pin.is_empty() {+ explicit_pin+ } else {+ core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()+ };+ let mut client = Client::connect(&url, &key, &repo_name, &pin)?; let remote_refs = client.list_refs()?; let mut commits = vec![bookmark_target]; let mut updates = Vec::new();@@ -684,8 +712,18 @@ } let mut objects = Vec::new(); let mut seen = HashSet::new();- collect_objects(&mut store, &commits, &mut objects, &mut seen)?;- client.push_objects(&root, &objects)?;+ let collecting = crate::core::Progress::new("collecting objects", commits.len());+ collect_objects(+ &mut store,+ &commits,+ &mut objects,+ &mut seen,+ Some(&collecting),+ )?;+ collecting.finish();+ let pushing = crate::core::Progress::new("pushing objects", objects.len());+ client.push_objects(&root, &objects, Some(&pushing))?;+ pushing.finish(); client.update_refs(&updates)?; output::info_prefix(); println!("pushed {bookmark}");@@ -719,24 +757,81 @@ fn serve(arguments: &[String]) -> Result<u8> { let mut repo = ".".to_string(); let mut stdio = false;+ let mut listen = String::new();+ let mut root = ".".to_string();+ let mut cert = String::new();+ let mut key = String::new();+ let mut quota = 0u64; let mut index = 0; while index < arguments.len() { let argument = &arguments[index]; if argument == "-stdio" { stdio = true;+ if index + 1 < arguments.len() && !core::is_flag(&arguments[index + 1]) {+ index += 1;+ repo = arguments[index].clone();+ }+ } else if argument == "-listen" {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new("-listen requires an address"));+ }+ listen = arguments[index].clone();+ } else if argument == "-root" {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new("-root requires a directory"));+ }+ root = arguments[index].clone();+ } else if argument == "-tls-cert" {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new("-tls-cert requires a path"));+ }+ cert = arguments[index].clone();+ } else if argument == "-tls-key" {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new("-tls-key requires a path"));+ }+ key = arguments[index].clone();+ } else if argument == "-quota" {+ index += 1;+ if index >= arguments.len() {+ return Err(Error::new("-quota requires a byte count"));+ }+ quota = arguments[index]+ .parse()+ .map_err(|_| Error::new("-quota requires a byte count"))?; } else if let Some(value) = argument.strip_prefix("-quota:") {- let _ = value;- } else if !core::is_flag(argument) {+ quota = value+ .parse()+ .map_err(|_| Error::new("-quota requires a byte count"))?;+ } else if core::is_flag(argument) {+ return Err(Error::new(format!("unknown serve option: {argument}")));+ } else { repo = argument.clone(); } index += 1; }- if !stdio {- return Err(Error::new("serve requires -stdio"));+ if stdio {+ let root =+ layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;+ crate::server::serve_stdio(&root, quota)?;+ return Ok(0); }- let root =- layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;- crate::server::serve_stdio(&root, 0)?;+ if listen.is_empty() {+ return Err(Error::new("serve requires -stdio or -listen"));+ }+ if cert.is_empty() || key.is_empty() {+ return Err(Error::new("TLS requires -tls-cert and -tls-key"));+ }+ let root = std::fs::canonicalize(&root)+ .map_err(|_| Error::new("cannot open the server root directory"))?;+ if !root.is_dir() {+ return Err(Error::new("the server root is not a directory"));+ }+ crate::server::serve_listen(&listen, &root, &cert, &key, quota)?; Ok(0) } @@ -944,7 +1039,8 @@ let url = remote_url(&root, &remote).ok_or_else(|| Error::new("unknown remote"))?; let key = remote_key_name(&root, &remote); let repo_name = messages::url_repo_name(&url);- let mut client = Client::connect(&url, &key, &repo_name)?;+ let pin = core::repo_config_value(&root, &remote_key(&remote, "tls-pin")).unwrap_or_default();+ let mut client = Client::connect(&url, &key, &repo_name, &pin)?; let (role, _) = client.whoami()?; println!("role: {}", messages::role_name(role)); Ok(0)--- a/veinsrs/src/cli/output.rs+++ b/veinsrs/src/cli/output.rs@@ -1,9 +1,7 @@-use std::io::IsTerminal;- use crate::core; pub fn enabled() -> bool {- std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal()+ core::colors_enabled() } fn style(text: &str, code: &str) -> String {@@ -11,15 +9,31 @@ format!("\x1b[{code}m{text}\x1b[0m") } else { text.to_string()+ }+}++pub fn print_styled(code: &str, text: &str) {+ if enabled() {+ print!("\x1b[{code}m{text}\x1b[0m");+ } else {+ print!("{text}"); } } pub fn error_prefix() {- print!("{}: ", style("error", "1;31"));+ if enabled() {+ print!("\x1b[1m\x1b[31merror\x1b[0m: ");+ } else {+ print!("error: ");+ } } pub fn warning_prefix() {- print!("{}: ", style("warning", "1;33"));+ if enabled() {+ print!("\x1b[1m\x1b[33mwarning\x1b[0m: ");+ } else {+ print!("warning: ");+ } } pub fn info_prefix() {@@ -43,7 +57,11 @@ } pub fn bold_cyan(text: &str) -> String {- style(text, "1;36")+ if enabled() {+ format!("\x1b[1m\x1b[96m{text}\x1b[0m")+ } else {+ text.to_string()+ } } pub fn print_cell(text: &str, width: usize) {@@ -54,14 +72,7 @@ } pub fn open_repo() -> Option<std::path::PathBuf> {- match crate::store::layout::discover(std::path::Path::new(".")) {- Ok(root) => Some(root),- Err(_) => {- error_prefix();- println!("not a veins repository");- None- }- }+ crate::store::layout::discover(std::path::Path::new(".")).ok() } pub fn status_path(path: &[u8], cwd_rel: &str) -> String {--- a/veinsrs/src/cli/refs.rs+++ b/veinsrs/src/cli/refs.rs@@ -47,6 +47,7 @@ }; match sub.as_str() { "set" | "mv" => bookmark_set(&arguments[1..]),+ "rename" | "move" => bookmark_rename(&arguments[1..]), "ls" => bookmark_list(&arguments[1..]), "rm" => bookmark_remove(&arguments[1..]), "help" | "-h" => {@@ -63,7 +64,7 @@ } fn bookmark_usage() {- println!("usage: vn bmk <set|mv|ls|rm> ...");+ println!("usage: vn bmk <set|rename|ls|rm> ..."); println!(); println!("manage named, movable pointers to commits (branches)"); println!();@@ -70,8 +71,53 @@ println!("subcommands:"); println!(" set <name> [-rev <rev>] create or move a bookmark (default: @)"); println!(" mv <name> [-rev <rev>] alias of set");+ println!(" rename <old> <new> rename a bookmark"); println!(" ls [-no-col-titles] list bookmarks"); println!(" rm <name> delete a bookmark");+}++fn bookmark_rename(arguments: &[String]) -> Result<u8> {+ let mut names = Vec::new();+ let mut end_flags = false;+ for argument in arguments {+ if !end_flags && argument == "--" {+ end_flags = true;+ } else if !end_flags && core::is_flag(argument) {+ return Err(Error::new(format!("unknown flag: {argument}")));+ } else {+ names.push(argument.clone());+ }+ }+ if names.len() != 2 {+ return Err(Error::new("bmk rename requires an old and a new name"));+ }+ let (old, new) = (&names[0], &names[1]);+ if !valid_ref_name(new) {+ return Err(Error::new(format!("invalid bookmark name: {new}")));+ }+ if old == new {+ return Err(Error::new("new bookmark name matches the old name"));+ }+ let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+ let mut store = Store::open(&root)?;+ let mut txn = Txn::begin(&root, &mut store)?;+ let Some(index) = ops::find_bookmark(txn.view(), old.as_bytes()) else {+ return Err(Error::new(format!("no such bookmark: {old}")));+ };+ if ops::find_bookmark(txn.view(), new.as_bytes()).is_some() {+ return Err(Error::new(format!("bookmark already exists: {new}")));+ }+ let mut bookmark = txn.view_mut().bookmarks.remove(index);+ bookmark.name = new.as_bytes().to_vec();+ txn.view_mut().bookmarks.push(bookmark);+ ops::rebuild_heads(txn.view_mut());+ txn.finish(&format!("bookmark rename {old} {new}"))?;+ if core::current_bookmark_name(&root).is_some_and(|current| current == *old) {+ core::set_current_bookmark(&root, new);+ }+ output::info_prefix();+ println!("renamed bookmark {old} to {new}");+ Ok(0) } fn bookmark_set(arguments: &[String]) -> Result<u8> {--- a/veinsrs/src/core.rs+++ b/veinsrs/src/core.rs@@ -549,6 +549,24 @@ pub fn stdin_is_terminal() -> bool { unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }+}++pub fn colors_enabled() -> bool {+ static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *ENABLED.get_or_init(|| {+ if env::var_os("NO_COLOR").is_some() {+ return false;+ }+ let forced =+ env::var_os("FORCE_COLOR").is_some_and(|value| !value.is_empty() && value != "0");+ if forced {+ return true;+ }+ if !stdout_is_terminal() {+ return false;+ }+ !env::var("TERM").is_ok_and(|term| term == "dumb")+ }) } pub fn stdout_is_terminal() -> bool {@@ -908,4 +926,229 @@ } } ignore_ignored(&rules, path, false)+}++const PROGRESS_WIDTH: usize = 24;++fn progress_enabled() -> bool {+ for name in ["NO_PROGRESS", "VN_NO_PROGRESS"] {+ if env::var_os(name).is_some_and(|value| !value.is_empty() && value != "0") {+ return false;+ }+ }+ if env::var_os("VN_PROGRESS").is_some_and(|value| !value.is_empty() && value != "0") {+ return true;+ }+ if env::var("TERM").is_ok_and(|term| term == "dumb") {+ return false;+ }+ stderr_is_terminal()+}++fn styled_info_prefix(color: bool) -> &'static str {+ if color {+ "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: "+ } else {+ "\r\x1b[2Kinfo: "+ }+}++struct ProgressState {+ total: usize,+ done: usize,+ last_done: usize,+ last_total: usize,+ last_draw: Option<std::time::Instant>,+ drawn: bool,+ finished: bool,+}++pub struct Progress {+ label: String,+ enabled: bool,+ state: std::sync::Mutex<ProgressState>,+}++impl Progress {+ pub fn new(label: impl Into<String>, total: usize) -> Self {+ Self {+ label: label.into(),+ enabled: progress_enabled(),+ state: std::sync::Mutex::new(ProgressState {+ total,+ done: 0,+ last_done: usize::MAX,+ last_total: usize::MAX,+ last_draw: None,+ drawn: false,+ finished: false,+ }),+ }+ }++ pub fn set_total(&self, total: usize) {+ if let Ok(mut state) = self.state.lock() {+ state.total = total;+ self.refresh(&mut state, true);+ }+ }++ pub fn update(&self, done: usize, force: bool) {+ if let Ok(mut state) = self.state.lock() {+ state.done = done;+ self.refresh(&mut state, force);+ }+ }++ pub fn advance(&self, amount: usize) {+ if let Ok(mut state) = self.state.lock() {+ state.done = state.done.saturating_add(amount);+ self.refresh(&mut state, false);+ }+ }++ pub fn finish(&self) {+ let Ok(mut state) = self.state.lock() else {+ return;+ };+ if !self.enabled || state.finished {+ return;+ }+ state.finished = true;+ if state.total > 0 {+ if state.done < state.total {+ state.done = state.total;+ }+ if !state.drawn || state.last_done != state.done || state.last_total != state.total {+ self.draw(&mut state);+ }+ eprintln!();+ } else if state.drawn {+ eprint!("\r\x1b[2K");+ let _ = std::io::stderr().flush();+ }+ state.drawn = false;+ }++ pub fn clear(&self) {+ let Ok(mut state) = self.state.lock() else {+ return;+ };+ if self.enabled && state.drawn {+ eprint!("\r\x1b[2K");+ let _ = std::io::stderr().flush();+ }+ state.drawn = false;+ state.finished = true;+ }++ fn refresh(&self, state: &mut ProgressState, force: bool) {+ if !self.enabled || state.finished {+ return;+ }+ let now = std::time::Instant::now();+ let complete = state.total > 0 && state.done >= state.total;+ if !force+ && !complete+ && state+ .last_draw+ .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_millis(66))+ {+ return;+ }+ state.last_draw = Some(now);+ self.draw(state);+ state.drawn = true;+ }++ fn draw(&self, state: &mut ProgressState) {+ let color = colors_enabled();+ let mut line = String::with_capacity(128);+ line.push_str(styled_info_prefix(color));+ line.push_str(&self.label);+ line.push_str(" ");+ if state.total > 0 {+ let filled = std::cmp::min(+ PROGRESS_WIDTH,+ ((state.done as u128 * PROGRESS_WIDTH as u128) / state.total as u128) as usize,+ );+ line.push('[');+ if filled >= PROGRESS_WIDTH {+ if color {+ line.push_str("\x1b[32m");+ }+ for _ in 0..PROGRESS_WIDTH {+ line.push('=');+ }+ } else {+ let head = if filled == 0 { 1 } else { filled };+ if color {+ line.push_str("\x1b[32m");+ }+ for _ in 0..head.saturating_sub(1) {+ line.push('=');+ }+ line.push('>');+ if color {+ line.push_str("\x1b[0m");+ }+ for _ in head..PROGRESS_WIDTH {+ line.push(' ');+ }+ }+ if color {+ line.push_str("\x1b[0m");+ }+ line.push(']');+ if color {+ line.push_str(" \x1b[36m");+ } else {+ line.push(' ');+ }+ line.push_str(&(state.done * 100 / state.total).min(100).to_string());+ line.push('%');+ if color {+ line.push_str("\x1b[0m\x1b[2m");+ }+ line.push(' ');+ line.push_str(&state.done.to_string());+ line.push('/');+ line.push_str(&state.total.to_string());+ if color {+ line.push_str("\x1b[0m");+ }+ } else {+ const FRAMES: [char; 4] = ['|', '/', '-', '\\'];+ let frame = FRAMES[state.done % 4];+ if color {+ line.push_str("\x1b[36m");+ line.push(frame);+ line.push_str("\x1b[0m\x1b[2m");+ } else {+ line.push(frame);+ }+ line.push(' ');+ line.push_str(&state.done.to_string());+ if color {+ line.push_str("\x1b[0m");+ }+ }+ eprint!("{line}");+ let _ = std::io::stderr().flush();+ state.last_done = state.done;+ state.last_total = state.total;+ }+}++impl Drop for Progress {+ fn drop(&mut self) {+ let Ok(state) = self.state.lock() else {+ return;+ };+ if !self.enabled || !state.drawn || state.finished {+ return;+ }+ eprint!("\r\x1b[2K");+ let _ = std::io::stderr().flush();+ } }--- a/veinsrs/src/git.rs+++ b/veinsrs/src/git.rs@@ -171,12 +171,15 @@ .collect(); ordered.reverse(); ordered.reverse();+ let progress = crate::core::Progress::new("importing commits", ordered.len()); 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)?;+ progress.advance(1); }+ progress.finish(); for (name, oid) in bookmarks { if let Some(target) = mapped.get(&oid.hex()) { set_bookmark(txn.view_mut(), &name, *target);@@ -504,7 +507,14 @@ 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)?;+ let progress = crate::core::Progress::new("checking out files", 0);+ crate::worktree::checkout::materialize_with_progress(+ root,+ &mut store,+ None,+ commit.root_tree,+ Some(&progress),+ )?; } Ok(()) })();--- a/veinsrs/src/protocol/client.rs+++ b/veinsrs/src/protocol/client.rs@@ -19,16 +19,38 @@ } impl Client {- pub fn connect(url: &str, key_name: &str, repo_name: &str) -> Result<Self> {+ pub fn connect(url: &str, key_name: &str, repo_name: &str, pin: &str) -> Result<Self> { let parsed = messages::parse_url(url).ok_or_else(|| Error::new("invalid remote URL"))?;- if parsed.tls || parsed.ssh {- return Err(Error::new("only file:// transports are supported"));- }- let stream = Stream::spawn(&[- "serve".to_string(),- "-stdio".to_string(),- parsed.path.clone(),- ])?;+ let stream = if parsed.ssh {+ let remote = [+ "vn".to_string(),+ "serve".to_string(),+ "-stdio".to_string(),+ parsed.path.clone(),+ ]+ .iter()+ .map(|part| crate::core::shell_quote_arg(part))+ .collect::<Vec<_>>()+ .join(" ");+ let mut arguments = Vec::new();+ if parsed.port != 22 {+ arguments.push("-p".to_string());+ arguments.push(parsed.port.to_string());+ }+ arguments.push(parsed.host.clone());+ arguments.push(remote);+ Stream::spawn_program("ssh", &arguments)+ .map_err(|_| Error::new("cannot start the SSH transport"))?+ } else if parsed.tls {+ super::tls::connect(&parsed.host, parsed.port, pin)?+ } else {+ Stream::spawn(&[+ "serve".to_string(),+ "-stdio".to_string(),+ parsed.path.clone(),+ ])?+ };+ let binding = stream.binding().to_vec(); let mut client = Self { stream, role: 0,@@ -82,7 +104,7 @@ repo_name, &hello_ok.server_nonce, &hello.client_nonce,- &[],+ &binding, ); if let Some(signature) = crypto::ed25519_sign(&key.seed, &message) { let auth = messages::Auth {@@ -231,7 +253,12 @@ messages::decode_bitmap(&frame.payload).ok_or_else(|| Error::new("invalid bitmap")) } - pub fn push_objects(&mut self, repo: &Path, ids: &[Id]) -> Result<()> {+ pub fn push_objects(+ &mut self,+ repo: &Path,+ ids: &[Id],+ progress: Option<&crate::core::Progress>,+ ) -> Result<()> { let request_id = (time::now_millis() & 0x7fff_ffff) as u32; if !self .stream@@ -255,6 +282,9 @@ .write_frame(wire::kind::RECORDS, request_id, &record) { return Err(Error::new("connection closed while sending object"));+ }+ if let Some(progress) = progress {+ progress.advance(1); } } let digest = hasher.finalize();--- a/veinsrs/src/protocol/mod.rs+++ b/veinsrs/src/protocol/mod.rs@@ -1,3 +1,4 @@ pub mod client; pub mod messages;+pub mod tls; pub mod wire;--- /dev/null+++ b/veinsrs/src/protocol/tls.rs@@ -0,0 +1,219 @@+use std::net::TcpStream;+use std::sync::Arc;++use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};+use rustls::pki_types::pem::PemObject;+use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};+use rustls::{+ ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,+ ServerConnection, SignatureScheme, StreamOwned,+};++use crate::error::{Error, Result};++use super::wire::Stream;++const EXPORTER_LABEL: &[u8] = b"EXPORTER-veins-auth/1";++#[derive(Debug)]+struct PinnedVerifier {+ algorithms: rustls::crypto::WebPkiSupportedAlgorithms,+}++impl ServerCertVerifier for PinnedVerifier {+ fn verify_server_cert(+ &self,+ _end_entity: &CertificateDer<'_>,+ _intermediates: &[CertificateDer<'_>],+ _server_name: &ServerName<'_>,+ _ocsp_response: &[u8],+ _now: UnixTime,+ ) -> std::result::Result<ServerCertVerified, rustls::Error> {+ Ok(ServerCertVerified::assertion())+ }++ fn verify_tls12_signature(+ &self,+ message: &[u8],+ cert: &CertificateDer<'_>,+ signature: &DigitallySignedStruct,+ ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {+ rustls::crypto::verify_tls12_signature(message, cert, signature, &self.algorithms)+ }++ fn verify_tls13_signature(+ &self,+ message: &[u8],+ cert: &CertificateDer<'_>,+ signature: &DigitallySignedStruct,+ ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {+ rustls::crypto::verify_tls13_signature(message, cert, signature, &self.algorithms)+ }++ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {+ self.algorithms.supported_schemes()+ }+}++pub fn client_context(pinned: bool) -> Result<Arc<ClientConfig>> {+ let provider = rustls::crypto::ring::default_provider();+ let builder = ClientConfig::builder_with_provider(Arc::new(provider.clone()))+ .with_protocol_versions(&[&rustls::version::TLS13])+ .map_err(|error| Error::new(error.to_string()))?;+ let config = if pinned {+ builder+ .dangerous()+ .with_custom_certificate_verifier(Arc::new(PinnedVerifier {+ algorithms: provider.signature_verification_algorithms,+ }))+ .with_no_client_auth()+ } else {+ let mut roots = RootCertStore::empty();+ let native = rustls_native_certs::load_native_certs();+ roots.add_parsable_certificates(native.certs);+ if roots.is_empty() {+ roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());+ }+ if roots.is_empty() {+ return Err(Error::new("no trusted TLS roots are available"));+ }+ builder.with_root_certificates(roots).with_no_client_auth()+ };+ Ok(Arc::new(config))+}++pub fn connect(host: &str, port: i32, pin: &str) -> Result<Stream> {+ let pinned = !pin.is_empty();+ let config = client_context(pinned)?;+ let name =+ ServerName::try_from(host.to_string()).map_err(|_| Error::new("invalid TLS host name"))?;+ let mut socket = TcpStream::connect((host, port as u16))+ .map_err(|_| Error::new("cannot connect: host refused the connection or is unreachable"))?;+ let mut connection = ClientConnection::new(config, name)+ .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+ connection+ .complete_io(&mut socket)+ .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+ if pinned {+ let Some(certificate) = connection+ .peer_certificates()+ .and_then(|certs| certs.first())+ else {+ return Err(Error::new("TLS certificate pin mismatch"));+ };+ let digest = ring::digest::digest(&ring::digest::SHA256, certificate.as_ref());+ if !hex_equal(&hex_encode(digest.as_ref()), pin) {+ return Err(Error::new("TLS certificate pin mismatch"));+ }+ }+ let binding = exporter(&connection);+ Ok(Stream::from_duplex(+ Box::new(StreamOwned::new(connection, socket)),+ binding,+ ))+}++pub fn server_context(cert_path: &str, key_path: &str) -> Result<Arc<ServerConfig>> {+ let certificates: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert_path)+ .map_err(|_| Error::new("cannot read the TLS certificate"))?+ .collect::<std::result::Result<_, _>>()+ .map_err(|_| Error::new("cannot parse the TLS certificate"))?;+ if certificates.is_empty() {+ return Err(Error::new("cannot parse the TLS certificate"));+ }+ let key = PrivateKeyDer::from_pem_file(key_path)+ .map_err(|_| Error::new("cannot read the TLS private key"))?;+ let provider = rustls::crypto::ring::default_provider();+ let config = ServerConfig::builder_with_provider(Arc::new(provider))+ .with_protocol_versions(&[&rustls::version::TLS13])+ .map_err(|error| Error::new(error.to_string()))?+ .with_no_client_auth()+ .with_single_cert(certificates, key)+ .map_err(|_| Error::new("cannot load the TLS certificate or key"))?;+ Ok(Arc::new(config))+}++pub fn accept(socket: TcpStream, config: Arc<ServerConfig>) -> Result<Stream> {+ let mut connection = ServerConnection::new(config)+ .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+ let mut socket = socket;+ connection+ .complete_io(&mut socket)+ .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+ let binding = exporter(&connection);+ Ok(Stream::from_duplex(+ Box::new(StreamOwned::new(connection, socket)),+ binding,+ ))+}++fn exporter(connection: &impl Exportable) -> Vec<u8> {+ let mut output = [0u8; 32];+ if connection+ .export_keying_material(&mut output, EXPORTER_LABEL, None)+ .is_ok()+ {+ output.to_vec()+ } else {+ Vec::new()+ }+}++trait Exportable {+ fn export_keying_material<T: AsMut<[u8]>>(+ &self,+ output: T,+ label: &[u8],+ context: Option<&[u8]>,+ ) -> std::result::Result<T, rustls::Error>;+}++impl Exportable for ClientConnection {+ fn export_keying_material<T: AsMut<[u8]>>(+ &self,+ output: T,+ label: &[u8],+ context: Option<&[u8]>,+ ) -> std::result::Result<T, rustls::Error> {+ ConnectionCommon::export_keying_material(self, output, label, context)+ }+}++impl Exportable for ServerConnection {+ fn export_keying_material<T: AsMut<[u8]>>(+ &self,+ output: T,+ label: &[u8],+ context: Option<&[u8]>,+ ) -> std::result::Result<T, rustls::Error> {+ ConnectionCommon::export_keying_material(self, output, label, context)+ }+}++use rustls::ConnectionCommon;++fn hex_encode(data: &[u8]) -> String {+ const DIGITS: &[u8; 16] = b"0123456789abcdef";+ let mut output = String::with_capacity(data.len() * 2);+ for byte in data {+ output.push(DIGITS[(byte >> 4) as usize] as char);+ output.push(DIGITS[(byte & 0x0f) as usize] as char);+ }+ output+}++fn hex_equal(left: &str, right: &str) -> bool {+ let mut left = left+ .bytes()+ .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');+ let mut right = right+ .bytes()+ .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');+ loop {+ match (left.next(), right.next()) {+ (None, None) => return true,+ (Some(a), Some(b)) if a.to_ascii_lowercase() == b.to_ascii_lowercase() => {}+ _ => return false,+ }+ }+}--- a/veinsrs/src/protocol/wire.rs+++ b/veinsrs/src/protocol/wire.rs@@ -1,4 +1,5 @@ use std::io::{Read, Write};+use std::sync::{Arc, Mutex}; use crate::error::{Error, Result}; use crate::object::MAX_OBJECT_BODY;@@ -5,6 +6,38 @@ use crate::object::id::Id; pub const MAX_FRAME: usize = 16 * 1024 * 1024;++pub trait Duplex: Read + Write + Send {}+impl<T: Read + Write + Send> Duplex for T {}++struct SharedReader(Arc<Mutex<Box<dyn Duplex>>>);++impl Read for SharedReader {+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+ self.0+ .lock()+ .map_err(|_| std::io::Error::other("stream lock poisoned"))?+ .read(buffer)+ }+}++struct SharedWriter(Arc<Mutex<Box<dyn Duplex>>>);++impl Write for SharedWriter {+ fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {+ self.0+ .lock()+ .map_err(|_| std::io::Error::other("stream lock poisoned"))?+ .write(buffer)+ }++ fn flush(&mut self) -> std::io::Result<()> {+ self.0+ .lock()+ .map_err(|_| std::io::Error::other("stream lock poisoned"))?+ .flush()+ }+} pub mod kind { pub const HELLO: u8 = 1;@@ -56,6 +89,7 @@ reader: Box<dyn Read + Send>, writer: Box<dyn Write + Send>, child: Option<std::process::Child>,+ binding: Vec<u8>, } impl Stream {@@ -64,12 +98,17 @@ reader: Box::new(std::io::stdin()), writer: Box::new(std::io::stdout()), child: None,+ binding: Vec::new(), } } pub fn spawn(arguments: &[String]) -> Result<Self> { let executable = std::env::current_exe().map_err(Error::from)?;- let mut child = std::process::Command::new(executable)+ Self::spawn_program(&executable.to_string_lossy(), arguments)+ }++ pub fn spawn_program(program: &str, arguments: &[String]) -> Result<Self> {+ let mut child = std::process::Command::new(program) .args(arguments) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped())@@ -88,7 +127,22 @@ reader: Box::new(stdout), writer: Box::new(stdin), child: Some(child),+ binding: Vec::new(), })+ }++ pub fn from_duplex(stream: Box<dyn Duplex>, binding: Vec<u8>) -> Self {+ let shared = Arc::new(Mutex::new(stream));+ Self {+ reader: Box::new(SharedReader(shared.clone())),+ writer: Box::new(SharedWriter(shared)),+ child: None,+ binding,+ }+ }++ pub fn binding(&self) -> &[u8] {+ &self.binding } fn read_exact(&mut self, buffer: &mut [u8]) -> bool {--- a/veinsrs/src/server.rs+++ b/veinsrs/src/server.rs@@ -1,4 +1,5 @@ use std::path::{Path, PathBuf};+use std::sync::Arc; use crate::crypto; use crate::error::Result;@@ -17,15 +18,22 @@ use crate::store::writer::Writer; const MAX_CHUNKS: usize = 4096;+const MAX_PUSH_RECORDS: usize = 100_000;+const QUOTA_RESERVE: u64 = 1 << 20;+const DRAIN_BYTES: usize = 64 << 20; struct Session { stream: Stream, repo: PathBuf,+ repo_present: bool,+ root: PathBuf,+ quota_bytes: u64, store: Store, access: crypto::Access, hello_repo: String, client_nonce: Vec<u8>, server_nonce: Vec<u8>,+ binding: Vec<u8>, version: u16, authed: bool, role: u8,@@ -196,6 +204,37 @@ } } Ok(())+}++fn safe_repo_name(name: &str) -> bool {+ if name.is_empty() || name.len() > 4096 {+ return false;+ }+ if name.starts_with('/') || name.contains('\0') || name.contains('\\') {+ return false;+ }+ name.split('/').all(|part| part != "..")+}++fn dir_usage(path: &Path, depth: usize) -> u64 {+ if depth > 64 {+ return 0;+ }+ let Ok(entries) = std::fs::read_dir(path) else {+ return 0;+ };+ let mut total = 0u64;+ for entry in entries.flatten() {+ let Ok(metadata) = entry.metadata() else {+ continue;+ };+ if metadata.is_file() {+ total = total.saturating_add(metadata.len());+ } else if metadata.is_dir() {+ total = total.saturating_add(dir_usage(&entry.path(), depth + 1));+ }+ }+ total } fn handle_hello(session: &mut Session, frame: &wire::Frame) -> bool {@@ -217,7 +256,34 @@ } session.hello_repo = hello.repo; session.client_nonce = hello.client_nonce;- if !session.repo.join(".veins").join("format").is_file() {+ if !session.repo_present {+ if !safe_repo_name(&session.hello_repo) {+ session.stream.write_error(+ frame.request_id,+ wire::error_code::NOT_FOUND,+ "repository not found",+ );+ return false;+ }+ let candidate = session+ .root+ .join(crate::core::path_from_bytes(session.hello_repo.as_bytes()));+ match crate::store::layout::discover(&candidate) {+ Ok(found) => {+ session.repo = found;+ session.repo_present = true;+ }+ Err(_) => {+ session.stream.write_error(+ frame.request_id,+ wire::error_code::NOT_FOUND,+ "repository not found",+ );+ return false;+ }+ }+ }+ if !session.repo_present || !session.repo.join(".veins").join("format").is_file() { session.stream.write_error( frame.request_id, wire::error_code::NOT_FOUND,@@ -291,7 +357,7 @@ &session.hello_repo, &session.server_nonce, &session.client_nonce,- &[],+ &session.binding, ); let valid = role != 255 && public_key.is_some_and(|key| crypto::ed25519_verify(&key, &message, &auth.signature));@@ -489,14 +555,46 @@ frame.request_id, &messages::encode_bitmap(&bits), ))+}++fn drain_push(session: &mut Session) -> bool {+ let mut total = 0usize;+ loop {+ let Some(frame) = session.stream.read_frame() else {+ return false;+ };+ if frame.kind == wire::kind::END {+ return true;+ }+ total = total.saturating_add(frame.payload.len());+ if total > DRAIN_BYTES {+ return false;+ }+ } } fn handle_put_records(session: &mut Session, frame: &wire::Frame) -> Result<bool> { if deny(session, frame.request_id, true) { return Ok(true);+ }+ let mut limit = 0u64;+ if session.quota_bytes > 0 {+ let used = dir_usage(&session.repo, 0);+ if used.saturating_add(QUOTA_RESERVE) >= session.quota_bytes {+ drain_push(session);+ session.stream.write_error(+ frame.request_id,+ wire::error_code::QUOTA,+ "storage quota exceeded",+ );+ return Ok(true);+ }+ limit = session.quota_bytes - used - QUOTA_RESERVE; } let mut writer = Writer::default();+ writer.set_limit(limit); let mut hasher = blake3::Hasher::new();+ let mut records = 0usize; loop { let Some(incoming) = session.stream.read_frame() else { return Ok(false);@@ -508,14 +606,30 @@ wire::error_code::HASH_MISMATCH, "transfer checksum mismatch", );+ return Ok(true); } break; } if incoming.kind != wire::kind::RECORDS {- return Ok(false);+ drain_push(session);+ session+ .stream+ .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");+ return Ok(true);+ }+ records += 1;+ if records > MAX_PUSH_RECORDS {+ drain_push(session);+ session.stream.write_error(+ frame.request_id,+ wire::error_code::TOO_LARGE,+ "too many objects in one push",+ );+ return Ok(true); } hasher.update(&incoming.payload); let Some(record) = wire::parse_record(&incoming.payload) else {+ drain_push(session); session .stream .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");@@ -522,6 +636,7 @@ return Ok(true); }; if object_id(record.kind, &record.body) != record.id {+ drain_push(session); session.stream.write_error( frame.request_id, wire::error_code::HASH_MISMATCH,@@ -530,12 +645,30 @@ return Ok(true); } writer.add_known(record.kind, record.id, record.body);+ if writer.quota_hit() {+ drain_push(session);+ session.stream.write_error(+ frame.request_id,+ wire::error_code::QUOTA,+ "storage quota exceeded",+ );+ return Ok(true);+ } }- if writer.finish(&session.repo) != 0 {+ let status = writer.finish(&session.repo);+ if status != 0 { session.stream.write_error( frame.request_id,- wire::error_code::INTERNAL,- "pack write failed",+ if status == 2 {+ wire::error_code::QUOTA+ } else {+ wire::error_code::INTERNAL+ },+ if status == 2 {+ "storage quota exceeded"+ } else {+ "pack write failed"+ }, ); return Ok(true); }@@ -707,15 +840,34 @@ } } -pub fn serve_stdio(repo: &Path, _quota: u64) -> Result<()> {+fn run_session(+ stream: Stream,+ fixed: Option<PathBuf>,+ root: Option<PathBuf>,+ binding: Vec<u8>,+ quota: u64,+) -> Result<()> {+ let repo_present = fixed.is_some();+ let repo = fixed.clone().unwrap_or_default();+ let base = root.clone().unwrap_or_default();+ let open_path = if repo_present { repo.clone() } else { base };+ let access = if repo_present {+ crypto::load_access(&repo)+ } else {+ crypto::empty_access()+ }; let mut session = Session {- stream: Stream::stdio(),- repo: repo.to_path_buf(),- store: Store::open(repo)?,- access: crypto::empty_access(),+ stream,+ repo,+ repo_present,+ root: root.unwrap_or_default(),+ quota_bytes: quota,+ store: Store::open(&open_path)?,+ access, hello_repo: String::new(), client_nonce: Vec::new(), server_nonce: Vec::new(),+ binding, version: messages::PROTOCOL_VERSION, authed: false, role: 0,@@ -731,6 +883,45 @@ Ok(true) => {} Ok(false) | Err(_) => break, }+ }+ Ok(())+}++pub fn serve_stdio(repo: &Path, quota: u64) -> Result<()> {+ run_session(+ Stream::stdio(),+ Some(repo.to_path_buf()),+ None,+ Vec::new(),+ quota,+ )+}++pub fn serve_listen(+ address: &str,+ root: &Path,+ cert_path: &str,+ key_path: &str,+ quota: u64,+) -> Result<()> {+ let config = super::protocol::tls::server_context(cert_path, key_path)?;+ let listener = std::net::TcpListener::bind(address)+ .map_err(|_| crate::error::Error::new(format!("cannot listen on {address}")))?;+ crate::cli::output::info_prefix();+ println!("listening on {address}");+ for incoming in listener.incoming() {+ let Ok(socket) = incoming else {+ break;+ };+ let config = Arc::clone(&config);+ let root = root.to_path_buf();+ std::thread::spawn(move || {+ let Ok(stream) = super::protocol::tls::accept(socket, config) else {+ return;+ };+ let binding = stream.binding().to_vec();+ let _ = run_session(stream, None, Some(root), binding, quota);+ }); } Ok(()) }--- a/veinsrs/src/worktree/checkout.rs+++ b/veinsrs/src/worktree/checkout.rs@@ -416,10 +416,20 @@ } pub fn materialize(+ root: &Path,+ store: &mut Store,+ old_root: Option<Id>,+ new_root: Id,+) -> Result<()> {+ materialize_with_progress(root, store, old_root, new_root, None)+}++pub fn materialize_with_progress( root: &Path, store: &mut Store, old_root: Option<Id>, new_root: Id,+ progress: Option<&core::Progress>, ) -> Result<()> { if old_root == Some(new_root) { return Ok(());@@ -484,14 +494,42 @@ ensure_safe_dirs(root, b"")?; store.preload()?;- files- .par_iter()- .try_for_each(|entry| write_entry(store, root, entry, &attributes))?;+ if let Some(progress) = progress+ && (!files.is_empty() || !conflicts.is_empty())+ {+ progress.set_total(files.len() + conflicts.len());+ }+ let written = files.par_iter().try_for_each(|entry| {+ write_entry(store, root, entry, &attributes)?;+ if let Some(progress) = progress {+ progress.advance(1);+ }+ Ok(())+ });+ if let Err(error) = written {+ if let Some(progress) = progress {+ progress.clear();+ }+ return Err(error);+ } for conflict in &conflicts {- materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)?;+ if let Err(error) =+ materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)+ {+ if let Some(progress) = progress {+ progress.clear();+ }+ return Err(error);+ }+ if let Some(progress) = progress {+ progress.advance(1);+ } } save_checkout_cache(root, &new_entries)?;+ if let Some(progress) = progress {+ progress.finish();+ } println!("info: checked out {} files", files.len()); Ok(()) }--- a/veinsrs/tests/integration.rs+++ b/veinsrs/tests/integration.rs@@ -1,7 +1,8 @@ use std::fs;+use std::net::TcpListener; use std::path::{Path, PathBuf};-use std::process::{Command, Output};-use std::time::{SystemTime, UNIX_EPOCH};+use std::process::{Command, Output, Stdio};+use std::time::{Duration, SystemTime, UNIX_EPOCH}; struct Fixture { root: PathBuf,@@ -320,6 +321,18 @@ f.commit("two"); let listing = f.vn(&["bmk", "ls"]); assert!(listing.contains("main"));+ f.vn(&["bmk", "rename", "main", "trunk"]);+ let listing = f.vn(&["bmk", "ls"]);+ assert!(listing.contains("trunk"));+ assert!(!listing.contains("main"));+ assert!(+ f.fail(&["bmk", "rename", "trunk", "trunk"])+ .contains("matches the old name")+ );+ assert!(+ f.fail(&["bmk", "rename", "missing", "other"])+ .contains("no such bookmark")+ ); f.vn(&["tag", "set", "v0.0.9"]); f.vn(&["tag", "set", "v0.0.10"]); assert_eq!(f.vn(&["tag", "latest"]).trim(), "v0.0.10");@@ -432,8 +445,168 @@ String::from_utf8_lossy(&output.stderr) ); assert!(!text.contains("panic"), "{command} {token}: {text}");+ }+ }+}++#[test]+fn error_prefix_is_colored() {+ let f = Fixture::new();+ f.init();+ let output = Command::new(env!("CARGO_BIN_EXE_vn"))+ .args(["bmk", "rename", "only"])+ .current_dir(&f.repo)+ .env("HOME", &f.home)+ .env("XDG_CONFIG_HOME", f.home.join(".config"))+ .env("FORCE_COLOR", "1")+ .env_remove("NO_COLOR")+ .output()+ .unwrap();+ assert!(!output.status.success());+ assert!(+ String::from_utf8_lossy(&output.stdout)+ .contains("\x1b[1m\x1b[31merror\x1b[0m: bmk rename requires")+ );+}++#[test]+fn inf_reports_breakdown_with_bars() {+ let f = Fixture::new();+ f.init();+ f.write("main.rs", "fn main() {}\n// two\n");+ f.write("notes.txt", "one\ntwo\nthree\n");+ f.commit("initial");+ let output = f.vn(&["inf"]);+ assert!(output.contains("Repository overview"));+ assert!(output.contains("Languages"));+ assert!(output.contains("Authors"));+ assert!(output.contains("Created"));+ assert!(output.contains("Size"));+ assert!(output.contains(".rs"));+ assert!(output.contains("lines"));+ assert!(output.contains('\u{2588}') || output.contains('\u{2591}'));+ let colored = Command::new(env!("CARGO_BIN_EXE_vn"))+ .args(["inf"])+ .current_dir(&f.repo)+ .env("HOME", &f.home)+ .env("XDG_CONFIG_HOME", f.home.join(".config"))+ .env("FORCE_COLOR", "1")+ .env_remove("NO_COLOR")+ .output()+ .unwrap();+ assert!(+ String::from_utf8_lossy(&colored.stdout).contains("\x1b[1m\x1b[96mRepository overview")+ );+}++#[test]+fn tls_clone_and_push() {+ if Command::new("openssl").arg("version").output().is_err() {+ return;+ }+ 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 cert = f.root.join("cert.pem");+ let key = f.root.join("key.pem");+ let generated = Command::new("openssl")+ .args([+ "req",+ "-x509",+ "-newkey",+ "rsa:2048",+ "-nodes",+ "-keyout",+ key.to_str().unwrap(),+ "-out",+ cert.to_str().unwrap(),+ "-days",+ "1",+ "-subj",+ "/CN=localhost",+ "-addext",+ "subjectAltName=DNS:localhost,IP:127.0.0.1",+ ])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .unwrap();+ if !generated.success() {+ return;+ }+ let fingerprint = Command::new("openssl")+ .args([+ "x509",+ "-in",+ cert.to_str().unwrap(),+ "-noout",+ "-fingerprint",+ "-sha256",+ ])+ .output()+ .unwrap();+ let pin = String::from_utf8_lossy(&fingerprint.stdout)+ .split('=')+ .nth(1)+ .unwrap_or("")+ .trim()+ .to_string();++ let probe = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = probe.local_addr().unwrap().port();+ drop(probe);+ let mut server = Command::new(env!("CARGO_BIN_EXE_vn"))+ .args([+ "serve",+ "-listen",+ &format!("127.0.0.1:{port}"),+ "-root",+ f.root.to_str().unwrap(),+ "-tls-cert",+ cert.to_str().unwrap(),+ "-tls-key",+ key.to_str().unwrap(),+ ])+ .current_dir(&f.root)+ .env("HOME", &f.home)+ .env("XDG_CONFIG_HOME", f.home.join(".config"))+ .env("NO_COLOR", "1")+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();++ let address = format!("127.0.0.1:{port}");+ let mut ready = false;+ for _ in 0..100 {+ if std::net::TcpStream::connect(&address).is_ok() {+ ready = true;+ break; }+ std::thread::sleep(Duration::from_millis(30)); }+ assert!(ready, "TLS server did not start");++ let clone = f.root.join("clone");+ let url = format!("veins://localhost:{port}/source");+ f.vn_in(+ &f.root,+ &[+ "clone",+ &url,+ clone.to_str().unwrap(),+ &format!("-pin:{pin}"),+ ],+ );+ assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");+ server.kill().ok();+ server.wait().ok(); } #[test]