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
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! Types for handling URLs and VCS-related information in package sources.

use std::{
    fmt::{Display, Formatter},
    str::FromStr,
};

use alpm_parsers::iter_str_context;
use serde::{Deserialize, Serialize};
use winnow::{
    ModalResult,
    Parser,
    ascii::{alpha1, space0},
    combinator::{alt, cut_err, eof, fail, opt, peek, repeat_till, terminated},
    error::{StrContext, StrContextValue},
    token::{any, rest},
};

use crate::Error;

/// Represents a URL.
///
/// It is used to represent the upstream URL of a package.
/// This type does not yet enforce a secure connection (e.g. HTTPS).
///
/// The `Url` type wraps the [`url::Url`] type.
///
/// ## Examples
///
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::Url;
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create Url from &str
/// let url = Url::from_str("https://example.com/download")?;
/// assert_eq!(url.as_str(), "https://example.com/download");
///
/// // Format as String
/// assert_eq!(format!("{url}"), "https://example.com/download");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Url(url::Url);

impl Url {
    /// Creates a new `Url` instance.
    pub fn new(url: url::Url) -> Result<Self, Error> {
        Ok(Self(url))
    }

    /// Returns a reference to the inner `url::Url` as a `&str`.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Consumes the `Url` and returns the inner `url::Url`.
    pub fn into_inner(self) -> url::Url {
        self.0
    }

    /// Returns a reference to the inner `url::Url`.
    pub fn inner(&self) -> &url::Url {
        &self.0
    }
}

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

impl FromStr for Url {
    type Err = Error;

    /// Creates a new `Url` instance from a string slice.
    ///
    /// ## Examples
    ///
    /// ```
    /// use std::str::FromStr;
    ///
    /// use alpm_types::Url;
    ///
    /// # fn main() -> Result<(), alpm_types::Error> {
    /// let url = Url::from_str("https://archlinux.org/")?;
    /// assert_eq!(url.as_str(), "https://archlinux.org/");
    /// # Ok(())
    /// # }
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let url = url::Url::parse(s).map_err(Error::InvalidUrl)?;
        Self::new(url)
    }
}

impl Display for Url {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A URL for package sources.
///
/// Wraps the [`Url`] type and provides optional information on [VCS] systems.
///
/// Can be created from custom URL strings, that in part resemble the default [URL syntax], e.g.:
///
/// ```txt
/// git+https://example.org/example-project.git#tag=v1.0.0?signed
/// ```
///
/// The above example provides an overview of the custom URL syntax:
///
/// - The optional [VCS] specifier `git` is prepended, directly followed by a "+" sign as delimiter,
/// - specific URL `fragment` types such as `tag` are used to encode information about the
///   particular VCS objects to address,
/// - the URL `query` component `signed` is used to indicate that OpenPGP signature verification is
///   required for a VCS type.
///
/// ## Note
///
/// The URL format used by [`SourceUrl`] deviates from the default [URL syntax] by allowing to
/// change the order of the `query` and `fragment` component!
///
/// Refer to the [alpm-package-source] documentation for a more detailed overview of the custom URL
/// syntax.
///
/// [URL syntax]: https://en.wikipedia.org/wiki/URL#Syntax
/// [VCS]: https://en.wikipedia.org/wiki/Version_control
/// [alpm-package-source]: https://alpm.archlinux.page/specifications/alpm-package-source.7.html
///
/// ## Examples
///
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::SourceUrl;
///
/// # fn main() -> Result<(), alpm_types::Error> {
/// // Create Url from &str
/// let url =
///     SourceUrl::from_str("git+https://your-vcs.org/example-project.git?signed#tag=v1.0.0")?;
/// assert_eq!(
///     &url.to_string(),
///     "git+https://your-vcs.org/example-project.git?signed#tag=v1.0.0"
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct SourceUrl {
    /// The URL from where the sources are retrieved.
    pub url: Url,
    /// Optional data on VCS systems using the URL for the retrieval of sources.
    pub vcs_info: Option<VcsInfo>,
}

impl FromStr for SourceUrl {
    type Err = Error;

    /// Creates a new `SourceUrl` instance from a string slice.
    ///
    /// ## Examples
    ///
    /// ```
    /// use std::str::FromStr;
    ///
    /// use alpm_types::SourceUrl;
    ///
    /// # fn main() -> Result<(), alpm_types::Error> {
    /// let url =
    ///     SourceUrl::from_str("git+https://your-vcs.org/example-project.git?signed#tag=v1.0.0")?;
    /// assert_eq!(
    ///     &url.to_string(),
    ///     "git+https://your-vcs.org/example-project.git?signed#tag=v1.0.0"
    /// );
    /// # Ok(())
    /// # }
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::parser.parse(s)?)
    }
}

impl Display for SourceUrl {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // If there's no vcs info, print the URL and return.
        let Some(vcs_info) = &self.vcs_info else {
            return write!(f, "{}", self.url.as_str());
        };

        let mut prefix = None;
        let url = self.url.as_str();
        let mut formatted_fragment = String::new();
        let mut query = String::new();

        // Build all components of a source url, based on the protocol and provided options
        match vcs_info {
            VcsInfo::Bzr { fragment } => {
                prefix = Some(VcsProtocol::Bzr);
                if let Some(fragment) = fragment {
                    formatted_fragment = format!("#{fragment}");
                }
            }
            VcsInfo::Fossil { fragment } => {
                prefix = Some(VcsProtocol::Fossil);
                if let Some(fragment) = fragment {
                    formatted_fragment = format!("#{fragment}");
                }
            }
            VcsInfo::Git { fragment, signed } => {
                // Only add the protocol prefix if the URL doesn't already encode the protocol
                if !url.starts_with("git://") {
                    prefix = Some(VcsProtocol::Git);
                }
                if *signed {
                    query = "?signed".to_string();
                }
                if let Some(fragment) = fragment {
                    formatted_fragment = format!("#{fragment}");
                }
            }
            VcsInfo::Hg { fragment } => {
                prefix = Some(VcsProtocol::Hg);
                if let Some(fragment) = fragment {
                    formatted_fragment = format!("#{fragment}");
                }
            }
            VcsInfo::Svn { fragment } => {
                // Only add the prefix if the URL doesn't already encode the protocol
                if !url.starts_with("svn://") {
                    prefix = Some(VcsProtocol::Svn);
                }
                if let Some(fragment) = fragment {
                    formatted_fragment = format!("#{fragment}");
                }
            }
        }

        let prefix = if let Some(prefix) = prefix {
            format!("{prefix}+")
        } else {
            String::new()
        };

        write!(f, "{prefix}{url}{query}{formatted_fragment}",)
    }
}

impl SourceUrl {
    /// Parses a full [`SourceUrl`] from a string slice.
    fn parser(input: &mut &str) -> ModalResult<SourceUrl> {
        // Check if we should use a VCS for this URL.
        let vcs = opt(VcsProtocol::parser).parse_next(input)?;

        let Some(vcs) = vcs else {
            // If there's no VCS, simply interpret the rest of the string as a URL.
            //
            // We explicitly don't look for ALPM related fragments or queries, as the fragment and
            // query might be a part of the inner URL string for retrieving the sources.
            let url = cut_err(rest.try_map(Url::from_str))
                .context(StrContext::Label("url"))
                .parse_next(input)?;
            return Ok(SourceUrl {
                url,
                vcs_info: None,
            });
        };

        // We now know that we look at a URL that's supposed to be used by a VCS.
        // Get the URL first, error if we cannot find it.
        let url = cut_err(SourceUrl::inner_url_parser.try_map(|url| Url::from_str(&url)))
            .context(StrContext::Label("url"))
            .parse_next(input)?;

        let vcs_info = VcsInfo::parser(vcs).parse_next(input)?;

        // Produce a special error message for unconsumed query parameters.
        // The unused result with error type are necessary to please the type checker.
        let _: Option<String> =
            opt(("?", rest)
                .take()
                .and_then(cut_err(fail.context(StrContext::Label(
                    "or duplicate query parameter for detected VCS.",
                )))))
            .parse_next(input)?;

        cut_err((space0, eof))
            .context(StrContext::Label("unexpected trailing content in URL."))
            .context(StrContext::Expected(StrContextValue::Description(
                "end of input.",
            )))
            .parse_next(input)?;

        Ok(SourceUrl {
            url,
            vcs_info: Some(vcs_info),
        })
    }

    /// Recognizes a URL in an alpm-package-source string.
    ///
    /// Considers all chars until a special char or the EOF is encountered:
    /// - `#` character that indicates a fragment
    /// - `?` character indicates a query
    /// - `EOF` we reached the end of the string.
    ///
    /// All of the above indicate that the end of the URL has been reached.
    /// The `#` or `?` are not consumed, so that an outer parser may continue parsing afterwards.
    fn inner_url_parser(input: &mut &str) -> ModalResult<String> {
        let (url, _) = repeat_till(0.., any, peek(alt(("#", "?", eof)))).parse_next(input)?;
        Ok(url)
    }
}

/// Information on Version Control Systems (VCS) using a URL.
///
/// Several different VCS systems can be used in the context of a [`SourceUrl`].
/// Each system supports addressing different types of objects and may optionally require signature
/// verification for those objects.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "protocol", rename_all = "lowercase")]
pub enum VcsInfo {
    /// Bazaar/Breezy VCS information.
    Bzr {
        /// Optional URL fragment information.
        fragment: Option<BzrFragment>,
    },
    /// Fossil VCS information.
    Fossil {
        /// Optional URL fragment information.
        fragment: Option<FossilFragment>,
    },
    /// Git VCS information.
    Git {
        /// Optional URL fragment information.
        fragment: Option<GitFragment>,
        /// Whether OpenPGP signature verification is required.
        signed: bool,
    },
    /// Mercurial VCS information.
    Hg {
        /// Optional URL fragment information.
        fragment: Option<HgFragment>,
    },
    /// Apache Subversion VCS information.
    Svn {
        /// Optional URL fragment information.
        fragment: Option<SvnFragment>,
    },
}

impl VcsInfo {
    /// Recognizes VCS-specific URL fragment and query based on a [`VcsProtocol`].
    ///
    /// As the parser is parameterized due to the earlier detected [`VcsProtocol`], it returns a
    /// new stateful parser closure.
    fn parser(vcs: VcsProtocol) -> impl FnMut(&mut &str) -> ModalResult<VcsInfo> {
        move |input: &mut &str| match vcs {
            VcsProtocol::Bzr => {
                let fragment = opt(BzrFragment::parser).parse_next(input)?;
                Ok(VcsInfo::Bzr { fragment })
            }
            VcsProtocol::Fossil => {
                let fragment = opt(FossilFragment::parser).parse_next(input)?;
                Ok(VcsInfo::Fossil { fragment })
            }
            VcsProtocol::Git => {
                // Pacman actually allows a parameter **after** the fragment, which is
                // theoretically an invalid URL.
                // Hence, we have to check for the parameter before and after the url.
                let mut signed = git_query(input)?;
                let fragment = opt(GitFragment::parser).parse_next(input)?;
                if !signed {
                    // Check for the theoretically invalid query after the fragment if it wasn't
                    // already at the front.
                    signed = git_query(input)?;
                }
                Ok(VcsInfo::Git { fragment, signed })
            }
            VcsProtocol::Hg => {
                let fragment = opt(HgFragment::parser).parse_next(input)?;
                Ok(VcsInfo::Hg { fragment })
            }
            VcsProtocol::Svn => {
                let fragment = opt(SvnFragment::parser).parse_next(input)?;
                Ok(VcsInfo::Svn { fragment })
            }
        }
    }
}

/// A VCS protocol
///
/// This identifier is only used during parsing to have some static representation of the detected
/// VCS.
/// This is necessary as the fragment and the query are parsed at a later step and we have to
/// keep track of the VCS somehow.
#[derive(strum::Display, strum::EnumString)]
#[strum(serialize_all = "lowercase")]
enum VcsProtocol {
    Bzr,
    Fossil,
    Git,
    Hg,
    Svn,
}

impl VcsProtocol {
    /// Parses the start of an alpm-package-source string to determine the VCS protocol in use.
    ///
    /// VCS protocol information is used in [`SourceUrl`]s and can be detected in the following
    /// ways:
    ///
    /// - An explicit VCS protocol identifier, followed by a literal `+`. E.g. `git+https://...`, `svn+https://...`
    /// - Some VCS (i.e. git and svn) support URLs in which their protocol type is exposed in the
    ///   `scheme` component of the URL itself:
    ///    - `git://...`
    ///    - `svn://...`
    fn parser(input: &mut &str) -> ModalResult<VcsProtocol> {
        // Check for an explicit vcs definition like `git+` first.
        let protocol =
            opt(terminated(alpha1.try_map(VcsProtocol::from_str), "+")).parse_next(input)?;

        if let Some(protocol) = protocol {
            return Ok(protocol);
        }

        // We didn't find any explicit identifiers.
        // Now see if we find any vcs protocol at the start of the URL.
        // Make sure to **not** consume anything from inside URL!
        //
        // If this doesn't find anything, it backtracks to the parent function.
        let protocol = peek(alt(("git://", "svn://"))).parse_next(input)?;

        match protocol {
            "git://" => Ok(VcsProtocol::Git),
            "svn://" => Ok(VcsProtocol::Svn),
            _ => unreachable!(),
        }
    }
}

/// Parses the value of a URL fragment from an alpm-package-source string.
///
/// Parsing is attempted after the URL fragment type has been determined.
///
/// E.g. `tag=v1.0.0`
///           ^^^^^^
///          This part
fn fragment_value(input: &mut &str) -> ModalResult<String> {
    // Error if we don't find the separator
    let _ = cut_err("=")
        .context(StrContext::Label("fragment separator"))
        .context(StrContext::Expected(StrContextValue::Description(
            "a literal '='",
        )))
        .parse_next(input)?;

    // Get the value of the fragment.
    let (value, _) = repeat_till(0.., any, peek(alt(("?", "#", eof)))).parse_next(input)?;

    Ok(value)
}

/// The available URL fragments and their values when using the Breezy VCS in a [`SourceUrl`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BzrFragment {
    /// A specific revision in the repository.
    Revision(String),
}

impl Display for BzrFragment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            BzrFragment::Revision(revision) => write!(f, "revision={revision}"),
        }
    }
}

impl BzrFragment {
    /// Recognizes URL fragments and values specific to Breezy VCS.
    ///
    /// This parser considers all variants of [`BzrFragment`] (including a leading `#` character).
    fn parser(input: &mut &str) -> ModalResult<BzrFragment> {
        // Check for the `#` fragment start first. If it isn't here, backtrack.
        let _ = "#".parse_next(input)?;

        // Expect the only allowed revision keyword.
        cut_err("revision")
            .context(StrContext::Label("bzr revision type"))
            .context(StrContext::Expected(StrContextValue::Description(
                "revision keyword",
            )))
            .parse_next(input)?;

        let value = fragment_value.parse_next(input)?;

        Ok(BzrFragment::Revision(value))
    }
}

/// The available URL fragments and their values when using the Fossil VCS in a [`SourceUrl`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FossilFragment {
    /// A specific branch in the repository.
    Branch(String),
    /// A specific commit in the repository.
    Commit(String),
    /// A specific tag in the repository.
    Tag(String),
}

impl Display for FossilFragment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            FossilFragment::Branch(revision) => write!(f, "branch={revision}"),
            FossilFragment::Commit(revision) => write!(f, "commit={revision}"),
            FossilFragment::Tag(revision) => write!(f, "tag={revision}"),
        }
    }
}

impl FossilFragment {
    /// Recognizes URL fragments and values specific to Fossil VCS.
    ///
    /// This parser considers all variants of [`FossilFragment`] as fragments in an
    /// alpm-package-source string (including the leading `#` character).
    fn parser(input: &mut &str) -> ModalResult<FossilFragment> {
        // Check for the `#` fragment start first. If it isn't here, backtrack.
        let _ = "#".parse_next(input)?;

        // Error if we don't find one of the expected fossil revision types.
        let version_keywords = ["branch", "commit", "tag"];
        let version_type = cut_err(alt(version_keywords))
            .context(StrContext::Label("fossil revision type"))
            .context_with(iter_str_context!([version_keywords]))
            .parse_next(input)?;

        let value = fragment_value.parse_next(input)?;

        match version_type {
            "branch" => Ok(FossilFragment::Branch(value.to_string())),
            "commit" => Ok(FossilFragment::Commit(value.to_string())),
            "tag" => Ok(FossilFragment::Tag(value.to_string())),
            _ => unreachable!(),
        }
    }
}

/// The available URL fragments and their values when using the Git VCS in a [`SourceUrl`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GitFragment {
    /// A specific branch in the repository.
    Branch(String),
    /// A specific commit in the repository.
    Commit(String),
    /// A specific tag in the repository.
    Tag(String),
}

impl Display for GitFragment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            GitFragment::Branch(revision) => write!(f, "branch={revision}"),
            GitFragment::Commit(revision) => write!(f, "commit={revision}"),
            GitFragment::Tag(revision) => write!(f, "tag={revision}"),
        }
    }
}

impl GitFragment {
    /// Recognizes URL fragments and values specific to the Git VCS.
    ///
    /// This parser considers all variants of [`GitFragment`] as fragments in an alpm-package-source
    /// string (including the leading `#` character).
    fn parser(input: &mut &str) -> ModalResult<GitFragment> {
        // Check for the `#` fragment start first. If it isn't here, backtrack.
        let _ = "#".parse_next(input)?;

        // Error if we don't find one of the expected git revision types.
        let version_keywords = ["branch", "commit", "tag"];
        let version_type = cut_err(alt(version_keywords))
            .context(StrContext::Label("git revision type"))
            .context_with(iter_str_context!([version_keywords]))
            .parse_next(input)?;

        let value = fragment_value.parse_next(input)?;

        match version_type {
            "branch" => Ok(GitFragment::Branch(value.to_string())),
            "commit" => Ok(GitFragment::Commit(value.to_string())),
            "tag" => Ok(GitFragment::Tag(value.to_string())),
            _ => unreachable!(),
        }
    }
}

/// Recognizes URL queries specific to the Git VCS.
///
/// This parser considers the `?signed` URL query in an alpm-package-source string.
fn git_query(input: &mut &str) -> ModalResult<bool> {
    let query = opt("?signed").parse_next(input)?;
    Ok(query.is_some())
}

/// An optional version specification used in a [`SourceUrl`] for the Hg VCS.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HgFragment {
    /// A specific branch in the repository.
    Branch(String),
    /// A specific revision in the repository.
    Revision(String),
    /// A specific tag in the repository.
    Tag(String),
}

impl Display for HgFragment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            HgFragment::Branch(revision) => write!(f, "branch={revision}"),
            HgFragment::Revision(revision) => write!(f, "revision={revision}"),
            HgFragment::Tag(revision) => write!(f, "tag={revision}"),
        }
    }
}

impl HgFragment {
    /// Recognizes URL fragments and values specific to the Mercurial VCS.
    ///
    /// This parser considers all variants of [`HgFragment`] as fragments in an alpm-package-source
    /// string (including the leading `#` character).
    fn parser(input: &mut &str) -> ModalResult<HgFragment> {
        // Check for the `#` fragment start first. If it isn't here, backtrack.
        let _ = "#".parse_next(input)?;

        // Error if we don't find one of the expected git revision types.
        let version_keywords = ["branch", "revision", "tag"];
        let version_type = cut_err(alt(version_keywords))
            .context(StrContext::Label("hg revision type"))
            .context_with(iter_str_context!([version_keywords]))
            .parse_next(input)?;

        let value = fragment_value.parse_next(input)?;

        match version_type {
            "branch" => Ok(HgFragment::Branch(value.to_string())),
            "revision" => Ok(HgFragment::Revision(value.to_string())),
            "tag" => Ok(HgFragment::Tag(value.to_string())),
            _ => unreachable!(),
        }
    }
}

/// The available URL fragments and their values when using Apache Subversion in a [`SourceUrl`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SvnFragment {
    /// A specific revision in the repository.
    Revision(String),
}

impl Display for SvnFragment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            SvnFragment::Revision(revision) => write!(f, "revision={revision}"),
        }
    }
}

impl SvnFragment {
    /// Recognizes URL fragments and values specific to Apache Subversion.
    ///
    /// This parser considers all variants of [`SvnFragment`] as fragments in an alpm-package-source
    /// string (including the leading `#` character).
    fn parser(input: &mut &str) -> ModalResult<SvnFragment> {
        // Check for the `#` fragment start first. If it isn't here, backtrack.
        let _ = "#".parse_next(input)?;

        // Expect the only allowed revision keyword.
        cut_err("revision")
            .context(StrContext::Label("svn revision type"))
            .context(StrContext::Expected(StrContextValue::Description(
                "revision keyword",
            )))
            .parse_next(input)?;

        let value = fragment_value.parse_next(input)?;

        Ok(SvnFragment::Revision(value))
    }
}

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

    use super::*;

    #[rstest]
    #[case("https://example.com/", Ok("https://example.com/"))]
    #[case(
        "https://example.com/path?query=1",
        Ok("https://example.com/path?query=1")
    )]
    #[case("ftp://example.com/", Ok("ftp://example.com/"))]
    #[case("not-a-url", Err(url::ParseError::RelativeUrlWithoutBase.into()))]
    fn test_url_parsing(#[case] input: &str, #[case] expected: Result<&str, Error>) {
        let result = input.parse::<Url>();
        assert_eq!(
            result.as_ref().map(|v| v.to_string()),
            expected.as_ref().map(|v| v.to_string())
        );

        if let Ok(url) = result {
            assert_eq!(url.as_str(), input);
        }
    }

    #[rstest]
    #[case(
        "git+https://example/project#tag=v1.0.0?signed",
        Some("git+https://example/project?signed#tag=v1.0.0"),
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Git {
                fragment: Some(GitFragment::Tag("v1.0.0".to_string())),
                signed: true
            })
        }
    )]
    #[case(
        "git+https://example/project?signed#tag=v1.0.0",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Git {
                fragment: Some(GitFragment::Tag("v1.0.0".to_string())),
                signed: true
            })
        }
    )]
    #[case(
        "git://example/project#commit=a51720b",
        None,
        SourceUrl {
            url: Url::from_str("git://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Git {
                fragment: Some(GitFragment::Commit("a51720b".to_string())),
                signed: false
            })
        }
    )]
    #[case(
        "svn+https://example/project#revision=a51720b",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Svn {
                fragment: Some(SvnFragment::Revision("a51720b".to_string())),
            })
        }
    )]
    #[case(
        "bzr+https://example/project#revision=a51720b",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Bzr {
                fragment: Some(BzrFragment::Revision("a51720b".to_string())),
            })
        }
    )]
    #[case(
        "hg+https://example/project#branch=feature",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Hg {
                fragment: Some(HgFragment::Branch("feature".to_string())),
            })
        }
    )]
    #[case(
        "fossil+https://example/project#branch=feature",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project").unwrap(),
            vcs_info: Some(VcsInfo::Fossil {
                fragment: Some(FossilFragment::Branch("feature".to_string())),
            })
        }
    )]
    #[case(
        "https://example/project#branch=feature?signed",
        None,
        SourceUrl {
            url: Url::from_str("https://example/project#branch=feature?signed").unwrap(),
            vcs_info: None,
        }
    )]
    fn test_source_url_parsing_success(
        #[case] input: &str,
        #[case] expected_to_string: Option<&str>,
        #[case] expected: SourceUrl,
    ) -> TestResult {
        let source_url = SourceUrl::from_str(input)?;
        assert_eq!(
            source_url, expected,
            "Parsed source_url should resemble the expected output."
        );

        // Some representations are shortened or brought into the proper representation, hence we
        // have a slightly different ToString output than input.
        let expected_to_string = expected_to_string.unwrap_or(input);
        assert_eq!(
            source_url.to_string(),
            expected_to_string,
            "Parsed and displayed source_url should resemble original."
        );

        Ok(())
    }

    /// Run the parser for SourceUrl and ensure that the expected parse error messages show up.
    #[rstest]
    #[case(
        "git+https://example/project#revision=v1.0.0?signed",
        "invalid git revision type\nexpected `branch`, `commit`, `tag`"
    )]
    #[case(
        "git+https://example/project#branch=feature#branch=feature",
        "invalid unexpected trailing content in URL."
    )]
    #[case(
        "git+https://example/project#branch=feature?signed?signed",
        "invalid or duplicate query parameter for detected VCS."
    )]
    #[case(
        "bzr+https://example/project#branch=feature",
        "invalid bzr revision type\nexpected revision keyword"
    )]
    #[case(
        "svn+https://example/project#branch=feature",
        "invalid svn revision type\nexpected revision keyword"
    )]
    #[case(
        "hg+https://example/project#commit=154021a",
        "invalid hg revision type\nexpected `branch`, `revision`, `tag`"
    )]
    #[case(
        "hg+https://example/project#branch=feature?signed",
        "invalid or duplicate query parameter for detected VCS."
    )]
    fn test_source_url_parsing_failure(#[case] input: &str, #[case] error_snippet: &str) {
        let result = SourceUrl::from_str(input);
        assert!(result.is_err(), "Invalid source_url should fail to parse.");
        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}"
        );
    }
}