Skip to main content

hedl_cli/commands/
validate.rs

1// Dweve HEDL - Hierarchical Entity Data Language
2//
3// Copyright (c) 2025 Dweve IP B.V. and individual contributors.
4//
5// SPDX-License-Identifier: Apache-2.0
6//
7// Licensed under the Apache License, Version 2.0 (the "License");
8// you may not use this file except in compliance with the License.
9// You may obtain a copy of the License in the LICENSE file at the
10// root of this repository or at: http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Validate command - HEDL file syntax and structure validation
19
20use super::read_file;
21use crate::error::CliError;
22use colored::Colorize;
23use hedl_core::{parse_with_limits, ParseOptions, ReferenceMode};
24
25/// Validate a HEDL file for syntax and structural correctness.
26///
27/// Parses a HEDL file and reports whether it is syntactically valid. In strict mode,
28/// all entity references must resolve to defined entities. In lenient mode, constraint
29/// violations become null values with diagnostics emitted separately.
30///
31/// # Arguments
32///
33/// * `file` - Path to the HEDL file to validate
34/// * `strict` - If `true`, enables strict reference validation (all references must resolve)
35/// * `lenient` - If `true`, uses lenient parsing mode (constraint violations become null)
36///
37/// # Returns
38///
39/// Returns `Ok(())` if the file is valid, `Err` with a descriptive error message otherwise.
40///
41/// # Errors
42///
43/// Returns `Err` if:
44/// - The file cannot be read
45/// - The file contains syntax errors
46/// - In strict mode, if any entity references cannot be resolved
47/// - In non-lenient mode, if constraints are violated
48///
49/// # Examples
50///
51/// ```no_run
52/// use hedl_cli::commands::validate;
53///
54/// # fn main() -> Result<(), hedl_cli::error::CliError> {
55/// // Validate a well-formed HEDL file
56/// validate("valid.hedl", false, false)?;
57///
58/// // Strict validation requires all references to resolve
59/// validate("references.hedl", true, false)?;
60///
61/// // Lenient mode allows constraint violations
62/// validate("data.hedl", false, true)?;
63///
64/// // Invalid syntax will fail
65/// let result = validate("invalid.hedl", false, false);
66/// assert!(result.is_err());
67/// # Ok(())
68/// # }
69/// ```
70///
71/// # Output
72///
73/// Prints a summary to stdout including:
74/// - File validation status (✓ or ✗)
75/// - HEDL version
76/// - Count of structs, aliases, and nests
77/// - Parse mode (strict/lenient)
78/// - Reference mode indicator if strict enabled
79pub fn validate(file: &str, strict: bool, lenient: bool) -> Result<(), CliError> {
80    let content = read_file(file)?;
81
82    // Configure parser options with strict reference mode
83    // Note: Parse mode (strict/lenient for constraints) is controlled by %MODE directive in the file,
84    // but we can override it via CLI flag if needed in the future
85    let options = ParseOptions {
86        reference_mode: if strict {
87            ReferenceMode::Strict
88        } else {
89            ReferenceMode::Lenient
90        },
91        ..ParseOptions::default()
92    };
93
94    match parse_with_limits(content.as_bytes(), options) {
95        Ok(doc) => {
96            println!("{} {}", "✓".green().bold(), file);
97            println!("  Version: {}.{}", doc.version.0, doc.version.1);
98            println!("  Structs: {}", doc.structs.len());
99            println!("  Aliases: {}", doc.aliases.len());
100            println!("  Nests: {}", doc.nests.len());
101
102            // Show modes
103            let mode_str = if lenient { "lenient" } else { "strict" };
104            println!("  Parse mode: {} (CLI override)", mode_str);
105
106            if strict {
107                println!("  Reference mode: strict (all references must resolve)");
108            }
109
110            Ok(())
111        }
112        Err(e) => {
113            println!("{} {}", "✗".red().bold(), file);
114            Err(CliError::parse(e.to_string()))
115        }
116    }
117}