cargo_kit/workspace/
config.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
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
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::{Template, TemplateItemId, TomlValue};
use anyhow::Context;
use toml_edit::{table, value, Array, DocumentMut as Document, Formatted, Value};

/// Config stored in `.cargo/config.toml` file.
#[warn(deprecated)]
#[derive(Debug, Clone)]
pub struct CargoConfig {
    path: PathBuf,
    document: Document,
}

impl CargoConfig {
    pub fn empty_from_manifest(manifest_path: &Path) -> Self {
        Self {
            path: config_path_from_manifest_path(manifest_path),
            document: Default::default(),
        }
    }

    pub fn from_path(path: &Path) -> anyhow::Result<Self> {
        let config = std::fs::read_to_string(path).context("Cannot read config.toml file")?;
        let document = config
            .parse::<Document>()
            .context("Cannot parse config.toml file")?;

        Ok(Self {
            document,
            path: path.to_path_buf(),
        })
    }

    pub fn get_text(&self) -> String {
        self.document.to_string()
    }

    pub fn apply_template(mut self, template: &Template) -> anyhow::Result<Self> {
        let rustflags: Vec<String> = template
            .iter_items()
            .filter_map(|(id, value)| {
                let value = match value {
                    TomlValue::String(value) => value.clone(),
                    TomlValue::Int(value) => value.to_string(),
                    TomlValue::Bool(value) => value.to_string(),
                };
                match id {
                    TemplateItemId::TargetCpuInstructionSet => {
                        Some(format!("-Ctarget-cpu={value}"))
                    }
                    TemplateItemId::FrontendThreads => Some(format!("-Zthreads={value}")),
                    TemplateItemId::Linker => Some(format!("-Clink-arg=-fuse-ld={value}")),
                    TemplateItemId::DebugInfo
                    | TemplateItemId::Strip
                    | TemplateItemId::Lto
                    | TemplateItemId::CodegenUnits
                    | TemplateItemId::Panic
                    | TemplateItemId::OptimizationLevel
                    | TemplateItemId::CodegenBackend
                    | TemplateItemId::Incremental
                    | TemplateItemId::SplitDebugInfo => None,
                }
            })
            .collect();
        if rustflags.is_empty() {
            return Ok(self);
        }

        let build = self
            .document
            .entry("build")
            .or_insert(table())
            .as_table_mut()
            .ok_or_else(|| anyhow::anyhow!("The build item in config.toml is not a table"))?;
        let flags = build.entry("rustflags").or_insert(value(Array::new()));

        let flag_map: HashMap<_, _> = rustflags
            .iter()
            .filter_map(|rustflag| {
                let Some((key, value)) = rustflag.split_once('=') else {
                    return None;
                };
                Some((key.to_string(), value.to_string()))
            })
            .collect();

        // build.rustflags can be either a string or an array of strings
        if let Some(array) = flags.as_array_mut() {
            // Find flags with the same key (e.g. -Ckey=val) and replace their values, to avoid
            // duplicating the keys.
            for item in array.iter_mut() {
                if let Some(val) = item.as_str() {
                    if let Some((key, _)) = val.split_once('=') {
                        if let Some(new_value) = flag_map.get(key) {
                            let decor = item.decor().clone();
                            let mut new_value =
                                Value::String(Formatted::new(format!("{key}={new_value}")));
                            *new_value.decor_mut() = decor;
                            *item = new_value;
                        }
                    }
                }
            }

            let existing_flags: HashSet<String> = array
                .iter()
                .filter_map(|v| v.as_str())
                .map(|s| s.to_string())
                .collect();
            for arg in rustflags {
                if !existing_flags.contains(&arg) {
                    array.push(Value::String(Formatted::new(arg)));
                }
            }
        } else if let Some(val) = flags.as_value_mut().filter(|v| v.is_str()) {
            let flattened_flags = rustflags.join(" ");
            let mut original_value = val.as_str().unwrap_or_default().to_string();
            if !original_value.ends_with(' ') && !original_value.is_empty() {
                original_value.push(' ');
            }
            original_value.push_str(&flattened_flags);
            let decor = val.decor().clone();
            *val = Value::String(Formatted::new(original_value));
            *val.decor_mut() = decor;
        } else {
            return Err(anyhow::anyhow!(
                "build.rustflags in config.toml is not a string or an array"
            ));
        }

        Ok(self)
    }

    pub fn write(self) -> anyhow::Result<()> {
        std::fs::create_dir_all(self.path.parent().expect("Missing config.toml parent"))
            .context("Cannot create config.toml parent directory")?;
        std::fs::write(&self.path, self.document.to_string())
            .context("Cannot write config.toml manifest")?;
        Ok(())
    }
}

pub fn config_path_from_manifest_path(manifest_path: &Path) -> PathBuf {
    manifest_path
        .parent()
        .map(|p| p.join(".cargo").join("config.toml"))
        .expect("Manifest path has no parent")
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use toml_edit::Document;

    use crate::template::TemplateBuilder;
    use crate::workspace::manifest::BuiltinProfile;
    use crate::{CargoConfig, Template, TemplateItemId, TomlValue};

    #[test]
    fn create_rustflags() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_empty_config().apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
        [build]
        rustflags = ["-Ctarget-cpu=native"]
        "###);
    }

    #[test]
    fn append_to_array_rustflags() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_config(
            r#"
[build]
rustflags = ["-Cbar=foo"]
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
    [build]
    rustflags = ["-Cbar=foo", "-Ctarget-cpu=native"]
    "###);
    }

    #[test]
    fn ignore_existing_entry() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "foo")]);
        let config = create_config(
            r#"
[build]
rustflags = ["-Ctarget-cpu=foo"]
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
        [build]
        rustflags = ["-Ctarget-cpu=foo"]
        "###);
    }

    #[test]
    fn append_to_empty_string_rustflags() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_config(
            r#"
[build]
rustflags = ""
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
            [build]
            rustflags = "-Ctarget-cpu=native"
            "###);
    }

    #[test]
    fn append_to_string_rustflags() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_config(
            r#"
[build]
rustflags = "-Cfoo=bar"
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
        [build]
        rustflags = "-Cfoo=bar -Ctarget-cpu=native"
        "###);
    }

    #[test]
    fn append_to_string_rustflags_keep_formatting() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_config(
            r#"
[build]
rustflags = "-Cfoo=bar" # Foo
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"
        [build]
        rustflags = "-Cfoo=bar -Ctarget-cpu=native" # Foo
        "###);
    }

    #[test]
    fn replace_rustflag_value() {
        let template = create_template(&[(TemplateItemId::TargetCpuInstructionSet, "native")]);
        let config = create_config(
            r#"
[build]
rustflags = [
    # Foo
    "-Ctarget-cpu=foo", # Foo
    "-Cbar=baz", # Foo
]
"#,
        );
        let config = config.apply_template(&template).unwrap();
        insta::assert_snapshot!(config.get_text(), @r###"

        [build]
        rustflags = [
            # Foo
            "-Ctarget-cpu=native", # Foo
            "-Cbar=baz", # Foo
        ]
        "###);
    }

    fn create_template(items: &[(TemplateItemId, &str)]) -> Template {
        let mut builder = TemplateBuilder::new(BuiltinProfile::Release);
        for (id, value) in items {
            builder = builder.item(*id, TomlValue::String(value.to_string()));
        }
        builder.build()
    }

    fn create_config(text: &str) -> CargoConfig {
        CargoConfig {
            path: Default::default(),
            document: Document::from_str(text).unwrap(),
        }
    }

    fn create_empty_config() -> CargoConfig {
        CargoConfig {
            path: Default::default(),
            document: Default::default(),
        }
    }
}