azdolint 0.3.0

CLI tool that validates Azure DevOps pipeline YAML files by checking that referenced variable groups and variables exist
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
//! Validation logic for pipeline variable groups and variables

use anyhow::Result;
use crate::azure::AzureDevOpsClient;

/// Result of validating a single variable group
#[derive(Debug, Clone)]
pub struct GroupValidationResult {
    /// Name of the variable group
    pub group_name: String,
    /// Whether the group exists in Azure DevOps
    pub exists: bool,
    /// Optional error message if validation failed
    pub error: Option<String>,
    /// Variable group ID if found
    pub group_id: Option<i32>,
}

/// Source of a validated variable
#[derive(Debug, Clone, PartialEq)]
pub enum VariableSource {
    /// Variable found in a variable group
    Group(String),
    /// Variable defined inline in the pipeline YAML
    Inline,
    /// Variable defined on the pipeline definition (not in YAML)
    PipelineDefinition,
    /// Variable not found
    NotFound,
}

/// Result of validating a single variable reference
#[derive(Debug)]
pub struct VariableValidationResult {
    /// Name of the variable being validated
    pub variable_name: String,
    /// Name of the variable group where it was found (if any)
    pub group_name: Option<String>,
    /// Whether the variable exists in any of the referenced groups
    pub exists: bool,
    /// Optional error message if validation failed
    pub error: Option<String>,
    /// Source of the variable (group, inline, or not found)
    pub source: VariableSource,
}

/// Validate that variable groups exist in Azure DevOps
///
/// # Arguments
/// * `group_names` - List of variable group names to validate
/// * `client` - Azure DevOps client for API calls
///
/// # Returns
/// * `Result<Vec<GroupValidationResult>>` - Validation results for each group
pub fn validate_variable_groups(
    group_names: Vec<String>,
    client: &AzureDevOpsClient,
) -> Result<Vec<GroupValidationResult>> {
    let mut results = Vec::new();

    for group_name in group_names {
        let result = match client.get_variable_group(&group_name) {
            Ok(group_data) => GroupValidationResult {
                group_name,
                exists: true,
                error: None,
                group_id: Some(group_data.id),
            },
            Err(e) => GroupValidationResult {
                group_name,
                exists: false,
                error: Some(e.to_string()),
                group_id: None,
            },
        };
        results.push(result);
    }

    Ok(results)
}

/// Validate that variables referenced in the pipeline exist in the variable groups,
/// are defined inline, or exist on the pipeline definition
///
/// # Arguments
/// * `variable_references` - List of variable names referenced in the pipeline (using $(variableName) syntax)
/// * `group_validation_results` - Results from validating variable groups (contains group IDs)
/// * `inline_variables` - List of variable names defined inline in the pipeline
/// * `pipeline_definition_variables` - List of variable names defined on the pipeline definition
/// * `client` - Azure DevOps client for API calls
///
/// # Returns
/// * `Result<Vec<VariableValidationResult>>` - Validation results for each variable
pub fn validate_variables(
    variable_references: Vec<String>,
    group_validation_results: &[GroupValidationResult],
    inline_variables: &[String],
    pipeline_definition_variables: &[String],
    client: &AzureDevOpsClient,
) -> Result<Vec<VariableValidationResult>> {
    // Collect all available variables from all existing groups
    let mut available_variables: Vec<(String, String)> = Vec::new(); // (variable_name, group_name)

    for group_result in group_validation_results {
        if group_result.exists {
            if let Some(group_id) = group_result.group_id {
                match client.get_variables_in_group(group_id) {
                    Ok(vars) => {
                        for var in vars {
                            available_variables.push((var, group_result.group_name.clone()));
                        }
                    }
                    Err(_) => {
                        // Skip groups that fail to fetch variables - already reported in group validation
                    }
                }
            }
        }
    }

    // Validate each variable reference
    let mut results = Vec::new();

    for var_name in variable_references {
        // First check if it's an inline variable (highest priority)
        if inline_variables.contains(&var_name) {
            results.push(VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: true,
                error: None,
                source: VariableSource::Inline,
            });
            continue;
        }

        // Check if it's a pipeline definition variable
        if pipeline_definition_variables.contains(&var_name) {
            results.push(VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: true,
                error: None,
                source: VariableSource::PipelineDefinition,
            });
            continue;
        }

        // Search for the variable in all available groups
        let found = available_variables
            .iter()
            .find(|(name, _)| name == &var_name);

        let result = match found {
            Some((_, group_name)) => VariableValidationResult {
                variable_name: var_name,
                group_name: Some(group_name.clone()),
                exists: true,
                error: None,
                source: VariableSource::Group(group_name.clone()),
            },
            None => VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: false,
                error: Some("Variable not found in any referenced variable group".to_string()),
                source: VariableSource::NotFound,
            },
        };
        results.push(result);
    }

    Ok(results)
}

/// Helper function to validate variables against pre-fetched available variables
/// This is used for testing without needing to call Azure CLI
pub fn validate_variables_against_available(
    variable_references: Vec<String>,
    available_variables: &[(String, String)], // (variable_name, group_name)
) -> Vec<VariableValidationResult> {
    validate_variables_against_available_with_inline(variable_references, available_variables, &[], &[])
}

/// Helper function to validate variables against pre-fetched available variables, inline variables,
/// and pipeline definition variables. This is used for testing without needing to call Azure CLI.
pub fn validate_variables_against_available_with_inline(
    variable_references: Vec<String>,
    available_variables: &[(String, String)], // (variable_name, group_name)
    inline_variables: &[String],
    pipeline_definition_variables: &[String],
) -> Vec<VariableValidationResult> {
    let mut results = Vec::new();

    for var_name in variable_references {
        // First check if it's an inline variable (highest priority)
        if inline_variables.contains(&var_name) {
            results.push(VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: true,
                error: None,
                source: VariableSource::Inline,
            });
            continue;
        }

        // Check if it's a pipeline definition variable
        if pipeline_definition_variables.contains(&var_name) {
            results.push(VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: true,
                error: None,
                source: VariableSource::PipelineDefinition,
            });
            continue;
        }

        let found = available_variables
            .iter()
            .find(|(name, _)| name == &var_name);

        let result = match found {
            Some((_, group_name)) => VariableValidationResult {
                variable_name: var_name,
                group_name: Some(group_name.clone()),
                exists: true,
                error: None,
                source: VariableSource::Group(group_name.clone()),
            },
            None => VariableValidationResult {
                variable_name: var_name,
                group_name: None,
                exists: false,
                error: Some("Variable not found in any referenced variable group".to_string()),
                source: VariableSource::NotFound,
            },
        };
        results.push(result);
    }

    results
}

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

    // Tests for GroupValidationResult struct
    #[test]
    fn test_group_validation_result_exists() {
        let result = GroupValidationResult {
            group_name: "MyGroup".to_string(),
            exists: true,
            error: None,
            group_id: Some(123),
        };

        assert_eq!(result.group_name, "MyGroup");
        assert!(result.exists);
        assert!(result.error.is_none());
        assert_eq!(result.group_id, Some(123));
    }

    #[test]
    fn test_group_validation_result_not_found() {
        let result = GroupValidationResult {
            group_name: "MissingGroup".to_string(),
            exists: false,
            error: Some("Group not found".to_string()),
            group_id: None,
        };

        assert_eq!(result.group_name, "MissingGroup");
        assert!(!result.exists);
        assert_eq!(result.error, Some("Group not found".to_string()));
        assert!(result.group_id.is_none());
    }

    // Tests for VariableValidationResult struct
    #[test]
    fn test_variable_validation_result_found() {
        let result = VariableValidationResult {
            variable_name: "ApiKey".to_string(),
            group_name: Some("Secrets".to_string()),
            exists: true,
            error: None,
            source: VariableSource::Group("Secrets".to_string()),
        };

        assert_eq!(result.variable_name, "ApiKey");
        assert_eq!(result.group_name, Some("Secrets".to_string()));
        assert!(result.exists);
        assert!(result.error.is_none());
        assert_eq!(result.source, VariableSource::Group("Secrets".to_string()));
    }

    #[test]
    fn test_variable_validation_result_not_found() {
        let result = VariableValidationResult {
            variable_name: "MissingVar".to_string(),
            group_name: None,
            exists: false,
            error: Some("Variable not found".to_string()),
            source: VariableSource::NotFound,
        };

        assert_eq!(result.variable_name, "MissingVar");
        assert!(result.group_name.is_none());
        assert!(!result.exists);
        assert!(result.error.is_some());
        assert_eq!(result.source, VariableSource::NotFound);
    }

    #[test]
    fn test_variable_validation_result_inline() {
        let result = VariableValidationResult {
            variable_name: "BuildConfig".to_string(),
            group_name: None,
            exists: true,
            error: None,
            source: VariableSource::Inline,
        };

        assert_eq!(result.variable_name, "BuildConfig");
        assert!(result.group_name.is_none());
        assert!(result.exists);
        assert!(result.error.is_none());
        assert_eq!(result.source, VariableSource::Inline);
    }

    // Tests for validate_variables_against_available function
    #[test]
    fn test_validate_all_variables_exist() {
        let available = vec![
            ("Var1".to_string(), "Group1".to_string()),
            ("Var2".to_string(), "Group1".to_string()),
            ("Var3".to_string(), "Group2".to_string()),
        ];

        let references = vec![
            "Var1".to_string(),
            "Var2".to_string(),
            "Var3".to_string(),
        ];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 3);
        assert!(results.iter().all(|r| r.exists));
        assert!(results.iter().all(|r| r.error.is_none()));

        // Check specific mappings
        assert_eq!(results[0].group_name, Some("Group1".to_string()));
        assert_eq!(results[1].group_name, Some("Group1".to_string()));
        assert_eq!(results[2].group_name, Some("Group2".to_string()));
    }

    #[test]
    fn test_validate_some_variables_missing() {
        let available = vec![
            ("Var1".to_string(), "Group1".to_string()),
            ("Var2".to_string(), "Group1".to_string()),
        ];

        let references = vec![
            "Var1".to_string(),
            "MissingVar".to_string(),
            "Var2".to_string(),
        ];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 3);

        // First variable should exist
        assert!(results[0].exists);
        assert_eq!(results[0].variable_name, "Var1");

        // Second variable should be missing
        assert!(!results[1].exists);
        assert_eq!(results[1].variable_name, "MissingVar");
        assert!(results[1].error.is_some());

        // Third variable should exist
        assert!(results[2].exists);
        assert_eq!(results[2].variable_name, "Var2");
    }

    #[test]
    fn test_validate_no_variables_exist() {
        let available = vec![
            ("Var1".to_string(), "Group1".to_string()),
        ];

        let references = vec![
            "Missing1".to_string(),
            "Missing2".to_string(),
        ];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|r| !r.exists));
        assert!(results.iter().all(|r| r.group_name.is_none()));
    }

    #[test]
    fn test_validate_empty_variable_references() {
        let available = vec![
            ("Var1".to_string(), "Group1".to_string()),
        ];

        let references: Vec<String> = vec![];

        let results = validate_variables_against_available(references, &available);

        assert!(results.is_empty());
    }

    #[test]
    fn test_validate_empty_available_variables() {
        let available: Vec<(String, String)> = vec![];

        let references = vec![
            "Var1".to_string(),
            "Var2".to_string(),
        ];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 2);
        assert!(results.iter().all(|r| !r.exists));
    }

    #[test]
    fn test_validate_variable_in_multiple_groups() {
        // Same variable name in multiple groups - should find the first one
        let available = vec![
            ("SharedVar".to_string(), "Group1".to_string()),
            ("SharedVar".to_string(), "Group2".to_string()),
        ];

        let references = vec!["SharedVar".to_string()];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 1);
        assert!(results[0].exists);
        // Should find the first occurrence (Group1)
        assert_eq!(results[0].group_name, Some("Group1".to_string()));
    }

    #[test]
    fn test_validate_case_sensitive_matching() {
        let available = vec![
            ("ConnectionString".to_string(), "Group1".to_string()),
        ];

        let references = vec![
            "ConnectionString".to_string(),
            "connectionstring".to_string(), // Different case
        ];

        let results = validate_variables_against_available(references, &available);

        assert_eq!(results.len(), 2);
        assert!(results[0].exists); // Exact match
        assert!(!results[1].exists); // Case mismatch - not found
    }

    #[test]
    fn test_validate_inline_variables() {
        let available = vec![
            ("GroupVar".to_string(), "Group1".to_string()),
        ];

        let inline = vec![
            "InlineVar1".to_string(),
            "InlineVar2".to_string(),
        ];

        let references = vec![
            "GroupVar".to_string(),
            "InlineVar1".to_string(),
            "MissingVar".to_string(),
        ];

        let results = validate_variables_against_available_with_inline(references, &available, &inline, &[]);

        assert_eq!(results.len(), 3);

        // First variable should be from group
        assert!(results[0].exists);
        assert_eq!(results[0].source, VariableSource::Group("Group1".to_string()));

        // Second variable should be inline
        assert!(results[1].exists);
        assert_eq!(results[1].source, VariableSource::Inline);

        // Third variable should be missing
        assert!(!results[2].exists);
        assert_eq!(results[2].source, VariableSource::NotFound);
    }

    #[test]
    fn test_inline_takes_precedence_over_group() {
        // If a variable is both inline and in a group, inline should take precedence
        let available = vec![
            ("SharedVar".to_string(), "Group1".to_string()),
        ];

        let inline = vec![
            "SharedVar".to_string(),
        ];

        let references = vec!["SharedVar".to_string()];

        let results = validate_variables_against_available_with_inline(references, &available, &inline, &[]);

        assert_eq!(results.len(), 1);
        assert!(results[0].exists);
        // Should be marked as inline, not group
        assert_eq!(results[0].source, VariableSource::Inline);
    }

    #[test]
    fn test_validate_pipeline_definition_variables() {
        let available = vec![("GroupVar".to_string(), "Group1".to_string())];
        let inline = vec!["InlineVar".to_string()];
        let pipeline_def = vec!["PipelineVar".to_string()];

        let references = vec![
            "GroupVar".to_string(),
            "InlineVar".to_string(),
            "PipelineVar".to_string(),
            "MissingVar".to_string(),
        ];

        let results = validate_variables_against_available_with_inline(
            references,
            &available,
            &inline,
            &pipeline_def,
        );

        assert_eq!(results.len(), 4);
        assert_eq!(results[0].source, VariableSource::Group("Group1".to_string()));
        assert_eq!(results[1].source, VariableSource::Inline);
        assert_eq!(results[2].source, VariableSource::PipelineDefinition);
        assert_eq!(results[3].source, VariableSource::NotFound);
    }

    #[test]
    fn test_inline_takes_precedence_over_pipeline_definition() {
        // If a variable is both inline and in pipeline definition, inline should take precedence
        let available: Vec<(String, String)> = vec![];
        let inline = vec!["SharedVar".to_string()];
        let pipeline_def = vec!["SharedVar".to_string()];

        let references = vec!["SharedVar".to_string()];

        let results = validate_variables_against_available_with_inline(
            references,
            &available,
            &inline,
            &pipeline_def,
        );

        assert_eq!(results.len(), 1);
        assert!(results[0].exists);
        // Should be marked as inline, not pipeline definition
        assert_eq!(results[0].source, VariableSource::Inline);
    }

    #[test]
    fn test_pipeline_definition_takes_precedence_over_group() {
        // If a variable is both in pipeline definition and a group, pipeline definition should take precedence
        let available = vec![("SharedVar".to_string(), "Group1".to_string())];
        let inline: Vec<String> = vec![];
        let pipeline_def = vec!["SharedVar".to_string()];

        let references = vec!["SharedVar".to_string()];

        let results = validate_variables_against_available_with_inline(
            references,
            &available,
            &inline,
            &pipeline_def,
        );

        assert_eq!(results.len(), 1);
        assert!(results[0].exists);
        // Should be marked as pipeline definition, not group
        assert_eq!(results[0].source, VariableSource::PipelineDefinition);
    }
}