dnf-repofile 0.1.1

Pure Rust library for parsing, managing, validating, diffing, and rendering DNF/YUM .repo configuration files
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Value types and newtypes for DNF repository configuration options.
//!
//! This module defines all the typed representations for DNF/YUM `.repo` file
//! options: identifiers ([`RepoId`], [`RepoName`]), numeric constraints
//! ([`Priority`], [`Cost`]), boolean values ([`DnfBool`]), composite types
//! ([`Throttle`], [`MetadataExpire`], [`ProxySetting`], [`StorageSize`]),
//! and enums for constrained value sets ([`IpResolve`], [`ProxyAuthMethod`],
//! [`MultilibPolicy`], etc.).
//!
//! Most newtypes are generated by the [`mod@nutype`] crate with built-in
//! validation, providing `try_new()`, `FromStr`, and `Display` implementations.

use nutype::nutype;
use url::Url;

// ===== Identifiers =====

/// A repository identifier (the `[repo-id]` section header).
///
/// Must be non-empty and match `^[A-Za-z0-9\-_.:]+$`.
///
/// # Examples
///
/// ```
/// use dnf_repofile::RepoId;
///
/// let id = RepoId::try_new("epel").unwrap();
/// assert_eq!(id.as_ref(), "epel");
/// ```
#[nutype(
    sanitize(trim),
    validate(not_empty, regex = r"^[A-Za-z0-9\-_.:]+$"),
    derive(
        Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Display, AsRef, Deref, FromStr,
    )
)]
pub struct RepoId(String);

/// A human-readable repository name.
///
/// Must be non-empty. Displayed by DNF during operations.
///
/// # Examples
///
/// ```
/// use dnf_repofile::RepoName;
///
/// let name = RepoName::try_new("Extra Packages for EPEL").unwrap();
/// assert_eq!(name.as_ref(), "Extra Packages for EPEL");
/// ```
#[nutype(
    sanitize(trim),
    validate(not_empty),
    derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr)
)]
pub struct RepoName(String);

/// A username for repository HTTP authentication.
///
/// # Examples
///
/// ```
/// use dnf_repofile::Username;
///
/// let user = Username::new("myuser");
/// assert_eq!(user.as_ref(), "myuser");
/// ```
#[nutype(
    sanitize(trim),
    derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr)
)]
pub struct Username(String);

/// A password for repository HTTP authentication.
///
/// # Examples
///
/// ```
/// use dnf_repofile::Password;
///
/// let pass = Password::new("s3cret");
/// assert!(pass.as_ref().len() > 0);
/// ```
#[nutype(derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr))]
pub struct Password(String);

/// A username for proxy HTTP authentication.
///
/// # Examples
///
/// ```
/// use dnf_repofile::ProxyUsername;
///
/// let user = ProxyUsername::new("proxyuser");
/// ```
#[nutype(
    sanitize(trim),
    derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr)
)]
pub struct ProxyUsername(String);

/// A password for proxy HTTP authentication.
///
/// # Examples
///
/// ```
/// use dnf_repofile::ProxyPassword;
///
/// let pass = ProxyPassword::new("proxypass");
/// ```
#[nutype(derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr))]
pub struct ProxyPassword(String);

/// A custom HTTP User-Agent header value.
///
/// # Examples
///
/// ```
/// use dnf_repofile::UserAgent;
///
/// let ua = UserAgent::new("MyDNFClient/1.0");
/// ```
#[nutype(
    sanitize(trim),
    derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr)
)]
pub struct UserAgent(String);

/// A module platform identifier for DNF modularity.
///
/// # Examples
///
/// ```
/// use dnf_repofile::ModulePlatformId;
///
/// let mp = ModulePlatformId::new("platform:f38");
/// ```
#[nutype(
    sanitize(trim),
    derive(Debug, Clone, PartialEq, Eq, Display, AsRef, Deref, FromStr)
)]
pub struct ModulePlatformId(String);

// ===== Numerics =====

/// Repository priority value (1–99, lower = higher priority).
///
/// Default is 99 when not explicitly set.
///
/// # Examples
///
/// ```
/// use dnf_repofile::Priority;
///
/// let p = Priority::try_new(50).unwrap();
/// assert_eq!(*p, 50);
/// ```
#[nutype(
    validate(greater_or_equal = 1, less_or_equal = 99),
    default = 99,
    derive(
        Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Display, Deref, Default
    )
)]
pub struct Priority(i32);

/// Repository cost value (0 or higher, higher = less preferred).
///
/// Default is 1000 when not explicitly set.
///
/// # Examples
///
/// ```
/// use dnf_repofile::Cost;
///
/// let c = Cost::try_new(500).unwrap();
/// assert_eq!(*c, 500);
/// ```
#[nutype(
    validate(greater_or_equal = 0),
    default = 1000,
    derive(
        Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Display, Deref, Default
    )
)]
pub struct Cost(i32);

/// Number of retries for network operations (default 10).
///
/// # Examples
///
/// ```
/// use dnf_repofile::Retries;
///
/// let r = Retries::try_new(5).unwrap();
/// assert_eq!(*r, 5);
/// ```
#[nutype(
    validate(greater_or_equal = 0),
    default = 10,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct Retries(u32);

/// Network timeout in seconds (default 30).
///
/// # Examples
///
/// ```
/// use dnf_repofile::TimeoutSeconds;
///
/// let t = TimeoutSeconds::try_new(60).unwrap();
/// assert_eq!(*t, 60);
/// ```
#[nutype(
    validate(greater_or_equal = 0),
    default = 30,
    derive(
        Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Display, Deref, Default
    )
)]
pub struct TimeoutSeconds(u32);

/// Maximum delta RPM percentage (0–100, default 75).
///
/// # Examples
///
/// ```
/// use dnf_repofile::DeltaRpmPercentage;
///
/// let p = DeltaRpmPercentage::try_new(50).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, less_or_equal = 100),
    default = 75,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct DeltaRpmPercentage(u32);

/// Maximum parallel downloads (0–20, default 3).
///
/// # Examples
///
/// ```
/// use dnf_repofile::MaxParallelDownloads;
///
/// let m = MaxParallelDownloads::try_new(5).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, less_or_equal = 20),
    default = 3,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct MaxParallelDownloads(u32);

/// Debug message verbosity level (0–10, default 2).
///
/// # Examples
///
/// ```
/// use dnf_repofile::DebugLevel;
///
/// let d = DebugLevel::try_new(5).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, less_or_equal = 10),
    default = 2,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct DebugLevel(u8);

/// Log file verbosity level (0–10, default 9).
///
/// # Examples
///
/// ```
/// use dnf_repofile::LogLevel;
///
/// let l = LogLevel::try_new(5).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, less_or_equal = 10),
    default = 9,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct LogLevel(u8);

/// Maximum number of install-only kernel packages to keep (default 3, cannot be 1).
///
/// # Examples
///
/// ```
/// use dnf_repofile::InstallOnlyLimit;
///
/// let limit = InstallOnlyLimit::try_new(3).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, predicate = |x| *x != 1),
    default = 3,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default),
)]
pub struct InstallOnlyLimit(u32);

/// Number of log files to keep before rotation (default 4).
///
/// # Examples
///
/// ```
/// use dnf_repofile::LogRotate;
///
/// let r = LogRotate::try_new(7).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0),
    default = 4,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct LogRotate(u32);

/// Time in seconds between metadata timer syncs (default 10800 = 3 hours).
///
/// # Examples
///
/// ```
/// use dnf_repofile::MetadataTimerSync;
///
/// let t = MetadataTimerSync::try_new(3600).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0),
    default = 10800,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct MetadataTimerSync(u32);

/// Error message verbosity level (0–10, default 3).
///
/// # Examples
///
/// ```
/// use dnf_repofile::ErrorLevel;
///
/// let e = ErrorLevel::try_new(5).unwrap();
/// ```
#[nutype(
    validate(greater_or_equal = 0, less_or_equal = 10),
    default = 3,
    derive(Debug, Clone, Copy, PartialEq, Eq, Display, Deref, Default)
)]
pub struct ErrorLevel(u8);

// ===== Composite value types =====

/// A storage size in bytes (e.g., bandwidth, minrate, log_size).
///
/// Supports human-readable suffixes: `K` (kibibytes), `M` (mebibytes),
/// `G` (gibibytes). Parsed from `.repo` file values like `"100M"` or `"10G"`.
///
/// # Examples
///
/// ```
/// use dnf_repofile::StorageSize;
///
/// let size = StorageSize(1024 * 1024); // 1 MiB
/// assert_eq!(size.0, 1048576);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StorageSize(pub u64);

/// How long metadata is considered valid before a refresh is required.
///
/// Can be a specific duration in seconds, or `Never` to disable expiration.
///
/// # Examples
///
/// ```
/// use dnf_repofile::MetadataExpire;
///
/// let expire = MetadataExpire::Duration(3600); // 1 hour
/// let never = MetadataExpire::Never;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetadataExpire {
    /// Metadata expires after this many seconds.
    Duration(u64),
    /// Metadata never expires.
    Never,
}

/// Bandwidth throttle: absolute storage size or percentage of total bandwidth.
///
/// Parsed from `.repo` file values like `"100M"` (absolute) or `"50%"` (percentage).
///
/// # Examples
///
/// ```
/// use dnf_repofile::Throttle;
///
/// let abs = Throttle::Absolute(dnf_repofile::StorageSize(1048576));
/// let pct = Throttle::Percent(50);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Throttle {
    /// Absolute bandwidth limit in bytes.
    Absolute(StorageSize),
    /// Percentage of total available bandwidth.
    Percent(u8),
}

/// Proxy configuration for a repository.
///
/// Can be unset (use system default), explicitly disabled, or a specific
/// proxy URL.
///
/// # Examples
///
/// ```
/// use dnf_repofile::ProxySetting;
///
/// let disabled = ProxySetting::Disabled;
/// let url_proxy = ProxySetting::Url("http://proxy:8080/".parse().unwrap());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxySetting {
    /// Use the default proxy configuration (no explicit setting).
    Unset,
    /// Explicitly disable proxy (`proxy=_none_`).
    Disabled,
    /// Use this specific proxy URL.
    Url(Url),
}

// ===== DNF Boolean =====

/// DNF boolean value.
///
/// DNF accepts multiple textual representations for booleans in `.repo` files:
///
/// | Input     | Result          |
/// |-----------|-----------------|
/// | `1`       | `True`          |
/// | `yes`     | `True`          |
/// | `true`    | `True`          |
/// | `on`      | `True`          |
/// | `0`       | `False`         |
/// | `no`      | `False`         |
/// | `false`   | `False`         |
/// | `off`     | `False`         |
///
/// # Examples
///
/// ```
/// use dnf_repofile::DnfBool;
///
/// // Parsing
/// let enabled = DnfBool::parse("1").unwrap();
/// assert_eq!(enabled, DnfBool::True);
///
/// // Convenience constructors
/// assert_eq!(DnfBool::yes(), DnfBool::True);
/// assert_eq!(DnfBool::no(), DnfBool::False);
///
/// // Conversion from bool
/// let d: DnfBool = true.into();
/// assert_eq!(d, DnfBool::True);
///
/// // Conversion to bool
/// let b: bool = DnfBool::True.into();
/// assert!(b);
///
/// // Display as "1" or "0"
/// assert_eq!(DnfBool::True.to_string(), "1");
/// assert_eq!(DnfBool::False.to_string(), "0");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DnfBool {
    /// Boolean true (parsed from `1`, `yes`, `true`, `on`).
    True,
    /// Boolean false (parsed from `0`, `no`, `false`, `off`).
    False,
}

impl DnfBool {
    /// Parse a DNF boolean string into a [`DnfBool`].
    ///
    /// Accepted values (case-insensitive):
    /// - `"1"`, `"yes"`, `"true"`, `"on"` → [`DnfBool::True`]
    /// - `"0"`, `"no"`, `"false"`, `"off"` → [`DnfBool::False`]
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::ParseBoolError`] if the input does not
    /// match any known boolean value.
    ///
    /// # Examples
    ///
    /// ```
    /// use dnf_repofile::DnfBool;
    ///
    /// assert!(DnfBool::parse("1").is_ok());
    /// assert!(DnfBool::parse("yes").is_ok());
    /// assert!(DnfBool::parse("TRUE").is_ok());
    /// assert!(DnfBool::parse("maybe").is_err());
    /// ```
    pub fn parse(s: &str) -> std::result::Result<Self, crate::error::ParseBoolError> {
        let lower: String = s.chars().map(|c| c.to_ascii_lowercase()).collect();
        match lower.as_str() {
            "1" | "yes" | "true" | "on" => Ok(DnfBool::True),
            "0" | "no" | "false" | "off" => Ok(DnfBool::False),
            _ => Err(crate::error::ParseBoolError {
                input: s.to_owned(),
            }),
        }
    }

    /// Convenience constructor for [`DnfBool::True`] (enabled).
    ///
    /// Equivalent to `DnfBool::True`.
    pub fn yes() -> Self {
        DnfBool::True
    }

    /// Convenience constructor for [`DnfBool::False`] (disabled).
    ///
    /// Equivalent to `DnfBool::False`.
    pub fn no() -> Self {
        DnfBool::False
    }
}

impl std::fmt::Display for DnfBool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DnfBool::True => write!(f, "1"),
            DnfBool::False => write!(f, "0"),
        }
    }
}

impl From<bool> for DnfBool {
    fn from(b: bool) -> Self {
        if b {
            DnfBool::True
        } else {
            DnfBool::False
        }
    }
}

impl From<DnfBool> for bool {
    fn from(d: DnfBool) -> bool {
        matches!(d, DnfBool::True)
    }
}

// ===== Enums =====

/// IP protocol version preference for network connections.
///
/// # Examples
///
/// ```
/// use dnf_repofile::IpResolve;
///
/// let v4 = IpResolve::V4;
/// let v6 = IpResolve::V6;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpResolve {
    /// Prefer IPv4 connections.
    V4,
    /// Prefer IPv6 connections.
    V6,
}

/// HTTP proxy authentication method.
///
/// # Examples
///
/// ```
/// use dnf_repofile::ProxyAuthMethod;
///
/// let method = ProxyAuthMethod::Basic;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProxyAuthMethod {
    /// Any available authentication method.
    Any,
    /// No authentication.
    None_,
    /// HTTP Basic authentication.
    Basic,
    /// HTTP Digest authentication.
    Digest,
    /// HTTP Negotiate authentication.
    Negotiate,
    /// NTLM authentication.
    Ntlm,
    /// Microsoft Digest IE authentication.
    DigestIe,
    /// NTLM Windows Bridge authentication.
    NtlmWb,
}

/// Repository metadata type (e.g., `rpm-md`).
///
/// # Examples
///
/// ```
/// use dnf_repofile::RepoMetadataType;
///
/// let rpmmd = RepoMetadataType::RpmMd;
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepoMetadataType {
    /// RPM-MD metadata format (standard).
    RpmMd,
}

/// Multilib package installation policy.
///
/// # Examples
///
/// ```
/// use dnf_repofile::MultilibPolicy;
///
/// let policy = MultilibPolicy::Best;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MultilibPolicy {
    /// Install the best-matching architecture.
    Best,
    /// Install all available architectures.
    All,
}

/// SQLite database persistence mode for repository metadata.
///
/// # Examples
///
/// ```
/// use dnf_repofile::Persistence;
///
/// let mode = Persistence::Auto;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Persistence {
    /// Automatically determine persistence.
    Auto,
    /// Do not persist metadata (keep in memory only).
    Transient,
    /// Persist metadata to disk.
    Persist,
}

/// RPM transaction verbosity level.
///
/// # Examples
///
/// ```
/// use dnf_repofile::RpmVerbosity;
///
/// let verbose = RpmVerbosity::Info;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RpmVerbosity {
    /// Critical messages only.
    Critical,
    /// Emergency messages only.
    Emergency,
    /// Error messages.
    Error,
    /// Warning messages.
    Warn,
    /// Informational messages.
    Info,
    /// Debug messages (most verbose).
    Debug,
}

/// RPM transaction flag controlling scripts, triggers, and other behaviors.
///
/// # Examples
///
/// ```
/// use dnf_repofile::TsFlag;
///
/// let flags = vec![TsFlag::NoScripts, TsFlag::NoDocs];
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TsFlag {
    /// Disable script execution.
    NoScripts,
    /// Test the transaction without making changes.
    Test,
    /// Disable trigger execution.
    NoTriggers,
    /// Skip documentation files.
    NoDocs,
    /// Only update the RPM database.
    JustDb,
    /// Disable SELinux contexts.
    NoContexts,
    /// Disable file capabilities.
    NoCaps,
    /// Disable cryptographic signature checks.
    NoCrypto,
    /// Detect and resolve dependency loops.
    Deploops,
    /// Disable RPM plugins.
    NoPlugins,
}

/// Describes how a repository advertises its metadata source.
///
/// Returned by [`Repo::url_source()`](crate::Repo::url_source).
///
/// # Examples
///
/// ```
/// use dnf_repofile::{Repo, RepoId, UrlSource};
///
/// let mut repo = Repo::new(RepoId::try_new("example").unwrap());
/// repo.metalink = Some("https://example.com/metalink".parse().unwrap());
///
/// match repo.url_source().unwrap() {
///     UrlSource::Metalink(url) => println!("Metalink: {}", url),
///     _ => unreachable!(),
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UrlSource {
    /// One or more direct base URLs for the repository.
    BaseUrl(Vec<Url>),
    /// A mirror list URL that resolves to a list of mirrors.
    MirrorList(Url),
    /// A metalink URL providing a signed list of mirrors and checksums.
    Metalink(Url),
}