fuchsia_pkg/
meta_package.rs

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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::errors::MetaPackageError;
use crate::path::PackagePath;
use fuchsia_url::{PackageName, PackageVariant};
use serde::{Deserialize, Serialize};
use std::convert::TryInto as _;
use std::io;

/// A `MetaPackage` represents the "meta/package" file of a meta.far (which is
/// a Fuchsia archive file of a Fuchsia package).
/// It validates that the name and variant (called "version" in json) are valid.
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct MetaPackage {
    name: PackageName,
    variant: PackageVariant,
}

impl MetaPackage {
    pub const PATH: &'static str = "meta/package";

    /// Create a `MetaPackage` with `name` and variant 0.
    pub fn from_name_and_variant_zero(name: PackageName) -> Self {
        Self { name, variant: PackageVariant::zero() }
    }

    /// Returns the package's name.
    pub fn name(&self) -> &PackageName {
        &self.name
    }

    /// Returns the package's variant.
    pub fn variant(&self) -> &PackageVariant {
        &self.variant
    }

    /// Convert into PackagePath.
    pub fn into_path(self) -> PackagePath {
        PackagePath::from_name_and_variant(self.name, self.variant)
    }

    /// Deserializes a `MetaPackage` from json.
    ///
    /// # Examples
    /// ```
    /// # use fuchsia_pkg::MetaPackage;
    /// let json = r#"
    ///     {"name": "package-name",
    ///      "version": "0"}"#;
    /// assert_eq!(
    ///     MetaPackage::deserialize(json.as_bytes()).unwrap(),
    ///     MetaPackage::from_name(
    ///         "package-name".parse().unwrap(),
    ///         "0".parse().unwrap(),
    ///     )
    /// );
    /// ```
    pub fn deserialize(reader: impl io::BufRead) -> Result<Self, MetaPackageError> {
        MetaPackage::from_v0(serde_json::from_reader(reader)?)
    }

    /// Serializes a `MetaPackage` to json.
    ///
    /// # Examples
    /// ```
    /// # use fuchsia_pkg::MetaPackage;
    /// let meta_package = MetaPackage::from_name("package-name".parse().unwrap());
    /// let mut v: Vec<u8> = vec![];
    /// meta_package.serialize(&mut v).unwrap();
    /// assert_eq!(std::str::from_utf8(v.as_slice()).unwrap(),
    ///            r#"{"name":"package-name","version":"0"}"#);
    /// ```
    pub fn serialize(&self, writer: impl io::Write) -> Result<(), MetaPackageError> {
        serde_json::to_writer(
            writer,
            &MetaPackageV0Serialize { name: self.name.as_ref(), variant: self.variant.as_ref() },
        )?;
        Ok(())
    }

    fn from_v0(v0: MetaPackageV0Deserialize) -> Result<MetaPackage, MetaPackageError> {
        Ok(MetaPackage {
            name: v0.name.try_into().map_err(MetaPackageError::PackageName)?,
            variant: v0.variant.try_into().map_err(MetaPackageError::PackageVariant)?,
        })
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
struct MetaPackageV0Deserialize {
    name: String,
    #[serde(rename = "version")]
    variant: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
struct MetaPackageV0Serialize<'a> {
    name: &'a str,
    #[serde(rename = "version")]
    variant: &'a str,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::*;
    use lazy_static::lazy_static;
    use proptest::prelude::*;
    use regex::Regex;

    #[test]
    fn test_accessors() {
        let meta_package = MetaPackage::from_name_and_variant_zero("foo".parse().unwrap());
        assert_eq!(meta_package.name(), &"foo".parse::<PackageName>().unwrap());
        assert_eq!(meta_package.variant(), &"0".parse::<PackageVariant>().unwrap());
    }

    #[test]
    fn test_serialize() {
        let meta_package = MetaPackage::from_name_and_variant_zero("package-name".parse().unwrap());
        let mut v: Vec<u8> = Vec::new();

        meta_package.serialize(&mut v).unwrap();

        let expected = r#"{"name":"package-name","version":"0"}"#;
        assert_eq!(v.as_slice(), expected.as_bytes());
    }

    #[test]
    fn test_deserialize() {
        let json_bytes = r#"{"name":"package-name","version":"0"}"#.as_bytes();
        assert_eq!(
            MetaPackage::deserialize(json_bytes).unwrap(),
            MetaPackage { name: "package-name".parse().unwrap(), variant: "0".parse().unwrap() }
        );
    }

    proptest! {
        #![proptest_config(ProptestConfig{
            failure_persistence: None,
            ..Default::default()
        })]

        #[test]
        fn test_serialize_deserialize_is_identity(
            meta_package in random_meta_package(),
        ) {
            let mut v: Vec<u8> = Vec::new();
            meta_package.serialize(&mut v).unwrap();
            let meta_package_round_trip = MetaPackage::deserialize(v.as_slice()).unwrap();
            assert_eq!(meta_package, meta_package_round_trip);
        }

        #[test]
        fn test_serialized_contains_no_whitespace(
            meta_package in random_meta_package(),
        ) {
            lazy_static! {
                static ref RE: Regex = Regex::new(r"(\p{White_Space})").unwrap();
            }
            let mut v: Vec<u8> = Vec::new();
            meta_package.serialize(&mut v).unwrap();
            assert!(!RE.is_match(std::str::from_utf8(v.as_slice()).unwrap()));
        }
    }
}