use-go-package 0.0.1

Go package metadata 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
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

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

use use_go_identifier::is_valid_ascii_go_identifier;

/// Error returned by Go package metadata constructors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GoPackageError {
    EmptyName,
    InvalidName,
    EmptyPath,
    EmptyPathSegment,
    InvalidPathSegment,
    UnknownLabel,
}

impl fmt::Display for GoPackageError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyName => formatter.write_str("Go package name cannot be empty"),
            Self::InvalidName => formatter.write_str("invalid Go package name"),
            Self::EmptyPath => formatter.write_str("Go package path cannot be empty"),
            Self::EmptyPathSegment => {
                formatter.write_str("Go package path contains an empty segment")
            }
            Self::InvalidPathSegment => formatter.write_str("invalid Go package path segment"),
            Self::UnknownLabel => formatter.write_str("unknown Go package metadata label"),
        }
    }
}

impl Error for GoPackageError {}

/// Validated Go package name metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoPackageName(String);

impl GoPackageName {
    /// Creates a package name from ASCII identifier-shaped text.
    ///
    /// # Errors
    ///
    /// Returns [`GoPackageError`] when the name is empty or not ASCII identifier-shaped.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoPackageError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            return Err(GoPackageError::EmptyName);
        }
        if !is_valid_ascii_go_identifier(trimmed) {
            return Err(GoPackageError::InvalidName);
        }
        Ok(Self(trimmed.to_string()))
    }

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

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

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

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

impl FromStr for GoPackageName {
    type Err = GoPackageError;

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

impl TryFrom<&str> for GoPackageName {
    type Error = GoPackageError;

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

/// Validated slash-separated Go package path metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoPackagePath(String);

impl GoPackagePath {
    /// Creates a package path from slash-separated text.
    ///
    /// # Errors
    ///
    /// Returns [`GoPackageError`] when the path is empty or contains empty/whitespace segments.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoPackageError> {
        let trimmed = value.as_ref().trim();
        validate_path(trimmed)?;
        Ok(Self(trimmed.to_string()))
    }

    /// Returns the package 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
    }

    /// Returns path segments.
    pub fn segments(&self) -> impl Iterator<Item = &str> {
        self.0.split('/')
    }
}

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

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

impl FromStr for GoPackagePath {
    type Err = GoPackageError;

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

impl TryFrom<&str> for GoPackagePath {
    type Error = GoPackageError;

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

/// Go package documentation name metadata.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GoPackageDocName(String);

impl GoPackageDocName {
    /// Creates a package documentation name from non-empty text.
    ///
    /// # Errors
    ///
    /// Returns [`GoPackageError::EmptyName`] when the value is empty after trimming.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GoPackageError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            Err(GoPackageError::EmptyName)
        } else {
            Ok(Self(trimmed.to_string()))
        }
    }

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

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

impl FromStr for GoPackageDocName {
    type Err = GoPackageError;

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

/// Go package visibility metadata.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GoPackageVisibility {
    Internal,
    Public,
}

impl GoPackageVisibility {
    /// Returns the visibility label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Internal => "internal",
            Self::Public => "public",
        }
    }
}

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

impl FromStr for GoPackageVisibility {
    type Err = GoPackageError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match normalized_label(value)?.as_str() {
            "internal" => Ok(Self::Internal),
            "public" => Ok(Self::Public),
            _ => Err(GoPackageError::UnknownLabel),
        }
    }
}

/// Go package layout metadata.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GoPackageLayout {
    SinglePackage,
    MultiPackage,
    InternalPackage,
    CmdPackage,
}

impl GoPackageLayout {
    /// Returns the layout label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SinglePackage => "single-package",
            Self::MultiPackage => "multi-package",
            Self::InternalPackage => "internal-package",
            Self::CmdPackage => "cmd-package",
        }
    }
}

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

impl FromStr for GoPackageLayout {
    type Err = GoPackageError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match normalized_label(value)?.as_str() {
            "single-package" | "single_package" | "single package" => Ok(Self::SinglePackage),
            "multi-package" | "multi_package" | "multi package" => Ok(Self::MultiPackage),
            "internal-package" | "internal_package" | "internal package" => {
                Ok(Self::InternalPackage)
            }
            "cmd-package" | "cmd_package" | "cmd package" => Ok(Self::CmdPackage),
            _ => Err(GoPackageError::UnknownLabel),
        }
    }
}

/// Go file kind metadata.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GoFileKind {
    Source,
    Test,
    Generated,
    BuildTagged,
    Cgo,
    ModuleConfig,
    WorkspaceConfig,
}

impl GoFileKind {
    /// Returns the file-kind label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Source => "source",
            Self::Test => "test",
            Self::Generated => "generated",
            Self::BuildTagged => "build-tagged",
            Self::Cgo => "cgo",
            Self::ModuleConfig => "module-config",
            Self::WorkspaceConfig => "workspace-config",
        }
    }
}

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

impl FromStr for GoFileKind {
    type Err = GoPackageError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match normalized_label(value)?.as_str() {
            "source" => Ok(Self::Source),
            "test" => Ok(Self::Test),
            "generated" => Ok(Self::Generated),
            "build-tagged" | "build_tagged" | "build tagged" => Ok(Self::BuildTagged),
            "cgo" => Ok(Self::Cgo),
            "module-config" | "module_config" | "module config" => Ok(Self::ModuleConfig),
            "workspace-config" | "workspace_config" | "workspace config" => {
                Ok(Self::WorkspaceConfig)
            }
            _ => Err(GoPackageError::UnknownLabel),
        }
    }
}

fn validate_path(value: &str) -> Result<(), GoPackageError> {
    if value.is_empty() {
        return Err(GoPackageError::EmptyPath);
    }
    for segment in value.split('/') {
        if segment.is_empty() {
            return Err(GoPackageError::EmptyPathSegment);
        }
        if segment.trim() != segment
            || segment.chars().any(char::is_whitespace)
            || segment.contains('\\')
        {
            return Err(GoPackageError::InvalidPathSegment);
        }
    }
    Ok(())
}

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

#[cfg(test)]
mod tests {
    use super::{
        GoFileKind, GoPackageDocName, GoPackageError, GoPackageLayout, GoPackageName,
        GoPackagePath, GoPackageVisibility,
    };

    #[test]
    fn validates_package_names() -> Result<(), GoPackageError> {
        let name = GoPackageName::new("http")?;
        assert_eq!(name.as_str(), "http");
        assert_eq!(GoPackageName::new(""), Err(GoPackageError::EmptyName));
        assert_eq!(
            GoPackageName::new("net/http"),
            Err(GoPackageError::InvalidName)
        );
        Ok(())
    }

    #[test]
    fn validates_package_paths() -> Result<(), GoPackageError> {
        let path = GoPackagePath::new("net/http")?;
        assert_eq!(path.segments().collect::<Vec<_>>(), vec!["net", "http"]);
        assert_eq!(GoPackagePath::new(""), Err(GoPackageError::EmptyPath));
        assert_eq!(
            GoPackagePath::new("net//http"),
            Err(GoPackageError::EmptyPathSegment)
        );
        assert_eq!(
            GoPackagePath::new("net/http server"),
            Err(GoPackageError::InvalidPathSegment)
        );
        Ok(())
    }

    #[test]
    fn stores_doc_names() -> Result<(), GoPackageError> {
        let doc_name = GoPackageDocName::new("Package http")?;
        assert_eq!(doc_name.to_string(), "Package http");
        Ok(())
    }

    #[test]
    fn parses_package_enums() -> Result<(), GoPackageError> {
        assert_eq!(
            "internal".parse::<GoPackageVisibility>()?,
            GoPackageVisibility::Internal
        );
        assert_eq!(
            "cmd package".parse::<GoPackageLayout>()?,
            GoPackageLayout::CmdPackage
        );
        assert_eq!(
            "build_tagged".parse::<GoFileKind>()?,
            GoFileKind::BuildTagged
        );
        assert_eq!(GoFileKind::ModuleConfig.to_string(), "module-config");
        Ok(())
    }
}