Cargo Toml Validator
Validate Rust Cargo.toml manifests for dependency issues, missing metadata, feature conflicts, workspace config, and crates.io publishing readiness. Use when...
Documentation & Preview
#!/usr/bin/env python3 """ Cargo.toml Validator Validate Rust Cargo.toml manifests for dependency issues, missing metadata, feature conflicts, workspace config, and crates.io publishing readiness. Usage: python3 cargo_toml_validator.py <command> <file> [--strict] [--format text|json|summary] Commands: validate, check, explain, suggest """
import sys import os import re import json import argparse import tomllib from typing import Any
---------------------------------------------------------------------------
Constants
---------------------------------------------------------------------------
VALID_EDITIONS = {"2015", "2018", "2021", "2024"} CURRENT_EDITIONS = {"2021", "2024"} OUTDATED_EDITIONS = {"2015", "2018"}
D6: Deprecated crate names -> suggested replacements
DEPRECATED_CRATES: dict[str, str] = { "failure": "anyhow or thiserror", "error-chain": "thiserror", "iron": "actix-web or axum", "rustc-serialize": "serde", "hyper 0.11": "hyper 1.x", "tokio 0.1": "tokio 1.x", "actix-web 3": "actix-web 4", "rocket 0.4": "rocket 0.5", }
Deprecated crate names that can be matched by name alone (no version check)
DEPRECATED_BY_NAME: dict[str, str] = { "failure": "anyhow or thiserror", "error-chain": "thiserror", "iron": "actix-web or axum", "rustc-serialize": "serde", }
Deprecated crate names that require version prefix check
DEPRECATED_BY_VERSION: dict[str, dict[str, str]] = { "hyper": {"0.11": "hyper 1.x"}, "tokio": {"0.1": "tokio 1.x"}, "actix-web": {"3": "actix-web 4"}, "rocket": {"0.4": "rocket 0.5"}, }
time crate: old versions (0.1, 0.2) -> suggest chrono or time 0.3+
Handled separately since "time" is also a valid modern crate
DEPENDENCY_SECTIONS = [ "dependencies", "dev-dependencies", "build-dependencies", "target", ]
---------------------------------------------------------------------------
Finding class
---------------------------------------------------------------------------
class Finding: """A single validation finding."""
SEVERITIES = ("error", "warning", "info")
def __init__(self, rule_id: str, severity: str, message: str, detail: str = ""): assert severity in self.SEVERITIES, f"Invalid severity: {severity}" self.rule_id = rule_id self.severity = severity self.message = message self.detail = detail
def to_dict(self) -> dict: d = { "rule_id": self.rule_id, "severity": self.severity, "message": self.message, } if self.detail: d["detail"] = self.detail return d
def __repr__(self): return f"Finding({self.rule_id}, {self.severity}, {self.message!r})"
---------------------------------------------------------------------------
TOML loading
---------------------------------------------------------------------------
def load_config(path: str) -> tuple[dict | None, Finding | None]: """Load and parse a Cargo.toml file. Returns (data, error_finding)."""
S1: File not found or unreadable
if not os.path.exists(path): return None, Finding("S1", "error", f"File not found: {path}") try: with open(path, "rb") as f: content = f.read() except OSError as e: return None, Finding("S1", "error", f"Cannot read file: {e}")
S2: Empty file
if len(content.strip()) == 0: return None, Finding("S2", "error", "File is empty")
S3: Invalid TOML syntax
try: data = tomllib.loads(content.decode("utf-8")) except tomllib.TOMLDecodeError as e: return None, Finding("S3", "error", f"Invalid TOML syntax: {e}") except UnicodeDecodeError as e: return None, Finding("S3", "error", f"File encoding error: {e}")
return data, None
---------------------------------------------------------------------------
Individual check functions
---------------------------------------------------------------------------
def check_structure(data: dict) -> list[Finding]: """S4, S5: Check for [package] section and required fields.""" findings: list[Finding] = [] has_package = "package" in data has_workspace = "workspace" in data is_virtual_workspace = has_workspace and not has_package
S4: Missing [package] section
if not has_package: if is_virtual_workspace: findings.append(Finding("S4", "warning", "No [package] section (virtual workspace)", "Virtual workspaces use [workspace] only. This is fine if intentional.")) else: findings.append(Finding("S4", "error", "Missing [package] section", "Every binary or library crate needs a [package] section.")) return findings
S5: Missing required fields in [package]
pkg = data["package"] if "name" not in pkg: findings.append(Finding("S5", "error", "Missing required field: package.name")) if "version" not in pkg:
version can be inherited from workspace, check for that
if not (isinstance(pkg.get("version"), dict) and pkg["version"].get("workspace")): findings.append(Finding("S5", "error", "Missing required field: package.version", "Set version directly or use version.workspace = true.")) if "edition" not in pkg: findings.append(Finding("S5", "warning", "Missing recommended field: package.edition", "Without edition, Rust defaults to 2015. Almost certainly wrong for new projects."))
return findings
def check_package_metadata(data: dict) -> list[Finding]: """M1-M4: Check package metadata quality.""" findings: list[Finding] = [] pkg = data.get("package", {})
if not pkg: return findings
M1: Missing edition field
edition = pkg.get("edition") if edition is None: findings.append(Finding("M1", "warning", "Missing edition field — defaults to 2015", "Add edition = \"2021\" or edition = \"2024\" to [package]."))
M2: Outdated edition
if edition is not None: edition_str = str(edition) if edition_str in OUTDATED_EDITIONS: findings.append(Finding("M2", "info", f"Outdated edition '{edition_str}' — consider upgrading to 2021 or 2024", "Run 'cargo fix --edition' to migrate.")) elif edition_str not in VALID_EDITIONS: findings.append(Finding("M2", "warning", f"Unknown edition '{edition_str}' — valid editions: {', '.join(sorted(VALID_EDITIONS))}"))
M3: Missing license or license-file
if "license" not in pkg and "license-file" not in pkg: findings.append(Finding("M3", "warning", "Missing license or license-file for crates.io publishing", "Add license = \"MIT\" or license-file = \"LICENSE\" to [package]."))
M4: Missing description
if "description" not in pkg: findings.append(Finding("M4", "warning", "Missing description for crates.io publishing", "Add description = \"...\" to [package]. Required for crates.io."))
return findings
def _extract_all_dependencies(data: dict) -> dict[str, dict[str, Any]]: """Extract all dependency sections. Returns {section_name: {dep_name: dep_spec}}.""" result = {}
for section in ["dependencies", "dev-dependencies", "build-dependencies"]: if section in data: result[section] = data[section]
Also extract target-specific dependencies
targets = data.get("target", {}) if isinstance(targets, dict): for target_name, target_data in targets.items(): if isinstance(target_data, dict): for section in ["dependencies", "dev-dependencies", "build-dependencies"]: if section in target_data: key = f"target.{target_name}.{section}" result[key] = target_data[section]
return result
def _parse_version_from_dep(dep_spec: Any) -> str | None: """Extract version string from a dependency specification.""" if isinstance(dep_spec, str): return dep_spec if isinstance(dep_spec, dict): return dep_spec.get("version") return None
def _is_git_dep(dep_spec: Any) -> bool: """Check if dependency uses git source.""" if isinstance(dep_spec, dict): return "git" in dep_spec return False
def _is_path_dep(dep_spec: Any) -> bool: """Check if dependency uses path source.""" if isinstance(dep_spec, dict): return "path" in dep_spec return False
def _git_is_pinned(dep_spec: dict) -> bool: """Check if a git dependency is pinned to rev, tag, or branch.""" return any(k in dep_spec for k in ("rev", "tag", "branch"))
def check_dependencies(data: dict) -> list[Finding]: """D1-D6: Check dependency declarations.""" findings: list[Finding] = [] all_deps = _extract_all_dependencies(data)
for section_name, deps in all_deps.items(): if not isinstance(deps, dict): continue
for dep_name, dep_spec in deps.items(): version = _parse_version_from_dep(dep_spec)
D1: Wildcard version
if version is not None and version.strip() == "*": findings.append(Finding("D1", "error", f"Wildcard version '*' for '{dep_name}' in [{section_name}]", "Wildcard dependencies are highly discouraged. Pin to a version range."))
D2: Unpinned dependency (empty version in table form)
if isinstance(dep_spec, dict) and "version" not in dep_spec: if not _is_git_dep(dep_spec) and not _is_path_dep(dep_spec):
Check for workspace inheritance
if not dep_spec.get("workspace"): findings.append(Finding("D2", "warning", f"Dependency '{dep_name}' in [{section_name}] has no version specifier", "Add a version field or use workspace = true."))
D3: Git dependency without pin
if _is_git_dep(dep_spec) and isinstance(dep_spec, dict): if not _git_is_pinned(dep_spec): git_url = dep_spec.get("git", "") findings.append(Finding("D3", "warning", f"Git dependency '{dep_name}' in [{section_name}] is not pinned", f"Pin to a rev, tag, or branch for reproducibility. URL: {git_url}"))
D4: Path dependency
if _is_path_dep(dep_spec) and isinstance(dep_spec, dict): path_val = dep_spec.get("path", "") findings.append(Finding("D4", "info", f"Path dependency '{dep_name}' in [{section_name}] — blocks crates.io publish", f"Path: {path_val}. Fine for local dev, but won't work on crates.io."))
D6: Deprecated crate names (by name alone)
if dep_name in DEPRECATED_BY_NAME: replacement = DEPRECATED_BY_NAME[dep_name] findings.append(Finding("D6", "info", f"Deprecated crate '{dep_name}' in [{section_name}] — consider '{replacement}'", f"'{dep_name}' is unmaintained. Migrate to {replacement}."))
D6: Deprecated crate names (by version prefix)
if dep_name in DEPRECATED_BY_VERSION and version is not None: for prefix, replacement in DEPRECATED_BY_VERSION[dep_name].items():
Check if version starts with the deprecated major version
clean_ver = version.lstrip("^~>=<! ") if clean_ver.startswith(prefix): findings.append(Finding("D6", "info", f"Outdated version of '{dep_name}'