bashrs 7.0.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

//! End-to-End Pipeline Tests
//!
//! Tests the complete transpilation pipeline including:
//! - CLI invocation
//! - Transpilation (build command)
//! - Binary creation (compile command)
//! - Script execution
//! - Multi-shell validation

use std::fs;
use std::process::Command;
use tempfile::TempDir;

#[test]
fn test_e2e_build_pipeline() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Step 1: Create a Rash source file
    let source = r#"
fn main() {
    let greeting = "Hello from E2E test!";
    let version = "1.0.0";
    echo(greeting);
    echo(version);
}

fn echo(msg: &str) {}
"#;

    let input_file = temp_dir.path().join("app.rs");
    let output_file = temp_dir.path().join("app.sh");

    fs::write(&input_file, source).expect("Failed to write source");

    // Step 2: Transpile with bashrs build
    let build_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "build"])
        .arg(input_file.to_str().unwrap())
        .arg("-o")
        .arg(output_file.to_str().unwrap())
        .output()
        .expect("Failed to run bashrs build");

    assert!(
        build_output.status.success(),
        "Build failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&build_output.stdout),
        String::from_utf8_lossy(&build_output.stderr)
    );

    // Step 3: Verify output file exists
    assert!(output_file.exists(), "Output file not created");

    let script_content = fs::read_to_string(&output_file).expect("Failed to read output file");

    // Step 4: Verify POSIX compliance markers
    assert!(script_content.contains("#!/bin/sh"), "Missing shebang");
    assert!(
        script_content.contains("Generated by"),
        "Missing generation comment"
    );

    // Step 5: Execute the generated script
    let run_output = Command::new("sh")
        .arg(&output_file)
        .output()
        .expect("Failed to execute generated script");

    assert!(
        run_output.status.success(),
        "Script execution failed:\nstderr: {}",
        String::from_utf8_lossy(&run_output.stderr)
    );

    let stdout = String::from_utf8_lossy(&run_output.stdout);
    assert!(
        stdout.contains("Hello from E2E test!"),
        "Output missing greeting"
    );
    assert!(stdout.contains("1.0.0"), "Output missing version");
}

#[test]
fn test_e2e_check_command() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Valid Rash code
    let valid_source = r#"
fn main() {
    let x = 42;
    let y = "test";
}
"#;

    let input_file = temp_dir.path().join("valid.rs");
    fs::write(&input_file, valid_source).expect("Failed to write source");

    // Test check command
    let check_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "check"])
        .arg(input_file.to_str().unwrap())
        .output()
        .expect("Failed to run bashrs check");

    assert!(
        check_output.status.success(),
        "Check failed for valid code:\nstderr: {}",
        String::from_utf8_lossy(&check_output.stderr)
    );
}

#[test]
fn test_e2e_check_command_invalid_syntax() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Invalid Rust syntax
    let invalid_source = "fn main( { }"; // Missing closing paren

    let input_file = temp_dir.path().join("invalid.rs");
    fs::write(&input_file, invalid_source).expect("Failed to write source");

    // Test check command should fail
    let check_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "check"])
        .arg(input_file.to_str().unwrap())
        .output()
        .expect("Failed to run bashrs check");

    assert!(
        !check_output.status.success(),
        "Check should fail for invalid syntax"
    );
}

#[test]
fn test_e2e_multi_shell_execution() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let source = r#"
fn main() {
    let test_var = "POSIX compatible";
    echo(test_var);
}

fn echo(msg: &str) {}
"#;

    let input_file = temp_dir.path().join("posix_test.rs");
    let output_file = temp_dir.path().join("posix_test.sh");

    fs::write(&input_file, source).expect("Failed to write source");

    // Transpile
    let build_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "build"])
        .arg(input_file.to_str().unwrap())
        .arg("-o")
        .arg(output_file.to_str().unwrap())
        .output()
        .expect("Failed to run bashrs build");

    assert!(build_output.status.success(), "Build failed");

    // Test with multiple shells
    let shells = vec!["sh", "dash", "bash"];

    for shell in shells {
        // Check if shell is available
        let which_output = Command::new("which")
            .arg(shell)
            .output()
            .expect("Failed to run which");

        if !which_output.status.success() {
            eprintln!("Skipping {} (not installed)", shell);
            continue;
        }

        // Run script with this shell
        let run_output = Command::new(shell)
            .arg(&output_file)
            .output()
            .unwrap_or_else(|_| panic!("Failed to run with {}", shell));

        assert!(
            run_output.status.success(),
            "Script failed with {}:\nstderr: {}",
            shell,
            String::from_utf8_lossy(&run_output.stderr)
        );

        let stdout = String::from_utf8_lossy(&run_output.stdout);
        assert!(
            stdout.contains("POSIX compatible"),
            "{} output missing expected text",
            shell
        );
    }
}

#[test]
fn test_e2e_compile_self_extracting() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let source = r#"
fn main() {
    let message = "Self-extracting binary!";
    echo(message);
}

fn echo(msg: &str) {}
"#;

    let input_file = temp_dir.path().join("binary.rs");
    let output_file = temp_dir.path().join("binary.sh");

    fs::write(&input_file, source).expect("Failed to write source");

    // Compile to self-extracting script
    let compile_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "compile"])
        .arg(input_file.to_str().unwrap())
        .arg("-o")
        .arg(output_file.to_str().unwrap())
        .arg("--self-extracting")
        .output()
        .expect("Failed to run bashrs compile");

    if !compile_output.status.success() {
        eprintln!(
            "Compile stderr: {}",
            String::from_utf8_lossy(&compile_output.stderr)
        );
        eprintln!("Note: Binary compilation may not be fully implemented in v1.0");
        // Don't fail test if binary compilation is not yet complete
        return;
    }

    assert!(output_file.exists(), "Self-extracting script not created");

    // Verify it's executable
    let metadata = fs::metadata(&output_file).expect("Failed to get metadata");

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let permissions = metadata.permissions();
        assert!(permissions.mode() & 0o111 != 0, "Script not executable");
    }
}

#[test]
fn test_e2e_verification_levels() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let source = r#"
fn main() {
    let x = 1 + 2;
}
"#;

    let input_file = temp_dir.path().join("verify_test.rs");
    fs::write(&input_file, source).expect("Failed to write source");

    // Test different verification levels
    let levels = vec!["none", "basic", "strict", "paranoid"];

    for level in levels {
        let output_file = temp_dir.path().join(format!("verify_{}.sh", level));

        let build_output = Command::new("cargo")
            .args(["run", "--bin", "bashrs", "--"])
            .arg("--verify")
            .arg(level)
            .arg("build")
            .arg(input_file.to_str().unwrap())
            .arg("-o")
            .arg(output_file.to_str().unwrap())
            .output()
            .unwrap_or_else(|_| panic!("Failed to build with verify={}", level));

        if !build_output.status.success() {
            eprintln!("Build with verify={} failed (may be expected)", level);
            continue;
        }

        assert!(
            output_file.exists(),
            "Output not created for verify={}",
            level
        );
    }
}

#[test]
fn test_e2e_target_dialects() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let source = r#"
fn main() {
    let msg = "Dialect test";
    echo(msg);
}

fn echo(msg: &str) {}
"#;

    let input_file = temp_dir.path().join("dialect_test.rs");
    fs::write(&input_file, source).expect("Failed to write source");

    // Test different target dialects
    let dialects = vec!["posix", "bash", "dash", "ash"];

    for dialect in dialects {
        let output_file = temp_dir.path().join(format!("target_{}.sh", dialect));

        let build_output = Command::new("cargo")
            .args(["run", "--bin", "bashrs", "--"])
            .arg("--target")
            .arg(dialect)
            .arg("build")
            .arg(input_file.to_str().unwrap())
            .arg("-o")
            .arg(output_file.to_str().unwrap())
            .output()
            .unwrap_or_else(|_| panic!("Failed to build with target={}", dialect));

        assert!(
            build_output.status.success(),
            "Build failed for target={}:\nstderr: {}",
            dialect,
            String::from_utf8_lossy(&build_output.stderr)
        );

        assert!(
            output_file.exists(),
            "Output not created for target={}",
            dialect
        );

        // Verify shebang matches dialect
        let content = fs::read_to_string(&output_file).expect("Failed to read output");
        assert!(
            content.starts_with("#!/bin/sh"),
            "Invalid shebang for {}",
            dialect
        );
    }
}

#[test]
fn test_e2e_complex_example() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Use one of our comprehensive examples
    let source = r#"
fn main() {
    let project_name = "test-project";
    let version = "1.0.0";

    echo("=== Installation ===");
    echo(&format!("Project: {}", project_name));
    echo(&format!("Version: {}", version));

    if check_prerequisites() {
        echo("✓ Prerequisites OK");
    } else {
        echo("✗ Prerequisites failed");
    }

    echo("Installation complete");
}

fn check_prerequisites() -> bool {
    true
}

fn echo(msg: &str) {}
fn format(template: &str, args: &str) -> String {
    String::new()
}
"#;

    let input_file = temp_dir.path().join("complex.rs");
    let output_file = temp_dir.path().join("complex.sh");

    fs::write(&input_file, source).expect("Failed to write source");

    // Transpile
    let build_output = Command::new("cargo")
        .args(["run", "--bin", "bashrs", "--", "build"])
        .arg(input_file.to_str().unwrap())
        .arg("-o")
        .arg(output_file.to_str().unwrap())
        .output()
        .expect("Failed to run bashrs build");

    if !build_output.status.success() {
        eprintln!("Complex example failed (may contain unsupported features)");
        return;
    }

    // Execute
    let run_output = Command::new("sh")
        .arg(&output_file)
        .output()
        .expect("Failed to execute script");

    if run_output.status.success() {
        let stdout = String::from_utf8_lossy(&run_output.stdout);
        assert!(stdout.contains("Installation"), "Output missing content");
    }
}