use anyhow::{Context, Result};
use clap::{Args, ValueEnum};
use std::fs;
use std::path::PathBuf;
#[derive(Args)]
pub struct ParseArgs {
#[arg(required = true)]
pub input: PathBuf,
#[arg(long, value_enum, default_value_t = ParseFormat::Human)]
pub format: ParseFormat,
#[arg(long, short)]
pub out: Option<PathBuf>,
#[arg(long)]
pub ast: bool,
#[arg(long)]
pub ast_v3: bool,
}
#[derive(ValueEnum, Clone, Debug, Copy, Default)]
pub enum ParseFormat {
#[default]
Human,
Json,
}
pub fn run(args: ParseArgs) -> Result<()> {
let source = fs::read_to_string(&args.input)
.with_context(|| format!("Failed to read file: {}", args.input.display()))?;
let graph = || -> Result<crate::Graph> {
let registry = crate::NamespaceRegistry::discover(&args.input)
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
let default_namespace = registry
.as_ref()
.and_then(|registry| registry.namespace_for(&args.input));
crate::application::resolve::resolve_filesystem_graph(
&args.input,
&source,
registry.as_ref(),
default_namespace,
)
.map_err(|diagnostics| {
anyhow::anyhow!(
"Parse error: {}",
diagnostics
.iter()
.map(|diagnostic| diagnostic.message.as_str())
.collect::<Vec<_>>()
.join("; ")
)
})
};
let output = match (args.ast || args.ast_v3, args.format) {
(true, ParseFormat::Json) => {
let internal_ast =
crate::parser::parse(&source).map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;
let schema_ast: crate::parser::ast_schema::Ast = internal_ast.into();
serde_json::to_string_pretty(&schema_ast).context("Failed to serialize AST to JSON")?
}
(true, ParseFormat::Human) => {
let ast =
crate::parser::parse(&source).map_err(|e| anyhow::anyhow!("Parse error: {}", e))?;
format!(
"AST parsed successfully: {}\n\
Namespace: {}\n\
Version: {}\n\
Declarations: {}",
args.input.display(),
ast.metadata.namespace.as_deref().unwrap_or("(none)"),
ast.metadata.version.as_deref().unwrap_or("(none)"),
ast.declarations.len()
)
}
(false, ParseFormat::Json) => {
let graph = graph()?;
serde_json::to_string_pretty(&graph).context("Failed to serialize Graph to JSON")?
}
(false, ParseFormat::Human) => {
let graph = graph()?;
format!(
"Graph parsed successfully: {}\n\
Entities: {}\n\
Resources: {}\n\
Flows: {}\n\
Roles: {}\n\
Relations: {}\n\
Resource instances: {}\n\
Entity instances: {}\n\
Policies: {}\n\
Patterns: {}",
args.input.display(),
graph.entity_count(),
graph.resource_count(),
graph.flow_count(),
graph.role_count(),
graph.relation_count(),
graph.instance_count(),
graph.entity_instance_count(),
graph.policy_count(),
graph.pattern_count()
)
}
};
match args.out {
Some(path) => {
fs::write(&path, &output)
.with_context(|| format!("Failed to write to: {}", path.display()))?;
eprintln!("Wrote output to: {}", path.display());
}
None => {
println!("{}", output);
}
}
Ok(())
}