braze-sync 0.12.0

GitOps CLI for managing Braze configuration as code
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! `braze-sync validate` — local-only structural and naming checks.
//!
//! Runs without a Braze API key so CI on fork PRs (where the secret
//! isn't available) can still gate merges. Issues are collected across
//! the whole run and reported at the end so a single pass surfaces
//! every problem.

use crate::config::ConfigFile;
use crate::error::Error;
use crate::fs::{
    catalog_io, content_block_io, custom_attribute_io, email_template_io, tag_io,
    try_read_resource_dir,
};
use crate::resource::ResourceKind;
use anyhow::anyhow;
use clap::Args;
use regex_lite::Regex;
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use super::selected_kinds;

#[derive(Args, Debug)]
pub struct ValidateArgs {
    /// Limit validation to a specific resource kind.
    #[arg(long, value_enum)]
    pub resource: Option<ResourceKind>,
}

#[derive(Debug)]
struct ValidationIssue {
    path: PathBuf,
    message: String,
}

pub async fn run(args: &ValidateArgs, cfg: &ConfigFile, config_dir: &Path) -> anyhow::Result<()> {
    let kinds = selected_kinds(args.resource, &cfg.resources);

    let mut issues: Vec<ValidationIssue> = Vec::new();

    for kind in kinds {
        match kind {
            ResourceKind::CatalogSchema => {
                let catalogs_root = config_dir.join(&cfg.resources.catalog_schema.path);
                let excludes = compile_kind_excludes(cfg, kind)?;
                validate_catalog_schemas(
                    &catalogs_root,
                    cfg.naming.catalog_name_pattern.as_deref(),
                    &excludes,
                    &mut issues,
                )?;
            }
            ResourceKind::ContentBlock => {
                let content_blocks_root = config_dir.join(&cfg.resources.content_block.path);
                let excludes = compile_kind_excludes(cfg, kind)?;
                validate_content_blocks(
                    &content_blocks_root,
                    cfg.naming.content_block_name_pattern.as_deref(),
                    &excludes,
                    &mut issues,
                )?;
            }
            ResourceKind::EmailTemplate => {
                let email_templates_root = config_dir.join(&cfg.resources.email_template.path);
                let excludes = compile_kind_excludes(cfg, kind)?;
                validate_email_templates(&email_templates_root, &excludes, &mut issues)?;
            }
            ResourceKind::CustomAttribute => {
                let registry_path = config_dir.join(&cfg.resources.custom_attribute.path);
                let excludes = compile_kind_excludes(cfg, kind)?;
                validate_custom_attributes(
                    &registry_path,
                    cfg.naming.custom_attribute_name_pattern.as_deref(),
                    &excludes,
                    &mut issues,
                )?;
            }
            ResourceKind::Tag => {
                let registry_path = config_dir.join(&cfg.resources.tag.path);
                let excludes = compile_kind_excludes(cfg, kind)?;
                validate_tags(
                    cfg,
                    config_dir,
                    &registry_path,
                    cfg.naming.tag_name_pattern.as_deref(),
                    &excludes,
                    &mut issues,
                )?;
            }
        }
    }

    if issues.is_empty() {
        eprintln!("✓ All checks passed.");
        return Ok(());
    }

    eprintln!("✗ Validation found {} issue(s):", issues.len());
    for issue in &issues {
        eprintln!("{}: {}", issue.path.display(), issue.message);
    }

    Err(Error::Config(format!("{} validation issue(s) found", issues.len())).into())
}

fn compile_kind_excludes(cfg: &ConfigFile, kind: ResourceKind) -> anyhow::Result<Vec<Regex>> {
    Ok(crate::config::compile_exclude_patterns(
        &cfg.resources.for_kind(kind).exclude_patterns,
        kind.as_str(),
    )?)
}

/// Try to open a resource root directory. Returns `None` (and pushes an
/// issue) when the path is missing or is a file — callers should return
/// `Ok(())` in that case.
fn open_resource_dir(
    root: &Path,
    kind_label: &str,
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<Option<std::fs::ReadDir>> {
    match try_read_resource_dir(root, kind_label) {
        Ok(rd) => Ok(rd),
        Err(Error::InvalidFormat { path, message }) => {
            issues.push(ValidationIssue { path, message });
            Ok(None)
        }
        Err(e) => Err(e.into()),
    }
}

/// Compile an optional naming-pattern regex, returning the raw string
/// alongside the compiled `Regex` so error messages can reference the
/// original pattern.  `config_key` names the config field for the error
/// message (e.g. `"catalog_name_pattern"`).
fn compile_name_pattern(
    raw: Option<&str>,
    config_key: &str,
) -> anyhow::Result<Option<(String, Regex)>> {
    match raw {
        Some(p) => Ok(Some((
            p.to_string(),
            Regex::new(p).map_err(|e| anyhow!("invalid {config_key} regex {p:?}: {e}"))?,
        ))),
        None => Ok(None),
    }
}

/// Check `name` against the compiled pattern and push a uniform
/// "does not match <config_key>" issue when it fails. `kind_label` is
/// the human-readable resource noun for the message (e.g. `"catalog"`).
fn check_name_pattern(
    pattern: Option<&(String, Regex)>,
    name: &str,
    path: &Path,
    kind_label: &str,
    config_key: &str,
    issues: &mut Vec<ValidationIssue>,
) {
    let Some((pattern_str, re)) = pattern else {
        return;
    };
    if !re.is_match(name) {
        issues.push(ValidationIssue {
            path: path.to_path_buf(),
            message: format!(
                "{kind_label} name '{name}' does not match {config_key} '{pattern_str}'"
            ),
        });
    }
}

fn validate_catalog_schemas(
    catalogs_root: &Path,
    name_pattern: Option<&str>,
    excludes: &[Regex],
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<()> {
    let Some(read_dir) = open_resource_dir(catalogs_root, "catalogs", issues)? else {
        return Ok(());
    };

    let pattern = compile_name_pattern(name_pattern, "catalog_name_pattern")?;

    for entry in read_dir {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            tracing::debug!(path = %entry.path().display(), "skipping non-directory entry");
            continue;
        }
        let dir = entry.path();
        let schema_path = dir.join("schema.yaml");
        if !schema_path.is_file() {
            continue;
        }

        let cat = match catalog_io::read_schema_file(&schema_path) {
            Ok(c) => c,
            Err(e) => {
                issues.push(ValidationIssue {
                    path: schema_path.clone(),
                    message: format!("parse error: {e}"),
                });
                continue;
            }
        };

        // Exclude is checked AFTER parse so a malformed file still
        // surfaces — excludes mean "don't enforce rules on this name",
        // not "silence this file". A broken YAML is a workspace problem
        // regardless of whether the resource is managed out of band.
        if crate::config::is_excluded(&cat.name, excludes) {
            continue;
        }

        // load_all_schemas treats dir/name mismatch as a hard error;
        // here we downgrade to a soft issue so a single run reports
        // every bad file.
        let dir_name = entry.file_name().to_string_lossy().into_owned();
        if cat.name != dir_name {
            issues.push(ValidationIssue {
                path: schema_path.clone(),
                message: format!(
                    "catalog name '{}' does not match its directory '{}'",
                    cat.name, dir_name
                ),
            });
        }

        check_name_pattern(
            pattern.as_ref(),
            &cat.name,
            &schema_path,
            "catalog",
            "catalog_name_pattern",
            issues,
        );
    }

    Ok(())
}

fn validate_content_blocks(
    content_blocks_root: &Path,
    name_pattern: Option<&str>,
    excludes: &[Regex],
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<()> {
    let Some(read_dir) = open_resource_dir(content_blocks_root, "content_blocks", issues)? else {
        return Ok(());
    };

    let pattern = compile_name_pattern(name_pattern, "content_block_name_pattern")?;

    for entry in read_dir {
        let entry = entry?;
        let path = entry.path();
        if !entry.file_type()?.is_file() {
            tracing::debug!(path = %path.display(), "skipping non-file entry");
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) != Some("liquid") {
            continue;
        }
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default()
            .to_string();

        let cb = match content_block_io::read_content_block_file(&path) {
            Ok(cb) => cb,
            Err(e) => {
                issues.push(ValidationIssue {
                    path: path.clone(),
                    message: format!("parse error: {e}"),
                });
                continue;
            }
        };

        if crate::config::is_excluded(&cb.name, excludes) {
            continue;
        }

        if cb.name != stem {
            issues.push(ValidationIssue {
                path: path.clone(),
                message: format!(
                    "content block name '{}' does not match its file stem '{}'",
                    cb.name, stem
                ),
            });
        }

        check_name_pattern(
            pattern.as_ref(),
            &cb.name,
            &path,
            "content block",
            "content_block_name_pattern",
            issues,
        );
    }

    Ok(())
}

fn validate_email_templates(
    email_templates_root: &Path,
    excludes: &[Regex],
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<()> {
    let Some(read_dir) = open_resource_dir(email_templates_root, "email_templates", issues)? else {
        return Ok(());
    };

    for entry in read_dir {
        let entry = entry?;
        let path = entry.path();
        if !entry.file_type()?.is_dir() {
            tracing::debug!(path = %path.display(), "skipping non-directory entry");
            continue;
        }
        let template_yaml_path = path.join("template.yaml");
        if !template_yaml_path.is_file() {
            continue;
        }
        let dir_name = entry.file_name().to_string_lossy().into_owned();

        let et = match email_template_io::read_email_template_dir(&path) {
            Ok(et) => et,
            Err(e) => {
                issues.push(ValidationIssue {
                    path: template_yaml_path.clone(),
                    message: format!("parse error: {e}"),
                });
                continue;
            }
        };

        if crate::config::is_excluded(&et.name, excludes) {
            continue;
        }

        if et.name != dir_name {
            issues.push(ValidationIssue {
                path: template_yaml_path.clone(),
                message: format!(
                    "email template name '{}' does not match its directory '{}'",
                    et.name, dir_name
                ),
            });
        }

        if et.subject.is_empty() {
            issues.push(ValidationIssue {
                path: template_yaml_path.clone(),
                message: format!("email template '{}' has an empty subject", et.name),
            });
        }
    }

    Ok(())
}

/// Tag-resource validation. Two checks:
///   1. Structural — the registry parses, has no duplicate names, and
///      every name matches the configured naming pattern.
///   2. Cross-reference — every tag referenced by a content_block or
///      email_template frontmatter exists in the registry. **This is the
///      check that prevents the "tag not found in Braze" apply failure
///      from happening in CI.**
fn validate_tags(
    cfg: &ConfigFile,
    config_dir: &Path,
    registry_path: &Path,
    name_pattern: Option<&str>,
    excludes: &[Regex],
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<()> {
    let registry_opt = match tag_io::load_registry(registry_path) {
        Ok(r) => r,
        Err(Error::YamlParse { path, source }) => {
            issues.push(ValidationIssue {
                path,
                message: format!("parse error: {source}"),
            });
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };

    if let Some(registry) = &registry_opt {
        let pattern = compile_name_pattern(name_pattern, "tag_name_pattern")?;
        let mut seen = HashSet::with_capacity(registry.tags.len());
        for t in &registry.tags {
            if crate::config::is_excluded(&t.name, excludes) {
                continue;
            }
            if !seen.insert(t.name.as_str()) {
                issues.push(ValidationIssue {
                    path: registry_path.to_path_buf(),
                    message: format!("duplicate tag name '{}'", t.name),
                });
            }
            check_name_pattern(
                pattern.as_ref(),
                &t.name,
                registry_path,
                "tag",
                "tag_name_pattern",
                issues,
            );
        }
    }

    // Resources matching their own kind's exclude_patterns are still
    // checked: the apply path doesn't skip them, so neither does this.
    if cfg.resources.content_block.enabled {
        let root = config_dir.join(&cfg.resources.content_block.path);
        walk_for_tag_refs(&root, "content_block", issues, |p| {
            if !p.is_file() || p.extension().and_then(|e| e.to_str()) != Some("liquid") {
                return Ok(None);
            }
            let cb = content_block_io::read_content_block_file(p)?;
            Ok(Some((cb.name, cb.tags)))
        })?
        .into_iter()
        .for_each(|(p, name, tags)| {
            check_resource_tags(
                registry_opt.as_ref(),
                excludes,
                &p,
                "content_block",
                &name,
                &tags,
                issues,
            );
        });
    }
    if cfg.resources.email_template.enabled {
        let root = config_dir.join(&cfg.resources.email_template.path);
        walk_for_tag_refs(&root, "email_template", issues, |p| {
            if !p.is_dir() || !p.join("template.yaml").is_file() {
                return Ok(None);
            }
            let et = email_template_io::read_email_template_dir(p)?;
            Ok(Some((et.name, et.tags)))
        })?
        .into_iter()
        .for_each(|(p, name, tags)| {
            check_resource_tags(
                registry_opt.as_ref(),
                excludes,
                &p,
                "email_template",
                &name,
                &tags,
                issues,
            );
        });
    }

    Ok(())
}

/// Walk a resource directory, skipping non-resource entries. The reader
/// returns `Ok(None)` for entries that aren't a resource of the kind,
/// `Ok(Some((name, tags)))` for valid ones, and `Err` for parse failures
/// (folded into `issues` so a single malformed file doesn't hide the
/// rest from `validate --resource tag`).
fn walk_for_tag_refs<F>(
    root: &Path,
    kind: &str,
    issues: &mut Vec<ValidationIssue>,
    mut read: F,
) -> anyhow::Result<Vec<(PathBuf, String, Vec<String>)>>
where
    F: FnMut(&Path) -> Result<Option<(String, Vec<String>)>, Error>,
{
    let mut out = Vec::new();
    let Some(rd) = try_read_resource_dir(root, kind)? else {
        return Ok(out);
    };
    for entry in rd.flatten() {
        let p = entry.path();
        match read(&p) {
            Ok(Some((name, tags))) => out.push((p, name, tags)),
            Ok(None) => {}
            Err(Error::YamlParse { path, source }) => issues.push(ValidationIssue {
                path,
                message: format!("parse error: {source}"),
            }),
            Err(e) => return Err(e.into()),
        }
    }
    Ok(out)
}

fn check_resource_tags(
    registry: Option<&crate::resource::TagRegistry>,
    excludes: &[Regex],
    path: &Path,
    kind: &str,
    resource_name: &str,
    tags: &[String],
    issues: &mut Vec<ValidationIssue>,
) {
    for t in tags {
        if crate::config::is_excluded(t, excludes) {
            continue;
        }
        let in_registry = registry.is_some_and(|r| r.contains(t));
        if !in_registry {
            issues.push(ValidationIssue {
                path: path.to_path_buf(),
                message: format!(
                    "{kind} '{resource_name}' references tag '{t}' which is not declared in tags/registry.yaml \
                     (apply will fail with HTTP 400 until the tag is created in the Braze dashboard \
                     and added to the registry)"
                ),
            });
        }
    }
}

fn validate_custom_attributes(
    registry_path: &Path,
    name_pattern: Option<&str>,
    excludes: &[Regex],
    issues: &mut Vec<ValidationIssue>,
) -> anyhow::Result<()> {
    let registry = match custom_attribute_io::load_registry(registry_path) {
        Ok(Some(r)) => r,
        Ok(None) => return Ok(()),
        Err(Error::YamlParse { path, source }) => {
            issues.push(ValidationIssue {
                path,
                message: format!("parse error: {source}"),
            });
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };

    let pattern = compile_name_pattern(name_pattern, "custom_attribute_name_pattern")?;

    let mut seen = HashSet::with_capacity(registry.attributes.len());
    for attr in &registry.attributes {
        if crate::config::is_excluded(&attr.name, excludes) {
            continue;
        }
        if !seen.insert(attr.name.as_str()) {
            issues.push(ValidationIssue {
                path: registry_path.to_path_buf(),
                message: format!("duplicate custom attribute name '{}'", attr.name),
            });
        }

        check_name_pattern(
            pattern.as_ref(),
            &attr.name,
            registry_path,
            "custom attribute",
            "custom_attribute_name_pattern",
            issues,
        );
    }

    Ok(())
}