gx 0.8.2

CLI to manage Github Actions dependencies
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
use crate::domain::action::identity::ActionId;
use crate::domain::action::spec::Spec;
use crate::domain::action::specifier::Specifier;
use crate::domain::workflow_actions::{
    ActionSet as WorkflowActionSet, JobId, Located as LocatedAction, Location as WorkflowLocation,
    StepIndex, WorkflowPath,
};
use std::collections::HashSet;

/// A version override for a specific workflow location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActionOverride {
    /// Relative path from repo root, e.g. ".github/workflows/deploy.yml".
    pub workflow: WorkflowPath,
    /// Job id, if scoped to a job.
    pub job: Option<JobId>,
    /// 0-based step index, if scoped to a step (requires job).
    pub step: Option<StepIndex>,
    /// The specifier to use at this location.
    pub version: Specifier,
}

/// Resolve the effective specifier for an action at a given workflow location.
///
/// Resolution order (most specific wins):
/// 1. Step-level override (workflow + job + step)
/// 2. Job-level override (workflow + job)
/// 3. Workflow-level override (workflow only)
/// 4. Global default (returned as `None` — caller falls back to it)
#[must_use]
pub fn resolve_version<'ovr>(
    overrides: &'ovr [ActionOverride],
    location: &WorkflowLocation,
) -> Option<&'ovr Specifier> {
    // Step-level: workflow + job + step all match
    if let (Some(job), Some(step)) = (&location.job, location.step) {
        for exc in overrides {
            if exc.workflow == location.workflow
                && exc.job.as_ref() == Some(job)
                && exc.step == Some(step)
            {
                return Some(&exc.version);
            }
        }
    }

    // Job-level: workflow + job match, no step in override
    if let Some(job) = &location.job {
        for exc in overrides {
            if exc.workflow == location.workflow
                && exc.job.as_ref() == Some(job)
                && exc.step.is_none()
            {
                return Some(&exc.version);
            }
        }
    }

    // Workflow-level: workflow matches, no job/step in override
    for exc in overrides {
        if exc.workflow == location.workflow && exc.job.is_none() && exc.step.is_none() {
            return Some(&exc.version);
        }
    }

    None
}

/// Compute all lock keys needed for overrides: one per (action, version) pair.
pub fn override_lock_keys<'ovr>(
    id: &'ovr ActionId,
    overrides: &'ovr [ActionOverride],
) -> impl Iterator<Item = Spec> + 'ovr {
    overrides
        .iter()
        .map(move |exc| Spec::new(id.clone(), exc.version.clone()))
}

/// Ensure overrides exist for every located step whose version differs from the manifest
/// global, **only when** multiple distinct versions of that action appear across workflows.
///
/// When only one version appears in workflows, no override is created.
#[expect(clippy::implicit_hasher, reason = "callers always use std HashMap")]
pub fn sync(
    actions_overrides: &mut std::collections::HashMap<ActionId, Vec<ActionOverride>>,
    actions_global: &std::collections::HashMap<ActionId, Spec>,
    located: &[LocatedAction],
    action_set: &WorkflowActionSet,
) {
    for action in located {
        let version_count = action_set.versions_for(&action.action.id).count();
        if version_count <= 1 {
            continue;
        }

        let global_specifier = match actions_global.get(&action.action.id) {
            Some(spec) => spec.specifier.clone(),
            None => continue,
        };

        let action_specifier = Specifier::from_v1(action.action.version.as_str());

        if action_specifier == global_specifier {
            continue;
        }

        let empty: &[ActionOverride] = &[];
        let existing_overrides = actions_overrides
            .get(&action.action.id)
            .map_or(empty, Vec::as_slice);

        let already_covered = existing_overrides.iter().any(|o| {
            o.workflow == action.location.workflow
                && o.job == action.location.job
                && o.step == action.location.step
        });

        if !already_covered {
            actions_overrides
                .entry(action.action.id.clone())
                .or_default()
                .push(ActionOverride {
                    workflow: action.location.workflow.clone(),
                    job: action.location.job.clone(),
                    step: action.location.step,
                    version: action_specifier,
                });
        }
    }
}

/// Remove override entries whose referenced workflow/job/step no longer exists in the
/// scanned set.
#[expect(clippy::implicit_hasher, reason = "callers always use std HashMap")]
pub fn prune_stale(
    actions_overrides: &mut std::collections::HashMap<ActionId, Vec<ActionOverride>>,
    located: &[LocatedAction],
) {
    let live_workflows: HashSet<&str> = located
        .iter()
        .map(|a| a.location.workflow.as_str())
        .collect();

    let updates: Vec<(ActionId, Vec<ActionOverride>)> = actions_overrides
        .iter()
        .map(|(id, overrides)| {
            let pruned: Vec<ActionOverride> = overrides
                .iter()
                .filter(|exc| {
                    if !live_workflows.contains(exc.workflow.as_str()) {
                        return false;
                    }
                    if let Some(job) = &exc.job {
                        let job_exists = located.iter().any(|a| {
                            a.location.workflow == exc.workflow
                                && a.location.job.as_ref() == Some(job)
                        });
                        if !job_exists {
                            return false;
                        }
                    }
                    if let (Some(job), Some(step)) = (&exc.job, exc.step) {
                        let step_exists = located.iter().any(|a| {
                            a.location.workflow == exc.workflow
                                && a.location.job.as_ref() == Some(job)
                                && a.location.step == Some(step)
                        });
                        if !step_exists {
                            return false;
                        }
                    }
                    true
                })
                .cloned()
                .collect();
            (id.clone(), pruned)
        })
        .collect();

    for (id, pruned) in updates {
        if pruned.is_empty() {
            actions_overrides.remove(&id);
        } else {
            actions_overrides.insert(id, pruned);
        }
    }
}

#[cfg(test)]
#[expect(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::get_unwrap,
    reason = "tests use unwrap, indexing, and other patterns freely"
)]
mod tests {
    use super::{ActionOverride, LocatedAction, prune_stale, resolve_version, sync};
    use crate::domain::action::identity::{ActionId, Version};
    use crate::domain::action::spec::Spec;
    use crate::domain::action::specifier::Specifier;
    use crate::domain::workflow_actions::{
        ActionSet as WorkflowActionSet, JobId, Location as WorkflowLocation, StepIndex,
        WorkflowPath,
    };

    use std::collections::HashMap;
    fn make_loc(workflow: &str, job: Option<&str>, step: Option<u16>) -> WorkflowLocation {
        WorkflowLocation {
            workflow: WorkflowPath::new(workflow),
            job: job.map(JobId::from),
            step: step.map(StepIndex::from),
        }
    }

    fn make_located(workflow: &str, action: &str, version: &str) -> LocatedAction {
        use crate::domain::workflow_actions::WorkflowAction;
        LocatedAction {
            action: WorkflowAction {
                id: ActionId::from(action),
                version: Version::from(version),
                sha: None,
            },
            location: make_loc(workflow, None, None),
        }
    }

    #[test]
    fn resolve_version_returns_none_when_no_overrides() {
        let overrides: Vec<ActionOverride> = vec![];
        let loc = make_loc(".github/workflows/ci.yml", Some("build"), Some(0));
        assert_eq!(resolve_version(&overrides, &loc), None);
    }

    #[test]
    fn resolve_version_workflow_level() {
        let overrides = vec![ActionOverride {
            workflow: WorkflowPath::new(".github/workflows/ci.yml"),
            job: None,
            step: None,
            version: Specifier::parse("^3"),
        }];
        let loc = make_loc(".github/workflows/ci.yml", Some("build"), Some(0));
        assert_eq!(
            resolve_version(&overrides, &loc),
            Some(&Specifier::parse("^3"))
        );
    }

    #[test]
    fn resolve_version_step_level_wins_over_workflow() {
        let overrides = vec![
            ActionOverride {
                workflow: WorkflowPath::new(".github/workflows/ci.yml"),
                job: None,
                step: None,
                version: Specifier::parse("^3"),
            },
            ActionOverride {
                workflow: WorkflowPath::new(".github/workflows/ci.yml"),
                job: Some(JobId::from("build")),
                step: Some(StepIndex::from(0_u16)),
                version: Specifier::parse("^2"),
            },
        ];
        let loc = make_loc(".github/workflows/ci.yml", Some("build"), Some(0));
        assert_eq!(
            resolve_version(&overrides, &loc),
            Some(&Specifier::parse("^2"))
        );
    }

    #[test]
    fn sync_no_op_when_single_version() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        let mut actions_global: HashMap<ActionId, Spec> = HashMap::new();
        actions_global.insert(
            ActionId::from("actions/checkout"),
            Spec::new(ActionId::from("actions/checkout"), Specifier::parse("^4")),
        );

        let mut action_set = WorkflowActionSet::new();
        let located = vec![make_located(
            ".github/workflows/ci.yml",
            "actions/checkout",
            "v4",
        )];
        for a in &located {
            action_set.add(&a.action);
        }

        sync(
            &mut actions_overrides,
            &actions_global,
            &located,
            &action_set,
        );
        assert!(
            actions_overrides
                .get(&ActionId::from("actions/checkout"))
                .is_none_or(Vec::is_empty)
        );
    }

    #[test]
    fn sync_adds_override_for_minority_version() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        let mut actions_global: HashMap<ActionId, Spec> = HashMap::new();
        actions_global.insert(
            ActionId::from("actions/checkout"),
            Spec::new(ActionId::from("actions/checkout"), Specifier::parse("^4")),
        );

        let mut action_set = WorkflowActionSet::new();
        let located = vec![
            make_located(".github/workflows/ci.yml", "actions/checkout", "v4"),
            make_located(".github/workflows/ci.yml", "actions/checkout", "v4"),
            make_located(".github/workflows/windows.yml", "actions/checkout", "v3"),
        ];
        for a in &located {
            action_set.add(&a.action);
        }

        sync(
            &mut actions_overrides,
            &actions_global,
            &located,
            &action_set,
        );
        let overrides = actions_overrides
            .get(&ActionId::from("actions/checkout"))
            .unwrap();
        assert_eq!(overrides.len(), 1);
        assert_eq!(
            overrides[0].workflow,
            WorkflowPath::new(".github/workflows/windows.yml")
        );
        assert_eq!(overrides[0].version, Specifier::from_v1("v3"));
    }

    #[test]
    fn prune_stale_removes_override_for_missing_workflow() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        actions_overrides.insert(
            ActionId::from("actions/checkout"),
            vec![ActionOverride {
                workflow: WorkflowPath::new(".github/workflows/deploy.yml"),
                job: None,
                step: None,
                version: Specifier::parse("v3"),
            }],
        );

        let located = vec![make_located(
            ".github/workflows/ci.yml",
            "actions/checkout",
            "v4",
        )];
        prune_stale(&mut actions_overrides, &located);

        assert!(
            actions_overrides
                .get(&ActionId::from("actions/checkout"))
                .is_none_or(Vec::is_empty)
        );
    }

    #[test]
    fn prune_stale_keeps_live_overrides() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        actions_overrides.insert(
            ActionId::from("actions/checkout"),
            vec![ActionOverride {
                workflow: WorkflowPath::new(".github/workflows/ci.yml"),
                job: None,
                step: None,
                version: Specifier::parse("v3"),
            }],
        );

        let located = vec![make_located(
            ".github/workflows/ci.yml",
            "actions/checkout",
            "v4",
        )];
        prune_stale(&mut actions_overrides, &located);

        assert_eq!(
            actions_overrides
                .get(&ActionId::from("actions/checkout"))
                .map(Vec::len),
            Some(1)
        );
    }

    // --- Override lifecycle tests (migrated from tidy/tests.rs) ---

    /// Multiple workflows with v6.0.1 + one with v5 → `sync` creates override for v5.
    #[test]
    fn sync_multiple_sha_workflows_with_minority_version() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        let mut actions_global: HashMap<ActionId, Spec> = HashMap::new();
        // Global is v6.0.1 (dominant version)
        actions_global.insert(
            ActionId::from("actions/checkout"),
            Spec::new(
                ActionId::from("actions/checkout"),
                Specifier::from_v1("v6.0.1"),
            ),
        );

        let mut action_set = WorkflowActionSet::new();
        let located = vec![
            make_located(".github/workflows/ci.yml", "actions/checkout", "v6.0.1"),
            make_located(".github/workflows/build.yml", "actions/checkout", "v6.0.1"),
            make_located(".github/workflows/windows.yml", "actions/checkout", "v5"),
        ];
        for a in &located {
            action_set.add(&a.action);
        }

        sync(
            &mut actions_overrides,
            &actions_global,
            &located,
            &action_set,
        );

        let overrides = actions_overrides
            .get(&ActionId::from("actions/checkout"))
            .expect("override must exist for minority version");
        assert_eq!(overrides.len(), 1, "exactly one override for v5");
        assert!(
            overrides[0].workflow.as_str().ends_with("windows.yml"),
            "override must be scoped to windows.yml"
        );
        assert_eq!(
            overrides[0].version,
            Specifier::from_v1("v5"),
            "override version must be v5"
        );
    }

    /// Stale override for deploy.yml (which no longer exists) is removed by prune.
    #[test]
    fn prune_stale_removes_deploy_yml_when_only_ci_exists() {
        let mut actions_overrides: HashMap<ActionId, Vec<ActionOverride>> = HashMap::new();
        actions_overrides.insert(
            ActionId::from("actions/checkout"),
            vec![ActionOverride {
                workflow: WorkflowPath::new(".github/workflows/deploy.yml"),
                job: None,
                step: None,
                version: Specifier::from_v1("v3"),
            }],
        );

        // Only ci.yml is live — deploy.yml has been deleted
        let located = vec![make_located(
            ".github/workflows/ci.yml",
            "actions/checkout",
            "v4",
        )];
        prune_stale(&mut actions_overrides, &located);

        assert!(
            actions_overrides
                .get(&ActionId::from("actions/checkout"))
                .is_none_or(Vec::is_empty),
            "stale deploy.yml override must be removed"
        );
    }
}