navid/veins / 24917e1275ff2e0c187fbe0716075c6e6df2ae07f659f6082227db9c452d8431 / veinsrs/src/cli/info.rs

info.rs

← veinsrs/src/cli · 30704 bytes · raw · download

use std::collections::HashMap;
use std::path::Path;

use rayon::prelude::*;

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<u8> {
    println!("veins v{} (store v1)", env!("CARGO_PKG_VERSION"));
    Ok(0)
}

pub fn help(arguments: &[String]) -> Result<u8> {
    let Some(command) = arguments.first() else {
        super::usage();
        return Ok(0);
    };
    let text = match command.as_str() {
        "log" => {
            "usage: vn log [-a] [-rev <revset>] [-lN | -fN] [-no-col-titles] [-p]\n\
             \nshow commit history, newest first\n\
             \noptions:\n  -a, -all                  show the entire history\n  -rev <revset>             show only the given revision set\n  -lN, -l <N>               show the last N commits (newest N)\n  -fN, -f <N>               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 <rev>] [<rev> <rev>] [<path>]\n\
             \nshow a unified diff, paged when stdout is a terminal\n\
             \noptions:\n  -a, -all                  print the whole diff at once\n  -rev <rev>                compare a revision with its parent\n"
        }
        "go" | "commit" => {
            "usage: vn go -m <message>\n\
             \nrecord the working copy and start a new change\n\
             \naliases: commit\n"
        }
        "attr" => {
            "usage: vn attr <gen|txt|bin|lf|crlf|cr|rm|ls> ...\n\
             \nadd or remove .vnattribs rules\n\
             \nsubcommands:\n  vn attr gen <glob>...\n  vn attr rm gen <glob>...\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 <rev>...\n\ncreate a merge commit; never fails\n",
        "rebase" => "usage: vn rebase -s <rev> [-d <rev>]\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] <path>\n\nresolve a conflicted path\n",
        "cfg" => "usage: vn cfg [<key>] [<value>]\n\nread and write configuration\n",
        "rm" => "usage: vn rm [-delete] <path>...\n\nuntrack paths\n",
        "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|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",
        "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 <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>] [-pin:<sha256>] [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 <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"
        }
        "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}")));
        }
    };
    print!("{text}");
    Ok(0)
}

pub fn fsck(arguments: &[String]) -> Result<u8> {
    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<u8> {
    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<u8> {
    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::<i32>()
                .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<u8> {
    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"
            )
        {
            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 = 0u64;
    let mut total_lines = 0u64;
    let mut generated_files = 0u64;
    let mut generated_lines = 0u64;
    let mut generated_bytes = 0u64;
    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_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));
            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 += result.lines;
                generated_bytes += result.bytes;
                if !include_generated {
                    continue;
                }
            }
            total_files += 1;
            total_lines += result.lines;
            let stat = by_ext.entry(result.ext).or_insert((0, 0, 0));
            stat.0 += 1;
            stat.1 += result.lines;
            stat.2 += result.bytes;
        }
    }

    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 {
            String::from_utf8_lossy(&commit.author.name).into_owned()
        };
        *authors.entry(name).or_insert(0) += 1;
    }

    println!();
    println!("{}", output::bold_cyan("Repository overview"));
    println!();
    row_value(
        "Project",
        &root.file_name().unwrap_or_default().to_string_lossy(),
    );
    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_files} files  {generated_lines} lines  {}",
            size_text(generated_bytes)
        );
        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.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!();
    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 {
    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
}