1use 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 #[arg(long, conflicts_with = "from_existing")]
15 pub force: bool,
16
17 #[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 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
193environments:
194 dev:
195 # Braze REST endpoint for your instance. See:
196 # https://www.braze.com/docs/api/basics/#endpoints
197 api_endpoint: https://rest.fra-02.braze.eu
198 # Name of the env var holding the API key — NEVER put the key itself
199 # in this file.
200 api_key_env: BRAZE_DEV_API_KEY
201 # prod:
202 # api_endpoint: https://rest.fra-02.braze.eu
203 # api_key_env: BRAZE_PROD_API_KEY
204
205resources:
206 catalog_schema:
207 enabled: true
208 path: catalogs/
209 content_block:
210 enabled: true
211 path: content_blocks/
212 email_template:
213 enabled: true
214 path: email_templates/
215 custom_attribute:
216 enabled: true
217 path: custom_attributes/registry.yaml
218
219# Optional name validators enforced by `braze-sync validate`.
220# naming:
221# catalog_name_pattern: "^[a-z][a-z0-9_]*$"
222# content_block_name_pattern: "^[a-zA-Z0-9_]+$"
223# custom_attribute_name_pattern: "^[a-z][a-z0-9_]*$"
224"#;
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn config_template_parses_as_valid_config() {
232 let tmp = tempfile::tempdir().unwrap();
233 let path = tmp.path().join("braze-sync.config.yaml");
234 fs::write(&path, CONFIG_TEMPLATE).unwrap();
235 let cfg = ConfigFile::load(&path).unwrap();
236 assert_eq!(cfg.version, 1);
237 assert_eq!(cfg.default_environment, "dev");
238 assert!(cfg.environments.contains_key("dev"));
239 }
240
241 #[test]
242 fn gitignore_entries_added_on_fresh_file() {
243 let tmp = tempfile::tempdir().unwrap();
244 let updated = update_gitignore(tmp.path()).unwrap();
245 assert!(updated);
246 let content = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
247 assert!(content.contains(".env"));
248 assert!(content.contains(".env.*"));
249 }
250
251 #[test]
252 fn gitignore_idempotent_on_second_run() {
253 let tmp = tempfile::tempdir().unwrap();
254 let first = update_gitignore(tmp.path()).unwrap();
255 assert!(first);
256 let second = update_gitignore(tmp.path()).unwrap();
257 assert!(!second);
258 }
259
260 #[test]
261 fn gitignore_preserves_existing_content() {
262 let tmp = tempfile::tempdir().unwrap();
263 let path = tmp.path().join(".gitignore");
264 fs::write(&path, "target/\ndist/\n").unwrap();
265 update_gitignore(tmp.path()).unwrap();
266 let content = fs::read_to_string(&path).unwrap();
267 assert!(content.contains("target/"));
268 assert!(content.contains("dist/"));
269 assert!(content.contains(".env"));
270 }
271
272 #[test]
273 fn gitignore_skips_already_present_entry() {
274 let tmp = tempfile::tempdir().unwrap();
275 let path = tmp.path().join(".gitignore");
276 fs::write(&path, ".env\n").unwrap();
277 let updated = update_gitignore(tmp.path()).unwrap();
278 assert!(updated);
279 let content = fs::read_to_string(&path).unwrap();
280 let count = content.lines().filter(|l| l.trim() == ".env").count();
281 assert_eq!(count, 1);
282 assert!(content.contains(".env.*"));
283 }
284
285 #[test]
286 fn scaffold_creates_all_four_dirs() {
287 let tmp = tempfile::tempdir().unwrap();
288 scaffold_resource_dirs(tmp.path()).unwrap();
289 for sub in SUBDIRS {
290 assert!(tmp.path().join(sub).is_dir());
291 }
292 }
293
294 #[test]
295 fn scaffold_is_idempotent() {
296 let tmp = tempfile::tempdir().unwrap();
297 scaffold_resource_dirs(tmp.path()).unwrap();
298 scaffold_resource_dirs(tmp.path()).unwrap();
299 }
300
301 #[test]
302 fn write_config_refuses_to_overwrite_without_force() {
303 let tmp = tempfile::tempdir().unwrap();
304 let path = tmp.path().join("braze-sync.config.yaml");
305 fs::write(&path, "version: 1\n# user edits\n").unwrap();
306 let err = write_config_file(&path, OnExisting::Fail).unwrap_err();
307 assert!(err.to_string().contains("--force"));
308 let content = fs::read_to_string(&path).unwrap();
309 assert!(content.contains("user edits"));
310 }
311
312 #[test]
313 fn write_config_overwrites_with_force() {
314 let tmp = tempfile::tempdir().unwrap();
315 let path = tmp.path().join("braze-sync.config.yaml");
316 fs::write(&path, "# old\n").unwrap();
317 let written = write_config_file(&path, OnExisting::Overwrite).unwrap();
318 assert!(written);
319 let content = fs::read_to_string(&path).unwrap();
320 assert!(content.contains("braze-sync configuration"));
321 }
322
323 #[test]
324 fn write_config_keeps_existing_on_keep() {
325 let tmp = tempfile::tempdir().unwrap();
326 let path = tmp.path().join("braze-sync.config.yaml");
327 fs::write(&path, "# operator-tuned\nversion: 1\n").unwrap();
328 let written = write_config_file(&path, OnExisting::Keep).unwrap();
329 assert!(!written);
330 let content = fs::read_to_string(&path).unwrap();
331 assert!(content.contains("operator-tuned"));
332 }
333
334 #[test]
335 fn write_config_writes_fresh_on_keep_when_no_existing() {
336 let tmp = tempfile::tempdir().unwrap();
337 let path = tmp.path().join("braze-sync.config.yaml");
338 let written = write_config_file(&path, OnExisting::Keep).unwrap();
339 assert!(written);
340 assert!(path.exists());
341 }
342}