navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/cli/commands/log.rs

log.rs

← veinsrs/src/cli/commands · 4500 bytes · raw · download

use std::path::Path;

use crate::cli::args;
use crate::error::Result;
use crate::object::id::Id;
use crate::store::graph;
use crate::store::layout;
use crate::store::ops;
use crate::store::reader::Store;
use crate::time;
use crate::worktree::snapshot;

struct Record {
    id: Id,
    change: String,
    seconds: i64,
    message: Vec<u8>,
    author: Vec<u8>,
}

pub fn run(arguments: &[String]) -> Result<u8> {
    let mut revision = String::new();
    let mut column_titles = true;
    let mut end_flags = false;
    let mut index = 0;
    while index < arguments.len() {
        let argument = &arguments[index];
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && (argument == "-r" || argument == "-rev") {
            index += 1;
            if index >= arguments.len() {
                return Err(crate::Error::new(format!("{argument} requires a revision")));
            }
            revision = arguments[index].clone();
        } else if !end_flags && argument == "-no-col-titles" {
            column_titles = false;
        } else if !end_flags && args::is_flag(argument) {
            return Err(crate::Error::new(format!("unknown flag: {argument}")));
        } else {
            revision = argument.clone();
        }
        index += 1;
    }

    let root = layout::discover(Path::new("."))?;
    let mut store = Store::open(&root)?;
    snapshot::run_with(&root, &mut store)?;
    let view = ops::current_view(&root, &mut store)?
        .ok_or_else(|| crate::Error::new("no operation state"))?;
    let working_copy = ops::working_copy_id(&view);

    let ids = if revision.is_empty() || revision == "all()" {
        let roots = graph::view_roots(&view);
        graph::collect_commits(&mut store, &roots)?
    } else if let Some(target) = graph::resolve_revision(&mut store, &view, &revision)? {
        graph::collect_commits(&mut store, &[target])?
    } else {
        Vec::new()
    };

    let mut records = Vec::new();
    for id in ids {
        let Some(commit) = graph::load_commit(&mut store, id)? else {
            continue;
        };
        records.push(Record {
            id,
            change: graph::base32_encode(commit.change_id),
            seconds: commit.committer.seconds,
            message: commit.message,
            author: commit.author.name,
        });
    }
    records.sort_by(|left, right| right.seconds.cmp(&left.seconds));

    let change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect();
    let mut change_width = 6;
    let mut author_width = 6;
    for (index, record) in records.iter().enumerate() {
        change_width = change_width.max(graph::short_change_id(&change_ids, index).len());
        author_width = author_width.max(record.author.len());
    }

    if column_titles {
        println!(
            "  {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  Message",
            "Commit",
            "Change",
            "Date",
            "Author",
            change_width = change_width,
            author_width = author_width,
        );
    }

    for (index, record) in records.iter().enumerate() {
        let marker = if working_copy == Some(record.id) {
            "@"
        } else {
            " "
        };
        let change = graph::short_change_id(&change_ids, index);
        let date = time::format_utc(record.seconds);
        let message = first_line(&record.message);
        print!(
            "{marker} {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  {}",
            record.id.short(),
            change,
            date,
            String::from_utf8_lossy(&record.author),
            String::from_utf8_lossy(message),
            change_width = change_width,
            author_width = author_width,
        );
        for name in ops::bookmark_names(&view, record.id) {
            print!(" [{}]", String::from_utf8_lossy(&name));
        }
        for name in ops::tag_names(&view, record.id) {
            print!(" <{}>", String::from_utf8_lossy(&name));
        }
        if change_ids
            .iter()
            .enumerate()
            .any(|(other, value)| other != index && *value == record.change)
        {
            print!(" (divergent)");
        }
        println!();
    }
    Ok(0)
}

fn first_line(message: &[u8]) -> &[u8] {
    match message.iter().position(|byte| *byte == b'\n') {
        Some(position) => &message[..position],
        None => message,
    }
}