Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/weaver_codegen_test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ fn main() {
.unwrap_or_else(|e| process_error(&logger, e));
let config = WeaverConfig::try_from_path("./templates/registry/rust")
.unwrap_or_else(|e| process_error(&logger, e));
let engine = TemplateEngine::new(config, loader, Params::default());
let engine = TemplateEngine::try_new(config, loader, Params::default())
.unwrap_or_else(|e| process_error(&logger, e));
let template_registry =
ResolvedRegistry::try_from_resolved_registry(&schema.registry, schema.catalog())
.unwrap_or_else(|e| process_error(&logger, e));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,6 @@ comment_formats:
default_comment_format: rust

templates:
- template: README.md
filter: .
application_mode: single
- template: lib.rs
filter: .
application_mode: single
- template: attributes/mod.rs.j2
filter: >
if $attributes then
Expand Down
62 changes: 55 additions & 7 deletions crates/weaver_forge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,11 @@ impl TryInto<serde_json::Value> for NewContext<'_> {

impl TemplateEngine {
/// Create a new template engine for the given Weaver config.
pub fn new(
pub fn try_new(
mut config: WeaverConfig,
loader: impl FileLoader + Send + Sync + 'static,
params: Params,
) -> Self {
) -> Result<Self, Error> {
// Compute the params for each template based on:
// - CLI-level params
// - Top-level params in the `weaver.yaml` file
Expand Down Expand Up @@ -228,11 +228,36 @@ impl TemplateEngine {
}
}

Self {
// Validate template files exist
let mut errors = Vec::new();
if let Some(templates) = config.templates.as_ref() {
let all_files = loader.all_files();
for template in templates {
// Check if any files match the template glob pattern
let matcher = template.template.compile_matcher();
let has_matches = all_files.iter().any(|file| matcher.is_match(file));

if !has_matches {
errors.push(InvalidTemplateFile {
template: PathBuf::from(template.template.glob()),
error: format!(
"Template pattern '{}' did not match any files",
template.template.glob()
),
});
}
}
}

if !errors.is_empty() {
return Err(Error::CompoundError(errors));
}

Ok(Self {
file_loader: Arc::new(loader),
target_config: config,
snippet_params: params,
}
})
}

/// Generate a template snippet from serializable context and a snippet identifier.
Expand Down Expand Up @@ -337,6 +362,10 @@ impl TemplateEngine {
output_dir: &Path,
output_directive: &OutputDirective,
) -> Result<(), Error> {
log::debug!(
"Processing template file: {template_file:#?}, output directory: {output_dir:#?}"
);

let yaml_params = Self::init_params(template.params.clone())?;
let params = Self::prepare_jq_context(&yaml_params)?;
let filter = Filter::new(template.filter.as_str());
Expand Down Expand Up @@ -729,7 +758,8 @@ mod tests {
let loader = FileSystemFileLoader::try_new("templates".into(), target)
.expect("Failed to create file system loader");
let config = WeaverConfig::try_from_path(format!("templates/{target}")).unwrap();
let engine = TemplateEngine::new(config, loader, cli_params);
let engine = TemplateEngine::try_new(config, loader, cli_params)
.expect("Failed to create template engine");
let schema = SchemaResolver::resolve_semantic_convention_registry(&mut registry, false)
.into_result_failing_non_fatal()
.expect("Failed to resolve registry");
Expand Down Expand Up @@ -884,7 +914,8 @@ mod tests {
.expect("Failed to create file system loader");
let config =
WeaverConfig::try_from_loader(&loader).expect("Failed to load `templates/weaver.yaml`");
let mut engine = TemplateEngine::new(config, loader, Params::default());
let mut engine = TemplateEngine::try_new(config, loader, Params::default())
.expect("Failed to create template engine");

// Add a template configuration for converter.md on top
// of the default template configuration. This is useful
Expand Down Expand Up @@ -956,7 +987,8 @@ mod tests {
let loader = FileSystemFileLoader::try_new("templates".into(), "py_compat")
.expect("Failed to create file system loader");
let config = WeaverConfig::try_from_loader(&loader).unwrap();
let engine = TemplateEngine::new(config, loader, Params::default());
let engine = TemplateEngine::try_new(config, loader, Params::default())
.expect("Failed to create template engine");
let context = Context {
text: "Hello, World!".to_owned(),
};
Expand Down Expand Up @@ -1045,4 +1077,20 @@ mod tests {

assert!(diff_dir(expected_output, observed_output).unwrap());
}

#[test]
fn test_wrong_config() {
let loader = FileSystemFileLoader::try_new("templates".into(), "wrong_config")
.expect("Failed to create file system loader");
let config = WeaverConfig::try_from_path("templates/wrong_config").unwrap();
let result = TemplateEngine::try_new(config, loader, Params::default());
assert!(result.is_err());
let error = result.err().unwrap();

let msg = format!("{error}");
assert!(
msg.contains("Template pattern 'does-not-exist.j2' did not match any files"),
"Unexpected error message - {msg}"
);
}
}
42 changes: 0 additions & 42 deletions crates/weaver_forge/templates/whitespace_control/weaver.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,45 +25,3 @@ templates:
- template: "**/registry.md"
filter: "."
application_mode: single
- template: "**/attribute_group.md"
filter: ".groups[] | select(.type == \"attribute_group\")"
application_mode: each
- template: "**/attribute_groups.md"
filter: ".groups[] | select(.type == \"attribute_group\")"
application_mode: single
- template: "**/event.md"
filter: ".groups[] | select(.type == \"event\")"
application_mode: each
- template: "**/events.md"
filter: ".groups[] | select(.type == \"event\")"
application_mode: single
- template: "**/group.md"
filter: ".groups"
application_mode: each
- template: "**/groups.md"
filter: ".groups"
application_mode: single
- template: "**/metric.md"
filter: ".groups[] | select(.type == \"metric\")"
application_mode: each
- template: "**/metrics.md"
filter: ".groups[] | select(.type == \"metric\")"
application_mode: single
- template: "**/resource.md"
filter: ".groups[] | select(.type == \"entity\")"
application_mode: each
- template: "**/resources.md"
filter: ".groups[] | select(.type == \"entity\")"
application_mode: single
- template: "**/scope.md"
filter: ".groups[] | select(.type == \"scope\")"
application_mode: each
- template: "**/scopes.md"
filter: ".groups[] | select(.type == \"scope\")"
application_mode: single
- template: "**/span.md"
filter: ".groups[] | select(.type == \"span\")"
application_mode: each
- template: "**/spans.md"
filter: ".groups[] | select(.type == \"span\")"
application_mode: single
1 change: 1 addition & 0 deletions crates/weaver_forge/templates/wrong_config/exists.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ ctx | tojson(indent=true) }}
8 changes: 8 additions & 0 deletions crates/weaver_forge/templates/wrong_config/weaver.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
templates:
- template: "does-not-exist.j2"
filter: "."
application_mode: single

- template: "exists.j2"
filter: "."
application_mode: single
2 changes: 1 addition & 1 deletion crates/weaver_semconv_gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ mod tests {
.insert("test".to_owned(), Value::String("param".to_owned()));
p
};
let template = TemplateEngine::new(config, loader, params);
let template = TemplateEngine::try_new(config, loader, params)?;
let registry_path = VirtualDirectoryPath::LocalFolder {
path: "data".to_owned(),
};
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ fn main() {
.format(|buf, record| writeln!(buf, "{}", record.args()))
.init();

log_error(format!("Debug is set to {}", cli.debug));
log::debug!("Debug is set to {}", cli.debug);
}

// Force the `miette` context to 5 lines.
Expand Down Expand Up @@ -170,7 +170,7 @@ fn print_diagnostics(
.expect("Failed to create the embedded file loader for the diagnostic templates");
let config = WeaverConfig::try_from_loader(&loader)
.expect("Failed to load `defaults/diagnostic_templates/weaver.yaml`");
let engine = TemplateEngine::new(config, loader, Params::default());
let engine = TemplateEngine::try_new(config, loader, Params::default())?;
let output_directive = if diagnostic_args.diagnostic_stdout {
OutputDirective::Stdout
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/registry/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub(crate) fn command(args: &RegistryDiffArgs) -> Result<ExitDirectives, Diagnos
.expect("Failed to create the embedded file loader for the diff templates");
let config = WeaverConfig::try_from_loader(&loader)
.expect("Failed to load `defaults/diff_templates/weaver.yaml`");
let engine = TemplateEngine::new(config, loader, Params::default());
let engine = TemplateEngine::try_new(config, loader, Params::default())?;

match engine.generate(&changes, output.as_path(), &output_directive) {
Ok(_) => {}
Expand Down
2 changes: 1 addition & 1 deletion src/registry/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ pub(crate) fn command(args: &RegistryGenerateArgs) -> Result<ExitDirectives, Dia
} else {
WeaverConfig::try_from_path(loader.root())
}?;
let engine = TemplateEngine::new(config, loader, params);
let engine = TemplateEngine::try_new(config, loader, params)?;

engine.generate(
&template_registry,
Expand Down
2 changes: 1 addition & 1 deletion src/registry/live_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ pub(crate) fn command(args: &RegistryLiveCheckArgs) -> Result<ExitDirectives, Di
error: format!("Failed to load `defaults/live_check_templates/weaver.yaml`: {e}"),
})
})?;
let engine = TemplateEngine::new(config, loader, Params::default());
let engine = TemplateEngine::try_new(config, loader, Params::default())?;

// Prepare the ingester
let ingester = match (&args.input_source, &args.input_format) {
Expand Down
2 changes: 1 addition & 1 deletion src/registry/update_markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub(crate) fn command(
let loader =
FileSystemFileLoader::try_new(templates_dir.path().join("registry"), &args.target)?;
let config = WeaverConfig::try_from_loader(&loader)?;
TemplateEngine::new(config, loader, params)
TemplateEngine::try_new(config, loader, params)?
};

let registry_path = &args.registry.registry;
Expand Down
Loading