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
extern crate toml_edit;

use self::toml_edit::{value, Array, Document};

#[derive(Copy, Clone)]
pub enum CrateType {
    Static,
    Dynamic,
}

pub fn set_crate_type(manifest: &str, target: CrateType) -> String {
    let mut doc = manifest.parse::<Document>().expect("Cargo.toml malformed");
    let mut array = Array::default();
    match target {
        CrateType::Static => array.push("staticlib"),
        CrateType::Dynamic => array.push("cdylib"),
    };
    doc["lib"]["crate-type"] = value(array);
    doc.to_string()
}

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

    #[test]
    fn adds_the_crate_type_specified() {
        let manifest = r#"
[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"
"#;

        let expected = r#"lib = {crate-type = ["cdylib"]}

[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"
"#;

        let new_manifest = set_crate_type(manifest, CrateType::Dynamic);
        assert_eq!(new_manifest, expected);
    }

    #[test]
    fn adds_the_another_crate_type_specified() {
        let manifest = r#"
[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"
"#;

        let expected = r#"lib = {crate-type = ["staticlib"]}

[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"
"#;

        let new_manifest = set_crate_type(manifest, CrateType::Static);
        assert_eq!(new_manifest, expected);
    }

    #[test]
    fn overrides_already_specified_crate_type() {
        let manifest = r#"
[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"

[lib]
crate-type = ["lib"]
"#;

        let expected = r#"
[package]
name = "cargo-crate-type"
version = "0.1.0"
authors = ["Example <example@example.com>"]

[dependencies]
toml_edit = "0.1.3"

[lib]
crate-type = ["staticlib"]
"#;

        let new_manifest = set_crate_type(manifest, CrateType::Static);
        assert_eq!(new_manifest, expected);
    }
}