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
use std::fmt;
use std::path::Path;
use std::str::FromStr;
mod toml;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Manifest {
package_id: PackageId,
metadata: ManifestMetadata,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ManifestMetadata {
pub authors: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PackageId {
name: String,
version: semver::Version,
}
impl Manifest {
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Manifest, anyhow::Error> {
let file_contents = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("could not read manifest file: {}", e))?;
Self::from_str(&file_contents)
}
pub fn package_id(&self) -> &PackageId {
&self.package_id
}
pub fn name(&self) -> &str {
self.package_id.name()
}
pub fn version(&self) -> &semver::Version {
self.package_id.version()
}
pub fn metadata(&self) -> &ManifestMetadata {
&self.metadata
}
}
impl PackageId {
pub fn name(&self) -> &str {
&self.name
}
pub fn version(&self) -> &semver::Version {
&self.version
}
}
impl fmt::Display for PackageId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} v{}", self.name(), self.version())
}
}
impl std::str::FromStr for Manifest {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let manifest = ::toml::from_str::<toml::TomlManifest>(s)
.map_err(|e| anyhow::anyhow!("could not parse manifest: {}", e))?;
manifest.into_real_manifest()
}
}
#[cfg(test)]
mod tests {
use crate::Manifest;
use std::str::FromStr;
#[test]
fn parse() {
let manifest = Manifest::from_str(
r#"
[package]
name="test"
version="0.2.0"
authors = ["Mun Team"]
"#,
)
.unwrap();
assert_eq!(manifest.name(), "test");
assert_eq!(
manifest.version(),
&semver::Version::from_str("0.2.0").unwrap()
);
assert_eq!(manifest.metadata().authors, vec!["Mun Team"]);
assert_eq!(format!("{}", manifest.package_id()), "test v0.2.0");
}
}