stand 0.2.2

A CLI tool for explicit environment variable management
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
// shell.rs command implementation
//
// Start an interactive subshell with environment variables loaded.

use crate::config::loader;
use crate::config::types::NestedBehavior;
use crate::crypto::decrypt_variables;
use crate::shell::{
    build_shell_environment, detect_user_shell, get_active_environment, is_stand_shell_active,
    spawn_shell,
};
use anyhow::{anyhow, Result};
use std::io::{self, IsTerminal, Write};
use std::path::Path;

/// Check if stdin is an interactive terminal
///
/// Returns false if:
/// - stdin is not a TTY
/// - STAND_FORCE_NON_TTY environment variable is set (for testing)
fn is_interactive_terminal() -> bool {
    if std::env::var("STAND_FORCE_NON_TTY").is_ok() {
        return false;
    }
    io::stdin().is_terminal()
}

/// Prompt user for confirmation before executing in a protected environment
fn prompt_confirmation(env_name: &str) -> Result<bool> {
    print!(
        "Environment '{}' requires confirmation.\nAre you sure you want to proceed? [y/N]: ",
        env_name
    );
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    let response = input.trim().to_lowercase();
    Ok(response == "y" || response == "yes")
}

/// Check if nesting is allowed based on configuration
fn check_nesting_allowed(behavior: Option<NestedBehavior>, current_env: &str) -> Result<bool> {
    let behavior = behavior.unwrap_or(NestedBehavior::Prevent);

    match behavior {
        NestedBehavior::Prevent => Err(anyhow!(
            "Already inside a Stand shell (environment: '{}').\n\
             Exit the current shell first, or use 'stand exec' for one-off commands.\n\
             Tip: Set nested_shell_behavior = \"allow\" in settings to permit nesting.",
            current_env
        )),
        NestedBehavior::Warn => {
            eprintln!(
                "Warning: Already inside a Stand shell (environment: '{}').\n\
                 Continuing with nested shell...",
                current_env
            );
            Ok(true)
        }
        NestedBehavior::Allow => Ok(true),
    }
}

/// Result of validating shell environment before spawning
#[derive(Debug)]
pub struct ValidatedShellEnv {
    /// Path to the shell executable
    pub shell_path: String,
    /// Environment variables to inject
    pub env_vars: std::collections::HashMap<String, String>,
    /// Name of the environment
    pub env_name: String,
}

/// Validate and prepare shell environment without spawning
///
/// This function performs all pre-spawn validation:
/// - Loads and validates configuration
/// - Checks for nesting
/// - Validates environment exists
/// - Handles confirmation prompts
///
/// Returns the validated environment ready for spawning, or an error.
pub fn validate_shell_environment(
    project_path: &Path,
    env_name: &str,
    skip_confirmation: bool,
    shell_override: Option<String>,
) -> Result<ValidatedShellEnv> {
    // Load configuration with inheritance applied
    let config = loader::load_config_toml_with_inheritance(project_path)?;

    // Check if we're already inside a Stand shell
    if is_stand_shell_active() {
        let current_env = get_active_environment().unwrap_or_else(|| "unknown".to_string());
        check_nesting_allowed(config.settings.nested_shell_behavior, &current_env)?;
    }

    // Check if environment exists
    let env = config.environments.get(env_name).ok_or_else(|| {
        let mut available: Vec<_> = config.environments.keys().cloned().collect();
        available.sort();
        anyhow!(
            "Environment '{}' not found. Available: {}",
            env_name,
            available.join(", ")
        )
    })?;

    // Check if confirmation is required
    if env.requires_confirmation.unwrap_or(false) && !skip_confirmation {
        // Check if stdin is a terminal - fail fast in non-interactive environments
        if !is_interactive_terminal() {
            return Err(anyhow!(
                "Environment '{}' requires confirmation but stdin is not a terminal.\n\
                 Use -y or --yes to skip confirmation in non-interactive environments.",
                env_name
            ));
        }
        // Prompt user for confirmation
        if !prompt_confirmation(env_name)? {
            return Err(anyhow!(
                "Execution cancelled. Use -y or --yes to skip confirmation."
            ));
        }
    }

    // Get shell path (use override if provided, otherwise detect from $SHELL)
    let shell_path = shell_override.unwrap_or_else(detect_user_shell);

    // Decrypt any encrypted variables
    let decrypted_vars = decrypt_variables(env.variables.clone(), project_path)
        .map_err(|e| anyhow!("Failed to decrypt variables: {}", e))?;

    // Build environment with Stand markers
    let project_root = project_path
        .to_str()
        .ok_or_else(|| anyhow!("Invalid project path"))?;
    let mut shell_env =
        build_shell_environment(decrypted_vars, env_name, project_root, &shell_path);

    // Add environment color for prompt customization
    if let Some(ref color) = env.color {
        shell_env.insert("STAND_ENV_COLOR".to_string(), color.clone());
    }

    // Add auto-exit flag (enabled by default, can be disabled with auto_exit_on_dir_change = false)
    if config.settings.auto_exit_on_dir_change != Some(false) {
        shell_env.insert("STAND_AUTO_EXIT".to_string(), "1".to_string());
    }

    Ok(ValidatedShellEnv {
        shell_path,
        env_vars: shell_env,
        env_name: env_name.to_string(),
    })
}

/// Start an interactive shell with the specified environment
///
/// # Arguments
/// * `project_path` - Path to the project directory containing .stand.toml
/// * `env_name` - Name of the environment to use
/// * `skip_confirmation` - If true, skip confirmation for environments with requires_confirmation=true
/// * `shell_override` - If provided, use this shell instead of $SHELL
pub fn start_shell_with_environment(
    project_path: &Path,
    env_name: &str,
    skip_confirmation: bool,
    shell_override: Option<String>,
) -> Result<i32> {
    let validated =
        validate_shell_environment(project_path, env_name, skip_confirmation, shell_override)?;

    // Print info message
    eprintln!(
        "Starting shell with environment '{}'. Type 'exit' to return.",
        validated.env_name
    );

    // Spawn the shell
    spawn_shell(&validated.shell_path, validated.env_vars)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::env;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_check_nesting_allowed_prevent_returns_error() {
        let result = check_nesting_allowed(Some(NestedBehavior::Prevent), "dev");
        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Already inside a Stand shell"));
        assert!(error_msg.contains("dev"));
    }

    #[test]
    fn test_check_nesting_allowed_allow_returns_ok() {
        let result = check_nesting_allowed(Some(NestedBehavior::Allow), "dev");
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_check_nesting_allowed_warn_returns_ok() {
        let result = check_nesting_allowed(Some(NestedBehavior::Warn), "dev");
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_check_nesting_allowed_default_is_prevent() {
        let result = check_nesting_allowed(None, "dev");
        assert!(result.is_err());
    }

    // Tests below use validate_shell_environment to avoid spawning actual shells
    // which could hang in CI or non-interactive environments.

    #[test]
    #[serial]
    fn test_shell_nonexistent_environment() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"


[environments.dev]
description = "Development environment"
DATABASE_URL = "postgres://localhost:5432/dev"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        let result = validate_shell_environment(dir.path(), "nonexistent", false, None);

        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Environment 'nonexistent' not found"));
        assert!(error_msg.contains("Available: dev"));
    }

    #[test]
    #[serial]
    fn test_shell_detects_nesting() {
        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"

nested_shell_behavior = "prevent"

[environments.dev]
description = "Development environment"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        // Simulate being inside a Stand shell
        env::set_var("STAND_ACTIVE", "1");
        env::set_var("STAND_ENVIRONMENT", "production");

        let result = validate_shell_environment(dir.path(), "dev", false, None);

        // Clean up
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("Already inside a Stand shell"));
        assert!(error_msg.contains("production"));
    }

    #[test]
    #[serial]
    fn test_shell_allows_nesting_when_configured() {
        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"

[settings]
nested_shell_behavior = "allow"

[environments.dev]
description = "Development environment"
TEST_VAR = "test_value"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        // Simulate being inside a Stand shell
        env::set_var("STAND_ACTIVE", "1");
        env::set_var("STAND_ENVIRONMENT", "production");

        // Use validate_shell_environment to avoid spawning shell
        let result = validate_shell_environment(dir.path(), "dev", false, None);

        // Clean up
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        // Should succeed - nesting is allowed
        assert!(result.is_ok());
        let validated = result.unwrap();
        assert_eq!(validated.env_name, "dev");
        assert!(validated.env_vars.contains_key("TEST_VAR"));
        assert!(validated.env_vars.contains_key("STAND_ACTIVE"));
    }

    #[test]
    #[serial]
    fn test_shell_requires_confirmation_non_tty() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        // Force non-TTY behavior for reliable testing
        env::set_var("STAND_FORCE_NON_TTY", "1");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"


[environments.prod]
description = "Production environment"
requires_confirmation = true
DATABASE_URL = "postgres://prod:5432/prod"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        let result = validate_shell_environment(dir.path(), "prod", false, None);

        // Clean up
        env::remove_var("STAND_FORCE_NON_TTY");

        assert!(result.is_err());
        let error_msg = format!("{}", result.unwrap_err());
        assert!(error_msg.contains("requires confirmation"));
        assert!(error_msg.contains("not a terminal"));
    }

    #[test]
    #[serial]
    fn test_shell_skips_confirmation_with_yes_flag() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"


[environments.prod]
description = "Production environment"
requires_confirmation = true
DATABASE_URL = "postgres://prod:5432/prod"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        // With skip_confirmation = true, should succeed
        let result = validate_shell_environment(dir.path(), "prod", true, None);

        assert!(result.is_ok());
        let validated = result.unwrap();
        assert_eq!(validated.env_name, "prod");
    }

    #[test]
    #[serial]
    fn test_shell_auto_exit_sets_env_var_when_enabled() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"

[settings]
auto_exit_on_dir_change = true

[environments.dev]
description = "Development environment"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        let result = validate_shell_environment(dir.path(), "dev", false, None);

        assert!(result.is_ok());
        let validated = result.unwrap();
        // STAND_AUTO_EXIT should be set when auto_exit_on_dir_change = true
        assert_eq!(
            validated.env_vars.get("STAND_AUTO_EXIT"),
            Some(&"1".to_string())
        );
    }

    #[test]
    #[serial]
    fn test_shell_auto_exit_not_set_when_disabled() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"

[settings]
auto_exit_on_dir_change = false

[environments.dev]
description = "Development environment"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        let result = validate_shell_environment(dir.path(), "dev", false, None);

        assert!(result.is_ok());
        let validated = result.unwrap();
        // STAND_AUTO_EXIT should NOT be set when auto_exit_on_dir_change = false
        assert!(!validated.env_vars.contains_key("STAND_AUTO_EXIT"));
    }

    #[test]
    #[serial]
    fn test_shell_auto_exit_enabled_by_default() {
        // Ensure we're not in a Stand shell
        env::remove_var("STAND_ACTIVE");
        env::remove_var("STAND_ENVIRONMENT");

        let dir = tempdir().unwrap();
        let config_content = r#"
version = "2.0"

[environments.dev]
description = "Development environment"
"#;

        let config_path = dir.path().join(".stand.toml");
        fs::write(&config_path, config_content).unwrap();

        let result = validate_shell_environment(dir.path(), "dev", false, None);

        assert!(result.is_ok());
        let validated = result.unwrap();
        // STAND_AUTO_EXIT should be set by default (when setting is not specified)
        assert_eq!(
            validated.env_vars.get("STAND_AUTO_EXIT"),
            Some(&"1".to_string())
        );
    }
}