Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

13.5 KB
Raw Blame
// ©AngelaMos | 2026
// acquire.rs

use std::path::{Path, PathBuf};
use std::time::Duration;

use lisdex_core::process::{self, CommandSpec, Execution};

pub const GIT_BIN: &str = "git";
pub const COPY_BIN: &str = "cp";
pub const DEFAULT_ACQUIRE_TIMEOUT_SECS: u64 = 900;

const GIT_URL_PREFIXES: [&str; 5] = ["http://", "https://", "git://", "ssh://", "file://"];
const SCP_LIKE_PREFIX: &str = "git@";
const GIT_SUFFIX: &str = ".git";
const GIT_DIR: &str = ".git";
const ARG_CLONE: &str = "clone";
const ARG_RECURSE: &str = "--recurse-submodules";
const ARG_DEPTH: &str = "--depth";
const DEPTH_SHALLOW: &str = "1";
const ARG_CHECKOUT: &str = "checkout";
const ARG_REV_PARSE: &str = "rev-parse";
const ARG_HEAD: &str = "HEAD";
const ARG_C: &str = "-C";
const ARG_ARCHIVE: &str = "-a";
const COPY_CONTENTS: &str = "/.";
const UNKNOWN_REVISION: &str = "unknown";

pub const MARKER_FILE: &str = ".lisdex-acquired";

#[derive(Debug, thiserror::Error)]
pub enum AcquireError {
    #[error("process error: {0}")]
    Process(#[from] process::ProcessError),
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("source path {0} does not exist")]
    MissingSource(PathBuf),
    #[error("destination {0} already holds files; pass reuse to build it again")]
    DestinationNotEmpty(PathBuf),
    #[error(
        "destination {path} holds a partial acquisition: no {marker} completion marker. An interrupted clone or copy leaves a tree that looks populated and reports a revision but is missing files. Delete it and acquire again"
    )]
    Incomplete { path: PathBuf, marker: &'static str },
    #[error("{command} failed ({code:?}): {output}")]
    Command {
        command: String,
        code: Option<i32>,
        output: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    Local(PathBuf),
    Git {
        url: String,
        reference: Option<String>,
    },
}

impl Source {
    #[must_use]
    pub fn parse(raw: &str) -> Source {
        let looks_remote = GIT_URL_PREFIXES
            .iter()
            .any(|prefix| raw.starts_with(prefix))
            || raw.starts_with(SCP_LIKE_PREFIX)
            || (raw.ends_with(GIT_SUFFIX) && !Path::new(raw).exists());
        if looks_remote {
            Source::Git {
                url: raw.to_owned(),
                reference: None,
            }
        } else {
            Source::Local(PathBuf::from(raw))
        }
    }

    #[must_use]
    pub fn at(self, reference: Option<String>) -> Source {
        match self {
            Source::Git { url, .. } => Source::Git { url, reference },
            local @ Source::Local(_) => local,
        }
    }

    #[must_use]
    pub fn label(&self) -> String {
        match self {
            Source::Local(path) => path.file_name().map_or_else(
                || path.display().to_string(),
                |name| name.to_string_lossy().into_owned(),
            ),
            Source::Git { url, .. } => url
                .rsplit('/')
                .next()
                .unwrap_or(url)
                .trim_end_matches(GIT_SUFFIX)
                .to_owned(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Acquisition {
    pub root: PathBuf,
    pub revision: Option<String>,
    pub reused: bool,
}

#[must_use]
pub fn clone_spec(url: &str, reference: Option<&str>, dest: &Path) -> CommandSpec {
    let mut spec = CommandSpec::new(GIT_BIN).arg(ARG_CLONE).arg(ARG_RECURSE);
    if reference.is_none() {
        spec = spec.arg(ARG_DEPTH).arg(DEPTH_SHALLOW);
    }
    spec.arg(url).path_arg(dest)
}

#[must_use]
pub fn checkout_spec(dest: &Path, reference: &str) -> CommandSpec {
    CommandSpec::new(GIT_BIN)
        .arg(ARG_C)
        .path_arg(dest)
        .arg(ARG_CHECKOUT)
        .arg(reference)
}

#[must_use]
pub fn copy_spec(source: &Path, dest: &Path) -> CommandSpec {
    CommandSpec::new(COPY_BIN)
        .arg(ARG_ARCHIVE)
        .arg(format!("{}{COPY_CONTENTS}", source.display()))
        .path_arg(dest)
}

fn is_populated(path: &Path) -> Result<bool, AcquireError> {
    if !path.is_dir() {
        return Ok(false);
    }
    let mut entries = std::fs::read_dir(path).map_err(|source| AcquireError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    Ok(entries.next().is_some())
}

#[must_use]
pub fn marker_path(root: &Path) -> PathBuf {
    root.join(MARKER_FILE)
}

#[must_use]
pub fn is_complete(root: &Path) -> bool {
    marker_path(root).is_file()
}

fn mark_complete(root: &Path, revision: Option<&str>) -> Result<(), AcquireError> {
    let path = marker_path(root);
    let contents = format!("{}\n", revision.unwrap_or(UNKNOWN_REVISION));
    std::fs::write(&path, contents).map_err(|source| AcquireError::Io { path, source })
}

fn checked(execution: Execution) -> Result<Execution, AcquireError> {
    if execution.success {
        return Ok(execution);
    }
    Err(AcquireError::Command {
        command: execution.command_line.clone(),
        code: execution.code,
        output: execution.tail(40),
    })
}

#[must_use]
pub fn revision(root: &Path) -> Option<String> {
    if !root.join(GIT_DIR).exists() {
        return None;
    }
    let spec = CommandSpec::new(GIT_BIN)
        .arg(ARG_C)
        .path_arg(root)
        .arg(ARG_REV_PARSE)
        .arg(ARG_HEAD);
    let execution = process::run(&spec, Duration::from_secs(DEFAULT_ACQUIRE_TIMEOUT_SECS)).ok()?;
    if !execution.success {
        return None;
    }
    let resolved = execution.output.trim().to_owned();
    if resolved.is_empty() {
        None
    } else {
        Some(resolved)
    }
}

pub fn acquire(source: &Source, dest: &Path, reuse: bool) -> Result<Acquisition, AcquireError> {
    if is_populated(dest)? {
        if !reuse {
            return Err(AcquireError::DestinationNotEmpty(dest.to_path_buf()));
        }
        if !is_complete(dest) {
            return Err(AcquireError::Incomplete {
                path: dest.to_path_buf(),
                marker: MARKER_FILE,
            });
        }
        return Ok(Acquisition {
            root: dest.to_path_buf(),
            revision: revision(dest),
            reused: true,
        });
    }

    let timeout = Duration::from_secs(DEFAULT_ACQUIRE_TIMEOUT_SECS);
    match source {
        Source::Local(path) => {
            if !path.is_dir() {
                return Err(AcquireError::MissingSource(path.clone()));
            }
            std::fs::create_dir_all(dest).map_err(|source| AcquireError::Io {
                path: dest.to_path_buf(),
                source,
            })?;
            checked(process::run(&copy_spec(path, dest), timeout)?)?;
        }
        Source::Git { url, reference } => {
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent).map_err(|source| AcquireError::Io {
                    path: parent.to_path_buf(),
                    source,
                })?;
            }
            checked(process::run(
                &clone_spec(url, reference.as_deref(), dest),
                timeout,
            )?)?;
            if let Some(reference) = reference {
                checked(process::run(&checkout_spec(dest, reference), timeout)?)?;
            }
        }
    }

    let resolved = revision(dest);
    mark_complete(dest, resolved.as_deref())?;
    Ok(Acquisition {
        root: dest.to_path_buf(),
        revision: resolved,
        reused: false,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scratch(name: &str) -> PathBuf {
        let dir = lisdex_core::scratch::path(&format!("acquire-{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn https_urls_are_git_sources() {
        assert_eq!(
            Source::parse("https://github.com/glennrp/libpng.git"),
            Source::Git {
                url: "https://github.com/glennrp/libpng.git".to_owned(),
                reference: None,
            }
        );
    }

    #[test]
    fn scp_style_urls_are_git_sources() {
        assert!(matches!(
            Source::parse("[email protected]:glennrp/libpng.git"),
            Source::Git { .. }
        ));
    }

    #[test]
    fn plain_paths_are_local_sources() {
        assert_eq!(
            Source::parse("/opt/magma-work/libpng/repo"),
            Source::Local(PathBuf::from("/opt/magma-work/libpng/repo"))
        );
    }

    #[test]
    fn an_existing_local_bare_repo_is_not_mistaken_for_a_url() {
        let dir = scratch("bare");
        let bare = dir.join("libpng.git");
        std::fs::create_dir_all(&bare).unwrap();
        assert_eq!(
            Source::parse(&bare.display().to_string()),
            Source::Local(bare)
        );
    }

    #[test]
    fn label_is_the_repository_name() {
        assert_eq!(
            Source::parse("https://github.com/glennrp/libpng.git").label(),
            "libpng"
        );
        assert_eq!(Source::parse("/opt/magma-work/libpng").label(), "libpng");
    }

    #[test]
    fn clone_without_a_reference_is_shallow() {
        let spec = clone_spec("https://example.invalid/p.git", None, Path::new("/w/p"));
        assert_eq!(spec.program, GIT_BIN);
        assert!(spec.args.iter().any(|arg| arg == ARG_DEPTH));
        assert!(spec.args.iter().any(|arg| arg == ARG_RECURSE));
        assert_eq!(spec.args.last().unwrap(), "/w/p");
    }

    #[test]
    fn clone_with_a_reference_is_deep_so_the_commit_is_reachable() {
        let spec = clone_spec(
            "https://example.invalid/p.git",
            Some("abc123"),
            Path::new("/w/p"),
        );
        assert!(!spec.args.iter().any(|arg| arg == ARG_DEPTH));
    }

    #[test]
    fn checkout_targets_the_cloned_tree() {
        let spec = checkout_spec(Path::new("/w/p"), "abc123");
        assert_eq!(spec.args, vec!["-C", "/w/p", "checkout", "abc123"]);
    }

    #[test]
    fn copy_spec_copies_contents_including_dotfiles() {
        let spec = copy_spec(Path::new("/src/repo"), Path::new("/w/repo"));
        assert_eq!(spec.args, vec!["-a", "/src/repo/.", "/w/repo"]);
    }

    #[test]
    fn acquiring_a_local_tree_copies_it_without_touching_the_original() {
        let dir = scratch("local");
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("configure.ac"), "AC_INIT").unwrap();
        std::fs::write(src.join(".hidden"), "dot").unwrap();

        let dest = dir.join("work");
        let acquired = acquire(&Source::Local(src.clone()), &dest, false).unwrap();

        assert_eq!(acquired.root, dest);
        assert!(!acquired.reused);
        assert_eq!(
            std::fs::read_to_string(dest.join("configure.ac")).unwrap(),
            "AC_INIT"
        );
        assert!(dest.join(".hidden").exists());
        assert!(src.join("configure.ac").exists());
    }

    #[test]
    fn acquiring_into_a_populated_destination_is_refused() {
        let dir = scratch("populated");
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        let dest = dir.join("work");
        std::fs::create_dir_all(&dest).unwrap();
        std::fs::write(dest.join("stale"), "old").unwrap();

        assert!(matches!(
            acquire(&Source::Local(src), &dest, false),
            Err(AcquireError::DestinationNotEmpty(_))
        ));
    }

    #[test]
    fn reuse_returns_the_existing_tree_untouched() {
        let dir = scratch("reuse");
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("kept"), "old").unwrap();
        let dest = dir.join("work");

        assert!(
            !acquire(&Source::Local(src.clone()), &dest, false)
                .unwrap()
                .reused
        );
        let acquired = acquire(&Source::Local(src), &dest, true).unwrap();
        assert!(acquired.reused);
        assert_eq!(std::fs::read_to_string(dest.join("kept")).unwrap(), "old");
    }

    #[test]
    fn a_finished_acquisition_records_its_completion_marker() {
        let dir = scratch("marked");
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("configure.ac"), "AC_INIT").unwrap();
        let dest = dir.join("work");

        assert!(!is_complete(&dest));
        acquire(&Source::Local(src), &dest, false).unwrap();
        assert!(
            is_complete(&dest),
            "a finished acquire must leave {MARKER_FILE}"
        );
        assert_eq!(
            std::fs::read_to_string(marker_path(&dest)).unwrap(),
            format!("{UNKNOWN_REVISION}\n")
        );
    }

    #[test]
    fn an_interrupted_clone_is_refused_on_reuse_rather_than_built_half_checked_out() {
        let dir = scratch("partial");
        let src = dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        let dest = dir.join("work");
        std::fs::create_dir_all(dest.join(GIT_DIR)).unwrap();
        std::fs::write(dest.join("Makefile"), "all:").unwrap();

        let refused = acquire(&Source::Local(src), &dest, true);
        assert!(
            matches!(refused, Err(AcquireError::Incomplete { .. })),
            "a populated but unmarked tree must be refused, got {refused:?}"
        );
    }

    #[test]
    fn acquiring_a_missing_local_tree_is_an_error() {
        let dir = scratch("missing");
        assert!(matches!(
            acquire(&Source::Local(dir.join("nope")), &dir.join("work"), false),
            Err(AcquireError::MissingSource(_))
        ));
    }

    #[test]
    fn revision_is_none_for_a_tree_without_git_metadata() {
        let dir = scratch("norev");
        assert_eq!(revision(&dir), None);
    }
}