Skip to main content

use_go_mod/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7use use_go_module::{GoModuleDependency, GoModulePath, GoModuleReplacement, GoModuleVersion};
8use use_go_version::{GoCompatibilityVersion, GoToolchainVersion};
9
10/// Error returned when parsing `go.mod` metadata labels fails.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum GoModError {
13    EmptyLabel,
14    UnknownLabel,
15}
16
17impl fmt::Display for GoModError {
18    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
19        match self {
20            Self::EmptyLabel => formatter.write_str("go.mod metadata label cannot be empty"),
21            Self::UnknownLabel => formatter.write_str("unknown go.mod metadata label"),
22        }
23    }
24}
25
26impl Error for GoModError {}
27
28/// `go.mod` config file kind.
29#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
30pub enum GoModConfigFile {
31    GoMod,
32}
33
34impl GoModConfigFile {
35    /// Returns the config file name.
36    #[must_use]
37    pub const fn as_str(self) -> &'static str {
38        "go.mod"
39    }
40}
41
42impl fmt::Display for GoModConfigFile {
43    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44        formatter.write_str(self.as_str())
45    }
46}
47
48impl FromStr for GoModConfigFile {
49    type Err = GoModError;
50
51    fn from_str(value: &str) -> Result<Self, Self::Err> {
52        match normalized_label(value)?.as_str() {
53            "go.mod" | "gomod" => Ok(Self::GoMod),
54            _ => Err(GoModError::UnknownLabel),
55        }
56    }
57}
58
59/// Lightweight `go.mod` file metadata.
60#[derive(Clone, Debug, Default, Eq, PartialEq)]
61pub struct GoModFile {
62    directives: Vec<GoModDirective>,
63}
64
65impl GoModFile {
66    /// Creates empty `go.mod` metadata.
67    #[must_use]
68    pub const fn new() -> Self {
69        Self {
70            directives: Vec::new(),
71        }
72    }
73
74    /// Adds a directive and returns the updated metadata.
75    #[must_use]
76    pub fn with_directive(mut self, directive: GoModDirective) -> Self {
77        self.directives.push(directive);
78        self
79    }
80
81    /// Returns the directives.
82    #[must_use]
83    pub fn directives(&self) -> &[GoModDirective] {
84        &self.directives
85    }
86}
87
88/// `go.mod` directive metadata.
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum GoModDirective {
91    Module(GoModModuleDirective),
92    Go(GoModGoDirective),
93    Toolchain(GoModToolchainDirective),
94    Require(GoModRequireDirective),
95    Replace(GoModReplaceDirective),
96    Exclude(GoModExcludeDirective),
97    Retract(GoModRetractDirective),
98}
99
100/// `module` directive metadata.
101#[derive(Clone, Debug, Eq, PartialEq)]
102pub struct GoModModuleDirective {
103    path: GoModulePath,
104}
105
106impl GoModModuleDirective {
107    /// Creates a `module` directive.
108    #[must_use]
109    pub const fn new(path: GoModulePath) -> Self {
110        Self { path }
111    }
112
113    /// Returns the module path.
114    #[must_use]
115    pub const fn path(&self) -> &GoModulePath {
116        &self.path
117    }
118}
119
120/// `go` directive metadata.
121#[derive(Clone, Copy, Debug, Eq, PartialEq)]
122pub struct GoModGoDirective {
123    version: GoCompatibilityVersion,
124}
125
126impl GoModGoDirective {
127    /// Creates a `go` directive.
128    #[must_use]
129    pub const fn new(version: GoCompatibilityVersion) -> Self {
130        Self { version }
131    }
132
133    /// Returns the compatibility version.
134    #[must_use]
135    pub const fn version(self) -> GoCompatibilityVersion {
136        self.version
137    }
138}
139
140/// `toolchain` directive metadata.
141#[derive(Clone, Copy, Debug, Eq, PartialEq)]
142pub struct GoModToolchainDirective {
143    version: GoToolchainVersion,
144}
145
146impl GoModToolchainDirective {
147    /// Creates a `toolchain` directive.
148    #[must_use]
149    pub const fn new(version: GoToolchainVersion) -> Self {
150        Self { version }
151    }
152
153    /// Returns the toolchain version.
154    #[must_use]
155    pub const fn version(self) -> GoToolchainVersion {
156        self.version
157    }
158}
159
160/// `require` directive metadata.
161#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct GoModRequireDirective {
163    dependency: GoModuleDependency,
164    indirect: bool,
165}
166
167impl GoModRequireDirective {
168    /// Creates a `require` directive.
169    #[must_use]
170    pub const fn new(dependency: GoModuleDependency) -> Self {
171        Self {
172            dependency,
173            indirect: false,
174        }
175    }
176
177    /// Marks the requirement as indirect.
178    #[must_use]
179    pub const fn indirect(mut self) -> Self {
180        self.indirect = true;
181        self
182    }
183
184    /// Returns the dependency metadata.
185    #[must_use]
186    pub const fn dependency(&self) -> &GoModuleDependency {
187        &self.dependency
188    }
189
190    /// Returns whether this directive is indirect.
191    #[must_use]
192    pub const fn is_indirect(&self) -> bool {
193        self.indirect
194    }
195}
196
197/// `replace` directive metadata.
198#[derive(Clone, Debug, Eq, PartialEq)]
199pub struct GoModReplaceDirective {
200    replacement: GoModuleReplacement,
201}
202
203impl GoModReplaceDirective {
204    /// Creates a `replace` directive.
205    #[must_use]
206    pub const fn new(replacement: GoModuleReplacement) -> Self {
207        Self { replacement }
208    }
209
210    /// Returns the replacement metadata.
211    #[must_use]
212    pub const fn replacement(&self) -> &GoModuleReplacement {
213        &self.replacement
214    }
215}
216
217/// `exclude` directive metadata.
218#[derive(Clone, Debug, Eq, PartialEq)]
219pub struct GoModExcludeDirective {
220    path: GoModulePath,
221    version: GoModuleVersion,
222}
223
224impl GoModExcludeDirective {
225    /// Creates an `exclude` directive.
226    #[must_use]
227    pub const fn new(path: GoModulePath, version: GoModuleVersion) -> Self {
228        Self { path, version }
229    }
230
231    /// Returns the module path.
232    #[must_use]
233    pub const fn path(&self) -> &GoModulePath {
234        &self.path
235    }
236
237    /// Returns the module version.
238    #[must_use]
239    pub const fn version(&self) -> &GoModuleVersion {
240        &self.version
241    }
242}
243
244/// `retract` directive metadata.
245#[derive(Clone, Debug, Eq, PartialEq)]
246pub struct GoModRetractDirective {
247    version: GoModuleVersion,
248    rationale: Option<String>,
249}
250
251impl GoModRetractDirective {
252    /// Creates a `retract` directive.
253    #[must_use]
254    pub const fn new(version: GoModuleVersion) -> Self {
255        Self {
256            version,
257            rationale: None,
258        }
259    }
260
261    /// Adds optional rationale text.
262    #[must_use]
263    pub fn with_rationale(mut self, rationale: impl AsRef<str>) -> Self {
264        let trimmed = rationale.as_ref().trim();
265        self.rationale = (!trimmed.is_empty()).then(|| trimmed.to_string());
266        self
267    }
268
269    /// Returns the module version.
270    #[must_use]
271    pub const fn version(&self) -> &GoModuleVersion {
272        &self.version
273    }
274
275    /// Returns optional rationale text.
276    #[must_use]
277    pub fn rationale(&self) -> Option<&str> {
278        self.rationale.as_deref()
279    }
280}
281
282fn normalized_label(value: &str) -> Result<String, GoModError> {
283    let trimmed = value.trim();
284    if trimmed.is_empty() {
285        Err(GoModError::EmptyLabel)
286    } else {
287        Ok(trimmed.to_ascii_lowercase())
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::{
294        GoModConfigFile, GoModDirective, GoModExcludeDirective, GoModFile, GoModGoDirective,
295        GoModModuleDirective, GoModReplaceDirective, GoModRequireDirective, GoModRetractDirective,
296        GoModToolchainDirective,
297    };
298    use use_go_module::{GoModuleDependency, GoModulePath, GoModuleReplacement, GoModuleVersion};
299    use use_go_version::{GoCompatibilityVersion, GoToolchainVersion, GoVersion};
300
301    #[test]
302    fn models_go_mod_directives() -> Result<(), Box<dyn std::error::Error>> {
303        let module_path = GoModulePath::new("example.com/project")?;
304        let module = GoModModuleDirective::new(module_path.clone());
305        let go = GoModGoDirective::new(GoCompatibilityVersion::new("1.22".parse::<GoVersion>()?));
306        let toolchain =
307            GoModToolchainDirective::new(GoToolchainVersion::new("1.22.0".parse::<GoVersion>()?));
308        let version = GoModuleVersion::new("v1.2.3")?;
309        let dependency = GoModuleDependency::new(module_path.clone(), version.clone());
310        let require = GoModRequireDirective::new(dependency).indirect();
311        let replacement = GoModReplaceDirective::new(GoModuleReplacement::new(
312            module_path.clone(),
313            GoModulePath::new("../project")?,
314        ));
315        let exclude = GoModExcludeDirective::new(module_path.clone(), version.clone());
316        let retract = GoModRetractDirective::new(version).with_rationale("bad release");
317        let file = GoModFile::new()
318            .with_directive(GoModDirective::Module(module))
319            .with_directive(GoModDirective::Go(go))
320            .with_directive(GoModDirective::Toolchain(toolchain))
321            .with_directive(GoModDirective::Require(require))
322            .with_directive(GoModDirective::Replace(replacement))
323            .with_directive(GoModDirective::Exclude(exclude))
324            .with_directive(GoModDirective::Retract(retract));
325
326        assert_eq!(file.directives().len(), 7);
327        Ok(())
328    }
329
330    #[test]
331    fn parses_config_file_labels() -> Result<(), Box<dyn std::error::Error>> {
332        assert_eq!("go.mod".parse::<GoModConfigFile>()?, GoModConfigFile::GoMod);
333        assert_eq!(GoModConfigFile::GoMod.to_string(), "go.mod");
334        Ok(())
335    }
336}