config-disassembler 0.4.5

Disassemble config files into smaller files and reassemble on demand.
Documentation
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
477
478
479
480
481
482
483
484
485
486
487
//! Reassemble a directory of split files (produced by [`disassemble`])
//! back into a single configuration file.
//!
//! [`disassemble`]: crate::disassemble::disassemble

use std::fs;
use std::path::{Path, PathBuf};

use jsonc_parser::ast;
use jsonc_parser::common::Ranged;
use serde_json::{Map, Value};

use crate::error::{Error, Result};
use crate::format::{jsonc_parse_options, ConversionOperation, Format};
use crate::meta::{Meta, Root};

/// Options controlling reassembly.
#[derive(Debug, Clone)]
pub struct ReassembleOptions {
    /// Directory containing the disassembled files and metadata.
    pub input_dir: PathBuf,
    /// Path to write the reassembled file to. If `None`, written next to
    /// the input directory using the original source filename (or the
    /// directory name with the chosen format's extension).
    pub output: Option<PathBuf>,
    /// Format to write the reassembled file in. Defaults to the format
    /// recorded as the original source format in the metadata.
    pub output_format: Option<Format>,
    /// Remove the input directory after a successful reassembly.
    pub post_purge: bool,
}

/// Reassemble a configuration file from a disassembled directory.
///
/// Returns the path of the reassembled output file.
pub fn reassemble(opts: ReassembleOptions) -> Result<PathBuf> {
    let dir = &opts.input_dir;
    if !dir.is_dir() {
        return Err(Error::Invalid(format!(
            "input is not a directory: {}",
            dir.display()
        )));
    }
    let meta = Meta::read(dir)?;
    let file_format = meta.file_format;
    let output_format: Format = opts.output_format.unwrap_or(meta.source_format);

    file_format.ensure_can_convert_to(output_format, ConversionOperation::Reassemble)?;

    let output_path = match opts.output.clone() {
        Some(p) => p,
        None => default_output_path(dir, &meta, output_format)?,
    };
    if let Some(parent) = output_path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)?;
        }
    }

    if file_format == Format::Jsonc && output_format == Format::Jsonc {
        fs::write(&output_path, assemble_jsonc_preserving(dir, &meta)?)?;
    } else {
        let value = match &meta.root {
            Root::Object {
                key_order,
                key_files,
                main_file,
            } => assemble_object(dir, key_order, key_files, main_file.as_deref(), file_format)?,
            Root::Array { files } => assemble_array(dir, files, file_format)?,
        };
        fs::write(&output_path, output_format.serialize(&value)?)?;
    }

    if opts.post_purge {
        fs::remove_dir_all(dir)?;
    }
    Ok(output_path)
}

fn assemble_object(
    dir: &Path,
    key_order: &[String],
    key_files: &std::collections::BTreeMap<String, String>,
    main_file: Option<&str>,
    file_format: Format,
) -> Result<Value> {
    let main_object: Map<String, Value> = match main_file {
        Some(name) => match file_format.load(&dir.join(name))? {
            Value::Object(map) => map,
            _ => {
                return Err(Error::Invalid(format!(
                    "main scalar file {name} did not contain an object"
                )));
            }
        },
        None => Map::new(),
    };

    let mut out = Map::new();
    for key in key_order {
        if let Some(filename) = key_files.get(key) {
            let loaded = file_format.load(&dir.join(filename))?;
            let value = unwrap_per_key_payload(file_format, key, filename, loaded)?;
            out.insert(key.clone(), value);
        } else if let Some(value) = main_object.get(key) {
            out.insert(key.clone(), value.clone());
        } else {
            return Err(Error::Invalid(format!(
                "metadata references key `{key}` but no file or scalar found"
            )));
        }
    }
    Ok(Value::Object(out))
}

fn unwrap_per_key_payload(
    file_format: Format,
    key: &str,
    filename: &str,
    loaded: Value,
) -> Result<Value> {
    file_format.unwrap_split_payload(key, filename, loaded)
}

fn assemble_array(dir: &Path, files: &[String], file_format: Format) -> Result<Value> {
    let mut items = Vec::with_capacity(files.len());
    for name in files {
        items.push(file_format.load(&dir.join(name))?);
    }
    Ok(Value::Array(items))
}

fn assemble_jsonc_preserving(dir: &Path, meta: &Meta) -> Result<String> {
    match &meta.root {
        Root::Object {
            key_order,
            key_files,
            main_file,
        } => assemble_jsonc_object(dir, key_order, key_files, main_file.as_deref()),
        Root::Array { files } => assemble_jsonc_array(dir, files),
    }
}

fn assemble_jsonc_object(
    dir: &Path,
    key_order: &[String],
    key_files: &std::collections::BTreeMap<String, String>,
    main_file: Option<&str>,
) -> Result<String> {
    let main_properties = match main_file {
        Some(name) => {
            let text = fs::read_to_string(dir.join(name))?;
            let ast = parse_jsonc_ast(&text)?;
            let ast::Value::Object(object) = ast else {
                return Err(Error::Invalid(format!(
                    "main scalar file {name} did not contain an object"
                )));
            };
            jsonc_object_properties(&text, object)
        }
        None => Vec::new(),
    };

    let mut segments = Vec::with_capacity(key_order.len());
    for key in key_order {
        if let Some(filename) = key_files.get(key) {
            let path = dir.join(filename);
            let text = fs::read_to_string(&path)?;
            Format::Jsonc.load(&path)?;
            segments.push(render_jsonc_property(key, &text)?);
        } else if let Some(property) = main_properties.iter().find(|property| &property.key == key)
        {
            segments.push(property.segment.clone());
        } else {
            return Err(Error::Invalid(format!(
                "metadata references key `{key}` but no file or scalar found"
            )));
        }
    }

    Ok(render_jsonc_object(segments.iter()))
}

fn assemble_jsonc_array(dir: &Path, files: &[String]) -> Result<String> {
    let mut segments = Vec::with_capacity(files.len());
    for name in files {
        let path = dir.join(name);
        let text = fs::read_to_string(&path)?;
        Format::Jsonc.load(&path)?;
        segments.push(render_jsonc_array_element(&text));
    }
    Ok(render_jsonc_array(segments.iter()))
}

struct JsoncPropertySyntax {
    key: String,
    segment: String,
}

fn jsonc_object_properties(text: &str, object: ast::Object<'_>) -> Vec<JsoncPropertySyntax> {
    object
        .properties
        .into_iter()
        .map(|property| {
            let key = property.name.clone().into_string();
            let property_range = property.range();
            let value_range = property.value.range();
            JsoncPropertySyntax {
                key,
                segment: jsonc_property_segment(text, property_range.start, value_range.end)
                    .to_string(),
            }
        })
        .collect()
}

fn parse_jsonc_ast(text: &str) -> Result<ast::Value<'_>> {
    jsonc_parser::parse_to_ast(text, &Default::default(), &jsonc_parse_options())
        .map_err(|e| Error::Invalid(format!("jsonc parse error: {e}")))?
        .value
        .ok_or_else(|| Error::Invalid("JSONC document did not contain a value".into()))
}

fn jsonc_property_segment(text: &str, property_start: usize, value_end: usize) -> &str {
    let start = leading_comment_start(text, line_start(text, property_start));
    let end = line_end(text, value_end);
    &text[start..end]
}

fn leading_comment_start(text: &str, mut start: usize) -> usize {
    while start > 0 {
        let previous_line_end = start.saturating_sub(1);
        let previous_line_start = line_start(text, previous_line_end);
        let line = &text[previous_line_start..previous_line_end];
        let trimmed = line.trim();
        if trimmed.is_empty()
            || trimmed.starts_with("//")
            || trimmed.starts_with("/*")
            || trimmed.starts_with('*')
            || trimmed.ends_with("*/")
        {
            start = previous_line_start;
        } else {
            break;
        }
    }
    start
}

fn line_start(text: &str, pos: usize) -> usize {
    text[..pos].rfind('\n').map(|idx| idx + 1).unwrap_or(0)
}

fn line_end(text: &str, pos: usize) -> usize {
    text[pos..]
        .find('\n')
        .map(|idx| pos + idx)
        .unwrap_or(text.len())
}

fn render_jsonc_property(key: &str, value_text: &str) -> Result<String> {
    let key = serde_json::to_string(key)?;
    let value_text = value_text.trim_matches(|c| c == '\r' || c == '\n');
    let mut lines = value_text.lines();
    let first = lines.next().unwrap_or("");
    let mut out = format!("  {key}: {first}");
    for line in lines {
        out.push('\n');
        out.push_str(line);
    }
    Ok(jsonc_segment_with_comma(&out))
}

fn render_jsonc_array_element(value_text: &str) -> String {
    let value_text = value_text.trim_matches(|c| c == '\r' || c == '\n');
    let mut out = String::new();
    for (idx, line) in value_text.lines().enumerate() {
        if idx > 0 {
            out.push('\n');
        }
        out.push_str("  ");
        out.push_str(line);
    }
    jsonc_segment_with_comma(&out)
}

fn render_jsonc_object<'a>(segments: impl IntoIterator<Item = &'a String>) -> String {
    let mut out = String::from("{\n");
    for segment in segments {
        out.push_str(&jsonc_segment_with_comma(segment));
        out.push('\n');
    }
    out.push_str("}\n");
    out
}

fn render_jsonc_array<'a>(segments: impl IntoIterator<Item = &'a String>) -> String {
    let mut out = String::from("[\n");
    for segment in segments {
        out.push_str(&jsonc_segment_with_comma(segment));
        out.push('\n');
    }
    out.push_str("]\n");
    out
}

fn jsonc_segment_with_comma(segment: &str) -> String {
    let segment = segment.trim_matches(|c| c == '\r' || c == '\n');
    if segment.trim_end().ends_with(',') {
        return segment.to_string();
    }

    let last_line_start = segment.rfind('\n').map(|idx| idx + 1).unwrap_or(0);
    let last_line = &segment[last_line_start..];
    if let Some(comment_start) = line_comment_start(last_line) {
        let comment_start = last_line_start + comment_start;
        let (before_comment, comment) = segment.split_at(comment_start);
        return format!("{},{}", before_comment.trim_end(), comment);
    }

    format!("{segment},")
}

fn line_comment_start(line: &str) -> Option<usize> {
    let mut chars = line.char_indices().peekable();
    let mut in_string = false;
    let mut escaped = false;

    while let Some((idx, ch)) = chars.next() {
        if in_string {
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            continue;
        }

        if ch == '"' {
            in_string = true;
        } else if ch == '/' && matches!(chars.peek(), Some((_, '/'))) {
            return Some(idx);
        }
    }

    None
}

fn default_output_path(dir: &Path, meta: &Meta, output_format: Format) -> Result<PathBuf> {
    let parent = dir.parent().unwrap_or(Path::new("."));
    let mut name = meta
        .source_filename
        .clone()
        .or_else(|| {
            dir.file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.to_string())
        })
        .ok_or_else(|| Error::Invalid("could not determine output file name".into()))?;
    let stem = match Path::new(&name).file_stem().and_then(|s| s.to_str()) {
        Some(s) => s.to_string(),
        None => name.clone(),
    };
    name = format!("{stem}.{}", output_format.extension());
    Ok(parent.join(name))
}

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

    #[test]
    fn unwrap_per_key_payload_passes_through_non_toml() {
        let v = json!({"unrelated": 1});
        let out = unwrap_per_key_payload(Format::Json, "key", "k.json", v.clone()).unwrap();
        assert_eq!(out, v);
    }

    #[test]
    fn unwrap_per_key_payload_extracts_wrapper_key_for_toml() {
        let v = json!({"servers": [{"host": "a"}]});
        let out = unwrap_per_key_payload(Format::Toml, "servers", "servers.toml", v).unwrap();
        assert_eq!(out, json!([{"host": "a"}]));
    }

    #[test]
    fn unwrap_per_key_payload_extracts_wrapper_key_for_ini() {
        let v = json!({"settings": {"host": "db.example.com"}});
        let out = unwrap_per_key_payload(Format::Ini, "settings", "settings.ini", v).unwrap();
        assert_eq!(out, json!({"host": "db.example.com"}));
    }

    #[test]
    fn unwrap_per_key_payload_errors_when_wrapper_key_missing() {
        let v = json!({"wrong": 1});
        let err =
            unwrap_per_key_payload(Format::Toml, "right", "x.toml", v).expect_err("should error");
        let msg = err.to_string();
        assert!(
            msg.contains("does not contain expected wrapper key"),
            "got: {msg}"
        );
        assert!(msg.contains("right"), "got: {msg}");
        assert!(msg.contains("x.toml"), "got: {msg}");
    }

    #[test]
    fn unwrap_per_key_payload_errors_when_ini_wrapper_key_missing() {
        let v = json!({"wrong": 1});
        let err =
            unwrap_per_key_payload(Format::Ini, "right", "x.ini", v).expect_err("should error");
        let msg = err.to_string();
        assert!(
            msg.contains("does not contain expected wrapper key"),
            "got: {msg}"
        );
        assert!(msg.contains("right"), "got: {msg}");
        assert!(msg.contains("x.ini"), "got: {msg}");
    }

    #[test]
    fn unwrap_per_key_payload_errors_on_non_object_for_toml() {
        // TOML's grammar guarantees this never occurs through Format::load,
        // but the defensive arm is still exercised here so any future
        // refactor that reaches it returns a clear error rather than
        // panicking.
        let err = unwrap_per_key_payload(Format::Toml, "k", "k.toml", json!([1, 2, 3]))
            .expect_err("should error");
        assert!(
            err.to_string().contains("did not deserialize to a table"),
            "got: {err}"
        );
    }

    #[test]
    fn jsonc_segment_with_comma_inserts_before_trailing_line_comment() {
        assert_eq!(
            jsonc_segment_with_comma(r#"  "name": "demo" // keep this comment"#),
            r#"  "name": "demo",// keep this comment"#
        );
    }

    #[test]
    fn jsonc_segment_with_comma_ignores_urls_inside_strings() {
        assert_eq!(
            jsonc_segment_with_comma(r#"  "url": "https://example.com/a""#),
            r#"  "url": "https://example.com/a","#
        );
    }

    #[test]
    fn assemble_jsonc_object_errors_when_main_file_is_not_object() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("_main.jsonc"), "[]\n").unwrap();

        let err = assemble_jsonc_object(tmp.path(), &[], &Default::default(), Some("_main.jsonc"))
            .expect_err("should reject non-object main file");

        assert!(
            err.to_string().contains("did not contain an object"),
            "got: {err}"
        );
    }

    #[test]
    fn assemble_jsonc_object_errors_when_metadata_key_is_missing() {
        let tmp = tempfile::tempdir().unwrap();
        fs::write(tmp.path().join("_main.jsonc"), "{}\n").unwrap();

        let err = assemble_jsonc_object(
            tmp.path(),
            &["missing".into()],
            &Default::default(),
            Some("_main.jsonc"),
        )
        .expect_err("should reject missing scalar key");

        assert!(
            err.to_string()
                .contains("metadata references key `missing`"),
            "got: {err}"
        );
    }
}