1use anyhow::{bail, Result};
6use colored::*;
7use std::fs;
8use std::path::Path;
9use crate::common::{self, ProjectType};
10
11const GUARDRAILS_TEMPLATE: &str = include_str!("../templates/guardrails_template.rs");
13
14const SECURE_REQUIREMENTS_TEMPLATE: &str = include_str!("../templates/secure_requirements.txt");
16
17pub fn run_init(language: &str) -> Result<()> {
19 match language {
20 "rust" => init_rust(),
21 "python" => init_python(),
22 "auto" => {
23 println!("{}", "Detecting project type...".cyan());
24 match common::detect_project_type() {
25 ProjectType::Rust => init_rust(),
26 ProjectType::Python => init_python(),
27 ProjectType::Unknown => bail!("Could not auto-detect project type. Please specify 'rust' or 'python'."),
28 }
29 }
30 _ => bail!(
31 "Unknown language: '{}'. Supported: rust, python, auto",
32 language
33 ),
34 }
35}
36
37fn init_rust() -> Result<()> {
38 let target_path = "src/guardrails.rs";
39
40 if Path::new(target_path).exists() {
41 println!(
42 "{} '{}' already exists. Skipping to avoid overwriting.",
43 "Warning:".yellow().bold(),
44 target_path
45 );
46 return Ok(());
47 }
48
49 if !Path::new("src").exists() {
50 fs::create_dir_all("src")?;
51 }
52
53 fs::write(target_path, GUARDRAILS_TEMPLATE)?;
54
55 println!("{} Generated '{}'", "â".green().bold(), target_path);
56 println!("");
57 println!(" {} Add 'regex = \"1.10\"' to your Cargo.toml", "Next steps:".cyan().bold());
58 println!(" Then use it in your code: 'mod guardrails; use guardrails::validate_input;'");
59
60 Ok(())
61}
62
63fn init_python() -> Result<()> {
64 let target_path = "secure_requirements.txt";
65
66 if Path::new(target_path).exists() {
67 println!(
68 "{} '{}' already exists. Skipping to avoid overwriting.",
69 "Warning:".yellow().bold(),
70 target_path
71 );
72 return Ok(());
73 }
74
75 fs::write(target_path, SECURE_REQUIREMENTS_TEMPLATE)?;
76
77 println!("{} Generated '{}'", "â".green().bold(), target_path);
78 println!("");
79 println!(" {} Append to requirements.txt:", "Next steps:".cyan().bold());
80 println!(" 'cat secure_requirements.txt >> requirements.txt && pip install -r requirements.txt'");
81
82 Ok(())
83}