use-go-module 0.0.1

Go module path, version, dependency, and replacement primitives for RustUse
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
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;

/// Error returned by Go module metadata constructors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GoModuleError {
    EmptyPath,
    InvalidPath,
    EmptyVersion,
    InvalidVersion,
    EmptyPseudoVersion,
    InvalidPseudoVersion,
}

impl fmt::Display for GoModuleError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyPath => formatter.write_str("Go module path cannot be empty"),
            Self::InvalidPath => formatter.write_str("invalid Go module path"),
            Self::EmptyVersion => formatter.write_str("Go module version cannot be empty"),
            Self::InvalidVersion => formatter.write_str("invalid Go module version"),
            Self::EmptyPseudoVersion => formatter.write_str("Go pseudo-version cannot be empty"),
            Self::InvalidPseudoVersion => formatter.write_str("invalid Go pseudo-version"),
        }
    }
}

impl Error for GoModuleError {}

/// Validated Go module path metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoModulePath(String);

impl GoModulePath {
    /// Creates a Go module path from non-empty text.
    ///
    /// # Errors
    ///
    /// Returns [`GoModuleError`] when the path is empty, has whitespace, or has empty slash segments.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            return Err(GoModuleError::EmptyPath);
        }
        if !is_valid_path_text(trimmed) {
            return Err(GoModuleError::InvalidPath);
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the module path.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the path and returns the owned text.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for GoModulePath {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for GoModulePath {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GoModulePath {
    type Err = GoModuleError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for GoModulePath {
    type Error = GoModuleError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Validated Go module version metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoModuleVersion(String);

impl GoModuleVersion {
    /// Creates a Go module version label.
    ///
    /// # Errors
    ///
    /// Returns [`GoModuleError`] when the version is empty or not lightweight `vMAJOR.MINOR.PATCH`-shaped.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            return Err(GoModuleError::EmptyVersion);
        }
        if !is_lightweight_module_version(trimmed) {
            return Err(GoModuleError::InvalidVersion);
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the module version label.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns whether this label is pseudo-version-shaped.
    #[must_use]
    pub fn is_pseudo_version(&self) -> bool {
        is_pseudo_version_like(self.as_str())
    }
}

impl AsRef<str> for GoModuleVersion {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for GoModuleVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GoModuleVersion {
    type Err = GoModuleError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for GoModuleVersion {
    type Error = GoModuleError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Validated Go pseudo-version metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoPseudoVersion(String);

impl GoPseudoVersion {
    /// Creates a pseudo-version-shaped label.
    ///
    /// # Errors
    ///
    /// Returns [`GoModuleError`] when the label is empty or not pseudo-version-like.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoModuleError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            return Err(GoModuleError::EmptyPseudoVersion);
        }
        if !is_pseudo_version_like(trimmed) {
            return Err(GoModuleError::InvalidPseudoVersion);
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the pseudo-version label.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for GoPseudoVersion {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for GoPseudoVersion {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GoPseudoVersion {
    type Err = GoModuleError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for GoPseudoVersion {
    type Error = GoModuleError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// Go module dependency metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleDependency {
    path: GoModulePath,
    version: GoModuleVersion,
}

impl GoModuleDependency {
    /// Creates module dependency metadata.
    #[must_use]
    pub const fn new(path: GoModulePath, version: GoModuleVersion) -> Self {
        Self { path, version }
    }

    /// Returns the dependency module path.
    #[must_use]
    pub const fn path(&self) -> &GoModulePath {
        &self.path
    }

    /// Returns the dependency module version.
    #[must_use]
    pub const fn version(&self) -> &GoModuleVersion {
        &self.version
    }
}

/// Go module replacement metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleReplacement {
    old_path: GoModulePath,
    old_version: Option<GoModuleVersion>,
    new_path: GoModulePath,
    new_version: Option<GoModuleVersion>,
}

impl GoModuleReplacement {
    /// Creates module replacement metadata.
    #[must_use]
    pub const fn new(old_path: GoModulePath, new_path: GoModulePath) -> Self {
        Self {
            old_path,
            old_version: None,
            new_path,
            new_version: None,
        }
    }

    /// Adds the old module version label.
    #[must_use]
    pub fn with_old_version(mut self, version: GoModuleVersion) -> Self {
        self.old_version = Some(version);
        self
    }

    /// Adds the replacement module version label.
    #[must_use]
    pub fn with_new_version(mut self, version: GoModuleVersion) -> Self {
        self.new_version = Some(version);
        self
    }

    /// Returns the replaced module path.
    #[must_use]
    pub const fn old_path(&self) -> &GoModulePath {
        &self.old_path
    }

    /// Returns the replaced module version.
    #[must_use]
    pub const fn old_version(&self) -> Option<&GoModuleVersion> {
        self.old_version.as_ref()
    }

    /// Returns the replacement module path.
    #[must_use]
    pub const fn new_path(&self) -> &GoModulePath {
        &self.new_path
    }

    /// Returns the replacement module version.
    #[must_use]
    pub const fn new_version(&self) -> Option<&GoModuleVersion> {
        self.new_version.as_ref()
    }
}

/// Go module requirement metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GoModuleRequirement {
    dependency: GoModuleDependency,
    indirect: bool,
}

impl GoModuleRequirement {
    /// Creates module requirement metadata.
    #[must_use]
    pub const fn new(dependency: GoModuleDependency) -> Self {
        Self {
            dependency,
            indirect: false,
        }
    }

    /// Marks the requirement as indirect.
    #[must_use]
    pub const fn indirect(mut self) -> Self {
        self.indirect = true;
        self
    }

    /// Returns the dependency metadata.
    #[must_use]
    pub const fn dependency(&self) -> &GoModuleDependency {
        &self.dependency
    }

    /// Returns whether this requirement is indirect.
    #[must_use]
    pub const fn is_indirect(&self) -> bool {
        self.indirect
    }
}

/// Go module directive kind metadata.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GoModuleDirectiveKind {
    Module,
    Go,
    Toolchain,
    Require,
    Replace,
    Exclude,
    Retract,
}

impl GoModuleDirectiveKind {
    /// Returns the directive label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Module => "module",
            Self::Go => "go",
            Self::Toolchain => "toolchain",
            Self::Require => "require",
            Self::Replace => "replace",
            Self::Exclude => "exclude",
            Self::Retract => "retract",
        }
    }
}

impl fmt::Display for GoModuleDirectiveKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GoModuleDirectiveKind {
    type Err = GoModuleError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match normalized_label(value)?.as_str() {
            "module" => Ok(Self::Module),
            "go" => Ok(Self::Go),
            "toolchain" => Ok(Self::Toolchain),
            "require" => Ok(Self::Require),
            "replace" => Ok(Self::Replace),
            "exclude" => Ok(Self::Exclude),
            "retract" => Ok(Self::Retract),
            _ => Err(GoModuleError::InvalidPath),
        }
    }
}

fn is_valid_path_text(value: &str) -> bool {
    !value.chars().any(char::is_whitespace)
        && !value.split('/').any(str::is_empty)
        && !value.contains('\\')
}

fn is_lightweight_module_version(value: &str) -> bool {
    let Some(rest) = value.strip_prefix('v') else {
        return false;
    };
    let base = rest.split('-').next().unwrap_or(rest);
    is_semver_core(base) && !value.split('-').any(str::is_empty)
}

fn is_semver_core(value: &str) -> bool {
    let mut components = value.split('.');
    let Some(major) = components.next() else {
        return false;
    };
    let Some(minor) = components.next() else {
        return false;
    };
    let Some(patch) = components.next() else {
        return false;
    };
    components.next().is_none()
        && is_ascii_digits(major)
        && is_ascii_digits(minor)
        && is_ascii_digits(patch)
}

fn is_pseudo_version_like(value: &str) -> bool {
    let parts = value.split('-').collect::<Vec<_>>();
    parts.len() >= 3
        && is_lightweight_module_version(value)
        && parts.iter().all(|part| !part.is_empty())
}

fn is_ascii_digits(value: &str) -> bool {
    !value.is_empty() && value.chars().all(|character| character.is_ascii_digit())
}

fn normalized_label(value: &str) -> Result<String, GoModuleError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        Err(GoModuleError::EmptyPath)
    } else {
        Ok(trimmed.to_ascii_lowercase())
    }
}

#[cfg(test)]
mod tests {
    use super::{
        GoModuleDependency, GoModuleDirectiveKind, GoModuleError, GoModulePath,
        GoModuleReplacement, GoModuleRequirement, GoModuleVersion, GoPseudoVersion,
    };

    #[test]
    fn validates_module_paths() -> Result<(), GoModuleError> {
        let path = GoModulePath::new("example.com/project/sub")?;
        assert_eq!(path.as_str(), "example.com/project/sub");
        assert_eq!(GoModulePath::new(""), Err(GoModuleError::EmptyPath));
        assert_eq!(
            GoModulePath::new("example.com//project"),
            Err(GoModuleError::InvalidPath)
        );
        assert_eq!(
            GoModulePath::new("example.com/project name"),
            Err(GoModuleError::InvalidPath)
        );
        Ok(())
    }

    #[test]
    fn validates_module_versions() -> Result<(), GoModuleError> {
        let version = GoModuleVersion::new("v1.2.3")?;
        let pseudo = GoModuleVersion::new("v0.0.0-20240101000000-abcdefabcdef")?;

        assert_eq!(version.as_str(), "v1.2.3");
        assert!(pseudo.is_pseudo_version());
        assert_eq!(
            GoModuleVersion::new("1.2.3"),
            Err(GoModuleError::InvalidVersion)
        );
        assert_eq!(
            GoModuleVersion::new("v1.2"),
            Err(GoModuleError::InvalidVersion)
        );
        Ok(())
    }

    #[test]
    fn validates_pseudo_versions() -> Result<(), GoModuleError> {
        let pseudo = GoPseudoVersion::new("v0.0.0-20240101000000-abcdefabcdef")?;
        assert_eq!(pseudo.as_str(), "v0.0.0-20240101000000-abcdefabcdef");
        assert_eq!(
            GoPseudoVersion::new("v1.2.3"),
            Err(GoModuleError::InvalidPseudoVersion)
        );
        Ok(())
    }

    #[test]
    fn models_dependency_requirement_and_replacement() -> Result<(), GoModuleError> {
        let path = GoModulePath::new("example.com/library")?;
        let version = GoModuleVersion::new("v1.2.3")?;
        let dependency = GoModuleDependency::new(path.clone(), version.clone());
        let requirement = GoModuleRequirement::new(dependency).indirect();
        let replacement = GoModuleReplacement::new(path, GoModulePath::new("../library")?)
            .with_old_version(version.clone())
            .with_new_version(version);

        assert!(requirement.is_indirect());
        assert_eq!(
            replacement.old_version().map(GoModuleVersion::as_str),
            Some("v1.2.3")
        );
        assert_eq!(replacement.new_path().as_str(), "../library");
        Ok(())
    }

    #[test]
    fn parses_directive_kinds() -> Result<(), GoModuleError> {
        assert_eq!(
            "require".parse::<GoModuleDirectiveKind>()?,
            GoModuleDirectiveKind::Require
        );
        assert_eq!(GoModuleDirectiveKind::Toolchain.to_string(), "toolchain");
        Ok(())
    }
}