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
use std::iter::FromIterator;

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
enum DependencySource {
    Version {
        version: Option<String>,
        path: Option<String>,
        registry: Option<String>,
    },
    Git {
        repo: String,
        branch: Option<String>,
    },
}

/// A dependency handled by Cargo
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct Dependency {
    /// The name of the dependency (as it is set in its `Cargo.toml` and known to crates.io)
    pub name: String,
    optional: bool,
    /// List of features to add (or None to keep features unchanged).
    pub features: Option<Vec<String>>,
    default_features: bool,
    source: DependencySource,
    /// If the dependency is renamed, this is the new name for the dependency
    /// as a string.  None if it is not renamed.
    rename: Option<String>,
}

impl Default for Dependency {
    fn default() -> Dependency {
        Dependency {
            name: "".into(),
            rename: None,
            optional: false,
            features: None,
            default_features: true,
            source: DependencySource::Version {
                version: None,
                path: None,
                registry: None,
            },
        }
    }
}

impl Dependency {
    /// Create a new dependency with a name
    pub fn new(name: &str) -> Dependency {
        Dependency {
            name: name.into(),
            ..Dependency::default()
        }
    }

    /// Set dependency to a given version
    pub fn set_version(mut self, version: &str) -> Dependency {
        // versions might have semver metadata appended which we do not want to
        // store in the cargo toml files.  This would cause a warning upon compilation
        // ("version requirement […] includes semver metadata which will be ignored")
        let version = version.split('+').next().unwrap();
        let (old_path, old_registry) = match self.source {
            DependencySource::Version { path, registry, .. } => (path, registry),
            _ => (None, None),
        };
        self.source = DependencySource::Version {
            version: Some(version.into()),
            path: old_path,
            registry: old_registry,
        };
        self
    }

    /// Set dependency to a given repository
    pub fn set_git(mut self, repo: &str, branch: Option<String>) -> Dependency {
        self.source = DependencySource::Git {
            repo: repo.into(),
            branch,
        };
        self
    }

    /// Set dependency to a given path
    pub fn set_path(mut self, path: &str) -> Dependency {
        let old_version = match self.source {
            DependencySource::Version { version, .. } => version,
            _ => None,
        };
        self.source = DependencySource::Version {
            version: old_version,
            path: Some(path.replace('\\', "/")),
            registry: None,
        };
        self
    }

    /// Set whether the dependency is optional
    pub fn set_optional(mut self, opt: bool) -> Dependency {
        self.optional = opt;
        self
    }
    /// Set features as an array of string (does some basic parsing)
    pub fn set_features(mut self, features: Option<Vec<String>>) -> Dependency {
        self.features = features.map(|f| {
            f.iter()
                .map(|x| x.split(' ').map(String::from))
                .flatten()
                .filter(|s| !s.is_empty())
                .collect::<Vec<String>>()
        });
        self
    }

    /// Set the value of default-features for the dependency
    pub fn set_default_features(mut self, default_features: bool) -> Dependency {
        self.default_features = default_features;
        self
    }

    /// Set the alias for the dependency
    pub fn set_rename(mut self, rename: &str) -> Dependency {
        self.rename = Some(rename.into());
        self
    }

    /// Get the dependency name as defined in the manifest,
    /// that is, either the alias (rename field if Some),
    /// or the official package name (name field).
    pub fn name_in_manifest(&self) -> &str {
        &self.rename().unwrap_or(&self.name)
    }

    /// Set the value of registry for the dependency
    pub fn set_registry(mut self, registry: &str) -> Dependency {
        let old_version = match self.source {
            DependencySource::Version { version, .. } => version,
            _ => None,
        };
        self.source = DependencySource::Version {
            version: old_version,
            path: None,
            registry: Some(registry.into()),
        };
        self
    }

    /// Get version of dependency
    pub fn version(&self) -> Option<&str> {
        if let DependencySource::Version {
            version: Some(ref version),
            ..
        } = self.source
        {
            Some(version)
        } else {
            None
        }
    }

    /// Get the alias for the dependency (if any)
    pub fn rename(&self) -> Option<&str> {
        match &self.rename {
            Some(rename) => Some(&rename),
            None => None,
        }
    }

    /// Convert dependency to TOML
    ///
    /// Returns a tuple with the dependency's name and either the version as a `String`
    /// or the path/git repository as an `InlineTable`.
    /// (If the dependency is set as `optional` or `default-features` is set to `false`,
    /// an `InlineTable` is returned in any case.)
    pub fn to_toml(&self) -> (String, toml_edit::Item) {
        let data: toml_edit::Item = match (
            self.optional,
            self.features.as_ref(),
            self.default_features,
            self.source.clone(),
            self.rename.as_ref(),
        ) {
            // Extra short when version flag only
            (
                false,
                None,
                true,
                DependencySource::Version {
                    version: Some(v),
                    path: None,
                    registry: None,
                },
                None,
            ) => toml_edit::value(v),
            // Other cases are represented as an inline table
            (optional, features, default_features, source, rename) => {
                let mut data = toml_edit::InlineTable::default();

                match source {
                    DependencySource::Version {
                        version,
                        path,
                        registry,
                    } => {
                        if let Some(v) = version {
                            data.get_or_insert("version", v);
                        }
                        if let Some(p) = path {
                            data.get_or_insert("path", p);
                        }
                        if let Some(r) = registry {
                            data.get_or_insert("registry", r);
                        }
                    }
                    DependencySource::Git { repo, branch } => {
                        data.get_or_insert("git", repo);
                        branch.map(|branch| data.get_or_insert("branch", branch));
                    }
                }
                if self.optional {
                    data.get_or_insert("optional", optional);
                }
                if let Some(features) = features {
                    let features = toml_edit::Value::from_iter(features.iter().cloned());
                    data.get_or_insert("features", features);
                }
                if !self.default_features {
                    data.get_or_insert("default-features", default_features);
                }
                if rename.is_some() {
                    data.get_or_insert("package", self.name.clone());
                }

                data.fmt();
                toml_edit::value(toml_edit::Value::InlineTable(data))
            }
        };

        (self.name_in_manifest().to_string(), data)
    }
}

#[cfg(test)]
mod tests {
    use crate::dependency::Dependency;

    #[test]
    fn to_toml_simple_dep() {
        let toml = Dependency::new("dep").to_toml();

        assert_eq!(toml.0, "dep".to_owned());
    }

    #[test]
    fn to_toml_simple_dep_with_version() {
        let toml = Dependency::new("dep").set_version("1.0").to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert_eq!(toml.1.as_str(), Some("1.0"));
    }

    #[test]
    fn to_toml_optional_dep() {
        let toml = Dependency::new("dep").set_optional(true).to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("optional").unwrap().as_bool(), Some(true));
    }

    #[test]
    fn to_toml_dep_without_default_features() {
        let toml = Dependency::new("dep").set_default_features(false).to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("default-features").unwrap().as_bool(), Some(false));
    }

    #[test]
    fn to_toml_dep_with_path_source() {
        let toml = Dependency::new("dep").set_path("~/foo/bar").to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("path").unwrap().as_str(), Some("~/foo/bar"));
    }

    #[test]
    fn to_toml_dep_with_git_source() {
        let toml = Dependency::new("dep")
            .set_git("https://foor/bar.git", None)
            .to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(
            dep.get("git").unwrap().as_str(),
            Some("https://foor/bar.git")
        );
    }

    #[test]
    fn to_toml_renamed_dep() {
        let toml = Dependency::new("dep").set_rename("d").to_toml();

        assert_eq!(toml.0, "d".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("package").unwrap().as_str(), Some("dep"));
    }

    #[test]
    fn to_toml_dep_from_alt_registry() {
        let toml = Dependency::new("dep").set_registry("alternative").to_toml();

        assert_eq!(toml.0, "dep".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("registry").unwrap().as_str(), Some("alternative"));
    }

    #[test]
    fn to_toml_complex_dep() {
        let toml = Dependency::new("dep")
            .set_version("1.0")
            .set_default_features(false)
            .set_rename("d")
            .to_toml();

        assert_eq!(toml.0, "d".to_owned());
        assert!(toml.1.is_inline_table());

        let dep = toml.1.as_inline_table().unwrap();
        assert_eq!(dep.get("package").unwrap().as_str(), Some("dep"));
        assert_eq!(dep.get("version").unwrap().as_str(), Some("1.0"));
        assert_eq!(dep.get("default-features").unwrap().as_bool(), Some(false));
    }

    #[test]
    fn paths_with_forward_slashes_are_left_as_is() {
        let path = "../sibling/crate";
        let dep = Dependency::new("dep").set_path(path);

        let (_, toml) = dep.to_toml();

        let table = toml.as_inline_table().unwrap();
        let got = table.get("path").unwrap().as_str().unwrap();
        assert_eq!(got, path);
    }

    #[test]
    fn normalise_windows_style_paths() {
        let original = r"..\sibling\crate";
        let should_be = "../sibling/crate";
        let dep = Dependency::new("dep").set_path(original);

        let (_, toml) = dep.to_toml();

        let table = toml.as_inline_table().unwrap();
        let got = table.get("path").unwrap().as_str().unwrap();
        assert_eq!(got, should_be);
    }
}