Skip to main content

wrkflw_parser/
gitlab.rs

1use crate::schema::{SchemaType, SchemaValidator};
2use crate::workflow;
3use std::collections::HashMap;
4use std::fs;
5use std::path::Path;
6use thiserror::Error;
7use wrkflw_models::gitlab::Pipeline;
8use wrkflw_models::ValidationResult;
9
10#[derive(Error, Debug)]
11pub enum GitlabParserError {
12    #[error("I/O error: {0}")]
13    IoError(#[from] std::io::Error),
14
15    #[error("YAML parsing error: {0}")]
16    YamlError(#[from] serde_yaml::Error),
17
18    #[error("Invalid pipeline structure: {0}")]
19    InvalidStructure(String),
20
21    #[error("Schema validation error: {0}")]
22    SchemaValidationError(String),
23}
24
25/// Parse a GitLab CI/CD pipeline file
26pub fn parse_pipeline(pipeline_path: &Path) -> Result<Pipeline, GitlabParserError> {
27    // Read the pipeline file
28    let pipeline_content = fs::read_to_string(pipeline_path)?;
29
30    // Validate against schema
31    let validator = SchemaValidator::new().map_err(GitlabParserError::SchemaValidationError)?;
32
33    validator
34        .validate_with_specific_schema(&pipeline_content, SchemaType::GitLab)
35        .map_err(GitlabParserError::SchemaValidationError)?;
36
37    // Parse the pipeline YAML
38    let pipeline: Pipeline = serde_yaml::from_str(&pipeline_content)?;
39
40    // Return the parsed pipeline
41    Ok(pipeline)
42}
43
44/// Validate the basic structure of a GitLab CI/CD pipeline
45pub fn validate_pipeline_structure(pipeline: &Pipeline) -> ValidationResult {
46    let mut result = ValidationResult::new();
47
48    // Check for at least one job
49    if pipeline.jobs.is_empty() {
50        result.add_issue("Pipeline must contain at least one job".to_string());
51    }
52
53    // Check for script in jobs
54    for (job_name, job) in &pipeline.jobs {
55        // Skip template jobs
56        if let Some(true) = job.template {
57            continue;
58        }
59
60        // Check for script or extends
61        if job.script.is_none() && job.extends.is_none() {
62            result.add_issue(format!(
63                "Job '{}' must have a script section or extend another job",
64                job_name
65            ));
66        }
67    }
68
69    // Check that referenced stages are defined
70    if let Some(stages) = &pipeline.stages {
71        for (job_name, job) in &pipeline.jobs {
72            if let Some(stage) = &job.stage {
73                if !stages.contains(stage) {
74                    result.add_issue(format!(
75                        "Job '{}' references undefined stage '{}'",
76                        job_name, stage
77                    ));
78                }
79            }
80        }
81    }
82
83    // Check that job dependencies exist
84    for (job_name, job) in &pipeline.jobs {
85        if let Some(dependencies) = &job.dependencies {
86            for dependency in dependencies {
87                if !pipeline.jobs.contains_key(dependency) {
88                    result.add_issue(format!(
89                        "Job '{}' depends on undefined job '{}'",
90                        job_name, dependency
91                    ));
92                }
93            }
94        }
95    }
96
97    // Check that job extensions exist
98    for (job_name, job) in &pipeline.jobs {
99        if let Some(extends) = &job.extends {
100            for extend in extends {
101                if !pipeline.jobs.contains_key(extend) {
102                    result.add_issue(format!(
103                        "Job '{}' extends undefined job '{}'",
104                        job_name, extend
105                    ));
106                }
107            }
108        }
109    }
110
111    result
112}
113
114/// Convert a GitLab CI/CD pipeline to a format compatible with the workflow executor
115pub fn convert_to_workflow_format(pipeline: &Pipeline) -> workflow::WorkflowDefinition {
116    // Create a new workflow with required fields
117    let mut workflow = workflow::WorkflowDefinition {
118        name: "Converted GitLab CI Pipeline".to_string(),
119        on: vec!["push".to_string()], // Default trigger
120        on_raw: serde_yaml::Value::String("push".to_string()),
121        jobs: HashMap::new(),
122        defaults: None,
123        env: HashMap::new(),
124    };
125
126    // Convert each GitLab job to a GitHub Actions job
127    for (job_name, gitlab_job) in &pipeline.jobs {
128        // Skip template jobs
129        if let Some(true) = gitlab_job.template {
130            continue;
131        }
132
133        // Create a new job
134        let mut job = workflow::Job {
135            runs_on: Some(vec!["ubuntu-latest".to_string()]), // Default runner
136            needs: None,
137            container: None,
138            steps: Vec::new(),
139            env: HashMap::new(),
140            strategy: None,
141            services: HashMap::new(),
142            if_condition: None,
143            outputs: None,
144            permissions: None,
145            uses: None,
146            with: None,
147            secrets: None,
148            timeout_minutes: None,
149            defaults: None,
150        };
151
152        // Add job-specific environment variables
153        if let Some(variables) = &gitlab_job.variables {
154            job.env.extend(variables.clone());
155        }
156
157        // Add global variables if they exist
158        if let Some(variables) = &pipeline.variables {
159            // Only add if not already defined at job level
160            for (key, value) in variables {
161                job.env.entry(key.clone()).or_insert_with(|| value.clone());
162            }
163        }
164
165        // Convert before_script to steps if it exists
166        if let Some(before_script) = &gitlab_job.before_script {
167            for (i, cmd) in before_script.iter().enumerate() {
168                job.steps.push(workflow::Step::with_run(
169                    format!("Before script {}", i + 1),
170                    cmd.clone(),
171                ));
172            }
173        }
174
175        // Convert main script to steps
176        if let Some(script) = &gitlab_job.script {
177            for (i, cmd) in script.iter().enumerate() {
178                job.steps.push(workflow::Step::with_run(
179                    format!("Run script line {}", i + 1),
180                    cmd.clone(),
181                ));
182            }
183        }
184
185        // Convert after_script to steps if it exists
186        if let Some(after_script) = &gitlab_job.after_script {
187            for (i, cmd) in after_script.iter().enumerate() {
188                let mut step =
189                    workflow::Step::with_run(format!("After script {}", i + 1), cmd.clone());
190                step.continue_on_error = Some(true); // After script should continue even if previous steps fail
191                job.steps.push(step);
192            }
193        }
194
195        // Add services if they exist
196        if let Some(services) = &gitlab_job.services {
197            for (i, service) in services.iter().enumerate() {
198                let service_name = format!("service-{}", i);
199                let service_image = match service {
200                    wrkflw_models::gitlab::Service::Simple(name) => name.clone(),
201                    wrkflw_models::gitlab::Service::Detailed { name, .. } => name.clone(),
202                };
203
204                let service = workflow::Service {
205                    image: service_image,
206                    ports: None,
207                    env: HashMap::new(),
208                    volumes: None,
209                    options: None,
210                };
211
212                job.services.insert(service_name, service);
213            }
214        }
215
216        // Add the job to the workflow
217        workflow.jobs.insert(job_name.clone(), job);
218    }
219
220    workflow
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    // use std::path::PathBuf; // unused
227    use tempfile::NamedTempFile;
228
229    #[test]
230    fn test_parse_simple_pipeline() {
231        // Create a temporary file with a simple GitLab CI/CD pipeline
232        let file = NamedTempFile::new().unwrap();
233        let content = r#"
234stages:
235  - build
236  - test
237
238build_job:
239  stage: build
240  script:
241    - echo "Building..."
242    - make build
243
244test_job:
245  stage: test
246  script:
247    - echo "Testing..."
248    - make test
249"#;
250        fs::write(&file, content).unwrap();
251
252        // Parse the pipeline
253        let pipeline = parse_pipeline(file.path()).unwrap();
254
255        // Validate basic structure
256        assert_eq!(pipeline.stages.as_ref().unwrap().len(), 2);
257        assert_eq!(pipeline.jobs.len(), 2);
258
259        // Check job contents
260        let build_job = pipeline.jobs.get("build_job").unwrap();
261        assert_eq!(build_job.stage.as_ref().unwrap(), "build");
262        assert_eq!(build_job.script.as_ref().unwrap().len(), 2);
263
264        let test_job = pipeline.jobs.get("test_job").unwrap();
265        assert_eq!(test_job.stage.as_ref().unwrap(), "test");
266        assert_eq!(test_job.script.as_ref().unwrap().len(), 2);
267    }
268}