jarvy 0.0.5

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
//! Shell rc file modification
//!
//! Updates shell configuration files (.bashrc, .zshrc, fish config) with:
//! - Export statements for environment variables
//! - Jarvy marker comments for easy identification
//! - Backup before modification
//! - Support for bash, zsh, and fish syntax

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

use super::expand::{EnvContext, expand_value};
use crate::telemetry;

/// Errors that can occur during shell rc modification
#[derive(Error, Debug)]
pub enum ShellError {
    #[error("Failed to read shell rc file: {0}")]
    ReadError(#[from] std::io::Error),
    #[error("Unsupported shell: {0}")]
    UnsupportedShell(String),
    #[error("Failed to backup rc file: {0}")]
    BackupError(String),
    #[error("Could not determine home directory")]
    NoHomeDirectory,
}

/// Supported shell types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShellType {
    Bash,
    Zsh,
    Fish,
    Sh,
    PowerShell,
}

impl ShellType {
    /// Get the export syntax for this shell
    pub fn export_syntax(&self) -> (&'static str, &'static str) {
        match self {
            ShellType::Fish => ("set -gx ", ""),
            ShellType::PowerShell => ("$env:", ""),
            _ => ("export ", ""),
        }
    }

    /// Get the rc file path for this shell
    pub fn rc_file(&self, home: &Path) -> PathBuf {
        match self {
            ShellType::Bash => home.join(".bashrc"),
            ShellType::Zsh => home.join(".zshrc"),
            ShellType::Fish => home.join(".config/fish/config.fish"),
            ShellType::Sh => home.join(".profile"),
            #[cfg(windows)]
            ShellType::PowerShell => {
                home.join("Documents/PowerShell/Microsoft.PowerShell_profile.ps1")
            }
            #[cfg(not(windows))]
            ShellType::PowerShell => {
                home.join(".config/powershell/Microsoft.PowerShell_profile.ps1")
            }
        }
    }

    /// Get comment syntax
    pub fn comment_prefix(&self) -> &'static str {
        "#"
    }
}

impl std::fmt::Display for ShellType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ShellType::Bash => write!(f, "bash"),
            ShellType::Zsh => write!(f, "zsh"),
            ShellType::Fish => write!(f, "fish"),
            ShellType::Sh => write!(f, "sh"),
            ShellType::PowerShell => write!(f, "powershell"),
        }
    }
}

/// Jarvy marker comments
const JARVY_START: &str = "# >>> jarvy managed start >>>";
const JARVY_END: &str = "# <<< jarvy managed end <<<";

/// Configuration for shell rc modification
#[derive(Debug, Clone)]
pub struct ShellConfig {
    /// Whether to backup the rc file before modification
    pub backup: bool,
    /// Whether to validate syntax after modification
    #[allow(dead_code)] // Reserved for shell syntax validation feature
    pub validate: bool,
}

impl Default for ShellConfig {
    fn default() -> Self {
        Self {
            backup: true,
            validate: false,
        }
    }
}

/// Detect the current shell type from environment
pub fn detect_shell() -> ShellType {
    // Check SHELL environment variable
    if let Ok(shell) = std::env::var("SHELL") {
        let shell_lower = shell.to_lowercase();
        if shell_lower.contains("zsh") {
            return ShellType::Zsh;
        } else if shell_lower.contains("bash") {
            return ShellType::Bash;
        } else if shell_lower.contains("fish") {
            return ShellType::Fish;
        } else if shell_lower.contains("pwsh") || shell_lower.contains("powershell") {
            return ShellType::PowerShell;
        }
    }

    // Default to bash on Unix, sh elsewhere
    #[cfg(unix)]
    {
        ShellType::Bash
    }
    #[cfg(not(unix))]
    {
        ShellType::Sh
    }
}

/// Parse shell type from string
pub fn parse_shell(s: &str) -> Result<ShellType, ShellError> {
    match s.to_lowercase().as_str() {
        "bash" => Ok(ShellType::Bash),
        "zsh" => Ok(ShellType::Zsh),
        "fish" => Ok(ShellType::Fish),
        "sh" => Ok(ShellType::Sh),
        "powershell" | "pwsh" => Ok(ShellType::PowerShell),
        _ => Err(ShellError::UnsupportedShell(s.to_string())),
    }
}

/// Update shell rc file with environment variables
///
/// # Arguments
/// * `shell` - The shell type to configure
/// * `vars` - HashMap of variable names to their (unexpanded) values
/// * `ctx` - Context for variable expansion
/// * `config` - Configuration for the modification
///
/// # Returns
/// Ok(path) with the path to the modified rc file, or an error
pub fn update_shell_rc(
    shell: ShellType,
    vars: &HashMap<String, String>,
    ctx: &EnvContext,
    config: &ShellConfig,
) -> Result<PathBuf, ShellError> {
    let home = dirs::home_dir().ok_or(ShellError::NoHomeDirectory)?;
    let rc_path = shell.rc_file(&home);

    // Ensure parent directory exists (for fish)
    if let Some(parent) = rc_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Read existing content
    let existing_content = if rc_path.exists() {
        fs::read_to_string(&rc_path)?
    } else {
        String::new()
    };

    // Backup if exists and configured
    if rc_path.exists() && config.backup {
        let backup_path = rc_path.with_extension(format!(
            "{}.jarvy.backup",
            rc_path
                .extension()
                .map(|s| s.to_string_lossy())
                .unwrap_or_default()
        ));
        fs::copy(&rc_path, &backup_path).map_err(|e| {
            ShellError::BackupError(format!(
                "Could not backup {} to {}: {}",
                rc_path.display(),
                backup_path.display(),
                e
            ))
        })?;
    }

    // Generate new content
    let new_content = update_rc_content(&existing_content, shell, vars, ctx);

    // Write the file
    fs::write(&rc_path, new_content)?;

    // Emit telemetry
    telemetry::env_shell_rc_updated(&shell.to_string(), vars.len());

    Ok(rc_path)
}

/// Update rc file content, preserving non-Jarvy content
fn update_rc_content(
    existing: &str,
    shell: ShellType,
    vars: &HashMap<String, String>,
    ctx: &EnvContext,
) -> String {
    let mut lines: Vec<String> = Vec::new();
    let mut in_jarvy_block = false;

    // Process existing content, removing old Jarvy block
    for line in existing.lines() {
        if line.trim() == JARVY_START {
            in_jarvy_block = true;
            continue;
        }
        if line.trim() == JARVY_END {
            in_jarvy_block = false;
            continue;
        }
        if !in_jarvy_block {
            lines.push(line.to_string());
        }
    }

    // Remove trailing empty lines
    while lines.last().map(|s| s.trim().is_empty()).unwrap_or(false) {
        lines.pop();
    }

    // Add new Jarvy block if there are variables
    if !vars.is_empty() {
        if !lines.is_empty() {
            lines.push(String::new());
        }
        lines.push(JARVY_START.to_string());
        lines.push(format!(
            "{} Generated by Jarvy - do not edit manually",
            shell.comment_prefix()
        ));

        let (export_prefix, export_suffix) = shell.export_syntax();

        // Sort keys for deterministic output
        let mut keys: Vec<_> = vars.keys().collect();
        keys.sort();

        for key in keys {
            let raw_value = &vars[key];
            let expanded_value = expand_value(raw_value, ctx);
            let quoted_value = shell_quote(&expanded_value, shell);
            lines.push(format!(
                "{}{}={}{}",
                export_prefix, key, quoted_value, export_suffix
            ));
        }

        lines.push(JARVY_END.to_string());
    }

    lines.join("\n") + "\n"
}

/// Quote a value for shell syntax
fn shell_quote(value: &str, shell: ShellType) -> String {
    match shell {
        ShellType::Fish => {
            // Fish uses different quoting rules
            if value.contains('\'') {
                // Use double quotes and escape special chars
                let escaped = value
                    .replace('\\', "\\\\")
                    .replace('"', "\\\"")
                    .replace('$', "\\$");
                format!("\"{}\"", escaped)
            } else if value.contains(' ') || value.contains('$') || value.contains('"') {
                format!("'{}'", value)
            } else {
                value.to_string()
            }
        }
        _ => {
            // Bash/Zsh/Sh quoting
            if value.is_empty()
                || value.contains(' ')
                || value.contains('$')
                || value.contains('`')
                || value.contains('"')
                || value.contains('\'')
                || value.contains('\\')
                || value.contains('#')
            {
                // Use double quotes and escape
                let escaped = value
                    .replace('\\', "\\\\")
                    .replace('"', "\\\"")
                    .replace('$', "\\$")
                    .replace('`', "\\`");
                format!("\"{}\"", escaped)
            } else {
                value.to_string()
            }
        }
    }
}

/// Preview what would be added to the shell rc file (for dry-run)
pub fn preview_shell_rc(
    shell: ShellType,
    vars: &HashMap<String, String>,
    ctx: &EnvContext,
) -> String {
    let mut lines = Vec::new();
    lines.push(JARVY_START.to_string());

    let (export_prefix, export_suffix) = shell.export_syntax();

    let mut keys: Vec<_> = vars.keys().collect();
    keys.sort();

    for key in keys {
        let raw_value = &vars[key];
        let expanded_value = expand_value(raw_value, ctx);
        let quoted_value = shell_quote(&expanded_value, shell);
        lines.push(format!(
            "{}{}={}{}",
            export_prefix, key, quoted_value, export_suffix
        ));
    }

    lines.push(JARVY_END.to_string());
    lines.join("\n")
}

/// Get the path to the shell rc file for the given shell type
#[allow(dead_code)] // Public API for shell rc path resolution
pub fn get_rc_path(shell: ShellType) -> Result<PathBuf, ShellError> {
    let home = dirs::home_dir().ok_or(ShellError::NoHomeDirectory)?;
    Ok(shell.rc_file(&home))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_shell() {
        // Just verify it doesn't panic
        let _shell = detect_shell();
    }

    #[test]
    fn test_parse_shell() {
        assert_eq!(parse_shell("bash").unwrap(), ShellType::Bash);
        assert_eq!(parse_shell("zsh").unwrap(), ShellType::Zsh);
        assert_eq!(parse_shell("fish").unwrap(), ShellType::Fish);
        assert_eq!(parse_shell("BASH").unwrap(), ShellType::Bash);
        assert!(parse_shell("unknown").is_err());
    }

    #[test]
    fn test_shell_export_syntax() {
        assert_eq!(ShellType::Bash.export_syntax(), ("export ", ""));
        assert_eq!(ShellType::Zsh.export_syntax(), ("export ", ""));
        assert_eq!(ShellType::Fish.export_syntax(), ("set -gx ", ""));
    }

    #[test]
    fn test_shell_quote_simple() {
        assert_eq!(shell_quote("simple", ShellType::Bash), "simple");
    }

    #[test]
    fn test_shell_quote_spaces() {
        assert_eq!(shell_quote("has spaces", ShellType::Bash), "\"has spaces\"");
    }

    #[test]
    fn test_shell_quote_special() {
        assert_eq!(shell_quote("has$var", ShellType::Bash), "\"has\\$var\"");
    }

    #[test]
    fn test_shell_quote_fish() {
        assert_eq!(shell_quote("has spaces", ShellType::Fish), "'has spaces'");
    }

    #[test]
    fn test_update_rc_content_new() {
        let mut vars = HashMap::new();
        vars.insert("MY_VAR".to_string(), "my_value".to_string());

        let ctx = EnvContext::new();
        let result = update_rc_content("", ShellType::Bash, &vars, &ctx);

        assert!(result.contains(JARVY_START));
        assert!(result.contains(JARVY_END));
        assert!(result.contains("export MY_VAR=my_value"));
    }

    #[test]
    fn test_update_rc_content_existing_jarvy_block() {
        let existing = format!(
            "# Some existing config\n{}\nexport OLD_VAR=old\n{}\n# More config",
            JARVY_START, JARVY_END
        );

        let mut vars = HashMap::new();
        vars.insert("NEW_VAR".to_string(), "new_value".to_string());

        let ctx = EnvContext::new();
        let result = update_rc_content(&existing, ShellType::Bash, &vars, &ctx);

        assert!(result.contains("Some existing config"));
        assert!(result.contains("More config"));
        assert!(result.contains("export NEW_VAR=new_value"));
        assert!(!result.contains("OLD_VAR"));
    }

    #[test]
    fn test_update_rc_content_preserve_order() {
        let mut vars = HashMap::new();
        vars.insert("Z_VAR".to_string(), "z".to_string());
        vars.insert("A_VAR".to_string(), "a".to_string());
        vars.insert("M_VAR".to_string(), "m".to_string());

        let ctx = EnvContext::new();
        let result = update_rc_content("", ShellType::Bash, &vars, &ctx);

        let a_pos = result.find("A_VAR").unwrap();
        let m_pos = result.find("M_VAR").unwrap();
        let z_pos = result.find("Z_VAR").unwrap();

        assert!(a_pos < m_pos);
        assert!(m_pos < z_pos);
    }

    #[test]
    fn test_update_rc_content_fish() {
        let mut vars = HashMap::new();
        vars.insert("MY_VAR".to_string(), "my_value".to_string());

        let ctx = EnvContext::new();
        let result = update_rc_content("", ShellType::Fish, &vars, &ctx);

        assert!(result.contains("set -gx MY_VAR=my_value"));
    }

    #[test]
    fn test_preview_shell_rc() {
        let mut vars = HashMap::new();
        vars.insert("TEST".to_string(), "value".to_string());

        let ctx = EnvContext::new();
        let preview = preview_shell_rc(ShellType::Bash, &vars, &ctx);

        assert!(preview.contains(JARVY_START));
        assert!(preview.contains("export TEST=value"));
    }
}