cargo-port 0.2.0

A TUI for inspecting and managing Rust projects
use super::rust_info::Cargo;
use crate::project::fields::ProjectFields;
use crate::project::git::CheckoutInfo;
use crate::project::git::WorktreeStatus;
use crate::project::info::ProjectInfo;
use crate::project::info::Visibility;
use crate::project::info::WorktreeHealth;
use crate::project::paths;
use crate::project::paths::AbsolutePath;
use crate::project::paths::DisplayPath;
use crate::project::paths::PackageName;
use crate::project::paths::RootDirectoryName;

/// A crate vendored under a parent Rust project.
///
/// Distinct from [`Package`](super::package::Package) because vendored crates do
/// not own lint state and cannot themselves have nested vendored children.
/// Keeping this as its own type makes those invariants structural rather than
/// relying on convention.
#[derive(Clone, Default)]
pub(crate) struct VendoredPackage {
    pub path:              AbsolutePath,
    pub name:              Option<String>,
    pub worktree_status:   WorktreeStatus,
    pub project_info:      ProjectInfo,
    pub cargo:             Cargo,
    pub crates_version:    Option<String>,
    pub crates_prerelease: Option<String>,
    pub crates_downloads:  Option<u64>,
}

impl VendoredPackage {
    pub fn package_name(&self) -> PackageName {
        PackageName(self.name.as_deref().map_or_else(
            || paths::directory_leaf(self.path.as_path()),
            str::to_string,
        ))
    }

    pub fn crates_version(&self) -> Option<&str> { self.crates_version.as_deref() }

    pub fn crates_prerelease(&self) -> Option<&str> { self.crates_prerelease.as_deref() }

    pub const fn crates_downloads(&self) -> Option<u64> { self.crates_downloads }

    pub fn set_crates_io(&mut self, version: String, prerelease: Option<String>, downloads: u64) {
        self.crates_version = Some(version);
        self.crates_prerelease = prerelease;
        self.crates_downloads = Some(downloads);
    }
}

impl ProjectFields for VendoredPackage {
    fn path(&self) -> &AbsolutePath { &self.path }

    fn name(&self) -> Option<&str> { self.name.as_deref() }

    fn visibility(&self) -> Visibility { self.project_info.visibility }

    fn worktree_health(&self) -> WorktreeHealth { self.project_info.worktree_health }

    fn disk_usage_bytes(&self) -> Option<u64> { self.project_info.disk_usage_bytes }

    fn git_info(&self) -> Option<&CheckoutInfo> { self.project_info.local_git_state.info() }

    fn info(&self) -> &ProjectInfo { &self.project_info }

    fn display_path(&self) -> DisplayPath { self.path.display_path() }

    fn root_directory_name(&self) -> RootDirectoryName {
        RootDirectoryName(paths::directory_leaf(self.path.as_path()))
    }

    fn worktree_status(&self) -> &WorktreeStatus { &self.worktree_status }

    fn crates_io_name(&self) -> Option<&str> {
        self.name.as_deref().filter(|_| self.cargo.publishable())
    }
}