fetch-source 0.1.2

Declare and fetch external sources programmatically
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
//! Core types for interacting with sources declared in `Cargo.toml`.

use super::error::FetchError;
use super::git::Git;
#[cfg(feature = "tar")]
use super::tar::Tar;

use derive_more::Deref;

/// The name of a source
pub type SourceName = String;

/// Errors encountered when parsing sources from `Cargo.toml`
#[derive(Debug, thiserror::Error)]
pub enum SourceParseError {
    /// An unknown source variant was encountered.
    #[error("expected a valid source type for source '{source_name}': expected one of: {known}", known = SOURCE_VARIANTS.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))]
    VariantUnknown {
        /// The name of the source whose variant wasn't recognised
        source_name: SourceName,
    },

    /// A source has multiple variants given.
    #[error("multiple source types for source '{source_name}': expected exactly one of: {known}", known = SOURCE_VARIANTS.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))]
    VariantMultiple {
        /// The name of the source with multiple variants
        source_name: SourceName,
    },

    /// A source has a variant which depends on a disabled feature.
    #[error("source '{source_name}' has type '{variant}' but needs disabled feature '{requires}'")]
    VariantDisabled {
        /// The name of the source
        source_name: SourceName,
        /// The source type
        variant: String,
        /// The disabled feature
        requires: String,
    },

    /// A toml value was expected to be a table.
    #[error("expected value '{name}' to be a toml table")]
    ValueNotTable {
        /// The key for the value which was expected to be a table
        name: String,
    },

    /// The `package.metadata.fetch-source` table was not found.
    #[error("required table 'package.metadata.fetch-source' not found in string")]
    SourceTableNotFound,

    /// A toml deserialisation error occurred.
    #[error(transparent)]
    TomlInvalid(#[from] toml::de::Error),

    /// A json error occurred.
    #[error(transparent)]
    JsonInvalid(#[from] serde_json::Error),
}

/// Represents the result of a fetch operation
pub type FetchResult<T> = Result<T, crate::FetchError>;

/// Represents a source that has been fetched from a remote location.
///
/// Notably implements [`AsRef<std::path::Path>`](std::path::Path) and [`AsRef<Source>`](Source).
#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
pub struct Artefact {
    // This is a combination of the fetched artefact and the source it was fetched from.
    // Note that the name associated with a source *must not* be stored in the cache. This avoids
    // using one name for a source but then unexpectedly returning another.
    /// The upstream source
    source: Source,
    /// The local copy
    path: std::path::PathBuf,
}

impl Artefact {
    /// Get the path to an artefact
    pub fn path(&self) -> &std::path::Path {
        &self.path
    }
}

impl AsRef<std::path::Path> for Artefact {
    fn as_ref(&self) -> &std::path::Path {
        &self.path
    }
}

impl AsRef<Source> for Artefact {
    fn as_ref(&self) -> &Source {
        &self.source
    }
}

impl AsRef<Source> for Source {
    fn as_ref(&self) -> &Source {
        self
    }
}

/// Allowed source variants.
#[derive(Debug, PartialEq, Eq, Hash)]
enum SourceVariant {
    Tar,
    Git,
}

const SOURCE_VARIANTS: &[SourceVariant] = &[SourceVariant::Tar, SourceVariant::Git];

impl std::fmt::Display for SourceVariant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Tar => write!(f, "tar"),
            Self::Git => write!(f, "git"),
        }
    }
}

impl SourceVariant {
    fn from<S: AsRef<str>>(name: S) -> Option<Self> {
        match name.as_ref() {
            "tar" => Some(Self::Tar),
            "git" => Some(Self::Git),
            _ => None,
        }
    }

    fn is_enabled(&self) -> bool {
        match self {
            Self::Tar => cfg!(feature = "tar"),
            Self::Git => true,
        }
    }

    fn feature(&self) -> Option<&'static str> {
        match self {
            Self::Tar => Some("tar"),
            Self::Git => None,
        }
    }
}

/// The digest associated with the definition of a [`Source`]
#[derive(
    Debug,
    Default,
    serde::Deserialize,
    serde::Serialize,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Clone,
    Deref,
)]
pub struct Digest(String);

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

/// Represents an entry in the `package.metadata.fetch-source` table.
#[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Source {
    #[cfg(feature = "tar")]
    #[serde(rename = "tar")]
    /// A remote tar archive
    Tar(Tar),
    #[serde(rename = "git")]
    /// A remote git repo
    Git(Git),
}

impl std::fmt::Display for Source {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "tar")]
            Source::Tar(tar) => write!(f, "tar source: {tar:?}"),
            Source::Git(git) => write!(f, "git source: {git:?}"),
        }
    }
}

impl Source {
    /// Calculate the digest of a source.
    pub fn digest<S: AsRef<Self>>(value: S) -> Digest {
        let json = serde_json::to_string(value.as_ref())
            .expect("Serialisation of Source should never fail");
        Digest(sha256::digest(json))
    }

    /// Fetch the remote source as declared in `Cargo.toml` and put the resulting [`Artefact`] in `dir`.
    pub fn fetch<P: AsRef<std::path::Path>>(self, dir: P) -> FetchResult<Artefact> {
        let dest = dir.as_ref();
        let result = match self {
            #[cfg(feature = "tar")]
            Source::Tar(ref tar) => tar.fetch(dest),
            Source::Git(ref git) => git.fetch(dest),
        };
        match result {
            Ok(path) => Ok(Artefact { source: self, path }),
            Err(err) => Err(FetchError::new(err, self)),
        }
    }

    /// Convert a name into a partial path. Each `::`-separated component maps onto a subdirectory.
    pub fn as_path_component<S: AsRef<str>>(name: S) -> std::path::PathBuf {
        std::path::PathBuf::from_iter(name.as_ref().split("::"))
    }

    fn enforce_one_valid_variant<S: ToString>(
        name: S,
        source: &toml::Table,
    ) -> Result<SourceVariant, SourceParseError> {
        let mut detected_variant = None;
        for key in source.keys() {
            if let Some(variant) = SourceVariant::from(key) {
                if detected_variant.is_some() {
                    return Err(SourceParseError::VariantMultiple {
                        source_name: name.to_string(),
                    });
                }
                if !variant.is_enabled() {
                    return Err(SourceParseError::VariantDisabled {
                        source_name: name.to_string(),
                        variant: variant.to_string(),
                        requires: variant.feature().unwrap_or("?").to_string(),
                    });
                }
                detected_variant = Some(variant);
            }
        }
        detected_variant.ok_or(SourceParseError::VariantUnknown {
            source_name: name.to_string(),
        })
    }

    /// Parse a TOML table into a `Source` instance. Exactly one key in the table must identify
    /// a valid, enabled source type, otherwise an error is returned.
    pub fn parse<S: ToString>(name: S, source: toml::Table) -> Result<Self, SourceParseError> {
        Self::enforce_one_valid_variant(name, &source)?;
        Ok(toml::Value::Table(source).try_into::<Self>()?)
    }
}

/// Represents the contents of the `package.metadata.fetch-source` table in a `Cargo.toml` file.
pub type SourcesTable = std::collections::HashMap<SourceName, Source>;

/// Parse a `package.metadata.fetch-source` table into a [`SourcesTable`](crate::source::SourcesTable) map
pub fn try_parse(table: &toml::Table) -> Result<SourcesTable, SourceParseError> {
    table
        .iter()
        .map(|(k, v)| match v.as_table() {
            Some(t) => Source::parse(k, t.to_owned()).map(|s| (k.to_owned(), s)),
            None => Err(SourceParseError::ValueNotTable { name: k.to_owned() }),
        })
        .collect()
}

/// Parse the contents of a Cargo.toml file containing the `package.metadata.fetch-source` table
/// into a [`SourcesTable`](crate::source::SourcesTable) map.
pub fn try_parse_toml<S: AsRef<str>>(toml_str: S) -> Result<SourcesTable, SourceParseError> {
    let table = toml_str.as_ref().parse::<toml::Table>()?;
    let sources_table = table
        .get("package")
        .and_then(|v| v.get("metadata"))
        .and_then(|v| v.get("fetch-source"))
        .and_then(|v| v.as_table())
        .ok_or(SourceParseError::SourceTableNotFound)?;
    try_parse(sources_table)
}

#[cfg(test)]
use SourceParseError::*;

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

    #[test]
    fn parse_good_git_source() {
        let source = build_from_json! {
            Source,
            "git": "git@github.com:foo/bar.git"
        };
        assert!(source.is_ok());
    }

    #[cfg(feature = "tar")]
    #[test]
    fn parse_good_tar_source() {
        let source = build_from_json! {
            Source,
            "tar": "https://example.com/foo.tar.gz"
        };
        assert!(source.is_ok());
    }

    #[cfg(not(feature = "tar"))]
    #[test]
    fn parse_good_tar_source_fails_when_feature_disabled() {
        let source = build_from_json! {
            Source,
            "tar": "https://example.com/foo.tar.gz"
        };
        assert!(
            matches!(source, Err(VariantDisabled { source_name: _, variant, requires })
                if variant == "tar" && requires == "tar"
            )
        );
    }

    #[test]
    fn parse_multiple_types_fails() {
        // NOTE: this test explicitly tests failure modes of Source::parse
        let source = Source::parse(
            "src",
            toml::toml! {
                tar = "https://example.com/foo.tar.gz"
                git = "git@github.com:foo/bar.git"
            },
        );
        assert!(matches!(source, Err(VariantMultiple { source_name })
            if source_name == "src"
        ));
    }

    #[test]
    fn parse_missing_type_fails() {
        // NOTE: this test explicitly tests failure modes of Source::parse
        let source = Source::parse(
            "src",
            toml::toml! {
                foo = "git@github.com:foo/bar.git"
            },
        );
        assert!(matches!(source, Err(VariantUnknown { source_name })
            if source_name == "src"
        ));
    }
}

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

    #[test]
    fn parse_invalid_toml_str_fails() {
        let document = "this is not a valid toml document :( uh-oh!";
        let result = try_parse_toml(document);
        assert!(matches!(result, Err(TomlInvalid(_))));
    }

    #[test]
    fn parse_doc_missing_sources_table_fails() {
        let document = r#"
            [package]
            name = "my_fun_test_suite"

            [package.metadata.wrong-name]
            foo = { git = "git@github.com:foo/bar.git" }
            bar = { tar = "https://example.com/foo.tar.gz" }
        "#;
        assert!(matches!(try_parse_toml(document), Err(SourceTableNotFound)));
    }

    #[test]
    fn parse_doc_source_value_not_a_table_fails() {
        let document = r#"
            [package]
            name = "my_fun_test_suite"

            [package.metadata.fetch-source]
            not-a-table = "actually a string"
        "#;
        assert!(matches!(
            try_parse_toml(document),
            Err(ValueNotTable { name }) if name == "not-a-table"
        ));
    }

    #[cfg(not(feature = "tar"))]
    #[test]
    fn parse_doc_source_variant_disabled_fails() {
        let document = r#"
            [package]
            name = "my_fun_test_suite"

            [package.metadata.fetch-source]
            bar = { tar = "https://example.com/foo.tar.gz" }
        "#;
        assert!(matches!(
            try_parse_toml(document),
            Err(VariantDisabled {
                source_name,
                variant,
                requires,
            }) if source_name == "bar" && variant == "tar" && requires == "tar"
        ));
    }

    #[test]
    fn parse_doc_source_multiple_variants_fails() {
        let document = r#"
            [package]
            name = "my_fun_test_suite"

            [package.metadata.fetch-source]
            bar = { tar = "https://example.com/foo.tar.gz", git = "git@github.com:foo/bar.git" }
        "#;
        assert!(matches!(
            try_parse_toml(document),
            Err(VariantMultiple { source_name }) if source_name == "bar"
        ));
    }

    #[test]
    fn parse_doc_source_unknown_variant_fails() {
        let document = r#"
            [package]
            name = "my_fun_test_suite"

            [package.metadata.fetch-source]
            bar = { zim = "https://example.com/foo.tar.gz" }
        "#;
        assert!(matches!(
            try_parse_toml(document),
            Err(VariantUnknown { source_name }) if source_name == "bar"
        ));
    }
}