# How to Validate CAD Geometry with Scripts and Inspect Commands in Text-to-CAD

> Validate CAD geometry with scripts and inspect commands in text-to-cad. Learn how to parse files, check integrity, and report errors efficiently.

- Repository: [earthtojake/text-to-cad](https://github.com/earthtojake/text-to-cad)
- Tags: how-to-guide
- Published: 2026-07-29

---

**The text-to-cad repository provides self-contained validation scripts for SDF, DXF, G-code, GLB, and STEP files that parse geometry files, check structural integrity, and report errors through a unified ValidationResult pattern.**

The earthtojake/text-to-cad project ships specialized validation utilities to verify CAD assets before they reach production. Whether you are inspecting SDF robot descriptions, DXF manifests, or G-code toolpaths, these scripts enforce geometric correctness through a consistent four-step validation workflow.

## Core Validation Architecture

The repository implements format-specific validators that remain self-contained to avoid cross-skill dependencies. Each validator targets a specific CAD format:

### SDF Validator

Located in [`plugins/cad/skills/sdf/scripts/sdf/validation.py`](https://github.com/earthtojake/text-to-cad/blob/main/plugins/cad/skills/sdf/scripts/sdf/validation.py), this validator parses SDF XML files and verifies required elements, numeric values, mesh URIs, joint definitions, and reference cycles. The entry point function `validate_sdf_xml` builds a `ValidationResult` object and walks the DOM tree using helper functions including `_validate_link`, `_validate_joint`, and `_validate_pose`.

### DXF Validator

The [`plugins/cad/skills/dxf/scripts/packages/cadpy/src/cadpy/validators.py`](https://github.com/earthtojake/text-to-cad/blob/main/plugins/cad/skills/dxf/scripts/packages/cadpy/src/cadpy/validators.py) module provides geometric checks for DXF manifests through the `cadpy` package. Key utilities include `assert_bbox_coordinate` for bounding-box validation, `assert_selector_count` for entity verification, and `geometry_summary_from_manifest` for extracting metadata statistics.

### G-Code Validator

Found in [`plugins/cad/skills/gcode/scripts/gcode_tool.py`](https://github.com/earthtojake/text-to-cad/blob/main/plugins/cad/skills/gcode/scripts/gcode_tool.py), this validator reads G-code files line-by-line to verify extrusion commands stay within printer build volumes, confirm feed rates are positive, and ensure files are not empty. The public function `validate_gcode_file` raises `GcodeValidationError` on validation failures.

### GLB and STEP Validator

The [`packages/cadpy/src/cadpy/step_targets.py`](https://github.com/earthtojake/text-to-cad/blob/main/packages/cadpy/src/cadpy/step_targets.py) module exports `validate_step_topology_artifact` to verify that generated GLB/STEP artifacts contain valid topology and that bounding boxes match expected dimensions. This utility is consumed by higher-level validation commands across multiple skills.

## Shared Validation Pattern

All validators follow an identical four-step architecture:

1. **Parse** the source file or manifest into an internal representation.
2. **Create** a `ValidationResult` object that collects `errors`, `warnings`, and `infos`.
3. **Walk** the data structure using focused helper functions that raise typed messages when rules are violated.
4. **Return** the `ValidationResult` (or raise exceptions in strict mode) allowing callers to decide whether to abort or continue processing.

This design keeps validators isolated and suitable for embedding in CI pipelines or user scripts.

## Command Line Validation

Each skill provides a CLI wrapper that forwards arguments to the underlying validator. Execute validations directly from your terminal:

```bash

# Validate an SDF robot description

cad-viewer sdf validate --source path/to/robot.sdf

# Validate a DXF manifest JSON

cad-viewer dxf validate --manifest path/to/model.json

# Validate G-code before printing

cad-viewer gcode validate --file path/to/print.gcode

```

Replace `cad-viewer` with your environment's specific launch script if using a custom installation.

## Programmatic Validation

Import the validation modules directly to integrate checks into Python applications.

### Validating SDF Files

```python
from pathlib import Path
from plugins.cad.skills.sdf.scripts.sdf.validation import validate_sdf_xml, raise_for_validation_errors

xml_content = Path("robot.sdf").read_text()
result = validate_sdf_xml(xml_content, source_path=Path("robot.sdf"))

# Raise exception on any error or warning

raise_for_validation_errors(result, strict=True)

```

### Validating DXF Bounding Boxes

```python
from plugins.cad.skills.dxf.scripts.packages.cadpy.src.cadpy.validators import (
    geometry_summary_from_manifest,
    assert_bbox_span,
)

manifest = {
    "bbox": {"min": [0, 0, 0], "max": [0.1, 0.2, 0.3]},
    "stats": {"shapeCount": 42, "faceCount": 200},
}

summary = geometry_summary_from_manifest(manifest)
assert_bbox_span(summary["bbox"], "x", 0.1)  # Raises AssertionError if mismatch

```

### Validating G-Code Safety

```python
from plugins.cad.skills.gcode.scripts.gcode_tool import validate_gcode_file

printer_profile = {"build_volume": [0.2, 0.2, 0.2]}
result = validate_gcode_file("print.gcode", printer_profile)

if not result.is_ok:
    print("Validation failed:", result.errors)

```

## CI/CD Integration

The repository includes test suites in `tests/python/skills/` that demonstrate automated validation. Add custom validation tests to your CI pipeline:

```python
def test_sdf_geometry():
    from plugins.cad.skills.sdf.scripts.sdf.validation import validate_sdf_xml, raise_for_validation_errors
    from pathlib import Path
    
    xml = Path("tests/fixtures/robot.sdf").read_text()
    result = validate_sdf_xml(xml, source_path=Path("robot.sdf"))
    
    # Fails CI on any validation issue

    raise_for_validation_errors(result, strict=True)

```

Execute the full test harness via [`scripts/test/test.sh`](https://github.com/earthtojake/text-to-cad/blob/main/scripts/test/test.sh) to automatically verify all CAD assets before deployment.

## Practical Validation Examples

### Example 1: Inspecting SDF Warnings

Capture and display specific validation warnings without raising exceptions:

```python
from pathlib import Path
from plugins.cad.skills.sdf.scripts.sdf.validation import validate_sdf_xml

source = Path("examples/robot.sdf")
result = validate_sdf_xml(source.read_text(), source_path=source)

for warning in result.warnings:
    print(f"⚠️  {warning.code}: {warning.message}")

print("✅ Validation complete")

```

### Example 2: DXF Coordinate Verification

Verify specific bounding box coordinates against manifest data:

```python
from plugins.cad.skills.dxf.scripts.packages.cadpy.src.cadpy.validators import (
    geometry_summary_from_manifest,
    assert_bbox_coordinate,
)

manifest = {
    "bbox": {"min": [-0.05, -0.05, 0.0], "max": [0.05, 0.05, 0.1]},
    "stats": {"shapeCount": 10, "faceCount": 120, "edgeCount": 240},
}

summary = geometry_summary_from_manifest(manifest)

# Verify Z-axis maximum matches expected value

assert_bbox_coordinate(summary["bbox"], "z", "max", 0.1)

```

### Example 3: GitHub Actions G-Code Validation

Integrate G-code validation into your GitHub Actions workflow:

```yaml
name: G-code validation
on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install dependencies
        run: python -m pip install -r requirements.txt
      - name: Validate G-code geometry
        run: |
          python - <<'PY'
          from plugins.cad.skills.gcode.scripts.gcode_tool import validate_gcode_file
          profile = {"build_volume": [0.25, 0.25, 0.25]}
          result = validate_gcode_file("models/sample.gcode", profile)
          if not result.is_ok:
              raise SystemExit("❌ G-code validation failed")
          print("✅ G-code is valid")
          PY

```

## Summary

- **Self-contained validators** in `plugins/cad/skills/*/scripts/` handle SDF, DXF, G-code, and GLB/STEP formats without cross-skill dependencies.
- **Unified API pattern** uses `ValidationResult` objects to collect errors, warnings, and informational messages.
- **Entry points** include `validate_sdf_xml`, `validate_gcode_file`, and `geometry_summary_from_manifest` for programmatic access.
- **CLI wrappers** provide command-line access via `cad-viewer <skill> validate` commands.
- **CI integration** is supported through standard Python test suites that can fail builds on validation errors.

## Frequently Asked Questions

### How do I validate SDF XML files programmatically?

Import `validate_sdf_xml` from `plugins/cad.skills.sdf.scripts.sdf.validation`. Pass the XML content as a string and the source file path to receive a `ValidationResult`. Call `raise_for_validation_errors(result, strict=True)` to automatically raise exceptions on any detected issues.

### What checks does the G-code validator perform?

The `validate_gcode_file` function in [`gcode_tool.py`](https://github.com/earthtojake/text-to-cad/blob/main/gcode_tool.py) verifies that extrusion commands remain within the printer's build volume, ensures feed rates are positive values, and confirms the file contains actual content rather than being empty. It returns a result object indicating success or specific validation failures.

### How can I integrate CAD validation into CI/CD pipelines?

Add Python test functions that import the validation modules (such as those in `tests/python/skills/`) and call the validators with `strict=True` mode. Running these tests via [`scripts/test/test.sh`](https://github.com/earthtojake/text-to-cad/blob/main/scripts/test/test.sh) or your preferred test runner will fail the build when geometry validation errors are detected, preventing invalid assets from reaching production.

### What is the difference between validate_sdf_xml and raise_for_validation_errors?

The `validate_sdf_xml` function performs the actual validation logic and returns a `ValidationResult` containing any errors or warnings. The `raise_for_validation_errors` function is a utility that examines that result and raises a Python exception if errors (or warnings in strict mode) are present, allowing you to separate validation execution from error handling logic.