markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
};

use serde::Deserialize;

use super::model::{
    Binary, ExternalDependency, Package, Workspace, WorkspaceDependency, WorkspacePackage,
};
use crate::{
    domain::{Metadata, MetadataContext},
    workspace,
};

impl Workspace {
    pub(crate) fn load(
        manifest_path: &Path,
        files: &crate::domain::IndexedFiles,
    ) -> Result<Self, crate::domain::Error> {
        let source = files
            .get(manifest_path)
            .and_then(|source| source.as_deref())
            .ok_or_else(|| {
                crate::domain::Error::message(
                    manifest_path,
                    "Cargo workspace manifest",
                    "configured manifest is missing or not UTF-8 text",
                )
            })?;
        let manifest: Manifest = toml::from_str(source).map_err(|error| {
            crate::domain::Error::parse(manifest_path, "Cargo workspace manifest", error)
        })?;
        let workspace = manifest.workspace.unwrap_or_default();
        let manifest_directory = manifest_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .to_path_buf();

        Ok(Self {
            manifest_directory,
            dependencies: workspace.dependencies,
            package: workspace.package,
        })
    }
}

pub(super) fn resolve(
    context: &MetadataContext<'_>,
    cargo_workspace: &Workspace,
    manifest_directories: &BTreeSet<PathBuf>,
) -> Result<Option<Metadata>, crate::domain::Error> {
    let path = context.manifest_path;
    let manifest: Manifest = toml::from_str(context.manifest_source)
        .map_err(|error| crate::domain::Error::parse(path, "Cargo.toml", error))?;
    let Some(package) = manifest.package else {
        return Ok(None);
    };
    let name = package.name;
    let description = package
        .description
        .and_then(|value| value.resolve(cargo_workspace.package.description.as_ref()));
    let version = package
        .version
        .and_then(|value| value.resolve(cargo_workspace.package.version.as_ref()));
    let rust_version = package
        .rust_version
        .and_then(|value| value.resolve(cargo_workspace.package.rust_version.as_ref()));
    let workspace_dependencies = resolve_workspace_dependencies(
        &manifest.dependencies,
        context.directory,
        cargo_workspace,
        manifest_directories,
    );
    let mut external_dependencies = manifest
        .dependencies
        .iter()
        .filter_map(|(name, value)| {
            let dependency = resolve_dependency(name, value, context.directory, cargo_workspace)?;

            (dependency.path.is_none()).then_some(())?;

            Some(ExternalDependency {
                name: name.clone(),
                version: dependency.version?,
            })
        })
        .collect::<Vec<_>>();
    let binaries = manifest
        .binaries
        .into_iter()
        .filter_map(|binary| {
            Some(Binary {
                name: binary.name?,
                required_features: binary.required_features,
            })
        })
        .collect();

    external_dependencies.sort_by(|left, right| left.name.cmp(&right.name));

    let mut metadata = Metadata {
        name,
        description,
        version,
        kind: "crate",
        ..Metadata::default()
    };

    metadata.insert_data(
        "cargo",
        Package {
            workspace_dependencies,
            features: manifest.features,
            binaries,
            tests: target_names(manifest.tests),
            benches: target_names(manifest.benches),
            examples: target_names(manifest.examples),
            external_dependencies,
            rust_version,
        },
    );

    Ok(Some(metadata))
}

fn target_names(targets: Vec<Target>) -> Box<[String]> {
    targets
        .into_iter()
        .filter_map(|target| target.name)
        .collect()
}

#[derive(Deserialize)]
struct Manifest {
    package: Option<ManifestPackage>,
    workspace: Option<ManifestWorkspace>,
    #[serde(default, rename = "bin")]
    binaries: Vec<ManifestBinary>,
    #[serde(default, rename = "test")]
    tests: Vec<Target>,
    #[serde(default, rename = "bench")]
    benches: Vec<Target>,
    #[serde(default, rename = "example")]
    examples: Vec<Target>,
    #[serde(default)]
    features: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    dependencies: BTreeMap<String, toml::Value>,
}

#[derive(Default, Deserialize)]
struct ManifestWorkspace {
    #[serde(default)]
    dependencies: BTreeMap<String, toml::Value>,
    #[serde(default)]
    package: WorkspacePackage,
}

#[derive(Deserialize)]
struct ManifestPackage {
    name: Option<String>,
    description: Option<InheritableString>,
    version: Option<InheritableString>,
    #[serde(rename = "rust-version")]
    rust_version: Option<InheritableString>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum InheritableString {
    Value(String),
    Workspace { workspace: bool },
}

impl InheritableString {
    fn resolve(self, inherited: Option<&String>) -> Option<String> {
        match self {
            Self::Value(value) => Some(value),
            Self::Workspace { workspace: true } => inherited.cloned(),
            Self::Workspace { workspace: false } => None,
        }
    }
}

#[derive(Deserialize)]
struct ManifestBinary {
    name: Option<String>,
    #[serde(default, rename = "required-features")]
    required_features: Box<[String]>,
}

#[derive(Deserialize)]
struct Target {
    name: Option<String>,
}

#[derive(Debug, Default)]
struct ResolvedDependency {
    path: Option<PathBuf>,
    version: Option<String>,
    optional: bool,
    features: Vec<Box<str>>,
    default_features: Option<bool>,
}

fn resolve_workspace_dependencies(
    dependencies: &BTreeMap<String, toml::Value>,
    package_directory: &Path,
    workspace: &Workspace,
    manifest_directories: &BTreeSet<PathBuf>,
) -> BTreeMap<String, WorkspaceDependency> {
    dependencies
        .iter()
        .filter_map(|(name, value)| {
            let dependency = resolve_dependency(name, value, package_directory, workspace)?;
            let path = dependency.path?;

            manifest_directories.contains(&path).then_some(())?;

            Some((
                name.clone(),
                WorkspaceDependency {
                    path: workspace::relative_path(package_directory, &path),
                    optional: dependency.optional,
                    features: dependency.features.into_iter().map(String::from).collect(),
                    default_features: dependency.default_features,
                },
            ))
        })
        .collect()
}

fn resolve_dependency(
    name: &str,
    value: &toml::Value,
    package_directory: &Path,
    workspace: &Workspace,
) -> Option<ResolvedDependency> {
    let local = parse_dependency(value)?;
    let inherits = value
        .as_table()
        .and_then(|table| table.get("workspace"))
        .and_then(toml::Value::as_bool)
        .unwrap_or(false);

    if !inherits {
        return Some(ResolvedDependency {
            path: local
                .path
                .map(|path| workspace::normalize(&package_directory.join(path))),
            ..local
        });
    }

    let inherited = parse_dependency(workspace.dependencies.get(name)?)?;
    let mut features = inherited.features;

    for feature in local.features {
        if !features.contains(&feature) {
            features.push(feature);
        }
    }

    Some(ResolvedDependency {
        path: inherited
            .path
            .map(|path| workspace::normalize(&workspace.manifest_directory.join(path))),
        version: inherited.version,
        optional: local.optional,
        features,
        default_features: local.default_features.or(inherited.default_features),
    })
}

fn parse_dependency(value: &toml::Value) -> Option<ResolvedDependency> {
    match value {
        toml::Value::String(version) => Some(ResolvedDependency {
            version: Some(version.clone()),
            ..ResolvedDependency::default()
        }),

        toml::Value::Table(table) => Some(ResolvedDependency {
            path: table
                .get("path")
                .and_then(toml::Value::as_str)
                .map(PathBuf::from),
            version: table
                .get("version")
                .and_then(toml::Value::as_str)
                .map(String::from),
            optional: table
                .get("optional")
                .and_then(toml::Value::as_bool)
                .unwrap_or(false),
            features: table
                .get("features")
                .and_then(toml::Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(toml::Value::as_str)
                .map(Box::<str>::from)
                .collect(),
            default_features: table.get("default-features").and_then(toml::Value::as_bool),
        }),

        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use googletest::prelude::*;

    use super::super::model::Package;
    use crate::{WorkspaceFile, WorkspaceIndex};

    #[gtest]
    fn resolves_inherited_package_fields_and_workspace_dependencies() -> Result<()> {
        let root = Path::new("/ws");
        let workspace = WorkspaceIndex::new_domain(
            root.to_path_buf(),
            vec![
                WorkspaceFile {
                    path: root.join("Cargo.toml"),
                    contents: Some(
                        "[workspace]\nmembers = [\"crates/*\"]\n[workspace.package]\nversion = \"1.2.3\"\nrust-version = \"1.95\"\n[workspace.dependencies]\nb = { path = \"crates/b\" }\n"
                            .into(),
                    ),
                },
                WorkspaceFile {
                    path: root.join("crates/a/Cargo.toml"),
                    contents: Some(
                        "[package]\nname = \"a\"\nversion.workspace = true\nrust-version.workspace = true\n[dependencies]\nb.workspace = true\n"
                            .into(),
                    ),
                },
                WorkspaceFile {
                    path: root.join("crates/b/Cargo.toml"),
                    contents: Some("[package]\nname = \"b\"\nversion = \"0.1.0\"\n".into()),
                },
            ],
            "cargo",
            toml::Value::Table(toml::toml! {
                manifests = ["Cargo.toml", "**/Cargo.toml"]
                workspace = "Cargo.toml"
                dependency-graph = true
            }),
        );
        let metadata = workspace.metadata(&root.join("crates/a")).or_fail()?;
        let package = metadata.data::<Package>("cargo").or_fail()?;

        verify_eq!(metadata.version.as_deref(), Some("1.2.3"))?;
        verify_eq!(package.rust_version.as_deref(), Some("1.95"))?;
        verify_eq!(package.workspace_dependencies["b"].path, "../b")
    }

    #[gtest]
    fn a_virtual_workspace_is_still_owned_by_cargo() -> Result<()> {
        let root = Path::new("/ws");
        let workspace = WorkspaceIndex::new_domain(
            root.to_path_buf(),
            vec![WorkspaceFile {
                path: root.join("Cargo.toml"),
                contents: Some("[workspace]\nmembers = []\n".into()),
            }],
            "cargo",
            toml::Value::Table(toml::toml! { manifests = ["Cargo.toml"] }),
        );
        let metadata = workspace.metadata(root).or_fail()?;

        verify_eq!(metadata.domain, Some("cargo"))
    }
}