alpm-types 0.11.2

Types for Arch Linux Package Management
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
use std::{
    fmt::{Display, Formatter},
    path::{Path, PathBuf},
    str::FromStr,
};

use serde::{Deserialize, Serialize};
use winnow::{
    ModalResult,
    Parser,
    combinator::{alt, cut_err, eof, peek, repeat_till},
    error::{StrContext, StrContextValue},
    token::{any, rest},
};

use crate::{Error, SharedLibraryPrefix};

/// A representation of an absolute path
///
/// AbsolutePath wraps a `PathBuf`, that is guaranteed to be absolute.
///
/// ## Examples
/// ```
/// use std::{path::PathBuf, str::FromStr};
///
/// use alpm_types::{AbsolutePath, Error};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create AbsolutePath from &str
/// assert_eq!(
///     AbsolutePath::from_str("/"),
///     AbsolutePath::new(PathBuf::from("/"))
/// );
/// assert_eq!(
///     AbsolutePath::from_str("./"),
///     Err(Error::PathNotAbsolute(PathBuf::from("./")))
/// );
///
/// // Format as String
/// assert_eq!("/", format!("{}", AbsolutePath::from_str("/")?));
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct AbsolutePath(PathBuf);

impl AbsolutePath {
    /// Create a new `AbsolutePath`
    pub fn new(path: PathBuf) -> Result<AbsolutePath, Error> {
        match path.is_absolute() {
            true => Ok(AbsolutePath(path)),
            false => Err(Error::PathNotAbsolute(path)),
        }
    }

    /// Return a reference to the inner type
    pub fn inner(&self) -> &Path {
        &self.0
    }
}

impl FromStr for AbsolutePath {
    type Err = Error;

    /// Parses an absolute path from a string
    ///
    /// # Errors
    ///
    /// Returns an error if the path is not absolute
    fn from_str(s: &str) -> Result<AbsolutePath, Self::Err> {
        match Path::new(s).is_absolute() {
            true => Ok(AbsolutePath(PathBuf::from(s))),
            false => Err(Error::PathNotAbsolute(PathBuf::from(s))),
        }
    }
}

impl Display for AbsolutePath {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.inner().display())
    }
}

/// An absolute path used as build directory
///
/// This is a type alias for [`AbsolutePath`]
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Error, BuildDirectory};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create BuildDirectory from &str and format it
/// assert_eq!(
///     "/etc",
///     BuildDirectory::from_str("/etc")?.to_string()
/// );
/// # Ok(())
/// # }
pub type BuildDirectory = AbsolutePath;

/// An absolute path used as start directory in a package build environment
///
/// This is a type alias for [`AbsolutePath`]
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Error, StartDirectory};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create StartDirectory from &str and format it
/// assert_eq!(
///     "/etc",
///     StartDirectory::from_str("/etc")?.to_string()
/// );
/// # Ok(())
/// # }
pub type StartDirectory = AbsolutePath;

/// A representation of a relative path
///
/// [`RelativePath`] wraps a [`PathBuf`] that is guaranteed to represent a relative path, regardless
/// of whether it points to a file or a directory.
///
/// ## Examples
///
/// ```
/// use std::{path::PathBuf, str::FromStr};
///
/// use alpm_types::{Error, RelativePath};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create RelativePath from &str
/// assert_eq!(
///     RelativePath::from_str("etc/test.conf"),
///     RelativePath::new(PathBuf::from("etc/test.conf"))
/// );
/// assert_eq!(
///     RelativePath::from_str("etc/"),
///     RelativePath::new(PathBuf::from("etc/"))
/// );
/// assert_eq!(
///     RelativePath::from_str("/etc/test.conf"),
///     Err(Error::PathNotRelative(PathBuf::from("/etc/test.conf")))
/// );
///
/// // Format as String
/// assert_eq!("test/", RelativePath::from_str("test/")?.to_string());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RelativePath(PathBuf);

impl RelativePath {
    /// Create a new [`RelativePath`]
    pub fn new(path: PathBuf) -> Result<RelativePath, Error> {
        if !path.is_relative() {
            return Err(Error::PathNotRelative(path));
        }
        Ok(RelativePath(path))
    }

    /// Consume `self` and return the inner [`PathBuf`]
    pub fn into_inner(self) -> PathBuf {
        self.0
    }
}

impl AsRef<Path> for RelativePath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

impl FromStr for RelativePath {
    type Err = Error;

    /// Parses a relative path from a string
    ///
    /// # Errors
    ///
    /// Returns an error if the path is not relative.
    fn from_str(s: &str) -> Result<RelativePath, Self::Err> {
        Self::new(PathBuf::from(s))
    }
}

impl Display for RelativePath {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.as_ref().display())
    }
}

/// A representation of a relative file path
///
/// `RelativeFilePath` wraps a `PathBuf` that is guaranteed to represent a
/// relative file path (i.e. it does not end with a `/`).
///
/// ## Examples
///
/// ```
/// use std::{path::PathBuf, str::FromStr};
///
/// use alpm_types::{Error, RelativeFilePath};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create RelativeFilePath from &str
/// assert_eq!(
///     RelativeFilePath::from_str("etc/test.conf"),
///     RelativeFilePath::new(PathBuf::from("etc/test.conf"))
/// );
/// assert_eq!(
///     RelativeFilePath::from_str("/etc/test.conf"),
///     Err(Error::PathNotRelative(PathBuf::from("/etc/test.conf")))
/// );
///
/// // Format as String
/// assert_eq!(
///     "test/test.txt",
///     RelativeFilePath::from_str("test/test.txt")?.to_string()
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RelativeFilePath(PathBuf);

impl RelativeFilePath {
    /// Create a new `RelativeFilePath`
    pub fn new(path: PathBuf) -> Result<RelativeFilePath, Error> {
        if path
            .to_string_lossy()
            .ends_with(std::path::MAIN_SEPARATOR_STR)
        {
            return Err(Error::PathIsNotAFile(path));
        }
        if !path.is_relative() {
            return Err(Error::PathNotRelative(path));
        }
        Ok(RelativeFilePath(path))
    }

    /// Return a reference to the inner type
    pub fn inner(&self) -> &Path {
        &self.0
    }
}

impl FromStr for RelativeFilePath {
    type Err = Error;

    /// Parses a relative path from a string
    ///
    /// # Errors
    ///
    /// Returns an error if the path is not relative
    fn from_str(s: &str) -> Result<RelativeFilePath, Self::Err> {
        Self::new(PathBuf::from(s))
    }
}

impl Display for RelativeFilePath {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.inner().display())
    }
}

/// The path of a packaged file that should be preserved during package operations
///
/// This is a type alias for [`RelativeFilePath`]
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::Backup;
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create Backup from &str and format it
/// assert_eq!(
///     "etc/test.conf",
///     Backup::from_str("etc/test.conf")?.to_string()
/// );
/// # Ok(())
/// # }
pub type Backup = RelativeFilePath;

/// A special install script that is to be included in the package
///
/// This is a type alias for [RelativeFilePath`]
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Error, Install};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create Install from &str and format it
/// assert_eq!(
///     "scripts/setup.install",
///     Install::from_str("scripts/setup.install")?.to_string()
/// );
/// # Ok(())
/// # }
pub type Install = RelativeFilePath;

/// The relative path to a changelog file that may be included in a package
///
/// This is a type alias for [`RelativeFilePath`]
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Error, Changelog};
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create Changelog from &str and format it
/// assert_eq!(
///     "changelog.md",
///     Changelog::from_str("changelog.md")?.to_string()
/// );
/// # Ok(())
/// # }
pub type Changelog = RelativeFilePath;

/// A lookup directory for shared object files.
///
/// Follows the [alpm-sonamev2] format, which encodes a `prefix` and a `directory`.
/// The same `prefix` is later used to identify the location of a **soname**, see
/// [`SonameV2`][crate::SonameV2].
///
/// [alpm-sonamev2]: https://alpm.archlinux.page/specifications/alpm-sonamev2.7.html
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SonameLookupDirectory {
    /// The lookup prefix for shared objects.
    pub prefix: SharedLibraryPrefix,
    /// The directory to look for shared objects in.
    pub directory: AbsolutePath,
}

impl SonameLookupDirectory {
    /// Creates a new lookup directory with a prefix and a directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use alpm_types::SonameLookupDirectory;
    ///
    /// # fn main() -> Result<(), alpm_types::Error> {
    /// SonameLookupDirectory::new("lib".parse()?, "/usr/lib".parse()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(prefix: SharedLibraryPrefix, directory: AbsolutePath) -> Self {
        Self { prefix, directory }
    }

    /// Parses a [`SonameLookupDirectory`] from a string slice.
    ///
    /// Consumes all of its input.
    ///
    /// See [`SonameLookupDirectory::from_str`] for more details.
    pub fn parser(input: &mut &str) -> ModalResult<Self> {
        // Parse until the first `:`, which separates the prefix from the directory.
        let prefix = cut_err(
            repeat_till(1.., any, peek(alt((":", eof))))
                .try_map(|(name, _): (String, &str)| SharedLibraryPrefix::from_str(&name)),
        )
        .context(StrContext::Label("prefix for a shared object lookup path"))
        .parse_next(input)?;

        // Take the delimiter.
        cut_err(":")
            .context(StrContext::Label("shared library prefix delimiter"))
            .context(StrContext::Expected(StrContextValue::Description(
                "shared library prefix `:`",
            )))
            .parse_next(input)?;

        // Parse the rest as a directory.
        let directory = rest
            .verify(|s: &str| !s.is_empty())
            .try_map(AbsolutePath::from_str)
            .context(StrContext::Label("directory"))
            .context(StrContext::Expected(StrContextValue::Description(
                "directory for a shared object lookup path",
            )))
            .parse_next(input)?;

        Ok(Self { prefix, directory })
    }
}

impl Display for SonameLookupDirectory {
    /// Converts the [`SonameLookupDirectory`] to a string.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.prefix, self.directory)
    }
}

impl FromStr for SonameLookupDirectory {
    type Err = Error;

    /// Creates a [`SonameLookupDirectory`] from a string slice.
    ///
    /// # Errors
    ///
    /// Returns an error if `input` can not be converted into a [`SonameLookupDirectory`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::str::FromStr;
    ///
    /// use alpm_types::SonameLookupDirectory;
    ///
    /// # fn main() -> Result<(), alpm_types::Error> {
    /// let dir = SonameLookupDirectory::from_str("lib:/usr/lib")?;
    /// assert_eq!(dir.to_string(), "lib:/usr/lib");
    /// assert!(SonameLookupDirectory::from_str(":/usr/lib").is_err());
    /// assert!(SonameLookupDirectory::from_str(":/usr/lib").is_err());
    /// assert!(SonameLookupDirectory::from_str("lib:").is_err());
    /// # Ok(())
    /// # }
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::parser.parse(s)?)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use testresult::TestResult;

    use super::*;

    #[rstest]
    #[case("/home", BuildDirectory::new(PathBuf::from("/home")))]
    #[case("./", Err(Error::PathNotAbsolute(PathBuf::from("./"))))]
    #[case("~/", Err(Error::PathNotAbsolute(PathBuf::from("~/"))))]
    #[case("foo.txt", Err(Error::PathNotAbsolute(PathBuf::from("foo.txt"))))]
    fn build_dir_from_string(#[case] s: &str, #[case] result: Result<BuildDirectory, Error>) {
        assert_eq!(BuildDirectory::from_str(s), result);
    }

    #[rstest]
    #[case("/start", StartDirectory::new(PathBuf::from("/start")))]
    #[case("./", Err(Error::PathNotAbsolute(PathBuf::from("./"))))]
    #[case("~/", Err(Error::PathNotAbsolute(PathBuf::from("~/"))))]
    #[case("foo.txt", Err(Error::PathNotAbsolute(PathBuf::from("foo.txt"))))]
    fn startdir_from_str(#[case] s: &str, #[case] result: Result<StartDirectory, Error>) {
        assert_eq!(StartDirectory::from_str(s), result);
    }

    #[rstest]
    #[case("etc/test.conf", RelativePath::new(PathBuf::from("etc/test.conf")))]
    #[case("etc/", RelativePath::new(PathBuf::from("etc/")))]
    #[case(
        "/etc/test.conf",
        Err(Error::PathNotRelative(PathBuf::from("/etc/test.conf")))
    )]
    #[case(
        "../etc/test.conf",
        RelativePath::new(PathBuf::from("../etc/test.conf"))
    )]
    fn relative_path_from_str(#[case] s: &str, #[case] result: Result<RelativePath, Error>) {
        assert_eq!(RelativePath::from_str(s), result);
    }

    #[rstest]
    #[case("etc/test.conf", RelativeFilePath::new(PathBuf::from("etc/test.conf")))]
    #[case(
        "/etc/test.conf",
        Err(Error::PathNotRelative(PathBuf::from("/etc/test.conf")))
    )]
    #[case("etc/", Err(Error::PathIsNotAFile(PathBuf::from("etc/"))))]
    #[case("etc", RelativeFilePath::new(PathBuf::from("etc")))]
    #[case(
        "../etc/test.conf",
        RelativeFilePath::new(PathBuf::from("../etc/test.conf"))
    )]
    fn relative_file_path_from_str(
        #[case] s: &str,
        #[case] result: Result<RelativeFilePath, Error>,
    ) {
        assert_eq!(RelativeFilePath::from_str(s), result);
    }

    #[rstest]
    #[case("lib:/usr/lib", SonameLookupDirectory {
        prefix: "lib".parse()?,
        directory: AbsolutePath::from_str("/usr/lib")?,
    })]
    #[case("lib32:/usr/lib32", SonameLookupDirectory {
        prefix: "lib32".parse()?,
        directory: AbsolutePath::from_str("/usr/lib32")?,
    })]
    fn soname_lookup_directory_from_string(
        #[case] input: &str,
        #[case] expected_result: SonameLookupDirectory,
    ) -> TestResult {
        let lookup_directory = SonameLookupDirectory::from_str(input)?;
        assert_eq!(expected_result, lookup_directory);
        assert_eq!(input, lookup_directory.to_string());
        Ok(())
    }

    #[rstest]
    #[case("lib", "invalid shared library prefix delimiter")]
    #[case("lib:", "invalid directory")]
    #[case(":/usr/lib", "invalid first character of package name")]
    fn invalid_soname_lookup_directory_parser(#[case] input: &str, #[case] error_snippet: &str) {
        let result = SonameLookupDirectory::from_str(input);
        assert!(result.is_err(), "Expected LookupDirectory parsing to fail");
        let err = result.unwrap_err();
        let pretty_error = err.to_string();
        assert!(
            pretty_error.contains(error_snippet),
            "Error:\n=====\n{pretty_error}\n=====\nshould contain snippet:\n\n{error_snippet}"
        );
    }
}