Skip to main content

braze_sync/cli/
init.rs

1//! `braze-sync init` — scaffold a new braze-sync workspace.
2
3use crate::config::ConfigFile;
4use anyhow::{bail, Context as _};
5use clap::Args;
6use std::fs;
7use std::io::Write as _;
8use std::path::{Path, PathBuf};
9
10#[derive(Args, Debug)]
11pub struct InitArgs {
12    /// Overwrite an existing `braze-sync.config.yaml`. Directories and
13    /// `.gitignore` are updated idempotently regardless.
14    #[arg(long, conflicts_with = "from_existing")]
15    pub force: bool,
16
17    /// After scaffolding, pull the current state from Braze into the new
18    /// layout. Requires the API key env var from the scaffolded config
19    /// (by default `BRAZE_DEV_API_KEY`) to be set.
20    #[arg(long)]
21    pub from_existing: bool,
22}
23
24pub async fn run(
25    args: &InitArgs,
26    config_path: &Path,
27    env_override: Option<&str>,
28) -> anyhow::Result<()> {
29    let config_dir = config_path
30        .parent()
31        .filter(|p| !p.as_os_str().is_empty())
32        .map(Path::to_path_buf)
33        .unwrap_or_else(|| PathBuf::from("."));
34
35    fs::create_dir_all(&config_dir)
36        .with_context(|| format!("creating config directory {}", config_dir.display()))?;
37
38    // --force and --from-existing are mutually exclusive (clap-enforced)
39    // to prevent silently discarding operator edits.
40    let on_existing = match (args.force, args.from_existing) {
41        (true, _) => OnExisting::Overwrite,
42        (false, true) => OnExisting::Keep,
43        (false, false) => OnExisting::Fail,
44    };
45    let config_written = write_config_file(config_path, on_existing)?;
46    scaffold_resource_dirs(&config_dir)?;
47    let gitignore_updated = update_gitignore(&config_dir)?;
48
49    eprintln!(
50        "✓ config:     {} ({})",
51        config_path.display(),
52        if config_written {
53            "written"
54        } else {
55            "exists, kept"
56        }
57    );
58    eprintln!("✓ directories: ensured");
59    eprintln!(
60        "✓ .gitignore: {}",
61        if gitignore_updated {
62            "updated"
63        } else {
64            "already has entries"
65        }
66    );
67
68    if args.from_existing {
69        if config_written {
70            eprintln!(
71                "⚠ --from-existing is using the freshly-scaffolded config — \
72                 the template's default endpoint will be hit. \
73                 Edit {} first if your Braze instance is elsewhere.",
74                config_path.display()
75            );
76        }
77        eprintln!("✓ --from-existing: loading config and pulling Braze state…");
78        run_from_existing(config_path, &config_dir, env_override).await?;
79    } else {
80        eprintln!();
81        eprintln!("Next steps:");
82        eprintln!("  1. export BRAZE_DEV_API_KEY=<your key>");
83        eprintln!("  2. braze-sync export            # pull current Braze state");
84        eprintln!("  3. braze-sync diff              # preview drift");
85    }
86
87    Ok(())
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91enum OnExisting {
92    Overwrite,
93    Keep,
94    Fail,
95}
96
97fn write_config_file(config_path: &Path, on_existing: OnExisting) -> anyhow::Result<bool> {
98    if config_path.exists() {
99        match on_existing {
100            OnExisting::Overwrite => {
101                eprintln!("⚠ {} exists; overwriting (--force)", config_path.display());
102            }
103            OnExisting::Keep => return Ok(false),
104            OnExisting::Fail => bail!(
105                "{} already exists; pass --force to overwrite",
106                config_path.display()
107            ),
108        }
109    }
110    fs::write(config_path, CONFIG_TEMPLATE)
111        .with_context(|| format!("writing config to {}", config_path.display()))?;
112    Ok(true)
113}
114
115const SUBDIRS: [&str; 4] = [
116    "catalogs",
117    "content_blocks",
118    "email_templates",
119    "custom_attributes",
120];
121
122const GITIGNORE_ENTRIES: [&str; 2] = [".env", ".env.*"];
123
124fn scaffold_resource_dirs(config_dir: &Path) -> anyhow::Result<()> {
125    for sub in SUBDIRS {
126        let dir = config_dir.join(sub);
127        fs::create_dir_all(&dir)
128            .with_context(|| format!("creating directory {}", dir.display()))?;
129    }
130    Ok(())
131}
132
133fn update_gitignore(config_dir: &Path) -> anyhow::Result<bool> {
134    let path = config_dir.join(".gitignore");
135
136    let existing = match fs::read_to_string(&path) {
137        Ok(s) => s,
138        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
139        Err(e) => {
140            return Err(e).with_context(|| format!("reading {}", path.display()));
141        }
142    };
143
144    let has_line = |needle: &str| existing.lines().any(|l| l.trim() == needle);
145    let missing: Vec<&str> = GITIGNORE_ENTRIES
146        .iter()
147        .copied()
148        .filter(|e| !has_line(e))
149        .collect();
150    if missing.is_empty() {
151        return Ok(false);
152    }
153
154    let mut f = fs::OpenOptions::new()
155        .create(true)
156        .append(true)
157        .open(&path)
158        .with_context(|| format!("opening {} for append", path.display()))?;
159
160    let prefix = match (existing.is_empty(), existing.ends_with('\n')) {
161        (true, _) => "# braze-sync\n",
162        (false, true) => "\n# braze-sync\n",
163        (false, false) => "\n\n# braze-sync\n",
164    };
165    f.write_all(prefix.as_bytes())?;
166    for entry in missing {
167        writeln!(f, "{entry}")?;
168    }
169    Ok(true)
170}
171
172async fn run_from_existing(
173    config_path: &Path,
174    config_dir: &Path,
175    env_override: Option<&str>,
176) -> anyhow::Result<()> {
177    let cfg = ConfigFile::load(config_path)
178        .with_context(|| format!("loading config from {}", config_path.display()))?;
179    let resolved = cfg
180        .resolve(env_override)
181        .context("resolving environment for --from-existing")?;
182
183    super::export::run(&super::export::ExportArgs::default(), resolved, config_dir).await
184}
185
186const CONFIG_TEMPLATE: &str = r#"# braze-sync configuration (v1 schema, frozen at v1.0).
187
188version: 1
189
190# Environment picked when --env is not passed.
191default_environment: dev
192
193defaults:
194  # Requests/minute cap applied via governor. Lower if you hit 429s.
195  rate_limit_per_minute: 40
196
197environments:
198  dev:
199    # Braze REST endpoint for your instance. See:
200    # https://www.braze.com/docs/api/basics/#endpoints
201    api_endpoint: https://rest.fra-02.braze.eu
202    # Name of the env var holding the API key — NEVER put the key itself
203    # in this file.
204    api_key_env: BRAZE_DEV_API_KEY
205  # prod:
206  #   api_endpoint: https://rest.fra-02.braze.eu
207  #   api_key_env: BRAZE_PROD_API_KEY
208  #   rate_limit_per_minute: 30
209
210resources:
211  catalog_schema:
212    enabled: true
213    path: catalogs/
214  catalog_items:
215    enabled: true
216    parallel_batches: 4
217  content_block:
218    enabled: true
219    path: content_blocks/
220  email_template:
221    enabled: true
222    path: email_templates/
223  custom_attribute:
224    enabled: true
225    path: custom_attributes/registry.yaml
226
227# Optional name validators enforced by `braze-sync validate`.
228# naming:
229#   catalog_name_pattern: "^[a-z][a-z0-9_]*$"
230#   content_block_name_pattern: "^[a-zA-Z0-9_]+$"
231#   custom_attribute_name_pattern: "^[a-z][a-z0-9_]*$"
232"#;
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn config_template_parses_as_valid_config() {
240        let tmp = tempfile::tempdir().unwrap();
241        let path = tmp.path().join("braze-sync.config.yaml");
242        fs::write(&path, CONFIG_TEMPLATE).unwrap();
243        let cfg = ConfigFile::load(&path).unwrap();
244        assert_eq!(cfg.version, 1);
245        assert_eq!(cfg.default_environment, "dev");
246        assert!(cfg.environments.contains_key("dev"));
247    }
248
249    #[test]
250    fn gitignore_entries_added_on_fresh_file() {
251        let tmp = tempfile::tempdir().unwrap();
252        let updated = update_gitignore(tmp.path()).unwrap();
253        assert!(updated);
254        let content = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
255        assert!(content.contains(".env"));
256        assert!(content.contains(".env.*"));
257    }
258
259    #[test]
260    fn gitignore_idempotent_on_second_run() {
261        let tmp = tempfile::tempdir().unwrap();
262        let first = update_gitignore(tmp.path()).unwrap();
263        assert!(first);
264        let second = update_gitignore(tmp.path()).unwrap();
265        assert!(!second);
266    }
267
268    #[test]
269    fn gitignore_preserves_existing_content() {
270        let tmp = tempfile::tempdir().unwrap();
271        let path = tmp.path().join(".gitignore");
272        fs::write(&path, "target/\ndist/\n").unwrap();
273        update_gitignore(tmp.path()).unwrap();
274        let content = fs::read_to_string(&path).unwrap();
275        assert!(content.contains("target/"));
276        assert!(content.contains("dist/"));
277        assert!(content.contains(".env"));
278    }
279
280    #[test]
281    fn gitignore_skips_already_present_entry() {
282        let tmp = tempfile::tempdir().unwrap();
283        let path = tmp.path().join(".gitignore");
284        fs::write(&path, ".env\n").unwrap();
285        let updated = update_gitignore(tmp.path()).unwrap();
286        assert!(updated);
287        let content = fs::read_to_string(&path).unwrap();
288        let count = content.lines().filter(|l| l.trim() == ".env").count();
289        assert_eq!(count, 1);
290        assert!(content.contains(".env.*"));
291    }
292
293    #[test]
294    fn scaffold_creates_all_four_dirs() {
295        let tmp = tempfile::tempdir().unwrap();
296        scaffold_resource_dirs(tmp.path()).unwrap();
297        for sub in SUBDIRS {
298            assert!(tmp.path().join(sub).is_dir());
299        }
300    }
301
302    #[test]
303    fn scaffold_is_idempotent() {
304        let tmp = tempfile::tempdir().unwrap();
305        scaffold_resource_dirs(tmp.path()).unwrap();
306        scaffold_resource_dirs(tmp.path()).unwrap();
307    }
308
309    #[test]
310    fn write_config_refuses_to_overwrite_without_force() {
311        let tmp = tempfile::tempdir().unwrap();
312        let path = tmp.path().join("braze-sync.config.yaml");
313        fs::write(&path, "version: 1\n# user edits\n").unwrap();
314        let err = write_config_file(&path, OnExisting::Fail).unwrap_err();
315        assert!(err.to_string().contains("--force"));
316        let content = fs::read_to_string(&path).unwrap();
317        assert!(content.contains("user edits"));
318    }
319
320    #[test]
321    fn write_config_overwrites_with_force() {
322        let tmp = tempfile::tempdir().unwrap();
323        let path = tmp.path().join("braze-sync.config.yaml");
324        fs::write(&path, "# old\n").unwrap();
325        let written = write_config_file(&path, OnExisting::Overwrite).unwrap();
326        assert!(written);
327        let content = fs::read_to_string(&path).unwrap();
328        assert!(content.contains("braze-sync configuration"));
329    }
330
331    #[test]
332    fn write_config_keeps_existing_on_keep() {
333        let tmp = tempfile::tempdir().unwrap();
334        let path = tmp.path().join("braze-sync.config.yaml");
335        fs::write(&path, "# operator-tuned\nversion: 1\n").unwrap();
336        let written = write_config_file(&path, OnExisting::Keep).unwrap();
337        assert!(!written);
338        let content = fs::read_to_string(&path).unwrap();
339        assert!(content.contains("operator-tuned"));
340    }
341
342    #[test]
343    fn write_config_writes_fresh_on_keep_when_no_existing() {
344        let tmp = tempfile::tempdir().unwrap();
345        let path = tmp.path().join("braze-sync.config.yaml");
346        let written = write_config_file(&path, OnExisting::Keep).unwrap();
347        assert!(written);
348        assert!(path.exists());
349    }
350}