gx 0.8.5

CLI to manage Github Actions dependencies
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
use super::specifier::higher_version;
use std::fmt;

/// Keep the first two path segments of an action reference: its owner and repo.
///
/// Subpath actions like "github/codeql-action/upload-sarif" name a directory
/// inside a repo, but every repo-level API addresses only "github/codeql-action".
#[must_use]
pub fn base_repo_of(owner_repo: &str) -> String {
    owner_repo.split('/').take(2).collect::<Vec<_>>().join("/")
}

/// Unique identifier for an action (e.g., "actions/checkout").
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ActionId(pub String);

impl ActionId {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Extract the base repository (owner/repo) from the action ID.
    #[must_use]
    pub fn base_repo(&self) -> Repository {
        Repository::from(base_repo_of(&self.0))
    }

    /// Build the GitHub compare URL for a version transition on this action's
    /// base repository, e.g. `https://github.com/actions/checkout/compare/v6.0.1...v6.0.3`.
    ///
    /// This is the single source of truth for changelog links: both the `--json`
    /// contract and the log line derive their compare URL here. Subpath actions
    /// collapse to their base repo (compare is a repo-level view).
    #[must_use]
    pub fn compare_url(&self, from: &Version, to: &Version) -> String {
        format!(
            "https://github.com/{}/compare/{}...{}",
            self.base_repo(),
            from,
            to
        )
    }
}

impl fmt::Display for ActionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for ActionId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for ActionId {
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

/// A version specifier (e.g., "v4", "v4.1.0").
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Version(pub String);

impl Version {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Create a normalized version with a 'v' prefix.
    /// Only adds a 'v' prefix when the string starts with a digit (semver without prefix).
    /// Non-numeric refs like branch names ("main", "develop") are returned as-is.
    /// Examples: "4" -> "v4", "4.1.0" -> "v4.1.0", "v4" -> "v4", "main" -> "main".
    #[must_use]
    pub fn normalized(s: &str) -> Self {
        if s.starts_with(|c: char| c.is_ascii_digit()) {
            Self(format!("v{s}"))
        } else {
            Self(s.to_owned())
        }
    }

    /// Select the highest version from a list.
    /// Prefers the highest semantic version if available.
    #[must_use]
    pub fn highest(versions: &[Version]) -> Option<Version> {
        versions
            .iter()
            .reduce(|a, b| if higher_version(a, b) == a { a } else { b })
            .cloned()
    }

    /// Detect the precision of this version string.
    /// "v4" → Major, "v4.1" → Minor, "v4.1.0" → Patch.
    /// For pre-releases, strips the suffix before counting (e.g., "v3.0.0-beta.2" → Patch).
    /// Returns None for non-semver versions (SHAs, branches).
    #[must_use]
    pub fn precision(&self) -> Option<VersionPrecision> {
        let stripped = self
            .0
            .strip_prefix('v')
            .or_else(|| self.0.strip_prefix('V'))
            .unwrap_or(&self.0);

        // Strip pre-release suffix (everything after the first '-') before counting components
        let base = stripped.split('-').next().unwrap_or(stripped);

        let parts: Vec<&str> = base.split('.').collect();
        match parts.as_slice() {
            [major] if !major.is_empty() && major.chars().all(|c| c.is_ascii_digit()) => {
                Some(VersionPrecision::Major)
            }
            [major, minor]
                if !major.is_empty()
                    && major.chars().all(|c| c.is_ascii_digit())
                    && !minor.is_empty()
                    && minor.chars().all(|c| c.is_ascii_digit()) =>
            {
                Some(VersionPrecision::Minor)
            }
            [major, minor, patch]
                if !major.is_empty()
                    && major.chars().all(|c| c.is_ascii_digit())
                    && !minor.is_empty()
                    && minor.chars().all(|c| c.is_ascii_digit())
                    && !patch.is_empty()
                    && patch.chars().all(|c| c.is_ascii_digit()) =>
            {
                Some(VersionPrecision::Patch)
            }
            _ => None,
        }
    }

    /// Derive a semver range specifier from this version based on its precision.
    /// Major ("v4") → "^4"
    /// Minor ("v4.2") → "^4.2"
    /// Patch ("v4.1.0") → "~4.1.0"
    /// Non-semver (SHAs, branches) → None.
    #[must_use]
    pub fn specifier(&self) -> Option<String> {
        let stripped = self
            .0
            .strip_prefix('v')
            .or_else(|| self.0.strip_prefix('V'))
            .unwrap_or(&self.0);

        match self.precision()? {
            VersionPrecision::Major | VersionPrecision::Minor => Some(format!("^{stripped}")),
            VersionPrecision::Patch => Some(format!("~{stripped}")),
        }
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for Version {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for Version {
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

/// How precisely a version is pinned, following semver component conventions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionPrecision {
    /// Only major version specified (e.g., "v4").
    Major,
    /// Major and minor specified (e.g., "v4.1").
    Minor,
    /// Full major.minor.patch specified (e.g., "v4.1.0").
    Patch,
}

/// A resolved commit SHA (40 hex characters).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommitSha(pub String);

impl CommitSha {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Check if a string is a full commit SHA (40 hexadecimal characters).
    #[must_use]
    pub fn is_valid(s: &str) -> bool {
        s.len() == 40 && s.chars().all(|c| c.is_ascii_hexdigit())
    }
}

impl fmt::Display for CommitSha {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for CommitSha {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for CommitSha {
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

/// An owner/repo identifier (e.g., "actions/checkout").
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Repository(String);

impl Repository {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Repository {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for Repository {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for Repository {
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

/// An ISO 8601 date string from commit metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommitDate(String);

impl CommitDate {
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for CommitDate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for CommitDate {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for CommitDate {
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::{ActionId, CommitSha, Version, VersionPrecision};

    #[test]
    fn action_id_base_repo() {
        let simple = ActionId::from("actions/checkout");
        assert_eq!(simple.base_repo().as_str(), "actions/checkout");

        let subpath = ActionId::from("github/codeql-action/upload-sarif");
        assert_eq!(subpath.base_repo().as_str(), "github/codeql-action");
    }

    #[test]
    fn compare_url_builds_github_compare_link() {
        let id = ActionId::from("actions/checkout");
        assert_eq!(
            id.compare_url(&Version::from("v6.0.1"), &Version::from("v6.0.3")),
            "https://github.com/actions/checkout/compare/v6.0.1...v6.0.3"
        );
    }

    #[test]
    fn compare_url_collapses_subpath_to_base_repo() {
        // A subpath action's changelog lives on its base repo, not the subpath.
        let id = ActionId::from("github/codeql-action/upload-sarif");
        assert_eq!(
            id.compare_url(&Version::from("v3.28.0"), &Version::from("v3.29.0")),
            "https://github.com/github/codeql-action/compare/v3.28.0...v3.29.0"
        );
    }

    #[test]
    fn commit_sha_is_valid() {
        assert!(CommitSha::is_valid(
            "a1b2c3d4e5f6789012345678901234567890abcd"
        ));
        assert!(CommitSha::is_valid(
            "0000000000000000000000000000000000000000"
        ));
        assert!(CommitSha::is_valid(
            "ffffffffffffffffffffffffffffffffffffffff"
        ));
    }

    #[test]
    fn commit_sha_is_valid_invalid_length() {
        assert!(!CommitSha::is_valid("abc123")); // Too short
        assert!(!CommitSha::is_valid(
            "a1b2c3d4e5f6789012345678901234567890abcde"
        )); // Too long (41 chars)
        assert!(!CommitSha::is_valid("")); // Empty
    }

    #[test]
    fn commit_sha_is_valid_invalid_chars() {
        assert!(!CommitSha::is_valid(
            "g1b2c3d4e5f6789012345678901234567890abcd"
        )); // 'g' is not hex
        assert!(!CommitSha::is_valid(
            "a1b2c3d4e5f6789012345678901234567890abc!"
        )); // '!' is not hex
    }

    #[test]
    fn version_normalized_with_v_prefix() {
        assert_eq!(Version::normalized("v4").as_str(), "v4");
        assert_eq!(Version::normalized("v4.1.0").as_str(), "v4.1.0");
        assert_eq!(Version::normalized("V4").as_str(), "V4");
    }

    #[test]
    fn version_normalized_without_v_prefix() {
        assert_eq!(Version::normalized("4").as_str(), "v4");
        assert_eq!(Version::normalized("4.1.0").as_str(), "v4.1.0");
    }

    #[test]
    fn precision_major() {
        assert_eq!(
            Version::from("v4").precision(),
            Some(VersionPrecision::Major)
        );
        assert_eq!(
            Version::from("v12").precision(),
            Some(VersionPrecision::Major)
        );
    }

    #[test]
    fn precision_minor() {
        assert_eq!(
            Version::from("v4.1").precision(),
            Some(VersionPrecision::Minor)
        );
        assert_eq!(
            Version::from("v4.0").precision(),
            Some(VersionPrecision::Minor)
        );
    }

    #[test]
    fn precision_patch() {
        assert_eq!(
            Version::from("v4.1.0").precision(),
            Some(VersionPrecision::Patch)
        );
        assert_eq!(
            Version::from("v4.1.2").precision(),
            Some(VersionPrecision::Patch)
        );
    }

    #[test]
    fn precision_non_semver() {
        assert!(Version::from("main").precision().is_none());
        assert!(
            Version::from("abc123def456789012345678901234567890abcd")
                .precision()
                .is_none()
        );
        assert!(Version::from("").precision().is_none());
    }

    #[test]
    fn precision_prerelease_patch() {
        assert_eq!(
            Version::from("v3.0.0-beta.2").precision(),
            Some(VersionPrecision::Patch)
        );
    }

    #[test]
    fn precision_prerelease_minor() {
        assert_eq!(
            Version::from("v3.0-rc.1").precision(),
            Some(VersionPrecision::Minor)
        );
    }

    #[test]
    fn precision_prerelease_major() {
        assert_eq!(
            Version::from("v3-alpha").precision(),
            Some(VersionPrecision::Major)
        );
    }

    #[test]
    fn specifier_major() {
        assert_eq!(Version::from("v4").specifier(), Some("^4".to_owned()));
        assert_eq!(Version::from("v12").specifier(), Some("^12".to_owned()));
    }

    #[test]
    fn specifier_minor() {
        assert_eq!(Version::from("v4.2").specifier(), Some("^4.2".to_owned()));
        assert_eq!(Version::from("v4.0").specifier(), Some("^4.0".to_owned()));
    }

    #[test]
    fn specifier_patch() {
        assert_eq!(
            Version::from("v4.1.0").specifier(),
            Some("~4.1.0".to_owned())
        );
        assert_eq!(
            Version::from("v4.1.2").specifier(),
            Some("~4.1.2".to_owned())
        );
    }

    #[test]
    fn specifier_non_semver() {
        assert!(Version::from("main").specifier().is_none());
        assert!(
            Version::from("abc123def456789012345678901234567890abcd")
                .specifier()
                .is_none()
        );
    }

    #[test]
    fn specifier_without_v_prefix() {
        // Version without prefix should still work
        let v = Version::from("4.2");
        assert_eq!(v.specifier(), Some("^4.2".to_owned()));
    }

    #[test]
    fn specifier_prerelease_patch() {
        assert_eq!(
            Version::from("v3.0.0-beta.2").specifier(),
            Some("~3.0.0-beta.2".to_owned())
        );
    }

    #[test]
    fn specifier_prerelease_minor() {
        assert_eq!(
            Version::from("v3.0-rc.1").specifier(),
            Some("^3.0-rc.1".to_owned())
        );
    }

    #[test]
    fn specifier_prerelease_major() {
        assert_eq!(
            Version::from("v3-alpha").specifier(),
            Some("^3-alpha".to_owned())
        );
    }

    #[test]
    fn version_specifier_uses_parse_semver() {
        // Ensure that Version::highest and parse_semver integration works correctly
        assert_eq!(
            Version::highest(&[Version::from("v4"), Version::from("main")]),
            Some(Version::from("v4"))
        );
    }
}