m3l-cli 0.7.0

M3L CLI tool — parse and validate .m3l.md schema files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
mod commands;
mod reader;

use std::path::{Path, PathBuf};
use std::process;

use clap::{Parser, Subcommand};

use m3l_core::{parse_string, resolve, validate, ProjectInfo, ValidateOptions};
use reader::{read_m3l_files, read_project_config};

#[derive(Parser)]
#[command(
    name = "m3l",
    version,
    about = "M3L parser and validator — parse .m3l, .m3l.md, .md files into JSON AST"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Parse M3L files and output JSON AST
    Parse {
        /// Input path (file or directory, defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Write output to file instead of stdout
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Analyze model dependencies and output a graph
    Analyze {
        /// Input path (file or directory, defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Output format: mermaid (default) or dot
        #[arg(long, default_value = "mermaid")]
        format: String,
    },

    /// Compare two M3L files and show differences
    Diff {
        /// First input file/directory
        left: PathBuf,

        /// Second input file/directory
        right: PathBuf,
    },

    /// Format M3L files into standardized output
    Format {
        /// Input path (file or directory, defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,
    },

    /// Lint M3L files for style and quality issues
    Lint {
        /// Input path (file or directory, defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Output format: human (default) or json
        #[arg(long, default_value = "human")]
        format: String,
    },

    /// Validate M3L files and report diagnostics
    Validate {
        /// Input path (file or directory, defaults to current directory)
        #[arg(default_value = ".")]
        path: PathBuf,

        /// Enable strict style guidelines
        #[arg(long)]
        strict: bool,

        /// Output format: human (default) or json
        #[arg(long, default_value = "human")]
        format: String,
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Parse { path, output } => match run_parse(&path, output.as_deref()) {
            Ok(json) => {
                if output.is_none() {
                    println!("{json}");
                }
            }
            Err(e) => {
                eprintln!("Error: {e}");
                process::exit(1);
            }
        },
        Commands::Analyze { path, format } => {
            match commands::analyze::run_analyze(&path, &format) {
                Ok(output) => {
                    println!("{output}");
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    process::exit(1);
                }
            }
        }
        Commands::Diff { left, right } => match run_diff(&left, &right) {
            Ok(output) => {
                println!("{output}");
            }
            Err(e) => {
                eprintln!("Error: {e}");
                process::exit(1);
            }
        },
        Commands::Format { path } => match commands::format::run_format(&path) {
            Ok(output) => {
                println!("{output}");
            }
            Err(e) => {
                eprintln!("Error: {e}");
                process::exit(1);
            }
        },
        Commands::Lint { path, format } => match commands::lint::run_lint(&path, &format) {
            Ok(output) => {
                println!("{output}");
            }
            Err(e) => {
                eprintln!("Error: {e}");
                process::exit(1);
            }
        },
        Commands::Validate {
            path,
            strict,
            format,
        } => match run_validate(&path, strict, &format) {
            Ok((output, error_count)) => {
                println!("{output}");
                if error_count > 0 {
                    process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Error: {e}");
                process::exit(1);
            }
        },
    }
}

pub fn build_ast(input_path: &Path) -> Result<m3l_core::M3lAst, String> {
    build_ast_with(input_path, m3l_core::ResolveOptions::default())
}

pub fn build_ast_with(
    input_path: &Path,
    options: m3l_core::ResolveOptions,
) -> Result<m3l_core::M3lAst, String> {
    let files = read_m3l_files(input_path)?;

    if files.is_empty() {
        return Err(format!(
            "No M3L files (.m3l, .m3l.md, .md) found at: {}",
            input_path.display()
        ));
    }

    let parsed_files: Vec<_> = files
        .iter()
        .map(|f| parse_string(&f.content, &f.path))
        .collect();

    // Read project config if input is a directory
    let project_info = if input_path.is_dir() {
        read_project_config(input_path).map(|c| ProjectInfo {
            name: c.name,
            version: c.version,
        })
    } else {
        None
    };

    let ast = m3l_core::resolve_with(&parsed_files, project_info, options);

    Ok(ast)
}

fn run_parse(input_path: &Path, output_file: Option<&Path>) -> Result<String, String> {
    let ast = build_ast(input_path)?;
    let json =
        serde_json::to_string_pretty(&ast).map_err(|e| format!("JSON serialization error: {e}"))?;

    if let Some(out_path) = output_file {
        std::fs::write(out_path, &json)
            .map_err(|e| format!("Failed to write {}: {e}", out_path.display()))?;
        return Ok(format!("Written to {}", out_path.display()));
    }

    Ok(json)
}

fn run_diff(left_path: &Path, right_path: &Path) -> Result<String, String> {
    let left_ast = build_ast(left_path)?;
    let right_ast = build_ast(right_path)?;

    let mut lines: Vec<String> = Vec::new();

    // Build name maps
    let left_models: std::collections::HashMap<&str, &m3l_core::ModelNode> = left_ast
        .models
        .iter()
        .chain(left_ast.views.iter())
        .map(|m| (m.name.as_str(), m))
        .collect();
    let right_models: std::collections::HashMap<&str, &m3l_core::ModelNode> = right_ast
        .models
        .iter()
        .chain(right_ast.views.iter())
        .map(|m| (m.name.as_str(), m))
        .collect();

    // Added models
    for name in right_models.keys() {
        if !left_models.contains_key(name) {
            lines.push(format!("+ model {name}"));
        }
    }

    // Removed models
    for name in left_models.keys() {
        if !right_models.contains_key(name) {
            lines.push(format!("- model {name}"));
        }
    }

    // Changed models (field-level diff)
    for (name, left_model) in &left_models {
        if let Some(right_model) = right_models.get(name) {
            let left_fields: std::collections::HashMap<&str, &m3l_core::FieldNode> = left_model
                .fields
                .iter()
                .map(|f| (f.name.as_str(), f))
                .collect();
            let right_fields: std::collections::HashMap<&str, &m3l_core::FieldNode> = right_model
                .fields
                .iter()
                .map(|f| (f.name.as_str(), f))
                .collect();

            for fname in right_fields.keys() {
                if !left_fields.contains_key(fname) {
                    lines.push(format!("+ {name}.{fname}"));
                }
            }
            for fname in left_fields.keys() {
                if !right_fields.contains_key(fname) {
                    lines.push(format!("- {name}.{fname}"));
                }
            }
            for (fname, lf) in &left_fields {
                if let Some(rf) = right_fields.get(fname) {
                    let mut changes = Vec::new();
                    if lf.field_type != rf.field_type {
                        changes.push(format!(
                            "type: {} → {}",
                            lf.field_type.as_deref().unwrap_or("none"),
                            rf.field_type.as_deref().unwrap_or("none")
                        ));
                    }
                    if lf.nullable != rf.nullable {
                        changes.push(format!("nullable: {} → {}", lf.nullable, rf.nullable));
                    }
                    if lf.array != rf.array {
                        changes.push(format!("array: {} → {}", lf.array, rf.array));
                    }
                    if !changes.is_empty() {
                        lines.push(format!("~ {name}.{fname}: {}", changes.join(", ")));
                    }
                }
            }
        }
    }

    // Enum diff
    let left_enums: std::collections::HashMap<&str, &m3l_core::EnumNode> = left_ast
        .enums
        .iter()
        .map(|e| (e.name.as_str(), e))
        .collect();
    let right_enums: std::collections::HashMap<&str, &m3l_core::EnumNode> = right_ast
        .enums
        .iter()
        .map(|e| (e.name.as_str(), e))
        .collect();

    for name in right_enums.keys() {
        if !left_enums.contains_key(name) {
            lines.push(format!("+ enum {name}"));
        }
    }
    for name in left_enums.keys() {
        if !right_enums.contains_key(name) {
            lines.push(format!("- enum {name}"));
        }
    }

    if lines.is_empty() {
        lines.push("No differences found.".into());
    } else {
        lines.sort();
        let add_count = lines.iter().filter(|l| l.starts_with('+')).count();
        let rem_count = lines.iter().filter(|l| l.starts_with('-')).count();
        let mod_count = lines.iter().filter(|l| l.starts_with('~')).count();
        lines.push(format!(
            "\n{} added, {} removed, {} modified",
            add_count, rem_count, mod_count
        ));
    }

    Ok(lines.join("\n"))
}

fn run_validate(input_path: &Path, strict: bool, format: &str) -> Result<(String, usize), String> {
    let files = read_m3l_files(input_path)?;

    if files.is_empty() {
        return Err(format!(
            "No M3L files (.m3l, .m3l.md, .md) found at: {}",
            input_path.display()
        ));
    }

    let parsed_files: Vec<_> = files
        .iter()
        .map(|f| parse_string(&f.content, &f.path))
        .collect();

    let project_info = if input_path.is_dir() {
        read_project_config(input_path).map(|c| ProjectInfo {
            name: c.name,
            version: c.version,
        })
    } else {
        None
    };

    let ast = resolve(&parsed_files, project_info);
    let result = validate(&ast, &ValidateOptions { strict });

    // ValidateResult already includes resolver diagnostics (cloned from AST)
    let error_count = result.errors.len();
    let warning_count = result.warnings.len();
    let file_count = ast.sources.len();

    if format == "json" {
        let diagnostics: Vec<&m3l_core::Diagnostic> =
            result.errors.iter().chain(result.warnings.iter()).collect();
        let output = serde_json::json!({
            "diagnostics": diagnostics,
            "summary": {
                "errors": error_count,
                "warnings": warning_count,
                "files": file_count,
            }
        });
        let json = serde_json::to_string_pretty(&output)
            .map_err(|e| format!("JSON serialization error: {e}"))?;
        return Ok((json, error_count));
    }

    // Human-readable format
    let mut lines: Vec<String> = Vec::new();

    for d in result.errors.iter().chain(result.warnings.iter()) {
        let severity = match d.severity {
            m3l_core::DiagnosticSeverity::Error => "error",
            m3l_core::DiagnosticSeverity::Warning => "warning",
        };
        lines.push(format!(
            "{}:{}:{} {}[{}]: {}",
            d.file, d.line, d.col, severity, d.code, d.message
        ));
    }

    let error_word = if error_count == 1 { "error" } else { "errors" };
    let warning_word = if warning_count == 1 {
        "warning"
    } else {
        "warnings"
    };
    let file_word = if file_count == 1 { "file" } else { "files" };
    lines.push(format!(
        "{error_count} {error_word}, {warning_count} {warning_word} in {file_count} {file_word}."
    ));

    Ok((lines.join("\n"), error_count))
}