bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
//! Container-native test matrix for installers (#110)
//!
//! Provides parallel multi-distro testing using Podman or Docker containers.
//!
//! # Example
//!
//! ```bash
//! # Run full matrix
//! bashrs installer test ./my-installer --matrix
//!
//! # Test specific platforms
//! bashrs installer test ./my-installer --matrix ubuntu:22.04,debian:12
//!
//! # Test specific architecture
//! bashrs installer test ./my-installer --matrix --arch arm64
//!
//! # Generate matrix report
//! bashrs installer test ./my-installer --matrix --report matrix-results.json
//! ```

use crate::models::{Error, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Container runtime type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContainerRuntime {
    /// Docker container runtime
    #[default]
    Docker,
    /// Podman container runtime (rootless preferred)
    Podman,
}

impl ContainerRuntime {
    /// Get the command name for this runtime
    pub fn command(&self) -> &'static str {
        match self {
            Self::Docker => "docker",
            Self::Podman => "podman",
        }
    }

    /// Detect available container runtime
    pub fn detect() -> Option<Self> {
        // Check for podman first (preferred for rootless)
        if std::process::Command::new("podman")
            .arg("--version")
            .output()
            .is_ok()
        {
            return Some(Self::Podman);
        }

        // Fall back to docker
        if std::process::Command::new("docker")
            .arg("--version")
            .output()
            .is_ok()
        {
            return Some(Self::Docker);
        }

        None
    }

    /// Check if runtime is available
    pub fn is_available(&self) -> bool {
        std::process::Command::new(self.command())
            .arg("--version")
            .output()
            .is_ok()
    }
}

/// CPU architecture
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Architecture {
    /// x86_64 / amd64
    #[default]
    Amd64,
    /// aarch64 / arm64
    Arm64,
    /// armv7
    Armv7,
}

impl Architecture {
    /// Parse from string
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "amd64" | "x86_64" | "x64" => Some(Self::Amd64),
            "arm64" | "aarch64" => Some(Self::Arm64),
            "armv7" | "arm" | "armhf" => Some(Self::Armv7),
            _ => None,
        }
    }

    /// Get docker platform string
    pub fn platform_string(&self) -> &'static str {
        match self {
            Self::Amd64 => "linux/amd64",
            Self::Arm64 => "linux/arm64",
            Self::Armv7 => "linux/arm/v7",
        }
    }

    /// Get display name
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Amd64 => "amd64",
            Self::Arm64 => "arm64",
            Self::Armv7 => "armv7",
        }
    }
}

/// A platform to test against
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Platform {
    /// Container image (e.g., "ubuntu:22.04")
    pub image: String,

    /// Target architecture
    pub arch: Architecture,

    /// Optional platform-specific notes
    pub notes: Option<String>,
}

impl Platform {
    /// Create a new platform
    pub fn new(image: &str, arch: Architecture) -> Self {
        Self {
            image: image.to_string(),
            arch,
            notes: None,
        }
    }

    /// Create with notes
    pub fn with_notes(image: &str, arch: Architecture, notes: &str) -> Self {
        Self {
            image: image.to_string(),
            arch,
            notes: Some(notes.to_string()),
        }
    }

    /// Parse from string like "ubuntu:22.04" or "ubuntu:22.04@arm64"
    pub fn parse(s: &str) -> Self {
        if let Some((image, arch_str)) = s.split_once('@') {
            let arch = Architecture::parse(arch_str).unwrap_or_default();
            Self::new(image, arch)
        } else {
            Self::new(s, Architecture::default())
        }
    }

    /// Get display string
    pub fn display(&self) -> String {
        format!("{}@{}", self.image, self.arch.display_name())
    }
}

/// Test status for a platform
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TestStatus {
    /// Tests passed
    Passed,
    /// Tests failed
    Failed,
    /// Tests were skipped
    Skipped,
    /// Tests are running
    Running,
    /// Tests are pending
    Pending,
    /// Test timed out
    TimedOut,
}

impl TestStatus {
    /// Get status symbol
    pub fn symbol(&self) -> &'static str {
        match self {
            Self::Passed => "",
            Self::Failed => "",
            Self::Skipped => "",
            Self::Running => "",
            Self::Pending => "",
            Self::TimedOut => "",
        }
    }

    /// Get status text
    pub fn text(&self) -> &'static str {
        match self {
            Self::Passed => "PASS",
            Self::Failed => "FAIL",
            Self::Skipped => "SKIP",
            Self::Running => "RUN",
            Self::Pending => "PEND",
            Self::TimedOut => "TIMEOUT",
        }
    }

    /// Check if status indicates success
    pub fn is_success(&self) -> bool {
        matches!(self, Self::Passed | Self::Skipped)
    }
}

/// Result of testing on a single platform
#[derive(Debug, Clone)]
pub struct PlatformResult {
    /// Platform that was tested
    pub platform: Platform,

    /// Test status
    pub status: TestStatus,

    /// Test duration
    pub duration: Duration,

    /// Number of steps that passed
    pub steps_passed: usize,

    /// Total number of steps
    pub steps_total: usize,

    /// Container ID (if applicable)
    pub container_id: Option<String>,

    /// Captured logs
    pub logs: String,

    /// Error message (if failed)
    pub error: Option<String>,

    /// Individual step results
    pub step_results: Vec<StepTestResult>,
}

impl PlatformResult {
    /// Create a passed result
    pub fn passed(platform: Platform, duration: Duration, steps: usize) -> Self {
        Self {
            platform,
            status: TestStatus::Passed,
            duration,
            steps_passed: steps,
            steps_total: steps,
            container_id: None,
            logs: String::new(),
            error: None,
            step_results: Vec::new(),
        }
    }

    /// Create a failed result
    pub fn failed(platform: Platform, duration: Duration, error: &str) -> Self {
        Self {
            platform,
            status: TestStatus::Failed,
            duration,
            steps_passed: 0,
            steps_total: 0,
            container_id: None,
            logs: String::new(),
            error: Some(error.to_string()),
            step_results: Vec::new(),
        }
    }

    /// Create a skipped result
    pub fn skipped(platform: Platform, reason: &str) -> Self {
        Self {
            platform,
            status: TestStatus::Skipped,
            duration: Duration::ZERO,
            steps_passed: 0,
            steps_total: 0,
            container_id: None,
            logs: String::new(),
            error: Some(reason.to_string()),
            step_results: Vec::new(),
        }
    }

    /// Format as table row
    pub fn format_row(&self) -> String {
        let _steps_str = if self.steps_total > 0 {
            format!("{}/{} passed", self.steps_passed, self.steps_total)
        } else {
            "N/A".to_string()
        };

        let duration_str = if self.duration.as_secs() > 0 {
            format!(
                "{}m {:02}s",
                self.duration.as_secs() / 60,
                self.duration.as_secs() % 60
            )
        } else {
            "-".to_string()
        };

        let notes = if let Some(ref err) = self.error {
            format!("{}", truncate(err, 40))
        } else {
            String::new()
        };

        format!(
            "  {:<22} {:<8} {} {}    {}{}",
            truncate(&self.platform.image, 22),
            self.platform.arch.display_name(),
            self.status.symbol(),
            self.status.text(),
            duration_str,
            notes
        )
    }
}

/// Result of testing a single step
#[derive(Debug, Clone)]
pub struct StepTestResult {
    /// Step ID
    pub step_id: String,

    /// Step name
    pub step_name: String,

    /// Whether step passed
    pub passed: bool,

    /// Duration
    pub duration: Duration,

    /// Error message if failed
    pub error: Option<String>,
}

/// Resource limits for containers
#[derive(Debug, Clone)]
pub struct ResourceLimits {
    /// Memory limit (e.g., "2G")
    pub memory: Option<String>,

    /// CPU limit (e.g., 2.0 for 2 CPUs)
    pub cpus: Option<f64>,

    /// Timeout for the entire test
    pub timeout: Duration,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            memory: Some("2G".to_string()),
            cpus: Some(2.0),
            timeout: Duration::from_secs(30 * 60), // 30 minutes
        }
    }
}

/// Configuration for container tests
#[derive(Debug, Clone)]
pub struct ContainerConfig {
    /// Container image
    pub image: String,

    /// Platform/architecture
    pub platform: Option<String>,

    /// Volume mounts (host_path, container_path)
    pub volumes: Vec<(PathBuf, PathBuf)>,

    /// Environment variables
    pub env: HashMap<String, String>,

    /// Resource limits
    pub limits: ResourceLimits,

    /// Working directory in container
    pub workdir: Option<PathBuf>,

    /// Whether to remove container after test
    pub remove_after: bool,
}

impl Default for ContainerConfig {
    fn default() -> Self {
        Self {
            image: String::new(),
            platform: None,
            volumes: Vec::new(),
            env: HashMap::new(),
            limits: ResourceLimits::default(),
            workdir: None,
            remove_after: true,
        }
    }
}

impl ContainerConfig {
    /// Create config for an image
    pub fn for_image(image: &str) -> Self {
        Self {
            image: image.to_string(),
            ..Default::default()
        }
    }

    /// Add a volume mount
    pub fn with_volume(mut self, host: impl AsRef<Path>, container: impl AsRef<Path>) -> Self {
        self.volumes.push((
            host.as_ref().to_path_buf(),
            container.as_ref().to_path_buf(),
        ));
        self
    }

    /// Add an environment variable
    pub fn with_env(mut self, key: &str, value: &str) -> Self {
        self.env.insert(key.to_string(), value.to_string());
        self
    }

    /// Set platform
    pub fn with_platform(mut self, platform: &str) -> Self {
        self.platform = Some(platform.to_string());
        self
    }
}

/// Matrix configuration
#[derive(Debug, Clone)]
pub struct MatrixConfig {
    /// Platforms to test
    pub platforms: Vec<Platform>,

    /// Maximum parallel tests
    pub parallelism: usize,

    /// Container runtime to use
    pub runtime: ContainerRuntime,

    /// Resource limits
    pub limits: ResourceLimits,

    /// Whether to continue on failure
    pub continue_on_failure: bool,

    /// Report output path
    pub report_path: Option<PathBuf>,
}

impl Default for MatrixConfig {
    fn default() -> Self {
        Self {
            platforms: Vec::new(),
            parallelism: 4,
            runtime: ContainerRuntime::default(),
            limits: ResourceLimits::default(),
            continue_on_failure: true,
            report_path: None,
        }
    }
}


include!("container_part2_incl2.rs");