Skip to main content

crate_cli/fmt/json/
fn.rs

1use super::*;
2
3/// Formats JSON (`.json`, `tsconfig.json`, `.vscode/*.json`) matching VS Code Prettier 3.7.4 `json` parser (`tabWidth: 2`, `printWidth: 80`, `objectWrap: "preserve"`, allows comments, strips trailing commas).
4///
5/// # Arguments
6///
7/// - `&str` - Raw JSON source text.
8///
9/// # Returns
10///
11/// - `Result<String, io::Error>` - Formatted JSON text, or an invalid-data I/O error on syntax failure.
12pub fn format_json(input: &str) -> Result<String, io::Error> {
13    format_json_dialect(input, tidy::json::Dialect::Json)
14}
15
16/// Formats JSON manifests (`package.json`, `package-lock.json`, `composer.json`) matching VS Code Prettier 3.7.4 `json-stringify` parser.
17///
18/// # Arguments
19///
20/// - `&str` - Raw JSON manifest text.
21///
22/// # Returns
23///
24/// - `Result<String, io::Error>` - Expanded JSON text, or an invalid-data I/O error on syntax failure.
25pub fn format_json_stringify(input: &str) -> Result<String, io::Error> {
26    format_json_dialect(input, tidy::json::Dialect::Stringify)
27}
28
29/// Formats JSONC (`.jsonc`, `.cjson`) matching VS Code Prettier 3.7.4 `jsonc` parser (preserving comments and `trailingComma: "all"`).
30///
31/// # Arguments
32///
33/// - `&str` - Raw JSONC source text.
34///
35/// # Returns
36///
37/// - `String` - Formatted JSONC text, or unchanged input if syntax errors occur.
38pub fn format_jsonc(input: &str) -> String {
39    format_json_dialect(input, tidy::json::Dialect::Jsonc)
40        .unwrap_or_else(|_: io::Error| input.to_string())
41}
42
43/// Formats JSON source using the requested `tidy::json::Dialect` and VS Code Prettier 3.7.4 options.
44///
45/// # Arguments
46///
47/// - `&str` - Raw JSON text.
48/// - `tidy::json::Dialect` - Target Prettier JSON dialect (`Json`, `Stringify`, or `Jsonc`).
49///
50/// # Returns
51///
52/// - `Result<String, io::Error>` - Formatted JSON string or invalid-data I/O error.
53fn format_json_dialect(input: &str, dialect: tidy::json::Dialect) -> Result<String, io::Error> {
54    let mut opts: Options = vscode_tidy_options();
55    opts.json.dialect = dialect;
56    tidy::json::format(input, &opts.json)
57        .map_err(|_: tidy::Error| io::Error::new(ErrorKind::InvalidData, ERROR_JSON_PARSE_FAILED))
58}