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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::fmt;

use toml_edit::{self, InlineTable, Table, Value};

/// Adds some methods to create `Dependency` objects from objects that impl `Display`
pub trait DependencyExt: fmt::Display {
    /// Constructs a `Dependency` using `self.to_string()` as the name, and `version` as the
    /// semver version
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// 
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = "foo".version("0.1.0");
    /// let expected = Dependency::version("foo", "0.1.0");
    /// assert_eq!(dep, expected);
    /// #   Ok(())
    /// # }
    /// ```
    fn version(&self, version: &str) -> Dependency {
        Dependency::version(&self.to_string(), version)
    }

    /// Constructs a `Dependency` using `self.to_string()` as the name, and `repo` as the git
    /// repository
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    ///
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = "foo".repo("https://github.com/bar/foo");
    /// let expected = Dependency::repo("foo", "https://github.com/bar/foo");
    /// assert_eq!(dep, expected);
    /// #   Ok(())
    /// # }
    /// ```
    fn repo(&self, repo: &str) -> Dependency {
        Dependency::repo(&self.to_string(), repo)
    }

    /// Constructs an optional dependency using `self.to_string()` as the name, and `version` as
    /// the semver version
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    ///
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = "foo".optional("0.1.0");
    /// let expected = Dependency::version("foo", "0.1.0")
    ///                           .optional(true)
    ///                           .build();
    /// assert_eq!(dep, expected);
    /// #   Ok(())
    /// # }
    /// ```
    fn optional(&self, version: &str) -> Dependency {
        Dependency::new(&self.to_string(), DependencyType::Crate(Crate { version: Some(version.to_string()) }))
                   .optional(true)
                   .build()
    }

    /// Constructs a `Dependency` using `self.to_string()` as the name and `path` as the path
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    ///
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = "foo".path("/path/to/foo");
    /// let expected = Dependency::path("foo", "/path/to/foo");
    /// assert_eq!(dep, expected);
    /// #   Ok(())
    /// # }
    /// ```
    fn path(&self, path: &str) -> Dependency {
        Dependency::new(&self.to_string(), DependencyType::Path(path.to_string()))
    }
}

impl<T: fmt::Display> DependencyExt for T {}

/// Represents a single dependency
#[derive(Debug, Clone, PartialEq)]
pub struct Dependency {
    pub(crate) label: String,
    pub(crate) dep_type: DependencyType,
    pub(crate) optional: Option<bool>,
    pub(crate) default_features: Option<bool>,
}

impl Dependency {
    fn new(label: &str, dep_type: DependencyType) -> Dependency {
        Dependency {
            label: label.to_string(),
            dep_type: dep_type,
            optional: None,
            default_features: None, 
        }
    }

    pub(crate) fn is_inline(&self) -> bool {
        // types of dependencies that look ok when rendered inline
        //
        // e.g.
        //
        // foo = "1.0.0"
        // bar = { path = "baz" }
        // qux = { git = "https://github.com/foo/bar" }
        let inline_type = match self.dep_type {
            DependencyType::Crate(..) => true,
            DependencyType::Repo(Repo { url: _, repo_type: None }) => true,
            DependencyType::Path(..) => true,
            _ => false
        };
        // adding `optional = true` inline looks ok, but not `default_features` (imo)
        match (inline_type, self.default_features) {
            (true, None) => return true,
            _ => return false,
        }
    }
    /* Constructors */
    /// Constructs a `Depedency` that points to a git repo
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::repo("foo", "https://github.com/foo/bar");
    /// // translates to:
    /// // [dependencies]
    /// // foo = { git = "https://github.com/foo/bar" }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn repo(label: &str, repo: &str) -> Dependency {
        Dependency::new(label, DependencyType::Repo(Repo { url: repo.into(), repo_type: None}))
    }

    /// Constructs a `Depedency` that specifies a semver version
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::version("foo", "0.1.0");
    /// // translates to:
    /// // [dependencies]
    /// // foo = "0.1.0"
    /// #   Ok(())
    /// # }
    /// ```
    pub fn version(label: &str, version: &str) -> Dependency {
        Dependency::new(label, DependencyType::Crate(Crate { version: Some(version.into())}))
    }

    /// Constructs a `Depedency` that points to a path
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::path("foo", "/path/to/foo");
    /// // translates to:
    /// // [dependencies]
    /// // foo = { path = "/path/to/foo" }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn path(label: &str, path: &str) -> Dependency {
        Dependency::new(label, DependencyType::Path(path.into()))
    }

    /// Constructs a `Depedency` that points to a specific revision of a repository
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::rev("foo", "https://github.com/foo/bar", "0a14cbe3928");
    /// // translates to:
    /// // [dependencies]
    /// // foo = { git = "https://github.com/foo/bar", rev = "0a14cbe3928" }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn rev(label: &str, repo: &str, rev: &str) -> Dependency {
        Dependency::new(label, DependencyType::Repo(Repo { url: repo.into(), repo_type: Some(RepoType::Rev(rev.into()))}))
    }

    /// Constructs a `Depedency` that points to a specific tag of a repository
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::tag("foo", "https://github.com/foo/bar", "v1.0.0");
    /// // translates to:
    /// // [dependencies]
    /// // foo = { git = "https://github.com/foo/bar", tag = "v1.0.0" }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn tag(label: &str, repo: &str, tag: &str) -> Dependency {
        Dependency::new(label, DependencyType::Repo(Repo { url: repo.into(), repo_type: Some(RepoType::Tag(tag.into()))}))
    }

    /// Constructs a `Depedency` that points to a specific branch of a repository
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::branch("foo", "https://github.com/foo/bar", "some-branch");
    /// // translates to:
    /// // [dependencies]
    /// // foo = { git = "https://github.com/foo/bar", branch = "some-branch" }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn branch(label: &str, repo: &str, branch: &str) -> Dependency {
        Dependency::new(label, DependencyType::Repo(Repo { url: repo.into(), repo_type: Some(RepoType::Branch(branch.into()))}))
    }

    /// If the builder pattern has been used to construct this `Dependency`, this takes ownership
    pub fn build(&self) -> Self {
        self.clone()
    }

    /// Mark this dependency as "optional = true"
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::version("foo", "0.1.0")
    ///                      .optional(true)
    ///                      .build();
    /// // translates to:
    /// // [dependencies]
    /// // foo = { version = "0.1.0", optional = true }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn optional(&mut self, optional: bool) -> &mut Self {
        self.optional = Some(optional);
        self
    }

    /// Specify whether this dependency is using the default features or not
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate cargo_toml_builder;
    /// # use std::error::Error;
    /// use cargo_toml_builder::prelude::*;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let dep = Dependency::version("foo", "0.1.0")
    ///                      .default_features(false)
    ///                      .build();
    /// // translates to:
    /// // [dependencies]
    /// // foo = { version = "0.1.0", default-features = false }
    /// #   Ok(())
    /// # }
    /// ```
    pub fn default_features(&mut self, default_features: bool) -> &mut Self {
        self.default_features = Some(default_features);
        self
    }

    // Non-builder methods

    pub(crate) fn only_version(&self) -> Option<&str> {
        if let DependencyType::Crate(Crate { ref version }) = self.dep_type {
            if self.optional.is_none() && self.default_features.is_none() {
                if let Some(v) = version {
                    return Some(&v);
                } else {
                    return Some("*");
                }
            }
        }
        None
    }

    pub(crate) fn render_into(&self, table: &mut Table) {
        if let Some(version) = self.only_version() {
            // inserts `label = "version"`
            *table.entry(&self.label) = toml_edit::value(version);
        } else {
            let inline_table = InlineTable::from(self);
            // inserts `label = { ... }`
            *table.entry(&self.label) = toml_edit::value(Value::InlineTable(inline_table));
        }
    }
}

impl<'a> From<&'a str> for Dependency {
    fn from(s: &'a str) -> Dependency {
        Dependency::new(s, DependencyType::Crate(Crate { version: None}))
    }
}

impl From<String> for Dependency {
    fn from(s: String) -> Dependency {
        Dependency::from(s.as_str())
    }
}

impl<'a> From<&'a Dependency> for Dependency {
    fn from(d: &Dependency) -> Dependency {
        d.clone()
    }
}

impl<'a> From<&'a mut Dependency> for Dependency {
    fn from(d: &'a mut Dependency) -> Dependency {
        d.clone()
    }
}

/// Represents the different types of dependencies
#[derive(Debug, Clone, PartialEq)]
pub enum DependencyType {
    /// This is a crate retrieved from a crate registry like crates.io using it's name and it's semver version number
    Crate(Crate),
    /// This is a crate retrieved from a git repository
    Repo(Repo),
    /// This is a crate retrieved from a filesystem path
    Path(String),
}

/// Represents a dependency that has a semver verison number
#[derive(Debug, Clone, PartialEq)]
pub struct Crate {
    pub(crate) version: Option<String>,
}

/// Represents a dependency that is retrieved from a git repository
#[derive(Debug, Clone, PartialEq)]
pub struct Repo {
    pub(crate) url: String,
    pub(crate) repo_type: Option<RepoType>,
}

/// Sets a specific commit of a repository to use
#[derive(Debug, Clone, PartialEq)]
pub enum RepoType {
    /// Sets the specific commit to the given hash
    Rev(String),
    /// Sets the specific commit to the commit pointed to by the given tag
    Tag(String),
    /// Sets the specific commit to the commit pointed to by the given branch name
    Branch(String),
}

impl From<Dependency> for InlineTable {
    fn from(d: Dependency) -> InlineTable {
        From::from(&d)
    }
}

impl<'a> From<&'a Dependency> for InlineTable {
    fn from(dep: &'a Dependency) -> InlineTable {
        let mut table = InlineTable::default();
        match dep.dep_type {
            DependencyType::Crate(Crate { version: None }) => {
                table.get_or_insert("version", "*");
            },
            DependencyType::Crate(Crate { version: Some(ref version) }) => {
                table.get_or_insert("version", version.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: None }) => {
                table.get_or_insert("git", url.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Rev(ref rev)) }) => {
                table.get_or_insert("git", url.as_str());
                table.get_or_insert("rev", rev.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Tag(ref tag)) }) => {
                table.get_or_insert("git", url.as_str());
                table.get_or_insert("tag", tag.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Branch(ref branch)) }) => {
                table.get_or_insert("git", url.as_str());
                table.get_or_insert("branch", branch.as_str());
            },
            DependencyType::Path(ref path) => {
                table.get_or_insert("path", path.as_str());
            },
        }
        if let Some(optional) = dep.optional {
            table.get_or_insert("optional", Value::from(optional));
        }
        if let Some(default_features) = dep.default_features {
            table.get_or_insert("default-features", Value::from(default_features));
        }
        table
    }
}

impl<'a> From<&'a Dependency> for Table {
    fn from(dep: &'a Dependency) -> Table {
        let mut table = Table::new();
        match dep.dep_type {
            DependencyType::Crate(Crate { version: None }) => {
                *table.entry("version") = toml_edit::value("*");
            },
            DependencyType::Crate(Crate { version: Some(ref version) }) => {
                *table.entry("version") = toml_edit::value(version.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: None }) => {
                *table.entry("git") = toml_edit::value(url.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Rev(ref rev)) }) => {
                *table.entry("git") = toml_edit::value(url.as_str());
                *table.entry("rev") = toml_edit::value(rev.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Tag(ref tag)) }) => {
                *table.entry("git") = toml_edit::value(url.as_str());
                *table.entry("tag") = toml_edit::value(tag.as_str());
            },
            DependencyType::Repo(Repo { ref url, repo_type: Some(RepoType::Branch(ref branch)) }) => {
                *table.entry("git") = toml_edit::value(url.as_str());
                *table.entry("branch") = toml_edit::value(branch.as_str());
            },
            DependencyType::Path(ref path) => {
                *table.entry("path") = toml_edit::value(path.as_str());
            },
        }
        if let Some(optional) = dep.optional {
            *table.entry("optional") = toml_edit::value(optional);
        }
        if let Some(default_features) = dep.default_features {
            *table.entry("default-features") = toml_edit::value(default_features);
        }
        table
    }
}