wrkflw-runtime 0.6.0

Runtime execution environment for wrkflw workflow engine
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
use crate::container::{ContainerError, ContainerOutput, ContainerRuntime};
use async_trait::async_trait;
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use tempfile::TempDir;
use which;
use wrkflw_logging;

// Global collection of resources to clean up
static EMULATION_WORKSPACES: Lazy<Mutex<Vec<PathBuf>>> = Lazy::new(|| Mutex::new(Vec::new()));
static EMULATION_PROCESSES: Lazy<Mutex<Vec<u32>>> = Lazy::new(|| Mutex::new(Vec::new()));

pub struct EmulationRuntime {
    #[allow(dead_code)]
    workspace: TempDir,
}

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

impl EmulationRuntime {
    pub fn new() -> Self {
        // Create a temporary workspace to simulate container isolation
        let workspace =
            tempfile::tempdir().expect("Failed to create temporary workspace for emulation");

        // Track this workspace for cleanup
        if let Ok(mut workspaces) = EMULATION_WORKSPACES.lock() {
            workspaces.push(workspace.path().to_path_buf());
        }

        EmulationRuntime { workspace }
    }

    #[allow(dead_code)]
    fn prepare_workspace(&self, _working_dir: &Path, volumes: &[(&Path, &Path)]) -> PathBuf {
        // Get the container root - this is the emulation workspace directory
        let container_root = self.workspace.path().to_path_buf();

        // Make sure we have a github/workspace subdirectory which is where
        // commands will be executed
        let github_workspace = container_root.join("github").join("workspace");
        fs::create_dir_all(&github_workspace)
            .expect("Failed to create github/workspace directory structure");

        // Map all volumes
        for (host_path, container_path) in volumes {
            // Determine target path - if it starts with /github/workspace, it goes to our workspace dir
            let target_path = if container_path.starts_with("/github/workspace") {
                // Map /github/workspace to our github_workspace directory
                let rel_path = container_path
                    .strip_prefix("/github/workspace")
                    .unwrap_or(Path::new(""));
                github_workspace.join(rel_path)
            } else if container_path.starts_with("/") {
                // Other absolute paths go under container_root
                container_root.join(container_path.strip_prefix("/").unwrap_or(container_path))
            } else {
                // Relative paths go directly under container_root
                container_root.join(container_path)
            };

            // Create parent directories
            if let Some(parent) = target_path.parent() {
                fs::create_dir_all(parent).expect("Failed to create directory structure");
            }

            // For directories, copy content recursively
            if host_path.is_dir() {
                // If the host path is the project root and container path is the workspace,
                // we want to copy all project files to the github/workspace directory
                if *container_path == Path::new("/github/workspace") {
                    // Use a recursive copy function to copy all files and directories
                    copy_directory_contents(host_path, &github_workspace)
                        .expect("Failed to copy project files to workspace");
                } else {
                    // Create the target directory
                    fs::create_dir_all(&target_path).expect("Failed to create target directory");

                    // Copy files in this directory (not recursive for simplicity)
                    for entry in fs::read_dir(host_path)
                        .expect("Failed to read source directory")
                        .flatten()
                    {
                        let source = entry.path();
                        let file_name = match source.file_name() {
                            Some(name) => name,
                            None => {
                                eprintln!(
                                    "Warning: Could not get file name from path: {:?}",
                                    source
                                );
                                continue; // Skip this file
                            }
                        };
                        let dest = target_path.join(file_name);

                        if source.is_file() {
                            if let Err(e) = fs::copy(&source, &dest) {
                                eprintln!(
                                    "Warning: Failed to copy file from {:?} to {:?}: {}",
                                    &source, &dest, e
                                );
                            }
                        } else {
                            // We could make this recursive if needed
                            fs::create_dir_all(&dest).expect("Failed to create subdirectory");
                        }
                    }
                }
            } else if host_path.is_file() {
                // Copy individual file
                let file_name = match host_path.file_name() {
                    Some(name) => name,
                    None => {
                        eprintln!(
                            "Warning: Could not get file name from path: {:?}",
                            host_path
                        );
                        continue; // Skip this file
                    }
                };
                let dest = target_path.join(file_name);
                if let Err(e) = fs::copy(host_path, &dest) {
                    eprintln!(
                        "Warning: Failed to copy file from {:?} to {:?}: {}",
                        host_path, &dest, e
                    );
                }
            }
        }

        // Return the github/workspace directory for command execution
        github_workspace
    }
}

#[async_trait]
impl ContainerRuntime for EmulationRuntime {
    async fn run_container(
        &self,
        _image: &str,
        command: &[&str],
        env_vars: &[(&str, &str)],
        working_dir: &Path,
        _volumes: &[(&Path, &Path)],
    ) -> Result<ContainerOutput, ContainerError> {
        // Build command string
        let mut command_str = String::new();
        for part in command {
            if !command_str.is_empty() {
                command_str.push(' ');
            }
            command_str.push_str(part);
        }

        // Log more detailed debugging information
        wrkflw_logging::info(&format!("Executing command in container: {}", command_str));
        wrkflw_logging::info(&format!("Working directory: {}", working_dir.display()));
        wrkflw_logging::info(&format!("Command length: {}", command.len()));

        if command.is_empty() {
            return Err(ContainerError::ContainerExecution(
                "Empty command array".to_string(),
            ));
        }

        // Print each command part separately for debugging
        for (i, part) in command.iter().enumerate() {
            wrkflw_logging::info(&format!("Command part {}: '{}'", i, part));
        }

        // Log environment variables
        wrkflw_logging::info("Environment variables:");
        for (key, value) in env_vars {
            wrkflw_logging::info(&format!("  {}={}", key, value));
        }

        // Find actual working directory - determine if we should use the current directory instead
        let actual_working_dir: PathBuf = if !working_dir.exists() {
            // Look for GITHUB_WORKSPACE or CI_PROJECT_DIR in env_vars
            let mut workspace_path = None;
            for (key, value) in env_vars {
                if *key == "GITHUB_WORKSPACE" || *key == "CI_PROJECT_DIR" {
                    workspace_path = Some(PathBuf::from(value));
                    break;
                }
            }

            // If found, use that as the working directory
            if let Some(path) = workspace_path {
                if path.exists() {
                    wrkflw_logging::info(&format!(
                        "Using environment-defined workspace: {}",
                        path.display()
                    ));
                    path
                } else {
                    // Fallback to current directory
                    let current_dir =
                        std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
                    wrkflw_logging::info(&format!(
                        "Using current directory: {}",
                        current_dir.display()
                    ));
                    current_dir
                }
            } else {
                // Fallback to current directory
                let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
                wrkflw_logging::info(&format!(
                    "Using current directory: {}",
                    current_dir.display()
                ));
                current_dir
            }
        } else {
            working_dir.to_path_buf()
        };

        wrkflw_logging::info(&format!(
            "Using actual working directory: {}",
            actual_working_dir.display()
        ));

        // Check if path contains the command (for shell script execution)
        let command_path = which::which(command[0]);
        match &command_path {
            Ok(path) => wrkflw_logging::info(&format!("Found command at: {}", path.display())),
            Err(e) => wrkflw_logging::error(&format!(
                "Command not found in PATH: {} - Error: {}",
                command[0], e
            )),
        }

        // First, check if this is a simple shell command (like echo)
        if command_str.starts_with("echo ")
            || command_str.starts_with("cp ")
            || command_str.starts_with("mkdir ")
            || command_str.starts_with("mv ")
        {
            wrkflw_logging::info("Executing as shell command");
            // Execute as a shell command
            let mut cmd = Command::new("sh");
            cmd.arg("-c");
            cmd.arg(&command_str);
            cmd.current_dir(&actual_working_dir);

            // Add environment variables
            for (key, value) in env_vars {
                cmd.env(key, value);
            }

            match cmd.output() {
                Ok(output_result) => {
                    let exit_code = output_result.status.code().unwrap_or(-1);
                    let output = String::from_utf8_lossy(&output_result.stdout).to_string();
                    let error = String::from_utf8_lossy(&output_result.stderr).to_string();

                    wrkflw_logging::debug(&format!(
                        "Shell command completed with exit code: {}",
                        exit_code
                    ));

                    if exit_code != 0 {
                        let mut error_details = format!(
                            "Command failed with exit code: {}\nCommand: {}\n\nError output:\n{}",
                            exit_code, command_str, error
                        );

                        // Add environment variables to error details
                        error_details.push_str("\n\nEnvironment variables:\n");
                        for (key, value) in env_vars {
                            if key.starts_with("GITHUB_") || key.starts_with("CI_") {
                                error_details.push_str(&format!("{}={}\n", key, value));
                            }
                        }

                        return Err(ContainerError::ContainerExecution(error_details));
                    }

                    return Ok(ContainerOutput {
                        stdout: output,
                        stderr: error,
                        exit_code,
                    });
                }
                Err(e) => {
                    return Err(ContainerError::ContainerExecution(format!(
                        "Failed to execute command: {}\nError: {}",
                        command_str, e
                    )));
                }
            }
        }

        // Special handling for Rust/Cargo commands
        if command_str.starts_with("cargo ") || command_str.starts_with("rustup ") {
            let parts: Vec<&str> = command_str.split_whitespace().collect();
            if parts.is_empty() {
                return Err(ContainerError::ContainerExecution(
                    "Empty command".to_string(),
                ));
            }

            let mut cmd = Command::new(parts[0]);

            // Always use the current directory for cargo/rust commands rather than the temporary directory
            let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
            wrkflw_logging::info(&format!(
                "Using project directory for Rust command: {}",
                current_dir.display()
            ));
            cmd.current_dir(&current_dir);

            // Add environment variables
            for (key, value) in env_vars {
                // Don't use the CI_PROJECT_DIR for CARGO_HOME, use the actual project directory
                if *key == "CARGO_HOME" && value.contains("${CI_PROJECT_DIR}") {
                    let cargo_home =
                        value.replace("${CI_PROJECT_DIR}", &current_dir.to_string_lossy());
                    wrkflw_logging::info(&format!("Setting CARGO_HOME to: {}", cargo_home));
                    cmd.env(key, cargo_home);
                } else {
                    cmd.env(key, value);
                }
            }

            // Add command arguments
            if parts.len() > 1 {
                cmd.args(&parts[1..]);
            }

            wrkflw_logging::debug(&format!(
                "Executing Rust command: {} in {}",
                command_str,
                current_dir.display()
            ));

            match cmd.output() {
                Ok(output_result) => {
                    let exit_code = output_result.status.code().unwrap_or(-1);
                    let output = String::from_utf8_lossy(&output_result.stdout).to_string();
                    let error = String::from_utf8_lossy(&output_result.stderr).to_string();

                    wrkflw_logging::debug(&format!("Command exit code: {}", exit_code));

                    if exit_code != 0 {
                        let mut error_details = format!(
                            "Command failed with exit code: {}\nCommand: {}\n\nError output:\n{}",
                            exit_code, command_str, error
                        );

                        // Add environment variables to error details
                        error_details.push_str("\n\nEnvironment variables:\n");
                        for (key, value) in env_vars {
                            if key.starts_with("GITHUB_")
                                || key.starts_with("RUST")
                                || key.starts_with("CARGO")
                                || key.starts_with("CI_")
                            {
                                error_details.push_str(&format!("{}={}\n", key, value));
                            }
                        }

                        return Err(ContainerError::ContainerExecution(error_details));
                    }

                    return Ok(ContainerOutput {
                        stdout: output,
                        stderr: error,
                        exit_code,
                    });
                }
                Err(e) => {
                    return Err(ContainerError::ContainerExecution(format!(
                        "Failed to execute Rust command: {}",
                        e
                    )));
                }
            }
        }

        // For other commands, use a shell as fallback
        let mut cmd = Command::new("sh");
        cmd.arg("-c");
        cmd.arg(&command_str);
        cmd.current_dir(&actual_working_dir);

        // Add environment variables
        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        match cmd.output() {
            Ok(output_result) => {
                let exit_code = output_result.status.code().unwrap_or(-1);
                let output = String::from_utf8_lossy(&output_result.stdout).to_string();
                let error = String::from_utf8_lossy(&output_result.stderr).to_string();

                wrkflw_logging::debug(&format!("Command completed with exit code: {}", exit_code));

                if exit_code != 0 {
                    let mut error_details = format!(
                        "Command failed with exit code: {}\nCommand: {}\n\nError output:\n{}",
                        exit_code, command_str, error
                    );

                    // Add environment variables to error details
                    error_details.push_str("\n\nEnvironment variables:\n");
                    for (key, value) in env_vars {
                        if key.starts_with("GITHUB_") || key.starts_with("CI_") {
                            error_details.push_str(&format!("{}={}\n", key, value));
                        }
                    }

                    return Err(ContainerError::ContainerExecution(error_details));
                }

                Ok(ContainerOutput {
                    stdout: format!(
                        "Emulated container execution with command: {}\n\nOutput:\n{}",
                        command_str, output
                    ),
                    stderr: error,
                    exit_code,
                })
            }
            Err(e) => {
                return Err(ContainerError::ContainerExecution(format!(
                    "Failed to execute command: {}\nError: {}",
                    command_str, e
                )));
            }
        }
    }

    async fn pull_image(&self, image: &str) -> Result<(), ContainerError> {
        wrkflw_logging::info(&format!("🔄 Emulation: Pretending to pull image {}", image));
        Ok(())
    }

    async fn build_image(&self, dockerfile: &Path, tag: &str) -> Result<(), ContainerError> {
        wrkflw_logging::info(&format!(
            "🔄 Emulation: Pretending to build image {} from {}",
            tag,
            dockerfile.display()
        ));
        Ok(())
    }

    async fn prepare_language_environment(
        &self,
        language: &str,
        version: Option<&str>,
        _additional_packages: Option<Vec<String>>,
    ) -> Result<String, ContainerError> {
        // For emulation runtime, we'll use a simplified approach
        // that doesn't require building custom images
        let base_image = match language {
            "python" => version.map_or("python:3.11-slim".to_string(), |v| format!("python:{}", v)),
            "node" => version.map_or("node:20-slim".to_string(), |v| format!("node:{}", v)),
            "java" => version.map_or("eclipse-temurin:17-jdk".to_string(), |v| {
                format!("eclipse-temurin:{}", v)
            }),
            "go" => version.map_or("golang:1.21-slim".to_string(), |v| format!("golang:{}", v)),
            "dotnet" => version.map_or("mcr.microsoft.com/dotnet/sdk:7.0".to_string(), |v| {
                format!("mcr.microsoft.com/dotnet/sdk:{}", v)
            }),
            "rust" => version.map_or("rust:latest".to_string(), |v| format!("rust:{}", v)),
            _ => {
                return Err(ContainerError::ContainerStart(format!(
                    "Unsupported language: {}",
                    language
                )))
            }
        };

        // For emulation, we'll just return the base image
        // The actual package installation will be handled during container execution
        Ok(base_image)
    }
}

#[allow(dead_code)]
fn copy_directory_contents(source: &Path, dest: &Path) -> std::io::Result<()> {
    // Create the destination directory if it doesn't exist
    fs::create_dir_all(dest)?;

    // Iterate through all entries in the source directory
    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let path = entry.path();
        let file_name = match path.file_name() {
            Some(name) => name,
            None => {
                eprintln!("Warning: Could not get file name from path: {:?}", path);
                continue; // Skip this file
            }
        };
        let dest_path = dest.join(file_name);

        // Skip hidden files (except .gitignore and .github might be useful)
        let file_name_str = file_name.to_string_lossy();
        if file_name_str.starts_with(".")
            && file_name_str != ".gitignore"
            && file_name_str != ".github"
        {
            continue;
        }

        // Skip target directory for Rust projects
        if file_name_str == "target" {
            continue;
        }

        if path.is_dir() {
            // Recursively copy subdirectories
            copy_directory_contents(&path, &dest_path)?;
        } else {
            // Copy files
            fs::copy(&path, &dest_path)?;
        }
    }

    Ok(())
}

pub async fn handle_special_action(action: &str) -> Result<(), ContainerError> {
    // Extract owner, repo and version from the action
    let action_parts: Vec<&str> = action.split('@').collect();
    let action_name = action_parts[0];
    let action_version = if action_parts.len() > 1 {
        action_parts[1]
    } else {
        "latest"
    };

    wrkflw_logging::info(&format!(
        "🔄 Processing action: {} @ {}",
        action_name, action_version
    ));

    // Handle specific known actions with special requirements
    if action.starts_with("cachix/install-nix-action") {
        wrkflw_logging::info("🔄 Emulating cachix/install-nix-action");

        // In emulation mode, check if nix is installed
        let nix_installed = Command::new("which")
            .arg("nix")
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false);

        if !nix_installed {
            wrkflw_logging::info("🔄 Emulation: Nix is required but not installed.");
            wrkflw_logging::info(
                "🔄 To use this workflow, please install Nix: https://nixos.org/download.html",
            );
            wrkflw_logging::info("🔄 Continuing emulation, but nix commands will fail.");
        } else {
            wrkflw_logging::info("🔄 Emulation: Using system-installed Nix");
        }
    } else if action.starts_with("actions-rs/cargo@") {
        // For actions-rs/cargo action, ensure Rust is available
        wrkflw_logging::info(&format!("🔄 Detected Rust cargo action: {}", action));

        // Verify Rust/cargo is installed
        check_command_available("cargo", "Rust/Cargo", "https://rustup.rs/");
    } else if action.starts_with("actions-rs/toolchain@") {
        // For actions-rs/toolchain action, check for Rust installation
        wrkflw_logging::info(&format!("🔄 Detected Rust toolchain action: {}", action));

        check_command_available("rustc", "Rust", "https://rustup.rs/");
    } else if action.starts_with("actions-rs/fmt@") {
        // For actions-rs/fmt action, check if rustfmt is available
        wrkflw_logging::info(&format!("🔄 Detected Rust formatter action: {}", action));

        check_command_available("rustfmt", "rustfmt", "rustup component add rustfmt");
    } else if action.starts_with("actions/setup-node@") {
        // Node.js setup action
        wrkflw_logging::info(&format!("🔄 Detected Node.js setup action: {}", action));

        check_command_available("node", "Node.js", "https://nodejs.org/");
    } else if action.starts_with("actions/setup-python@") {
        // Python setup action
        wrkflw_logging::info(&format!("🔄 Detected Python setup action: {}", action));

        check_command_available("python", "Python", "https://www.python.org/downloads/");
    } else if action.starts_with("actions/setup-java@") {
        // Java setup action
        wrkflw_logging::info(&format!("🔄 Detected Java setup action: {}", action));

        check_command_available("java", "Java", "https://adoptium.net/");
    } else if action.starts_with("actions/checkout@") {
        // Git checkout action - this is handled implicitly by our workspace setup
        wrkflw_logging::info("🔄 Detected checkout action - workspace files are already prepared");
    } else if action.starts_with("actions/cache@") {
        // Cache action - can't really emulate caching effectively
        wrkflw_logging::info(
            "🔄 Detected cache action - caching is not fully supported in emulation mode",
        );
    } else {
        // Generic action we don't have special handling for
        wrkflw_logging::info(&format!(
            "🔄 Action '{}' has no special handling in emulation mode",
            action_name
        ));
    }

    // Always return success - the actual command execution will happen in execute_step
    Ok(())
}

// Helper function to check if a command is available on the system
fn check_command_available(command: &str, name: &str, install_url: &str) {
    let is_available = Command::new("which")
        .arg(command)
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false);

    if !is_available {
        wrkflw_logging::warning(&format!("{} is required but not found on the system", name));
        wrkflw_logging::info(&format!(
            "To use this action, please install {}: {}",
            name, install_url
        ));
        wrkflw_logging::info(&format!(
            "Continuing emulation, but {} commands will fail",
            name
        ));
    } else {
        // Try to get version information
        if let Ok(output) = Command::new(command).arg("--version").output() {
            if output.status.success() {
                let version = String::from_utf8_lossy(&output.stdout);
                wrkflw_logging::info(&format!("🔄 Using system {}: {}", name, version.trim()));
            }
        }
    }
}

// Add a function to help set up appropriate environment variables for different actions
#[allow(dead_code)]
fn add_action_env_vars(
    env_map: &mut HashMap<String, String>,
    action: &str,
    with_params: &Option<HashMap<String, String>>,
) {
    if let Some(params) = with_params {
        if action.starts_with("actions/setup-node") {
            // For Node.js actions, add NODE_VERSION
            if let Some(version) = params.get("node-version") {
                env_map.insert("NODE_VERSION".to_string(), version.clone());
            }

            // Set NPM/Yarn paths if needed
            env_map.insert(
                "NPM_CONFIG_PREFIX".to_string(),
                "/tmp/.npm-global".to_string(),
            );
            env_map.insert("PATH".to_string(), "/tmp/.npm-global/bin:$PATH".to_string());
        } else if action.starts_with("actions/setup-python") {
            // For Python actions, add PYTHON_VERSION
            if let Some(version) = params.get("python-version") {
                env_map.insert("PYTHON_VERSION".to_string(), version.clone());
            }

            // Set pip cache directories
            env_map.insert("PIP_CACHE_DIR".to_string(), "/tmp/.pip-cache".to_string());
        } else if action.starts_with("actions/setup-java") {
            // For Java actions, add JAVA_VERSION
            if let Some(version) = params.get("java-version") {
                env_map.insert("JAVA_VERSION".to_string(), version.clone());
            }

            // Set JAVA_HOME
            env_map.insert(
                "JAVA_HOME".to_string(),
                "/usr/lib/jvm/default-java".to_string(),
            );
        }
    }
}

// Function to clean up emulation resources
pub async fn cleanup_resources() {
    cleanup_processes().await;
    cleanup_workspaces().await;
}

// Clean up any tracked processes
async fn cleanup_processes() {
    let processes_to_cleanup = {
        if let Ok(processes) = EMULATION_PROCESSES.lock() {
            processes.clone()
        } else {
            vec![]
        }
    };

    for pid in processes_to_cleanup {
        wrkflw_logging::info(&format!("Cleaning up emulated process: {}", pid));

        #[cfg(unix)]
        {
            // On Unix-like systems, use kill command
            let _ = Command::new("kill")
                .arg("-TERM")
                .arg(pid.to_string())
                .output();
        }

        #[cfg(windows)]
        {
            // On Windows, use taskkill
            let _ = Command::new("taskkill")
                .arg("/F")
                .arg("/PID")
                .arg(&pid.to_string())
                .output();
        }

        // Remove from tracking
        if let Ok(mut processes) = EMULATION_PROCESSES.lock() {
            processes.retain(|p| *p != pid);
        }
    }
}

// Clean up any tracked workspaces
async fn cleanup_workspaces() {
    let workspaces_to_cleanup = {
        if let Ok(workspaces) = EMULATION_WORKSPACES.lock() {
            workspaces.clone()
        } else {
            vec![]
        }
    };

    for workspace_path in workspaces_to_cleanup {
        wrkflw_logging::info(&format!(
            "Cleaning up emulation workspace: {}",
            workspace_path.display()
        ));

        // Only attempt to remove if it exists
        if workspace_path.exists() {
            match fs::remove_dir_all(&workspace_path) {
                Ok(_) => wrkflw_logging::info("Successfully removed workspace directory"),
                Err(e) => wrkflw_logging::error(&format!("Error removing workspace: {}", e)),
            }
        }

        // Remove from tracking
        if let Ok(mut workspaces) = EMULATION_WORKSPACES.lock() {
            workspaces.retain(|w| *w != workspace_path);
        }
    }
}

// Add process to tracking
#[allow(dead_code)]
pub fn track_process(pid: u32) {
    if let Ok(mut processes) = EMULATION_PROCESSES.lock() {
        processes.push(pid);
    }
}

// Remove process from tracking
#[allow(dead_code)]
pub fn untrack_process(pid: u32) {
    if let Ok(mut processes) = EMULATION_PROCESSES.lock() {
        processes.retain(|p| *p != pid);
    }
}

// Track additional workspace paths if needed
#[allow(dead_code)]
pub fn track_workspace(path: &Path) {
    if let Ok(mut workspaces) = EMULATION_WORKSPACES.lock() {
        workspaces.push(path.to_path_buf());
    }
}

// Remove workspace from tracking
#[allow(dead_code)]
pub fn untrack_workspace(path: &Path) {
    if let Ok(mut workspaces) = EMULATION_WORKSPACES.lock() {
        workspaces.retain(|w| *w != path);
    }
}

// Public accessor functions for testing
#[cfg(test)]
pub fn get_tracked_workspaces() -> Vec<PathBuf> {
    if let Ok(workspaces) = EMULATION_WORKSPACES.lock() {
        workspaces.clone()
    } else {
        vec![]
    }
}

#[cfg(test)]
pub fn get_tracked_processes() -> Vec<u32> {
    if let Ok(processes) = EMULATION_PROCESSES.lock() {
        processes.clone()
    } else {
        vec![]
    }
}