jarvy 0.0.3

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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Hook execution module for running shell scripts before/after tool installation.
//!
//! Supports bash, zsh, sh on Unix and PowerShell on Windows.
//! Includes timeout support and environment variable injection.

use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use thiserror::Error;
use wait_timeout::ChildExt;

use crate::config::{DEFAULT_HOOK_TIMEOUT, HookSettings};
use crate::telemetry;
use crate::tools::Os;

/// Errors that can occur during hook execution
#[derive(Error, Debug)]
pub enum HookError {
    #[error("Hook timed out after {0} seconds")]
    Timeout(u64),

    #[error("Hook failed with exit code {0}: {1}")]
    Failed(i32, String),

    #[error("Hook process was terminated by signal")]
    Terminated,

    #[error("Failed to spawn hook process: {0}")]
    SpawnError(#[from] std::io::Error),

    #[error("Shell not found: {0}")]
    #[allow(dead_code)] // Reserved for shell validation feature
    ShellNotFound(String),
}

/// Result type for hook operations
pub type HookResult<T> = Result<T, HookError>;

/// Configuration for a single hook execution
#[derive(Debug, Clone)]
pub struct HookConfig {
    /// Shell to use for execution
    pub shell: String,
    /// Timeout in seconds
    pub timeout: u64,
    /// Continue setup if hook fails
    pub continue_on_error: bool,
}

impl Default for HookConfig {
    fn default() -> Self {
        Self {
            shell: detect_shell(),
            timeout: DEFAULT_HOOK_TIMEOUT,
            continue_on_error: false,
        }
    }
}

impl From<&HookSettings> for HookConfig {
    fn from(settings: &HookSettings) -> Self {
        Self {
            shell: settings.shell.clone(),
            timeout: settings.timeout,
            continue_on_error: settings.continue_on_error,
        }
    }
}

/// Environment variables to inject into hook scripts
#[derive(Debug, Clone, Default)]
pub struct HookEnv {
    /// Tool name (e.g., "node", "rust")
    pub tool: Option<String>,
    /// Installed version
    pub version: Option<String>,
    /// Operating system
    pub os: Option<Os>,
    /// CPU architecture
    pub arch: Option<String>,
    /// Jarvy home directory
    pub jarvy_home: Option<String>,
    /// Additional custom environment variables
    pub custom: HashMap<String, String>,
}

impl HookEnv {
    /// Create environment for a specific tool
    pub fn for_tool(name: &str, version: &str) -> Self {
        Self {
            tool: Some(name.to_string()),
            version: Some(version.to_string()),
            os: Some(crate::tools::current_os()),
            arch: Some(std::env::consts::ARCH.to_string()),
            jarvy_home: dirs::home_dir().map(|p| p.join(".jarvy").to_string_lossy().to_string()),
            custom: HashMap::new(),
        }
    }

    /// Create environment for global hooks (pre_setup, post_setup)
    pub fn global() -> Self {
        Self {
            tool: None,
            version: None,
            os: Some(crate::tools::current_os()),
            arch: Some(std::env::consts::ARCH.to_string()),
            jarvy_home: dirs::home_dir().map(|p| p.join(".jarvy").to_string_lossy().to_string()),
            custom: HashMap::new(),
        }
    }

    /// Add a custom environment variable
    #[allow(dead_code)] // Builder API for hook environment
    pub fn with_var(mut self, key: &str, value: &str) -> Self {
        self.custom.insert(key.to_string(), value.to_string());
        self
    }

    /// Convert to a HashMap for Command::envs()
    fn to_env_map(&self) -> HashMap<String, String> {
        let mut env = HashMap::new();

        if let Some(ref tool) = self.tool {
            env.insert("JARVY_TOOL".to_string(), tool.clone());
        }
        if let Some(ref version) = self.version {
            env.insert("JARVY_VERSION".to_string(), version.clone());
        }
        if let Some(ref os) = self.os {
            env.insert("JARVY_OS".to_string(), format!("{:?}", os).to_lowercase());
        }
        if let Some(ref arch) = self.arch {
            env.insert("JARVY_ARCH".to_string(), arch.clone());
        }
        if let Some(ref home) = self.jarvy_home {
            env.insert("JARVY_HOME".to_string(), home.clone());
        }

        // Add custom vars
        for (k, v) in &self.custom {
            env.insert(k.clone(), v.clone());
        }

        env
    }
}

/// A hook to be executed
#[derive(Debug, Clone)]
pub struct Hook {
    /// The script content to execute
    pub script: String,
    /// Configuration for execution
    pub config: HookConfig,
    /// Environment variables to inject
    pub env: HookEnv,
    /// Description for logging
    pub description: String,
}

impl Hook {
    /// Create a new hook with default configuration
    #[allow(dead_code)] // Public API for programmatic hook creation
    pub fn new(script: &str, description: &str) -> Self {
        Self {
            script: script.to_string(),
            config: HookConfig::default(),
            env: HookEnv::global(),
            description: description.to_string(),
        }
    }

    /// Create a hook with custom configuration
    pub fn with_config(script: &str, description: &str, config: HookConfig) -> Self {
        Self {
            script: script.to_string(),
            config,
            env: HookEnv::global(),
            description: description.to_string(),
        }
    }

    /// Set environment variables for the hook
    pub fn with_env(mut self, env: HookEnv) -> Self {
        self.env = env;
        self
    }

    /// Execute the hook script
    ///
    /// Returns Ok(output) on success, or HookError on failure.
    /// Output is streamed to stdout/stderr in real-time.
    pub fn execute(&self) -> HookResult<String> {
        println!("  Running hook: {}", self.description);

        // Determine hook type for telemetry
        let hook_type = self.determine_hook_type();
        let tool = self.env.tool.as_deref();

        // Emit hook started telemetry
        telemetry::hook_started(&self.description, &hook_type, tool);
        let start = Instant::now();

        let (shell, args) = build_shell_command(&self.config.shell, &self.script)?;

        let mut child = Command::new(&shell)
            .args(&args)
            .envs(self.env.to_env_map())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;

        // Capture stdout in a separate thread
        let stdout = child.stdout.take();
        let stderr = child.stderr.take();

        let stdout_handle = std::thread::spawn(move || {
            let mut output = String::new();
            if let Some(stdout) = stdout {
                let reader = BufReader::new(stdout);
                for line in reader.lines().map_while(Result::ok) {
                    println!("    {}", line);
                    output.push_str(&line);
                    output.push('\n');
                }
            }
            output
        });

        let stderr_handle = std::thread::spawn(move || {
            let mut output = String::new();
            if let Some(stderr) = stderr {
                let reader = BufReader::new(stderr);
                for line in reader.lines().map_while(Result::ok) {
                    eprintln!("    {}", line);
                    output.push_str(&line);
                    output.push('\n');
                }
            }
            output
        });

        // Wait with timeout
        let timeout = Duration::from_secs(self.config.timeout);
        let status = match child.wait_timeout(timeout)? {
            Some(status) => status,
            None => {
                // Timeout - kill the process
                let _ = child.kill();
                let _ = child.wait();
                telemetry::hook_timeout(&self.description, &hook_type, self.config.timeout);
                return Err(HookError::Timeout(self.config.timeout));
            }
        };

        // Wait for output threads
        let stdout_output = stdout_handle.join().unwrap_or_default();
        let stderr_output = stderr_handle.join().unwrap_or_default();

        let duration = start.elapsed();
        if status.success() {
            println!("  Hook completed successfully");
            telemetry::hook_completed(&self.description, &hook_type, duration, 0);
            Ok(stdout_output)
        } else {
            let code = status.code().unwrap_or(-1);
            if code == -1 {
                telemetry::hook_failed(
                    &self.description,
                    &hook_type,
                    "terminated by signal",
                    "terminated",
                );
                Err(HookError::Terminated)
            } else {
                telemetry::hook_failed(&self.description, &hook_type, &stderr_output, "exit_code");
                Err(HookError::Failed(code, stderr_output))
            }
        }
    }

    /// Determine hook type from description
    fn determine_hook_type(&self) -> String {
        if self.description.contains("pre_setup") {
            "pre_setup".to_string()
        } else if self.description.contains("post_setup") {
            "post_setup".to_string()
        } else if self.description.contains("post_install") {
            "post_install".to_string()
        } else if self.description.contains("default_hook") {
            "default_hook".to_string()
        } else {
            "custom".to_string()
        }
    }

    /// Execute in dry-run mode (just print what would happen)
    pub fn dry_run(&self) {
        println!("  [DRY-RUN] Would run hook: {}", self.description);
        println!("    Shell: {}", self.config.shell);
        println!("    Timeout: {}s", self.config.timeout);
        println!("    Continue on error: {}", self.config.continue_on_error);
        println!("    Script:");
        for line in self.script.lines() {
            println!("      {}", line);
        }
        if !self.env.to_env_map().is_empty() {
            println!("    Environment:");
            for (k, v) in self.env.to_env_map() {
                println!("      {}={}", k, v);
            }
        }
    }
}

/// Detect the default shell for the current platform
pub fn detect_shell() -> String {
    #[cfg(windows)]
    {
        "powershell".to_string()
    }
    #[cfg(not(windows))]
    {
        std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
    }
}

/// Build the shell command and arguments for script execution
fn build_shell_command(shell: &str, script: &str) -> HookResult<(String, Vec<String>)> {
    let shell_lower = shell.to_lowercase();

    // Determine the shell binary and args based on the shell name
    let (shell_bin, args) = if shell_lower.contains("powershell") || shell_lower == "pwsh" {
        // PowerShell
        let bin = if cfg!(windows) {
            "powershell.exe"
        } else {
            "pwsh" // PowerShell Core on Unix
        };
        (
            bin.to_string(),
            vec![
                "-NoProfile".to_string(),
                "-Command".to_string(),
                script.to_string(),
            ],
        )
    } else if shell_lower.contains("cmd") {
        // Windows CMD
        (
            "cmd.exe".to_string(),
            vec!["/C".to_string(), script.to_string()],
        )
    } else {
        // Unix shells (bash, zsh, sh, fish, etc.)
        let shell_path = if shell.starts_with('/') {
            shell.to_string()
        } else {
            // Try to find the shell in common locations
            let paths = [
                format!("/bin/{}", shell),
                format!("/usr/bin/{}", shell),
                format!("/usr/local/bin/{}", shell),
            ];
            paths
                .iter()
                .find(|p| std::path::Path::new(p).exists())
                .cloned()
                .unwrap_or_else(|| shell.to_string())
        };

        // Fish has different syntax
        if shell_lower == "fish" {
            (shell_path, vec!["-c".to_string(), script.to_string()])
        } else {
            // bash, zsh, sh, etc.
            (shell_path, vec!["-c".to_string(), script.to_string()])
        }
    };

    Ok((shell_bin, args))
}

/// Execute a list of hooks, respecting continue_on_error settings
#[allow(dead_code)] // Public API for batch hook execution
pub fn execute_hooks(hooks: &[Hook], dry_run: bool) -> HookResult<()> {
    for hook in hooks {
        if dry_run {
            hook.dry_run();
            continue;
        }

        match hook.execute() {
            Ok(_) => {}
            Err(e) => {
                if hook.config.continue_on_error {
                    eprintln!("  Warning: Hook failed but continuing: {}", e);
                } else {
                    return Err(e);
                }
            }
        }
    }
    Ok(())
}

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

    #[test]
    fn test_detect_shell() {
        let shell = detect_shell();
        assert!(!shell.is_empty());
        #[cfg(windows)]
        assert_eq!(shell, "powershell");
    }

    #[test]
    fn test_hook_config_default() {
        let config = HookConfig::default();
        assert_eq!(config.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!config.continue_on_error);
    }

    #[test]
    fn test_hook_env_for_tool() {
        let env = HookEnv::for_tool("node", "20.0.0");
        let map = env.to_env_map();
        assert_eq!(map.get("JARVY_TOOL"), Some(&"node".to_string()));
        assert_eq!(map.get("JARVY_VERSION"), Some(&"20.0.0".to_string()));
        assert!(map.contains_key("JARVY_OS"));
        assert!(map.contains_key("JARVY_ARCH"));
    }

    #[test]
    fn test_hook_env_global() {
        let env = HookEnv::global();
        let map = env.to_env_map();
        assert!(!map.contains_key("JARVY_TOOL"));
        assert!(!map.contains_key("JARVY_VERSION"));
        assert!(map.contains_key("JARVY_OS"));
        assert!(map.contains_key("JARVY_ARCH"));
    }

    #[test]
    fn test_hook_env_custom() {
        let env = HookEnv::global().with_var("MY_VAR", "my_value");
        let map = env.to_env_map();
        assert_eq!(map.get("MY_VAR"), Some(&"my_value".to_string()));
    }

    #[test]
    fn test_build_shell_command_bash() {
        let (shell, args) = build_shell_command("bash", "echo hello").unwrap();
        assert!(shell.contains("bash") || shell == "bash");
        assert_eq!(args, vec!["-c", "echo hello"]);
    }

    #[test]
    fn test_build_shell_command_sh() {
        let (shell, args) = build_shell_command("/bin/sh", "echo hello").unwrap();
        assert_eq!(shell, "/bin/sh");
        assert_eq!(args, vec!["-c", "echo hello"]);
    }

    #[test]
    fn test_build_shell_command_powershell() {
        let (shell, args) = build_shell_command("powershell", "Write-Host hello").unwrap();
        #[cfg(windows)]
        assert_eq!(shell, "powershell.exe");
        #[cfg(not(windows))]
        assert_eq!(shell, "pwsh");
        assert!(args.contains(&"-Command".to_string()));
    }

    #[test]
    fn test_hook_creation() {
        let hook = Hook::new("echo test", "Test hook");
        assert_eq!(hook.script, "echo test");
        assert_eq!(hook.description, "Test hook");
    }

    #[test]
    fn test_hook_with_env() {
        let hook =
            Hook::new("echo $JARVY_TOOL", "Tool hook").with_env(HookEnv::for_tool("git", "2.40.0"));
        let map = hook.env.to_env_map();
        assert_eq!(map.get("JARVY_TOOL"), Some(&"git".to_string()));
    }

    #[test]
    #[cfg(unix)]
    fn test_hook_execute_simple() {
        let hook = Hook::new("echo 'hello from hook'", "Simple echo");
        let result = hook.execute();
        assert!(result.is_ok());
        assert!(result.unwrap().contains("hello from hook"));
    }

    #[test]
    #[cfg(unix)]
    fn test_hook_execute_with_env() {
        let hook = Hook::new("echo $JARVY_TOOL", "Echo tool name")
            .with_env(HookEnv::for_tool("testool", "1.0.0"));
        let result = hook.execute();
        assert!(result.is_ok());
        assert!(result.unwrap().contains("testool"));
    }

    #[test]
    #[cfg(unix)]
    fn test_hook_execute_failure() {
        let hook = Hook::new("exit 1", "Failing hook");
        let result = hook.execute();
        assert!(result.is_err());
        match result {
            Err(HookError::Failed(code, _)) => assert_eq!(code, 1),
            _ => panic!("Expected Failed error"),
        }
    }

    #[test]
    fn test_hook_dry_run() {
        // Just ensure it doesn't panic
        let hook = Hook::new("echo test", "Dry run test");
        hook.dry_run();
    }
}