Skip to main content

rippy_cli/
stdlib.rs

1//! Embedded stdlib rules — default safety rules shipped with the binary.
2//!
3//! These are loaded as the lowest-priority tier in the config system.
4//! User and project config override stdlib rules via last-match-wins.
5
6use std::io::Write as _;
7use std::path::Path;
8use std::process::ExitCode;
9
10use crate::cli::InitArgs;
11use crate::config::{self, ConfigDirective};
12use crate::error::RippyError;
13use crate::packages::Package;
14
15// Simple tool rules (split from simple.toml)
16const CARGO_TOML: &str = include_str!("stdlib/cargo.toml");
17const BREW_TOML: &str = include_str!("stdlib/brew.toml");
18const PIP_TOML: &str = include_str!("stdlib/pip.toml");
19const TERRAFORM_TOML: &str = include_str!("stdlib/terraform.toml");
20const PYTEST_TOML: &str = include_str!("stdlib/pytest.toml");
21const MAKE_TOML: &str = include_str!("stdlib/make.toml");
22const RUSTUP_TOML: &str = include_str!("stdlib/rustup.toml");
23const OPENSSL_TOML: &str = include_str!("stdlib/openssl.toml");
24
25// File operations
26const FILE_OPS_TOML: &str = include_str!("stdlib/file_ops.toml");
27
28// Dangerous command rules (split from dangerous.toml)
29const BUILTINS_TOML: &str = include_str!("stdlib/builtins.toml");
30const SUDO_TOML: &str = include_str!("stdlib/sudo.toml");
31const SSH_TOML: &str = include_str!("stdlib/ssh.toml");
32const INTERPRETERS_TOML: &str = include_str!("stdlib/interpreters.toml");
33const PACKAGE_MANAGERS_TOML: &str = include_str!("stdlib/package_managers.toml");
34
35/// All embedded stdlib TOML sources in loading order.
36const STDLIB_SOURCES: &[(&str, &str)] = &[
37    // Simple tools
38    ("(stdlib:cargo)", CARGO_TOML),
39    ("(stdlib:brew)", BREW_TOML),
40    ("(stdlib:pip)", PIP_TOML),
41    ("(stdlib:terraform)", TERRAFORM_TOML),
42    ("(stdlib:pytest)", PYTEST_TOML),
43    ("(stdlib:make)", MAKE_TOML),
44    ("(stdlib:rustup)", RUSTUP_TOML),
45    ("(stdlib:openssl)", OPENSSL_TOML),
46    // File operations
47    ("(stdlib:file_ops)", FILE_OPS_TOML),
48    // Dangerous commands
49    ("(stdlib:builtins)", BUILTINS_TOML),
50    ("(stdlib:sudo)", SUDO_TOML),
51    ("(stdlib:ssh)", SSH_TOML),
52    ("(stdlib:interpreters)", INTERPRETERS_TOML),
53    ("(stdlib:package_managers)", PACKAGE_MANAGERS_TOML),
54];
55
56/// Parse all embedded stdlib TOML into config directives.
57///
58/// # Errors
59///
60/// Returns `RippyError::Config` if any embedded TOML is malformed (a build bug).
61pub fn stdlib_directives() -> Result<Vec<ConfigDirective>, RippyError> {
62    let mut directives = Vec::new();
63    for (label, source) in STDLIB_SOURCES {
64        let parsed = crate::toml_config::parse_toml_config(source, Path::new(label))?;
65        directives.extend(parsed);
66    }
67    Ok(directives)
68}
69
70/// Return the concatenated raw TOML for all stdlib files.
71#[must_use]
72pub fn stdlib_toml() -> String {
73    let mut out = String::new();
74    for (_, source) in STDLIB_SOURCES {
75        out.push_str(source);
76        out.push('\n');
77    }
78    out
79}
80
81/// Run the `rippy init` command — create config with a safety package.
82///
83/// # Errors
84///
85/// Returns `RippyError::Setup` if the file cannot be written.
86pub fn run_init(args: &InitArgs) -> Result<ExitCode, RippyError> {
87    if args.stdout {
88        print!("{}", stdlib_toml());
89        return Ok(ExitCode::SUCCESS);
90    }
91
92    let package = resolve_init_package(args)?;
93
94    let path = if args.global {
95        config::home_dir()
96            .map(|h| h.join(".rippy/config.toml"))
97            .ok_or_else(|| RippyError::Setup("could not determine home directory".into()))?
98    } else {
99        std::path::PathBuf::from(".rippy.toml")
100    };
101
102    if path.exists() {
103        return Err(RippyError::Setup(format!(
104            "{} already exists. Remove it first or edit manually.",
105            path.display()
106        )));
107    }
108
109    crate::profile_cmd::write_package_setting(&path, package.name())?;
110
111    if !args.global {
112        crate::trust::TrustGuard::for_new_file(&path).commit();
113    }
114
115    eprintln!(
116        "[rippy] Created {} with package \"{}\"\n  \
117         \"{}\"\n  \
118         Run `rippy profile show {}` for details, or edit {} to customize.",
119        path.display(),
120        package.name(),
121        package.tagline(),
122        package.name(),
123        path.display(),
124    );
125    Ok(ExitCode::SUCCESS)
126}
127
128/// Determine which package to use: from `--package` flag, interactive prompt,
129/// or default to `develop` when stdin is not a terminal.
130fn resolve_init_package(args: &InitArgs) -> Result<Package, RippyError> {
131    if let Some(name) = &args.package {
132        return Package::parse(name).map_err(RippyError::Setup);
133    }
134
135    if is_interactive() {
136        return prompt_package_selection();
137    }
138
139    // Non-interactive: default to develop.
140    Ok(Package::Develop)
141}
142
143fn is_interactive() -> bool {
144    use std::io::IsTerminal;
145    std::io::stdin().is_terminal()
146}
147
148fn prompt_package_selection() -> Result<Package, RippyError> {
149    let packages = Package::all();
150    let default_idx = packages
151        .iter()
152        .position(|p| *p == Package::Develop)
153        .unwrap_or(0);
154
155    eprintln!("\nWhich package fits your workflow?\n");
156    for (i, pkg) in packages.iter().enumerate() {
157        let recommended = if i == default_idx {
158            "  (recommended)"
159        } else {
160            ""
161        };
162        eprintln!(
163            "  [{}] {:<12}[{}]  {}{recommended}",
164            i + 1,
165            pkg.name(),
166            pkg.shield(),
167            pkg.tagline(),
168        );
169    }
170    eprint!(
171        "\nSelect [1-{}] (default: {}): ",
172        packages.len(),
173        default_idx + 1
174    );
175    let _ = std::io::stderr().flush();
176
177    let mut input = String::new();
178    if std::io::stdin().read_line(&mut input).is_err() {
179        return Ok(packages[default_idx]);
180    }
181
182    let trimmed = input.trim();
183    if trimmed.is_empty() {
184        return Ok(packages[default_idx]);
185    }
186
187    // Try as a 1-based index first, then as a package name.
188    if let Ok(n) = trimmed.parse::<usize>()
189        && n >= 1
190        && n <= packages.len()
191    {
192        return Ok(packages[n - 1]);
193    }
194
195    Package::parse(trimmed).map_err(RippyError::Setup)
196}
197
198#[cfg(test)]
199#[allow(clippy::unwrap_used)]
200mod tests {
201    use super::*;
202    use crate::config::Config;
203    use crate::verdict::Decision;
204
205    #[test]
206    fn stdlib_parses_without_error() {
207        let directives = stdlib_directives().unwrap();
208        assert!(!directives.is_empty());
209    }
210
211    #[test]
212    fn stdlib_cargo_safe_subcommands() {
213        let config = Config::from_directives(stdlib_directives().unwrap());
214        let v = config.match_command("cargo test --release", None);
215        assert!(v.is_some());
216        assert_eq!(v.unwrap().decision, Decision::Allow);
217    }
218
219    #[test]
220    fn stdlib_cargo_ask_subcommands() {
221        let config = Config::from_directives(stdlib_directives().unwrap());
222        let v = config.match_command("cargo run", None);
223        assert!(v.is_some());
224        assert_eq!(v.unwrap().decision, Decision::Ask);
225    }
226
227    #[test]
228    fn stdlib_cargo_unknown_defaults_to_ask() {
229        let config = Config::from_directives(stdlib_directives().unwrap());
230        let v = config.match_command("cargo some-unknown-subcommand", None);
231        assert!(v.is_some());
232        assert_eq!(v.unwrap().decision, Decision::Ask);
233    }
234
235    #[test]
236    fn stdlib_file_ops_ask() {
237        let config = Config::from_directives(stdlib_directives().unwrap());
238        for cmd in &["rm -rf /tmp/test", "mv a b", "chmod 755 file"] {
239            let v = config.match_command(cmd, None);
240            assert!(v.is_some(), "expected match for {cmd}");
241            assert_eq!(v.unwrap().decision, Decision::Ask, "expected ask for {cmd}");
242        }
243    }
244
245    #[test]
246    fn stdlib_dangerous_commands_ask() {
247        let config = Config::from_directives(stdlib_directives().unwrap());
248        for cmd in &["sudo apt install foo", "ssh user@host", "eval echo hi"] {
249            let v = config.match_command(cmd, None);
250            assert!(v.is_some(), "expected match for {cmd}");
251            assert_eq!(v.unwrap().decision, Decision::Ask, "expected ask for {cmd}");
252        }
253    }
254
255    #[test]
256    fn stdlib_toml_not_empty() {
257        let toml = stdlib_toml();
258        assert!(toml.contains("[[rules]]"));
259        assert!(toml.contains("cargo"));
260    }
261
262    #[test]
263    fn init_refuses_existing_file() {
264        let dir = tempfile::TempDir::new().unwrap();
265        let path = dir.path().join(".rippy.toml");
266        std::fs::write(&path, "existing").unwrap();
267
268        let original = std::env::current_dir().unwrap();
269        std::env::set_current_dir(dir.path()).unwrap();
270        let result = run_init(&InitArgs {
271            global: false,
272            stdout: false,
273            package: Some("develop".into()),
274        });
275        std::env::set_current_dir(original).unwrap();
276
277        assert!(result.is_err());
278    }
279}