use std::collections::HashMap; use std::path::Path; use crate::core; use crate::error::{Error, Result}; use crate::object::tree::{self, KIND_CONFLICT, KIND_SUBTREE}; use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_CONFLICT, TYPE_OPERATION, TYPE_TREE, TYPE_VIEW}; use crate::store::graph; use crate::store::layout; use crate::store::ops; use crate::store::reader::Store; use crate::worktree::attributes::{AttributeRules, AttributeText}; use super::output; pub fn version() -> Result { println!("veins v{} (store v1)", env!("CARGO_PKG_VERSION")); Ok(0) } pub fn help(arguments: &[String]) -> Result { let Some(command) = arguments.first() else { super::usage(); return Ok(0); }; let text = match command.as_str() { "log" => { "usage: vn log [-a] [-rev ] [-lN | -fN] [-no-col-titles] [-p]\n\ \nshow commit history, newest first\n\ \noptions:\n -a, -all show the entire history\n -rev show only the given revision set\n -lN, -l show the last N commits (newest N)\n -fN, -f show the first N commits (oldest N)\n -no-col-titles omit column titles\n -p page the full history through the pager\n" } "show" => { "usage: vn show [-a] [rev] [-no-col-titles]\n\ \nshow a commit's metadata and its diff against its first parent\n\ \noptions:\n -a, -all print the whole output at once\n -no-col-titles omit the metadata labels\n" } "diff" => { "usage: vn diff [-a] [-rev ] [ ] []\n\ \nshow a unified diff, paged when stdout is a terminal\n\ \noptions:\n -a, -all print the whole diff at once\n -rev compare a revision with its parent\n" } "go" | "commit" => { "usage: vn go -m \n\ \nrecord the working copy and start a new change\n\ \naliases: commit\n" } "attr" => { "usage: vn attr ...\n\ \nadd or remove .vnattribs rules\n\ \nsubcommands:\n vn attr gen ...\n vn attr rm gen ...\n vn attr ls\n" } "stat" | "status" => "usage: vn stat\n\nshow working-copy changes\n", "ls" => "usage: vn ls [rev] [-plain]\n\nlist tracked files\n", "hash" => "usage: vn hash [rev] [-short|-long]\n\nprint the commit hash for a revision\n", "new" => "usage: vn new [rev...]\n\nstart a new change\n", "co" | "checkout" => "usage: vn co [rev]\n\nwrite a revision into the working directory\n", "merge" => "usage: vn merge ...\n\ncreate a merge commit; never fails\n", "rebase" => "usage: vn rebase -s [-d ]\n\nrewrite changes onto a new parent\n", "xs" => "usage: vn xs [-porcelain]\n\nlist conflicted paths\n", "resolve" => "usage: vn resolve [-take ours|theirs] \n\nresolve a conflicted path\n", "cfg" => "usage: vn cfg [] []\n\nread and write configuration\n", "rm" => "usage: vn rm [-delete] ...\n\nuntrack paths\n", "mv" => "usage: vn mv \n\nmove a tracked file\n", "ex" => "usage: vn ex ...\n\nadd exclude rules\n", "edit" => "usage: vn edit [path]...\n\nopen paths in the configured editor\n", "bmk" => "usage: vn bmk ...\n\nmanage named branch pointers\n", "tag" => "usage: vn tag ...\n\nmanage named tags\n", "op" => "usage: vn op ...\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", "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 ...\n\nimport from or export to git\n" } "remote" => "usage: vn remote ...\n\nmanage native remotes\n", "clone" => { "usage: vn clone [-blobs:head|none|all] [-key:] [path]\n\nclone a repository\n" } "fetch" => "usage: vn fetch [] [path]\n\nfetch from a native remote\n", "pull" => { "usage: vn pull [] [path]\n\nfetch and fast-forward the current bookmark\n" } "push" | "psh" => { "usage: vn push [] [] [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 ...\n\nmanage local Ed25519 keys\n", "auth" => { "usage: vn auth ...\n\nremember keys for hosts and set a default\n" } "access" => { "usage: vn access ...\n\nmanage a served repository's access file\n" } "whoami" => "usage: vn whoami []\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}"))); } }; print!("{text}"); Ok(0) } pub fn fsck(arguments: &[String]) -> Result { let mut path = ".".to_string(); let mut verbose = false; let mut end_flags = false; for argument in arguments { if !end_flags && argument == "--" { end_flags = true; } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") { verbose = true; } else if !end_flags && core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}"))); } else { path = argument.clone(); } } let root = layout::discover(Path::new(&path)) .map_err(|_| Error::new(format!("not a veins repository: {path}")))?; fsck_repository(&root, verbose) } fn fsck_repository(root: &Path, verbose: bool) -> Result { let mut errors = 0usize; let mut warnings = 0usize; let format = core::read_file_opt(&layout::format_path(root), 0); match format { Some(data) if data == b"veins-store 1" || data == b"veins-store 1\n" => {} _ => { output::error_prefix(); println!("fsck: {}: invalid .veins/format", root.display()); errors += 1; } } let promisor = core::read_file_opt(&layout::config_path(root), 0) .is_some_and(|data| data.windows(8).any(|window| window == b"promisor")); let packs = layout::packs_dir(root); let names = core::list_directory(&packs); let mut store = Store::open(root)?; let mut seen_objects: HashMap<_, ()> = HashMap::new(); for name in &names { let text = String::from_utf8_lossy(name); if !text.ends_with(".vpack") { continue; } let path = packs.join(core::path_from_bytes(name)); let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else { output::error_prefix(); println!("fsck: {}: cannot read pack", path.display()); errors += 1; continue; }; let pack = match crate::store::pack::decode(data) { Ok(pack) => pack, Err(_) => { output::error_prefix(); println!("fsck: {}: invalid pack", path.display()); errors += 1; continue; } }; 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) else { output::error_prefix(); println!("fsck: {}: pack has no index", path.display()); errors += 1; continue; }; let index = match crate::store::index::decode(&index_data, Some(pack.trailer)) { Ok(index) => index, Err(_) => { output::error_prefix(); println!("fsck: {}: invalid index", index_path.display()); errors += 1; continue; } }; if index.entries.len() != pack.records.len() { output::error_prefix(); println!( "fsck: {}: pack and index object counts differ", path.display() ); errors += 1; continue; } let mut visited = vec![false; pack.records.len()]; for entry in &index.entries { let Some(position) = pack.find_by_offset(entry.offset) else { output::error_prefix(); println!( "fsck: {}: index offset names no record for {}", path.display(), entry.id.to_hex() ); errors += 1; continue; }; if pack.records[position].id != entry.id { output::error_prefix(); println!( "fsck: {}: index id does not match record for {}", path.display(), entry.id.to_hex() ); errors += 1; } if visited[position] { output::error_prefix(); println!( "fsck: {}: record indexed more than once {}", path.display(), entry.id.to_hex() ); errors += 1; } visited[position] = true; } for position in 0..pack.records.len() { if !visited[position] { output::error_prefix(); println!( "fsck: {}: record is not indexed {}", path.display(), pack.records[position].id.to_hex() ); errors += 1; } let record = &pack.records[position]; let Ok(body) = pack.get(position) else { output::error_prefix(); println!( "fsck: {}: invalid record {}", path.display(), record.id.to_hex() ); errors += 1; continue; }; if crate::object::id::object_id(record.kind, &body) != record.id { output::error_prefix(); println!( "fsck: {}: hash mismatch for {}", path.display(), record.id.to_hex() ); errors += 1; continue; } if seen_objects.insert(record.id, ()).is_some() { warnings += 1; } check_object_refs( &mut store, &body, record.kind, promisor, &mut errors, &mut warnings, )?; } } let heads = ops::read_heads(root)?; for head in heads { if store.operation(head)?.is_none() { output::error_prefix(); println!("fsck: operation head is missing: {}", head.to_hex()); errors += 1; } } if verbose && warnings > 0 { output::warning_prefix(); println!("{warnings} warning(s)"); } if errors == 0 { output::info_prefix(); println!("fsck: clean"); Ok(0) } else { output::error_prefix(); println!("{errors} error(s)"); Ok(1) } } fn check_object_refs( store: &mut Store, body: &[u8], kind: u8, promisor: bool, errors: &mut usize, warnings: &mut usize, ) -> Result<()> { let mut check = |id: crate::object::id::Id, expected: u8| -> Result<()> { if store.contains(id) { return Ok(()); } if promisor && matches!(expected, crate::object::TYPE_CHUNK | TYPE_BLOB) { *warnings += 1; } else { output::error_prefix(); println!("fsck: missing object {}", id.to_hex()); *errors += 1; } Ok(()) }; match kind { TYPE_BLOB => { if let Ok(blob) = crate::object::blob::decode(body) { if blob.form != crate::object::blob::BlobForm::Inline { let expected = if blob.form == crate::object::blob::BlobForm::Leaf { crate::object::TYPE_CHUNK } else { TYPE_BLOB }; for entry in blob.entries { check(entry.id, expected)?; } } } } TYPE_TREE => { if let Ok(tree) = tree::decode(body) { for entry in tree.entries { match entry.kind { tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => { check(entry.target, TYPE_BLOB)?; } KIND_SUBTREE => check(entry.target, TYPE_TREE)?, KIND_CONFLICT => check(entry.target, TYPE_CONFLICT)?, _ => {} } } } } TYPE_CONFLICT => { if let Ok(conflict) = crate::object::conflict::decode(body) { for value in conflict.adds.iter().chain(conflict.removes.iter()) { if let Some(target) = value.target { let expected = match value.kind { 1 | 2 | 3 => TYPE_BLOB, 4 => TYPE_TREE, 6 => TYPE_CONFLICT, _ => continue, }; check(target, expected)?; } } } } TYPE_COMMIT => { if let Ok(commit) = crate::object::commit::decode(body) { for parent in commit.parents { check(parent, TYPE_COMMIT)?; } check(commit.root_tree, TYPE_TREE)?; } } TYPE_OPERATION => { if let Ok(operation) = crate::object::view::decode_operation(body) { for parent in operation.parents { check(parent, TYPE_OPERATION)?; } check(operation.view, TYPE_VIEW)?; } } TYPE_VIEW => { if let Ok(view) = crate::object::view::decode_view(body) { for head in view.heads { check(head, TYPE_COMMIT)?; } } } _ => {} } Ok(()) } pub fn repack(arguments: &[String]) -> Result { let mut path = ".".to_string(); let mut verbose = false; let mut level = 6; let mut end_flags = false; for argument in arguments { if !end_flags && argument == "--" { end_flags = true; } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") { verbose = true; } else if !end_flags && let Some(value) = argument.strip_prefix("-level:") { level = value .parse::() .map_err(|_| Error::new("-level: requires a value (1-19)"))?; if !(1..=19).contains(&level) { return Err(Error::new("compression level must be between 1 and 19")); } } else if !end_flags && core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}"))); } else { path = argument.clone(); } } let root = layout::discover(Path::new(&path)) .map_err(|_| Error::new(format!("not a veins repository: {path}")))?; let packs = layout::packs_dir(&root); let mut objects = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut before = 0u64; let mut names = core::list_directory(&packs); names.sort(); for name in names { let text = String::from_utf8_lossy(&name); if !text.ends_with(".vpack") { continue; } let path = packs.join(core::path_from_bytes(&name)); let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else { output::error_prefix(); println!("cannot read pack {text}"); return Ok(1); }; before += data.len() as u64; let Ok(pack) = crate::store::pack::decode(data) else { output::error_prefix(); println!("cannot decode pack {text}"); return Ok(1); }; for (index, record) in pack.records.iter().enumerate() { if !seen.insert(record.id) { continue; } let Ok(body) = pack.get(index) else { output::error_prefix(); println!("cannot read object {}", record.id.to_hex()); return Ok(1); }; objects.push(crate::object::RawObject::known( record.kind, record.id, body, )); } } if objects.is_empty() { output::info_prefix(); println!("no objects to repack"); return Ok(0); } let output_pack = crate::store::pack::encode(&objects, level); if crate::store::pack::write_output(&root, &output_pack, 0) != 0 { output::error_prefix(); println!("cannot write repacked pack"); return Ok(1); } for name in core::list_directory(&packs) { let text = String::from_utf8_lossy(&name); let is_pack = text.ends_with(".vpack"); let is_index = text.ends_with(".vidx"); if !is_pack && !is_index { continue; } let stem = if is_pack { &text[..text.len() - 6] } else { &text[..text.len() - 5] }; if stem == output_pack.name { continue; } let _ = core::remove_file(&packs.join(core::path_from_bytes(&name))); } if verbose { output::info_prefix(); println!( "repacked {} objects, {} KiB -> {} KiB", output_pack.count, before / 1024, (output_pack.pack.len() + output_pack.index.len()) as u64 / 1024 ); } Ok(0) } pub fn inf(arguments: &[String]) -> Result { let mut include_generated = false; let mut end_flags = false; for argument in arguments { if !end_flags && argument == "--" { end_flags = true; } else if !end_flags && matches!(argument.as_str(), "-inc-gen" | "-include-generated") { include_generated = true; } else if !end_flags && core::is_flag(argument) { return Err(Error::new(format!("unknown flag: {argument}"))); } } 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)?.unwrap_or_default(); let working = ops::working_copy_id(&view); let rules = AttributeRules::load(&root); let mut total_files = 0usize; let mut total_lines = 0u64; let mut generated_files = 0usize; let mut generated_lines = 0u64; let mut generated_bytes = 0u64; let mut by_ext: HashMap = 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 attributes = rules.lookup(&String::from_utf8_lossy(&entry.path)); let data = graph::read_blob(&mut store, entry.target)?.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 { generated_files += 1; generated_lines += lines; generated_bytes += data.len() as u64; 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)); stat.0 += 1; stat.1 += lines; stat.2 += data.len() as u64; } } let mut commits = 0usize; let mut authors: HashMap = 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 name = if commit.author.name.is_empty() { "(unknown)".to_string() } else { String::from_utf8_lossy(&commit.author.name).into_owned() }; *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(|| "".to_string()) ); 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()); if generated_files > 0 { print!( "Generated {generated_files} files {generated_lines} lines {generated_bytes} B" ); if !include_generated { print!(" (excluded; use -inc-gen)"); } println!(); } println!(); println!("{}", output::bold_cyan("Languages")); println!(); if by_ext.is_empty() { 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"); } } 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"); } println!(); Ok(0) } fn count_nonblank(data: &[u8]) -> u64 { let mut count = 0; let mut start = 0; while start <= data.len() { let end = data[start..] .iter() .position(|byte| *byte == b'\n') .map(|offset| start + offset) .unwrap_or(data.len()); if data[start..end] .iter() .any(|byte| !matches!(*byte, b' ' | b'\t' | b'\r')) { count += 1; } if end >= data.len() { break; } 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(), } }