Skip to content

oxfmt: Support config for prettier formatting #16530

@leaysgur

Description

@leaysgur

This is also necessary as part of #15665

  • JS: Expose napi setupConfig(config: string): Promise<void> function
    • Use JSON.parse() and cache it
  • JS: Use this cached config in subsequent call
  • Rust: Find the config location
  • Rust: Load it as serde_json::Value
  • Rust: Load it also as Oxfmtrc
  • Rust: Merge them as prettier-way serde_json::Value
    • Can not build from struct because we don't know each plugin options
    • Skip useless fields like ignorePatterns, experimentalSortImports
  • Rust: Send it as String to JS with calling setup_config
// oxfmt/cli/format.rs?
// Need to consider no config case
fn load_config(path: &Path) -> Result<(FormatOptions, Value), String> {
    let mut json_string = read_file(path)
        .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
    json_strip_comments::strip(&mut json_string)
        .map_err(|e| format!("Failed to strip comments: {e}"))?;

    let mut config: Value = serde_json::from_str(&json_string)
        .map_err(|e| format!("Failed to parse JSON: {e}"))?;

    let oxfmtrc: Oxfmtrc = serde_json::from_value(config.clone())
        .map_err(|e| format!("Failed to parse config: {e}"))?;

    let options = oxfmtrc.into_format_options()?;

    update_prettier_config(&options, &mut config);

    Ok((options, config))
}

// oxfmtrc.rs
pub fn update_prettier_config(options: &FormatOptions, config: &mut serde_json::Value) {
	let Some(obj) = config.as_object_mut() else {
	    return;
	};
	
	obj.insert("printWidth".to_string(), serde_json::json!(options.line_width.value()));
	// ...
}

// oxfmt/main_napi.rs
ExternalFormatter::new(setup_config_cb, ..);

// oxfmt/core/external_formatter.rs
impl ExternalFormatter {
	fn setup_config() {
		// ...
	}
}

// oxfmt/cli/format.rs
// Before walk
external_formatter.setup_config(serde_json::to_string(&config));

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions