zarlib 0.19.0

ZAR archive library with compression, deduplication, and commit-based history
Documentation
use super::commit_details::COMMIT_NAME_KEY;
use super::common::parse_commit_id;
use crate::{LogicalHeader, MetadataType};
use globset::{GlobBuilder, GlobMatcher};
use std::collections::HashSet;

/// Selects an inclusive range of commits or commits whose names match patterns.
///
/// Unspecified range endpoints mean the beginning or end of the archive.
/// Name patterns are mutually exclusive with range endpoints.
#[derive(Debug, Clone, Copy, Default)]
pub struct CommitSelection<'a> {
    pub from: Option<&'a str>,
    pub to: Option<&'a str>,
    pub names: &'a [String],
}

pub(super) struct CommitSelector {
    from: Option<[u8; 4]>,
    to: Option<[u8; 4]>,
    names: Vec<GlobMatcher>,
    seen: HashSet<[u8; 4]>,
    started: bool,
    ended: bool,
}

impl CommitSelector {
    pub(super) fn new(selection: CommitSelection<'_>) -> Result<Self, Box<dyn std::error::Error>> {
        if !selection.names.is_empty() && (selection.from.is_some() || selection.to.is_some()) {
            return Err("commit name patterns cannot be combined with a commit range".into());
        }
        let names = selection
            .names
            .iter()
            .map(|pattern| {
                if pattern.is_empty() {
                    return Err("commit name pattern must not be empty".into());
                }
                Ok(GlobBuilder::new(pattern)
                    .backslash_escape(false)
                    .literal_separator(false)
                    .build()?
                    .compile_matcher())
            })
            .collect::<Result<Vec<_>, Box<dyn std::error::Error>>>()?;
        Ok(Self {
            from: selection.from.map(parse_commit_id).transpose()?,
            to: selection.to.map(parse_commit_id).transpose()?,
            names,
            seen: HashSet::new(),
            started: selection.from.is_none(),
            ended: false,
        })
    }

    pub(super) fn observe(
        &mut self,
        id: [u8; 4],
        header: Option<&LogicalHeader>,
    ) -> Result<bool, Box<dyn std::error::Error>> {
        if !self.seen.insert(id) {
            return Err(crate::TocError::DuplicateCommitId(id).into());
        }
        if self.from == Some(id) {
            if self.ended {
                return Err("first commit occurs after last commit".into());
            }
            self.started = true;
        }
        let in_range = self.started && !self.ended;
        if self.to == Some(id) {
            if !self.started {
                return Err("last commit occurs before first commit".into());
            }
            self.ended = true;
        }
        if !self.names.is_empty() {
            let header = header.ok_or("password required to match commit names")?;
            return Ok(match header.metadata.get(COMMIT_NAME_KEY) {
                Some(MetadataType::String(name)) => self.names.iter().any(|m| m.is_match(name)),
                _ => false,
            });
        }
        Ok(in_range)
    }

    pub(super) fn finish(&self) -> Result<(), Box<dyn std::error::Error>> {
        if self.from.is_some_and(|id| !self.seen.contains(&id)) {
            return Err("first commit ID was not found".into());
        }
        if self.to.is_some_and(|id| !self.seen.contains(&id)) {
            return Err("last commit ID was not found".into());
        }
        Ok(())
    }
}