upskill 0.2.0

Author and distribute AI-assistance content across coding agents
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
use std::fmt;
use std::path::PathBuf;

use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GithubRepo {
    pub owner: String,
    pub name: String,
    pub git_ref: Option<String>,
    pub subfolder: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitlabRepo {
    pub host: String,
    pub owner: String,
    pub name: String,
    pub git_ref: Option<String>,
    pub subfolder: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstallSource {
    Github(GithubRepo),
    Gitlab(GitlabRepo),
    LocalPath(PathBuf),
}

/// Stable, round-trippable string label for use in lockfiles, log lines,
/// and CLI output. Format mirrors what `parse_install_source` accepts:
///
/// - `github:<owner>/<name>[@<ref>][:<subfolder>]`
/// - `gitlab:<owner>/<name>[@<ref>][:<subfolder>]` (host omitted when
///   `gitlab.com`; otherwise `gitlab+<host>:...`)
/// - `local:<path>` (absolute when known, otherwise as-given)
impl fmt::Display for InstallSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InstallSource::Github(r) => write!(f, "github:{}/{}", r.owner, r.name)
                .and_then(|_| match &r.git_ref {
                    Some(g) => write!(f, "@{}", g),
                    None => Ok(()),
                })
                .and_then(|_| match &r.subfolder {
                    Some(s) => write!(f, ":{}", s),
                    None => Ok(()),
                }),
            InstallSource::Gitlab(r) => {
                if r.host == "gitlab.com" {
                    write!(f, "gitlab:{}/{}", r.owner, r.name)?;
                } else {
                    write!(f, "gitlab+{}:{}/{}", r.host, r.owner, r.name)?;
                }
                if let Some(g) = &r.git_ref {
                    write!(f, "@{}", g)?;
                }
                if let Some(s) = &r.subfolder {
                    write!(f, ":{}", s)?;
                }
                Ok(())
            }
            InstallSource::LocalPath(p) => write!(f, "local:{}", p.display()),
        }
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum SourceParseError {
    #[error("source must be in owner/repo format")]
    InvalidFormat,
    #[error("owner and repo must be non-empty")]
    EmptySegment,
    #[error("subfolder path must be non-empty")]
    EmptySubfolder,
    #[error("ref must be non-empty")]
    EmptyRef,
}

pub fn parse_install_source(source: &str) -> Result<InstallSource, SourceParseError> {
    if source.starts_with("./") || source.starts_with("../") || source.starts_with('/') {
        return Ok(InstallSource::LocalPath(PathBuf::from(source)));
    }

    // gitlab: prefix
    if let Some(rest) = source.strip_prefix("gitlab:") {
        return parse_gitlab_source(rest, "gitlab.com").map(InstallSource::Gitlab);
    }

    // HTTPS URLs
    if let Some(rest) = source.strip_prefix("https://") {
        return parse_url_source(rest);
    }

    parse_github_source(source).map(InstallSource::Github)
}

/// Parse a lockfile source label produced by the [`Display`] impl back
/// into an [`InstallSource`]. The inverse of `Display::fmt` and the
/// counterpart to [`parse_install_source`], which accepts user-facing
/// shorthand instead of the canonical labels.
///
/// Recognised labels:
/// - `github:<owner>/<name>[@<ref>][:<subfolder>]`
/// - `gitlab:<owner>/<name>[@<ref>][:<subfolder>]` — host is `gitlab.com`
/// - `gitlab+<host>:<owner>/<name>[@<ref>][:<subfolder>]` — self-hosted
/// - `local:<path>` — absolute on round-trip; passed through verbatim
pub fn parse_install_source_label(label: &str) -> Result<InstallSource, SourceParseError> {
    if let Some(rest) = label.strip_prefix("local:") {
        return Ok(InstallSource::LocalPath(PathBuf::from(rest)));
    }
    if let Some(rest) = label.strip_prefix("github:") {
        return parse_github_source(rest).map(InstallSource::Github);
    }
    if let Some(rest) = label.strip_prefix("gitlab+") {
        let (host, after) = rest
            .split_once(':')
            .ok_or(SourceParseError::InvalidFormat)?;
        if host.is_empty() {
            return Err(SourceParseError::EmptySegment);
        }
        return parse_gitlab_source(after, host).map(InstallSource::Gitlab);
    }
    if let Some(rest) = label.strip_prefix("gitlab:") {
        return parse_gitlab_source(rest, "gitlab.com").map(InstallSource::Gitlab);
    }
    Err(SourceParseError::InvalidFormat)
}

fn parse_url_source(url_without_scheme: &str) -> Result<InstallSource, SourceParseError> {
    // Split host from path: "gitlab.com/owner/repo@ref:sub" or "github.com/owner/repo"
    let (host_part, path_part) = url_without_scheme
        .split_once('/')
        .ok_or(SourceParseError::InvalidFormat)?;

    // Strip port from host for comparison
    let host_name = host_part.split(':').next().unwrap_or(host_part);

    if host_name == "github.com" {
        return parse_github_source(path_part).map(InstallSource::Github);
    }

    // Everything else (gitlab.com, self-hosted) treated as GitLab-compatible
    parse_gitlab_source(path_part, host_part).map(InstallSource::Gitlab)
}

fn parse_gitlab_source(source: &str, host: &str) -> Result<GitlabRepo, SourceParseError> {
    // Split off :subfolder first
    let (before_subfolder, subfolder) = if let Some((before, sub)) = source.split_once(':') {
        // Avoid confusing port numbers with subfolders — port is on the host, not here
        if sub.trim().is_empty() {
            return Err(SourceParseError::EmptySubfolder);
        }
        (before, Some(sub.to_string()))
    } else {
        (source, None)
    };

    // Split off @ref
    let (repo_source, git_ref) = if let Some((before, r)) = before_subfolder.split_once('@') {
        if r.trim().is_empty() {
            return Err(SourceParseError::EmptyRef);
        }
        (before, Some(r.to_string()))
    } else {
        (before_subfolder, None)
    };

    let (owner, name) = repo_source
        .split_once('/')
        .ok_or(SourceParseError::InvalidFormat)?;

    if owner.trim().is_empty() || name.trim().is_empty() {
        return Err(SourceParseError::EmptySegment);
    }

    if repo_source.matches('/').count() != 1 {
        return Err(SourceParseError::InvalidFormat);
    }

    Ok(GitlabRepo {
        host: host.to_string(),
        owner: owner.to_string(),
        name: name.to_string(),
        git_ref,
        subfolder,
    })
}

pub fn parse_github_source(source: &str) -> Result<GithubRepo, SourceParseError> {
    // Split off :subfolder first
    let (before_subfolder, subfolder) = if let Some((before, sub)) = source.split_once(':') {
        if sub.trim().is_empty() {
            return Err(SourceParseError::EmptySubfolder);
        }
        (before, Some(sub.to_string()))
    } else {
        (source, None)
    };

    // Split off @ref
    let (repo_source, git_ref) = if let Some((before, r)) = before_subfolder.split_once('@') {
        if r.trim().is_empty() {
            return Err(SourceParseError::EmptyRef);
        }
        (before, Some(r.to_string()))
    } else {
        (before_subfolder, None)
    };

    let mut repo = parse_github_repo(repo_source)?;
    repo.git_ref = git_ref;
    repo.subfolder = subfolder;
    Ok(repo)
}

pub(crate) fn parse_github_repo(source: &str) -> Result<GithubRepo, SourceParseError> {
    let Some((owner, name)) = source.split_once('/') else {
        return Err(SourceParseError::InvalidFormat);
    };

    if owner.trim().is_empty() || name.trim().is_empty() {
        return Err(SourceParseError::EmptySegment);
    }

    if source.matches('/').count() != 1 {
        return Err(SourceParseError::InvalidFormat);
    }

    Ok(GithubRepo {
        owner: owner.to_string(),
        name: name.to_string(),
        git_ref: None,
        subfolder: None,
    })
}

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

    #[test]
    fn parse_valid_owner_repo() {
        let repo = parse_github_repo("microsoft/skills").expect("must parse");
        assert_eq!(repo.owner, "microsoft");
        assert_eq!(repo.name, "skills");
        assert_eq!(repo.subfolder, None);
    }

    #[test]
    fn reject_missing_separator() {
        let err = parse_github_repo("microsoft-skills").expect_err("must fail");
        assert_eq!(err, SourceParseError::InvalidFormat);
    }

    #[test]
    fn reject_empty_owner() {
        let err = parse_github_repo("/skills").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptySegment);
    }

    #[test]
    fn reject_empty_repo() {
        let err = parse_github_repo("microsoft/").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptySegment);
    }

    #[test]
    fn reject_extra_slashes() {
        let err = parse_github_repo("a/b/c").expect_err("must fail");
        assert_eq!(err, SourceParseError::InvalidFormat);
    }

    #[test]
    fn parse_local_path_dot_slash() {
        let source = parse_install_source("./my-skills").expect("must parse");
        assert_eq!(
            source,
            InstallSource::LocalPath(PathBuf::from("./my-skills"))
        );
    }

    #[test]
    fn parse_local_path_dot_dot_slash() {
        let source = parse_install_source("../shared/skills").expect("must parse");
        assert_eq!(
            source,
            InstallSource::LocalPath(PathBuf::from("../shared/skills"))
        );
    }

    #[test]
    fn parse_local_path_absolute() {
        let source = parse_install_source("/tmp/skills").expect("must parse");
        assert_eq!(
            source,
            InstallSource::LocalPath(PathBuf::from("/tmp/skills"))
        );
    }

    #[test]
    fn parse_github_source_with_subfolder() {
        let source = parse_install_source("microsoft/skills:subfolder/path").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.owner, "microsoft");
        assert_eq!(repo.name, "skills");
        assert_eq!(repo.subfolder.as_deref(), Some("subfolder/path"));
    }

    #[test]
    fn parse_github_source_without_subfolder() {
        let source = parse_install_source("microsoft/skills").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.owner, "microsoft");
        assert_eq!(repo.name, "skills");
        assert_eq!(repo.subfolder, None);
    }

    #[test]
    fn reject_empty_subfolder() {
        let err = parse_install_source("microsoft/skills:").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptySubfolder);
    }

    #[test]
    fn reject_whitespace_subfolder() {
        let err = parse_install_source("microsoft/skills: ").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptySubfolder);
    }

    #[test]
    fn parse_ref_branch() {
        let source = parse_install_source("microsoft/skills@main").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.owner, "microsoft");
        assert_eq!(repo.name, "skills");
        assert_eq!(repo.git_ref.as_deref(), Some("main"));
        assert_eq!(repo.subfolder, None);
    }

    #[test]
    fn parse_ref_tag() {
        let source = parse_install_source("microsoft/skills@v1.0").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.git_ref.as_deref(), Some("v1.0"));
    }

    #[test]
    fn parse_ref_commit_sha() {
        let source = parse_install_source("microsoft/skills@abc1234def5678").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.git_ref.as_deref(), Some("abc1234def5678"));
    }

    #[test]
    fn parse_ref_with_subfolder() {
        let source = parse_install_source("microsoft/skills@v1.0:tools/lint").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.git_ref.as_deref(), Some("v1.0"));
        assert_eq!(repo.subfolder.as_deref(), Some("tools/lint"));
    }

    #[test]
    fn reject_empty_ref() {
        let err = parse_install_source("microsoft/skills@").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptyRef);
    }

    #[test]
    fn reject_empty_ref_with_subfolder() {
        let err = parse_install_source("microsoft/skills@:tools").expect_err("must fail");
        assert_eq!(err, SourceParseError::EmptyRef);
    }

    // GitLab source tests

    #[test]
    fn parse_gitlab_prefix() {
        let source = parse_install_source("gitlab:team/skills").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.host, "gitlab.com");
        assert_eq!(repo.owner, "team");
        assert_eq!(repo.name, "skills");
    }

    #[test]
    fn parse_gitlab_prefix_with_ref() {
        let source = parse_install_source("gitlab:team/skills@v2.0").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.git_ref.as_deref(), Some("v2.0"));
    }

    #[test]
    fn parse_gitlab_prefix_with_subfolder() {
        let source =
            parse_install_source("gitlab:team/skills@v1.0:tools/lint").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.git_ref.as_deref(), Some("v1.0"));
        assert_eq!(repo.subfolder.as_deref(), Some("tools/lint"));
    }

    #[test]
    fn parse_gitlab_url() {
        let source = parse_install_source("https://gitlab.com/team/skills").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.host, "gitlab.com");
        assert_eq!(repo.owner, "team");
        assert_eq!(repo.name, "skills");
    }

    #[test]
    fn parse_github_url() {
        let source =
            parse_install_source("https://github.com/microsoft/skills").expect("must parse");
        let InstallSource::Github(repo) = source else {
            panic!("expected Github");
        };
        assert_eq!(repo.owner, "microsoft");
        assert_eq!(repo.name, "skills");
    }

    #[test]
    fn parse_selfhosted_gitlab_url() {
        let source =
            parse_install_source("https://git.company.com/team/skills").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.host, "git.company.com");
        assert_eq!(repo.owner, "team");
        assert_eq!(repo.name, "skills");
    }

    #[test]
    fn parse_selfhosted_gitlab_with_port() {
        let source =
            parse_install_source("https://git.company.com:8443/team/skills").expect("must parse");
        let InstallSource::Gitlab(repo) = source else {
            panic!("expected Gitlab");
        };
        assert_eq!(repo.host, "git.company.com:8443");
        assert_eq!(repo.owner, "team");
        assert_eq!(repo.name, "skills");
    }

    // Lockfile source label round-trip — every shape Display can produce
    // must round-trip through parse_install_source_label so `update` can
    // reconstruct the source from a lockfile entry.

    fn assert_label_roundtrip(s: &InstallSource) {
        let label = s.to_string();
        let parsed = parse_install_source_label(&label)
            .unwrap_or_else(|e| panic!("round-trip failed for `{label}`: {e:?}"));
        assert_eq!(&parsed, s, "round-trip mismatch for `{label}`");
    }

    #[test]
    fn label_roundtrip_local_path() {
        assert_label_roundtrip(&InstallSource::LocalPath(PathBuf::from("/abs/path")));
        assert_label_roundtrip(&InstallSource::LocalPath(PathBuf::from(
            "/path with spaces/x",
        )));
    }

    #[test]
    fn label_roundtrip_github_minimal() {
        assert_label_roundtrip(&InstallSource::Github(GithubRepo {
            owner: "driftsys".into(),
            name: "skills".into(),
            git_ref: None,
            subfolder: None,
        }));
    }

    #[test]
    fn label_roundtrip_github_full() {
        assert_label_roundtrip(&InstallSource::Github(GithubRepo {
            owner: "driftsys".into(),
            name: "skills".into(),
            git_ref: Some("v1.2.3".into()),
            subfolder: Some("rules/lint".into()),
        }));
    }

    #[test]
    fn label_roundtrip_gitlab_dot_com() {
        assert_label_roundtrip(&InstallSource::Gitlab(GitlabRepo {
            host: "gitlab.com".into(),
            owner: "team".into(),
            name: "skills".into(),
            git_ref: Some("main".into()),
            subfolder: None,
        }));
    }

    #[test]
    fn label_roundtrip_gitlab_self_hosted() {
        assert_label_roundtrip(&InstallSource::Gitlab(GitlabRepo {
            host: "gitlab.example.com".into(),
            owner: "team".into(),
            name: "rules".into(),
            git_ref: None,
            subfolder: Some("a/b".into()),
        }));
    }

    #[test]
    fn label_rejects_bare_string() {
        let err = parse_install_source_label("driftsys/skills").expect_err("must reject");
        assert_eq!(err, SourceParseError::InvalidFormat);
    }

    #[test]
    fn label_rejects_gitlab_plus_without_host() {
        let err = parse_install_source_label("gitlab+:team/x").expect_err("must reject");
        assert_eq!(err, SourceParseError::EmptySegment);
    }
}