mc_repack_core/min/
json.rs

1use json_comments::StripComments;
2use serde_json::Value;
3
4use crate::cfg::{acfg, ConfigHolder};
5
6use super::{brackets, BracketsError, Result_};
7
8
9acfg!(
10    /// A JSON minifier that accepts [`JSONConfig`].
11    MinifierJSON: JSONConfig
12);
13impl ConfigHolder<MinifierJSON> {
14    pub(super) fn minify(&self, b: &[u8], vout: &mut Vec<u8>) -> Result_ {
15        let b = brackets(b).ok_or(BracketsError)?;
16        let mut sv: Value = serde_json::from_reader(StripComments::new(b))?;
17        if self.remove_underscored {
18            if let Value::Object(xm) = &mut sv {
19                uncomment_json_recursive(xm);
20            }
21        }
22        serde_json::to_writer(vout, &sv)?;
23        Ok(())
24    }
25}
26
27/// Configuration for JSON minifier
28#[cfg_attr(feature = "serde-cfg", derive(serde::Serialize, serde::Deserialize))]
29pub struct JSONConfig {
30    /// An optional flag that enables removing underscored keys.
31    /// Defaults to `true`.
32    pub remove_underscored: bool
33}
34impl Default for JSONConfig {
35    fn default() -> Self {
36        Self { remove_underscored: true }
37    }
38}
39
40fn uncomment_json_recursive(m: &mut serde_json::Map<String, Value>) {
41    m.retain(|k, v| {
42        if k.starts_with('_') { return false; }
43        if let Value::Object(xm) = v {
44            uncomment_json_recursive(xm);
45        }
46        true
47    });
48}