pipeline-service 2.1.0

Pipeline execution service for roxid
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
// Shell Runner
// Executes script, bash, pwsh, and powershell steps

use crate::parser::models::{StepResult, StepStatus, Value};

use std::collections::HashMap;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;

/// Shell types supported by the runner
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
    /// Default shell (sh on Unix, cmd on Windows)
    Default,
    /// Bash shell
    Bash,
    /// PowerShell Core (cross-platform)
    Pwsh,
    /// Windows PowerShell (Windows only, falls back to pwsh)
    PowerShell,
}

impl Shell {
    /// Get the shell executable and arguments
    fn get_command(&self) -> (&'static str, &'static [&'static str]) {
        match self {
            Shell::Default => {
                if cfg!(target_os = "windows") {
                    ("cmd", &["/C"])
                } else {
                    ("sh", &["-c"])
                }
            }
            Shell::Bash => ("bash", &["-c"]),
            Shell::Pwsh => ("pwsh", &["-NoLogo", "-NoProfile", "-Command"]),
            Shell::PowerShell => {
                if cfg!(target_os = "windows") {
                    ("powershell.exe", &["-NoLogo", "-NoProfile", "-Command"])
                } else {
                    // Fall back to pwsh on non-Windows
                    ("pwsh", &["-NoLogo", "-NoProfile", "-Command"])
                }
            }
        }
    }
}

/// Configuration for shell execution
#[derive(Debug, Clone, Default)]
pub struct ShellConfig {
    /// Working directory for the script
    pub working_dir: Option<String>,
    /// Fail if there's output to stderr
    pub fail_on_stderr: bool,
    /// Error action preference (for PowerShell)
    pub error_action_preference: Option<String>,
    /// Timeout in seconds (None = no timeout)
    pub timeout: Option<Duration>,
}

/// Output collected during script execution
#[derive(Debug, Clone, Default)]
pub struct ShellOutput {
    /// Standard output
    pub stdout: String,
    /// Standard error
    pub stderr: String,
    /// Exit code (if available)
    pub exit_code: Option<i32>,
    /// Outputs extracted from logging commands
    pub outputs: HashMap<String, String>,
    /// Variables set via logging commands
    pub variables: HashMap<String, Value>,
}

/// Callback for handling output lines in real-time
pub type OutputCallback = Box<dyn Fn(&str, bool) + Send + Sync>;

/// Shell runner for executing scripts
pub struct ShellRunner {
    /// Default shell to use
    default_shell: Shell,
}

impl ShellRunner {
    /// Create a new shell runner with the default shell
    pub fn new() -> Self {
        Self {
            default_shell: Shell::Default,
        }
    }

    /// Create a shell runner with a specific default shell
    pub fn with_default_shell(shell: Shell) -> Self {
        Self {
            default_shell: shell,
        }
    }

    /// Execute a script using the default shell
    pub async fn run_script(
        &self,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
    ) -> ShellOutput {
        self.run_with_shell(self.default_shell, script, env, working_dir, config)
            .await
    }

    /// Execute a bash script
    pub async fn run_bash(
        &self,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
    ) -> ShellOutput {
        self.run_with_shell(Shell::Bash, script, env, working_dir, config)
            .await
    }

    /// Execute a PowerShell Core (pwsh) script
    pub async fn run_pwsh(
        &self,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
    ) -> ShellOutput {
        // Wrap script with error action preference if specified
        let script = if let Some(pref) = &config.error_action_preference {
            format!("$ErrorActionPreference = '{}'\n{}", pref, script)
        } else {
            script.to_string()
        };

        self.run_with_shell(Shell::Pwsh, &script, env, working_dir, config)
            .await
    }

    /// Execute a Windows PowerShell script
    pub async fn run_powershell(
        &self,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
    ) -> ShellOutput {
        // Wrap script with error action preference if specified
        let script = if let Some(pref) = &config.error_action_preference {
            format!("$ErrorActionPreference = '{}'\n{}", pref, script)
        } else {
            script.to_string()
        };

        self.run_with_shell(Shell::PowerShell, &script, env, working_dir, config)
            .await
    }

    /// Execute a script with a specific shell
    async fn run_with_shell(
        &self,
        shell: Shell,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
    ) -> ShellOutput {
        let (shell_cmd, shell_args) = shell.get_command();

        // Determine working directory
        let work_dir = config
            .working_dir
            .as_ref()
            .map(Path::new)
            .unwrap_or(working_dir);

        let mut cmd = Command::new(shell_cmd);
        cmd.args(shell_args);
        cmd.arg(script);
        cmd.current_dir(work_dir);
        cmd.envs(env);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        // Spawn the process
        let mut child = match cmd.spawn() {
            Ok(child) => child,
            Err(e) => {
                return ShellOutput {
                    stdout: String::new(),
                    stderr: format!("Failed to spawn shell process '{}': {}", shell_cmd, e),
                    exit_code: None,
                    outputs: HashMap::new(),
                    variables: HashMap::new(),
                };
            }
        };

        let stdout = child.stdout.take().expect("stdout was piped");
        let stderr = child.stderr.take().expect("stderr was piped");

        // Read output streams concurrently
        let stdout_reader = BufReader::new(stdout);
        let stderr_reader = BufReader::new(stderr);

        let stdout_handle = tokio::spawn(async move {
            let mut lines = stdout_reader.lines();
            let mut output = String::new();
            while let Ok(Some(line)) = lines.next_line().await {
                if !output.is_empty() {
                    output.push('\n');
                }
                output.push_str(&line);
            }
            output
        });

        let stderr_handle = tokio::spawn(async move {
            let mut lines = stderr_reader.lines();
            let mut output = String::new();
            while let Ok(Some(line)) = lines.next_line().await {
                if !output.is_empty() {
                    output.push('\n');
                }
                output.push_str(&line);
            }
            output
        });

        // Wait for completion with optional timeout
        let wait_result = if let Some(timeout) = config.timeout {
            match tokio::time::timeout(timeout, child.wait()).await {
                Ok(result) => result,
                Err(_) => {
                    // Timeout - kill the process
                    let _ = child.kill().await;
                    return ShellOutput {
                        stdout: stdout_handle.await.unwrap_or_default(),
                        stderr: format!("Process timed out after {:?}", timeout),
                        exit_code: None,
                        outputs: HashMap::new(),
                        variables: HashMap::new(),
                    };
                }
            }
        } else {
            child.wait().await
        };

        let exit_code = wait_result.ok().and_then(|s| s.code());
        let stdout = stdout_handle.await.unwrap_or_default();
        let stderr = stderr_handle.await.unwrap_or_default();

        // Parse logging commands from stdout
        let (outputs, variables) = parse_logging_commands(&stdout);

        ShellOutput {
            stdout,
            stderr,
            exit_code,
            outputs,
            variables,
        }
    }

    /// Execute a script with real-time output streaming
    pub async fn run_script_streaming(
        &self,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
        on_output: OutputCallback,
    ) -> ShellOutput {
        self.run_with_shell_streaming(
            self.default_shell,
            script,
            env,
            working_dir,
            config,
            on_output,
        )
        .await
    }

    /// Execute a script with real-time output streaming using a specific shell
    async fn run_with_shell_streaming(
        &self,
        shell: Shell,
        script: &str,
        env: &HashMap<String, String>,
        working_dir: &Path,
        config: &ShellConfig,
        on_output: OutputCallback,
    ) -> ShellOutput {
        let (shell_cmd, shell_args) = shell.get_command();

        let work_dir = config
            .working_dir
            .as_ref()
            .map(Path::new)
            .unwrap_or(working_dir);

        let mut cmd = Command::new(shell_cmd);
        cmd.args(shell_args);
        cmd.arg(script);
        cmd.current_dir(work_dir);
        cmd.envs(env);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        let mut child = match cmd.spawn() {
            Ok(child) => child,
            Err(e) => {
                return ShellOutput {
                    stdout: String::new(),
                    stderr: format!("Failed to spawn shell process '{}': {}", shell_cmd, e),
                    exit_code: None,
                    outputs: HashMap::new(),
                    variables: HashMap::new(),
                };
            }
        };

        let stdout = child.stdout.take().expect("stdout was piped");
        let stderr = child.stderr.take().expect("stderr was piped");

        let stdout_reader = BufReader::new(stdout);
        let stderr_reader = BufReader::new(stderr);

        let on_output = std::sync::Arc::new(on_output);
        let on_output_stdout = on_output.clone();
        let on_output_stderr = on_output;

        // Stream stdout
        let stdout_handle = tokio::spawn(async move {
            let mut lines = stdout_reader.lines();
            let mut output = String::new();
            while let Ok(Some(line)) = lines.next_line().await {
                on_output_stdout(&line, false);
                if !output.is_empty() {
                    output.push('\n');
                }
                output.push_str(&line);
            }
            output
        });

        // Stream stderr
        let stderr_handle = tokio::spawn(async move {
            let mut lines = stderr_reader.lines();
            let mut output = String::new();
            while let Ok(Some(line)) = lines.next_line().await {
                on_output_stderr(&line, true);
                if !output.is_empty() {
                    output.push('\n');
                }
                output.push_str(&line);
            }
            output
        });

        let wait_result = if let Some(timeout) = config.timeout {
            match tokio::time::timeout(timeout, child.wait()).await {
                Ok(result) => result,
                Err(_) => {
                    let _ = child.kill().await;
                    return ShellOutput {
                        stdout: stdout_handle.await.unwrap_or_default(),
                        stderr: format!("Process timed out after {:?}", timeout),
                        exit_code: None,
                        outputs: HashMap::new(),
                        variables: HashMap::new(),
                    };
                }
            }
        } else {
            child.wait().await
        };

        let exit_code = wait_result.ok().and_then(|s| s.code());
        let stdout = stdout_handle.await.unwrap_or_default();
        let stderr = stderr_handle.await.unwrap_or_default();

        let (outputs, variables) = parse_logging_commands(&stdout);

        ShellOutput {
            stdout,
            stderr,
            exit_code,
            outputs,
            variables,
        }
    }

    /// Convert shell output to a step result
    pub fn to_step_result(
        &self,
        output: ShellOutput,
        step_name: Option<String>,
        display_name: Option<String>,
        fail_on_stderr: bool,
        duration: Duration,
    ) -> StepResult {
        let status = if output.exit_code.map(|c| c != 0).unwrap_or(true)
            || (fail_on_stderr && !output.stderr.is_empty())
        {
            StepStatus::Failed
        } else {
            StepStatus::Succeeded
        };

        StepResult {
            step_name,
            display_name,
            status,
            output: output.stdout,
            error: if output.stderr.is_empty() {
                None
            } else {
                Some(output.stderr)
            },
            duration,
            exit_code: output.exit_code,
            outputs: output.outputs,
        }
    }
}

impl Default for ShellRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse Azure DevOps logging commands from output
fn parse_logging_commands(output: &str) -> (HashMap<String, String>, HashMap<String, Value>) {
    let mut outputs = HashMap::new();
    let mut variables = HashMap::new();

    for line in output.lines() {
        // ##vso[task.setvariable variable=name;isoutput=true;issecret=false]value
        if let Some(rest) = line.strip_prefix("##vso[task.setvariable") {
            if let Some((props, value)) = rest.split_once(']') {
                let mut var_name = None;
                let mut is_output = false;
                let mut is_secret = false;

                for prop in props.split(';') {
                    let prop = prop.trim();
                    if let Some(name) = prop.strip_prefix("variable=") {
                        var_name = Some(name.to_string());
                    } else if prop == "isoutput=true" || prop == "isOutput=true" {
                        is_output = true;
                    } else if prop == "issecret=true" || prop == "isSecret=true" {
                        is_secret = true;
                    }
                }

                if let Some(name) = var_name {
                    if is_output {
                        outputs.insert(name.clone(), value.to_string());
                    }
                    if !is_secret {
                        variables.insert(name, Value::String(value.to_string()));
                    }
                }
            }
        }
        // ##vso[task.setVariable variable=name]value (alternate format)
        else if let Some(rest) = line.strip_prefix("##vso[task.setVariable") {
            if let Some((props, value)) = rest.split_once(']') {
                let mut var_name = None;
                let mut is_output = false;
                let mut is_secret = false;

                for prop in props.split(';') {
                    let prop = prop.trim();
                    if let Some(name) = prop.strip_prefix("variable=") {
                        var_name = Some(name.to_string());
                    } else if prop == "isoutput=true" || prop == "isOutput=true" {
                        is_output = true;
                    } else if prop == "issecret=true" || prop == "isSecret=true" {
                        is_secret = true;
                    }
                }

                if let Some(name) = var_name {
                    if is_output {
                        outputs.insert(name.clone(), value.to_string());
                    }
                    if !is_secret {
                        variables.insert(name, Value::String(value.to_string()));
                    }
                }
            }
        }
        // ##vso[task.prependpath]path
        else if let Some(rest) = line.strip_prefix("##vso[task.prependpath]") {
            // Store prepend path requests
            let existing = variables
                .entry("_PREPEND_PATH".to_string())
                .or_insert_with(|| Value::Array(vec![]));
            if let Value::Array(arr) = existing {
                arr.push(Value::String(rest.to_string()));
            }
        }
        // ##vso[task.uploadfile]path
        else if let Some(rest) = line.strip_prefix("##vso[task.uploadfile]") {
            let existing = variables
                .entry("_UPLOAD_FILES".to_string())
                .or_insert_with(|| Value::Array(vec![]));
            if let Value::Array(arr) = existing {
                arr.push(Value::String(rest.to_string()));
            }
        }
        // ##vso[artifact.upload containerfolder=folder;artifactname=name]path
        // Skip for now - artifact handling
        // ##vso[build.addbuildtag]tag
        else if let Some(rest) = line.strip_prefix("##vso[build.addbuildtag]") {
            let existing = variables
                .entry("_BUILD_TAGS".to_string())
                .or_insert_with(|| Value::Array(vec![]));
            if let Value::Array(arr) = existing {
                arr.push(Value::String(rest.to_string()));
            }
        }
        // ##vso[task.complete result=Succeeded;]message
        else if let Some(rest) = line.strip_prefix("##vso[task.complete") {
            if let Some((props, _message)) = rest.split_once(']') {
                for prop in props.split(';') {
                    let prop = prop.trim();
                    if let Some(result) = prop.strip_prefix("result=") {
                        variables.insert(
                            "_TASK_RESULT".to_string(),
                            Value::String(result.to_string()),
                        );
                    }
                }
            }
        }
    }

    (outputs, variables)
}

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

    #[tokio::test]
    async fn test_shell_runner_echo() {
        let runner = ShellRunner::new();
        let env = HashMap::new();
        let working_dir = std::env::current_dir().unwrap();
        let config = ShellConfig::default();

        let output = runner
            .run_script("echo hello", &env, &working_dir, &config)
            .await;

        assert_eq!(output.exit_code, Some(0));
        assert!(output.stdout.contains("hello"));
        assert!(output.stderr.is_empty());
    }

    #[tokio::test]
    async fn test_shell_runner_with_env() {
        let runner = ShellRunner::new();
        let mut env = HashMap::new();
        env.insert("MY_VAR".to_string(), "test_value".to_string());
        let working_dir = std::env::current_dir().unwrap();
        let config = ShellConfig::default();

        let script = if cfg!(target_os = "windows") {
            "echo %MY_VAR%"
        } else {
            "echo $MY_VAR"
        };

        let output = runner.run_script(script, &env, &working_dir, &config).await;

        assert_eq!(output.exit_code, Some(0));
        assert!(output.stdout.contains("test_value"));
    }

    #[tokio::test]
    async fn test_shell_runner_bash() {
        let runner = ShellRunner::new();
        let env = HashMap::new();
        let working_dir = std::env::current_dir().unwrap();
        let config = ShellConfig::default();

        let output = runner
            .run_bash("echo 'bash test'", &env, &working_dir, &config)
            .await;

        // This test might fail if bash is not installed
        if output.exit_code == Some(0) {
            assert!(output.stdout.contains("bash test"));
        }
    }

    #[tokio::test]
    async fn test_shell_runner_exit_code() {
        let runner = ShellRunner::new();
        let env = HashMap::new();
        let working_dir = std::env::current_dir().unwrap();
        let config = ShellConfig::default();

        let output = runner
            .run_script("exit 42", &env, &working_dir, &config)
            .await;

        assert_eq!(output.exit_code, Some(42));
    }

    #[tokio::test]
    async fn test_shell_runner_stderr() {
        let runner = ShellRunner::new();
        let env = HashMap::new();
        let working_dir = std::env::current_dir().unwrap();
        let config = ShellConfig::default();

        let output = runner
            .run_script("echo error >&2", &env, &working_dir, &config)
            .await;

        assert_eq!(output.exit_code, Some(0));
        assert!(output.stderr.contains("error"));
    }

    #[test]
    fn test_parse_logging_commands_setvariable() {
        let output = r#"
Starting build
##vso[task.setvariable variable=version]1.0.0
##vso[task.setvariable variable=output;isoutput=true]result_value
Build complete
"#;

        let (outputs, variables) = parse_logging_commands(output);

        assert_eq!(
            variables.get("version"),
            Some(&Value::String("1.0.0".to_string()))
        );
        assert_eq!(outputs.get("output"), Some(&"result_value".to_string()));
        assert_eq!(
            variables.get("output"),
            Some(&Value::String("result_value".to_string()))
        );
    }

    #[test]
    fn test_parse_logging_commands_secret() {
        let output = "##vso[task.setvariable variable=password;issecret=true]secretvalue";

        let (outputs, variables) = parse_logging_commands(output);

        // Secrets should not be stored in variables
        assert!(!variables.contains_key("password"));
        assert!(!outputs.contains_key("password"));
    }

    #[test]
    fn test_parse_logging_commands_build_tag() {
        let output = r#"
##vso[build.addbuildtag]release
##vso[build.addbuildtag]v1.0
"#;

        let (_outputs, variables) = parse_logging_commands(output);

        let tags = variables.get("_BUILD_TAGS").unwrap();
        if let Value::Array(arr) = tags {
            assert_eq!(arr.len(), 2);
            assert_eq!(arr[0], Value::String("release".to_string()));
            assert_eq!(arr[1], Value::String("v1.0".to_string()));
        } else {
            panic!("Expected array");
        }
    }

    #[test]
    fn test_to_step_result_success() {
        let runner = ShellRunner::new();
        let output = ShellOutput {
            stdout: "Success".to_string(),
            stderr: String::new(),
            exit_code: Some(0),
            outputs: HashMap::new(),
            variables: HashMap::new(),
        };

        let result = runner.to_step_result(
            output,
            Some("test_step".to_string()),
            Some("Test Step".to_string()),
            false,
            Duration::from_secs(1),
        );

        assert_eq!(result.status, StepStatus::Succeeded);
        assert_eq!(result.output, "Success");
        assert!(result.error.is_none());
        assert_eq!(result.exit_code, Some(0));
    }

    #[test]
    fn test_to_step_result_fail_on_stderr() {
        let runner = ShellRunner::new();
        let output = ShellOutput {
            stdout: "Output".to_string(),
            stderr: "Warning message".to_string(),
            exit_code: Some(0),
            outputs: HashMap::new(),
            variables: HashMap::new(),
        };

        let result = runner.to_step_result(output, None, None, true, Duration::from_secs(1));

        assert_eq!(result.status, StepStatus::Failed);
        assert_eq!(result.error, Some("Warning message".to_string()));
    }
}