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
use regex::Regex;
use std::borrow::Cow;
use std::str::FromStr;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedVcs {
    pub repo_url: String,
    pub branch: Option<String>,
    pub subpath: Option<String>,
}

impl FromStr for ParsedVcs {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut s: Cow<str> = s.trim().into();
        let mut subpath: Option<String> = None;
        let branch: Option<String>;
        let repo_url: String;
        let re = Regex::new(r" \[([^] ]+)\]").unwrap();

        if let Some(ref m) = re.find(s.as_ref()) {
            subpath = Some(m.as_str()[2..m.as_str().len() - 1].to_string());
            s = Cow::Owned([s[..m.start()].to_string(), s[m.end()..].to_string()].concat());
        }

        if let Some(index) = s.find(" -b ") {
            let (url, branch_str) = s.split_at(index);
            branch = Some(branch_str[4..].to_string());
            repo_url = url.to_string();
        } else {
            branch = None;
            repo_url = s.to_string();
        }

        Ok(ParsedVcs {
            repo_url,
            branch,
            subpath,
        })
    }
}

impl std::fmt::Display for ParsedVcs {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(&self.repo_url)?;

        if let Some(branch) = &self.branch {
            write!(f, " -b {}", branch)?;
        }

        if let Some(subpath) = &self.subpath {
            write!(f, " [{}]", subpath)?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub enum Vcs {
    Git {
        repo_url: String,
        branch: Option<String>,
        subpath: Option<String>,
    },
    Bzr {
        repo_url: String,
        subpath: Option<String>,
    },
    Hg {
        repo_url: String,
    },
    Svn {
        url: String,
    },
    Cvs {
        root: String,
        module: Option<String>,
    },
}

impl Vcs {
    pub fn from_field(name: &str, value: &str) -> Result<Vcs, String> {
        match name {
            "Git" => {
                let parsed_vcs: ParsedVcs =
                    value.parse::<ParsedVcs>().map_err(|e| e.to_string())?;
                Ok(Vcs::Git {
                    repo_url: parsed_vcs.repo_url,
                    branch: parsed_vcs.branch,
                    subpath: parsed_vcs.subpath,
                })
            }
            "Bzr" => {
                let parsed_vcs: ParsedVcs =
                    value.parse::<ParsedVcs>().map_err(|e| e.to_string())?;
                if parsed_vcs.branch.is_some() {
                    return Err("Invalid branch value for Vcs-Bzr".to_string());
                }
                Ok(Vcs::Bzr {
                    repo_url: parsed_vcs.repo_url,
                    subpath: parsed_vcs.subpath,
                })
            }
            "Hg" => Ok(Vcs::Hg {
                repo_url: value.to_string(),
            }),
            "Svn" => Ok(Vcs::Svn {
                url: value.to_string(),
            }),
            "Cvs" => {
                if let Some((root, module)) = value.split_once(' ') {
                    Ok(Vcs::Cvs {
                        root: root.to_string(),
                        module: Some(module.to_string()),
                    })
                } else {
                    Ok(Vcs::Cvs {
                        root: value.to_string(),
                        module: None,
                    })
                }
            }
            n => Err(format!("Unknown VCS: {}", n)),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_vcs_info() {
        let vcs_info = ParsedVcs::from_str("https://github.com/jelmer/example").unwrap();
        assert_eq!(vcs_info.repo_url, "https://github.com/jelmer/example");
        assert_eq!(vcs_info.branch, None);
        assert_eq!(vcs_info.subpath, None);
    }

    #[test]
    fn test_vcs_info_with_branch() {
        let vcs_info = ParsedVcs::from_str("https://github.com/jelmer/example -b branch").unwrap();
        assert_eq!(vcs_info.repo_url, "https://github.com/jelmer/example");
        assert_eq!(vcs_info.branch, Some("branch".to_string()));
        assert_eq!(vcs_info.subpath, None);
    }

    #[test]
    fn test_vcs_info_with_subpath() {
        let vcs_info = ParsedVcs::from_str("https://github.com/jelmer/example [subpath]").unwrap();
        assert_eq!(vcs_info.repo_url, "https://github.com/jelmer/example");
        assert_eq!(vcs_info.branch, None);
        assert_eq!(vcs_info.subpath, Some("subpath".to_string()));
    }

    #[test]
    fn test_vcs_info_with_branch_and_subpath() {
        let vcs_info =
            ParsedVcs::from_str("https://github.com/jelmer/example -b branch [subpath]").unwrap();
        assert_eq!(vcs_info.repo_url, "https://github.com/jelmer/example");
        assert_eq!(vcs_info.branch, Some("branch".to_string()));
        assert_eq!(vcs_info.subpath, Some("subpath".to_string()));
    }

    #[test]
    fn test_eq() {
        let vcs_info1 =
            ParsedVcs::from_str("https://github.com/jelmer/example -b branch [subpath]").unwrap();
        let vcs_info2 =
            ParsedVcs::from_str("https://github.com/jelmer/example -b branch [subpath]").unwrap();
        let vcs_info3 =
            ParsedVcs::from_str("https://example.com/jelmer/example -b branch [subpath]").unwrap();

        assert_eq!(vcs_info1, vcs_info2);
        assert_ne!(vcs_info1, vcs_info3);
    }
}