aboutsummaryrefslogtreecommitdiff
path: root/alacritty/src/migrate/mod.rs
blob: 58f381de38107cfca17b13a4d9e09f4f4dac86e9 (plain) (blame)
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
//! Configuration file migration.

use std::fmt::Debug;
use std::path::Path;
use std::{fs, mem};

use tempfile::NamedTempFile;
use toml_edit::{DocumentMut, Item};

use crate::cli::MigrateOptions;
use crate::config;

mod yaml;

/// Handle migration.
pub fn migrate(options: MigrateOptions) {
    // Find configuration file path.
    let config_path = options
        .config_file
        .clone()
        .or_else(|| config::installed_config("toml"))
        .or_else(|| config::installed_config("yml"));

    // Abort if system has no installed configuration.
    let config_path = match config_path {
        Some(config_path) => config_path,
        None => {
            eprintln!("No configuration file found");
            std::process::exit(1);
        },
    };

    // If we're doing a wet run, perform a dry run first for safety.
    if !options.dry_run {
        #[allow(clippy::redundant_clone)]
        let mut options = options.clone();
        options.silent = true;
        options.dry_run = true;
        if let Err(err) = migrate_config(&options, &config_path, config::IMPORT_RECURSION_LIMIT) {
            eprintln!("Configuration file migration failed:");
            eprintln!("    {config_path:?}: {err}");
            std::process::exit(1);
        }
    }

    // Migrate the root config.
    match migrate_config(&options, &config_path, config::IMPORT_RECURSION_LIMIT) {
        Ok(migration) => {
            if !options.silent {
                println!("{}", migration.success_message(false));
            }
        },
        Err(err) => {
            eprintln!("Configuration file migration failed:");
            eprintln!("    {config_path:?}: {err}");
            std::process::exit(1);
        },
    }
}

/// Migrate a specific configuration file.
fn migrate_config<'a>(
    options: &MigrateOptions,
    path: &'a Path,
    recursion_limit: usize,
) -> Result<Migration<'a>, String> {
    // Ensure configuration file has an extension.
    let path_str = path.to_string_lossy();
    let (prefix, suffix) = match path_str.rsplit_once('.') {
        Some((prefix, suffix)) => (prefix, suffix),
        None => return Err("missing file extension".to_string()),
    };

    // Handle legacy YAML files.
    if suffix == "yml" {
        let new_path = yaml::migrate(options, path, recursion_limit, prefix)?;
        return Ok(Migration::Yaml((path, new_path)));
    }

    // TOML only does renames, so return early if they are disabled.
    if options.skip_renames {
        if options.dry_run {
            eprintln!("Ignoring TOML file {path:?} since `--skip-renames` was supplied");
        }
        return Ok(Migration::Toml(path));
    }

    // Read TOML file and perform all in-file migrations.
    let toml = fs::read_to_string(path).map_err(|err| format!("{err}"))?;
    let mut migrated = migrate_toml(toml)?;

    // Recursively migrate imports.
    migrate_imports(options, path, &mut migrated, recursion_limit)?;

    // Write migrated TOML file.
    write_results(options, path, &migrated.to_string())?;

    Ok(Migration::Toml(path))
}

/// Migrate TOML config to the latest version.
fn migrate_toml(toml: String) -> Result<DocumentMut, String> {
    // Parse TOML file.
    let mut document = match toml.parse::<DocumentMut>() {
        Ok(document) => document,
        Err(err) => return Err(format!("TOML parsing error: {err}")),
    };

    // Move `draw_bold_text_with_bright_colors` to its own section.
    move_value(&mut document, &["draw_bold_text_with_bright_colors"], &[
        "colors",
        "draw_bold_text_with_bright_colors",
    ])?;

    // Move bindings to their own section.
    move_value(&mut document, &["key_bindings"], &["keyboard", "bindings"])?;
    move_value(&mut document, &["mouse_bindings"], &["mouse", "bindings"])?;

    // Avoid warnings due to introduction of the new `general` section.
    move_value(&mut document, &["live_config_reload"], &["general", "live_config_reload"])?;
    move_value(&mut document, &["working_directory"], &["general", "working_directory"])?;
    move_value(&mut document, &["ipc_socket"], &["general", "ipc_socket"])?;
    move_value(&mut document, &["import"], &["general", "import"])?;
    move_value(&mut document, &["shell"], &["terminal", "shell"])?;

    Ok(document)
}

/// Migrate TOML imports to the latest version.
fn migrate_imports(
    options: &MigrateOptions,
    path: &Path,
    document: &mut DocumentMut,
    recursion_limit: usize,
) -> Result<(), String> {
    // Check if any imports need to be processed.
    let imports = match document
        .get("general")
        .and_then(|general| general.get("import"))
        .and_then(|import| import.as_array())
    {
        Some(array) if !array.is_empty() => array,
        _ => return Ok(()),
    };

    // Abort once recursion limit is exceeded.
    if recursion_limit == 0 {
        return Err("Exceeded maximum configuration import depth".into());
    }

    // Migrate each import.
    for import in imports.into_iter().filter_map(|item| item.as_str()) {
        let normalized_path = config::normalize_import(path, import);
        let migration = migrate_config(options, &normalized_path, recursion_limit)?;
        if options.dry_run {
            println!("{}", migration.success_message(true));
        }
    }

    Ok(())
}

/// Move a TOML value from one map to another.
fn move_value(document: &mut DocumentMut, origin: &[&str], target: &[&str]) -> Result<(), String> {
    // Find and remove the original item.
    let (mut origin_key, mut origin_item) = (None, document.as_item_mut());
    for element in origin {
        let table = match origin_item.as_table_like_mut() {
            Some(table) => table,
            None => panic!("Moving from unsupported TOML structure"),
        };

        let (key, item) = match table.get_key_value_mut(element) {
            Some((key, item)) => (key, item),
            None => return Ok(()),
        };

        dbg!(&key);
        origin_key = Some(key);
        origin_item = item;

        // Ensure no empty tables are left behind.
        if let Some(table) = origin_item.as_table_mut() {
            table.set_implicit(true)
        }
    }

    let origin_key_decor =
        origin_key.map(|key| (key.leaf_decor().clone(), key.dotted_decor().clone()));
    let origin_item = mem::replace(origin_item, Item::None);

    // Create all dependencies for the new location.
    let mut target_item = document.as_item_mut();
    for (i, element) in target.iter().enumerate() {
        let table = match target_item.as_table_like_mut() {
            Some(table) => table,
            None => panic!("Moving into unsupported TOML structure"),
        };

        if i + 1 == target.len() {
            table.insert(element, origin_item);
            // Move original key decorations.
            if let Some((leaf, dotted)) = origin_key_decor {
                let mut key = table.key_mut(element).unwrap();
                *key.leaf_decor_mut() = leaf;
                *key.dotted_decor_mut() = dotted;
            }

            break;
        } else {
            // Create missing parent tables.
            target_item = target_item[element].or_insert(toml_edit::table());
        }
    }

    Ok(())
}

/// Write migrated TOML to its target location.
fn write_results<P>(options: &MigrateOptions, path: P, toml: &str) -> Result<(), String>
where
    P: AsRef<Path> + Debug,
{
    let path = path.as_ref();
    if options.dry_run && !options.silent {
        // Output new content to STDOUT.
        println!(
            "\nv-----Start TOML for {path:?}-----v\n\n{toml}\n^-----End TOML for {path:?}-----^\n"
        );
    } else if !options.dry_run {
        // Atomically replace the configuration file.
        let tmp = NamedTempFile::new_in(path.parent().unwrap())
            .map_err(|err| format!("could not create temporary file: {err}"))?;
        fs::write(tmp.path(), toml).map_err(|err| format!("filesystem error: {err}"))?;
        tmp.persist(path).map_err(|err| format!("atomic replacement failed: {err}"))?;
    }
    Ok(())
}

/// Performed migration mode.
enum Migration<'a> {
    /// In-place TOML migration.
    Toml(&'a Path),
    /// YAML to TOML migration.
    Yaml((&'a Path, String)),
}

impl<'a> Migration<'a> {
    /// Get the success message for this migration.
    fn success_message(&self, import: bool) -> String {
        match self {
            Self::Yaml((original_path, new_path)) if import => {
                format!("Successfully migrated import {original_path:?} to {new_path:?}")
            },
            Self::Yaml((original_path, new_path)) => {
                format!("Successfully migrated {original_path:?} to {new_path:?}")
            },
            Self::Toml(original_path) if import => {
                format!("Successfully migrated import {original_path:?}")
            },
            Self::Toml(original_path) => format!("Successfully migrated {original_path:?}"),
        }
    }

    /// Get the file path after migration.
    fn new_path(&self) -> String {
        match self {
            Self::Toml(path) => path.to_string_lossy().into(),
            Self::Yaml((_, path)) => path.into(),
        }
    }
}

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

    #[test]
    fn move_values() {
        let input = r#"
# This is a root_value.
#
# Use it with care.
root_value = 3

[table]
table_value = 5

[preexisting]
not_moved = 9
        "#;

        let mut document = input.parse::<DocumentMut>().unwrap();

        move_value(&mut document, &["root_value"], &["new_table", "root_value"]).unwrap();
        move_value(&mut document, &["table", "table_value"], &[
            "preexisting",
            "subtable",
            "new_name",
        ])
        .unwrap();

        let output = document.to_string();

        let expected = r#"
[preexisting]
not_moved = 9

[preexisting.subtable]
new_name = 5

[new_table]

# This is a root_value.
#
# Use it with care.
root_value = 3
        "#;

        assert_eq!(output, expected);
    }

    #[test]
    fn migrate_empty() {
        assert!(migrate_toml(String::new()).unwrap().to_string().is_empty());
    }
}