navid/veins / e362a182625e66b06bd48dcda2992ca49b89e9b8638e55b72b043f1e7ea705b1 / veins-rust/src/identity.rs

identity.rs

← veins-rust/src · 3210 bytes · raw · download

use std::env;
use std::fs;
use std::path::Path;

use crate::object::commit::Sig;
use crate::store::layout;
use crate::time;

struct Config {
    entries: Vec<(String, String)>,
}

impl Config {
    fn load(root: &Path) -> Self {
        let mut entries = Vec::new();
        let mut section = String::new();
        if let Ok(text) = fs::read_to_string(layout::config_path(root)) {
            for raw in text.lines() {
                let line = raw.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                if line.starts_with('[') && line.ends_with(']') {
                    section = line[1..line.len() - 1].trim().to_string();
                    continue;
                }
                let Some((key, value)) = line.split_once('=') else {
                    continue;
                };
                let key = key.trim();
                let full_key = if section.is_empty() {
                    key.to_string()
                } else {
                    format!("{section}.{key}")
                };
                entries.push((full_key, unquote(strip_comment(value))));
            }
        }
        Self { entries }
    }

    fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value.as_str())
    }
}

fn strip_comment(value: &str) -> &str {
    let mut quoted = false;
    for (index, byte) in value.bytes().enumerate() {
        match byte {
            b'"' => quoted = !quoted,
            b'#' if !quoted => return value[..index].trim(),
            _ => {}
        }
    }
    value.trim()
}

fn unquote(value: &str) -> String {
    if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
        value[1..value.len() - 1].to_string()
    } else {
        value.to_string()
    }
}

fn first_config(root: &Path, key: &str, environment: &[&str], fallback: &str) -> String {
    let config = Config::load(root);
    if let Some(value) = config.get(key)
        && !value.is_empty()
    {
        return value.to_string();
    }
    for name in environment {
        if let Ok(value) = env::var(name)
            && !value.is_empty()
        {
            return value;
        }
    }
    fallback.to_string()
}

pub fn signature(root: &Path) -> Sig {
    Sig {
        name: first_config(root, "user.name", &["GIT_AUTHOR_NAME", "USER"], "unknown").into_bytes(),
        email: first_config(root, "user.email", &["GIT_AUTHOR_EMAIL", "EMAIL"], "unknown")
            .into_bytes(),
        seconds: time::now_seconds(),
        tz_min: 0,
    }
}

pub fn random_change_id() -> [u8; 16] {
    use std::io::Read;

    let mut value = [0u8; 16];
    if let Ok(mut file) = fs::File::open("/dev/urandom")
        && file.read_exact(&mut value).is_ok()
    {
        return value;
    }
    let mut hasher = blake3::Hasher::new();
    hasher.update(&time::now_millis().to_le_bytes());
    hasher.update(&std::process::id().to_le_bytes());
    hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());
    value.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    value
}