Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion apps/oxfmt/src/lsp/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use oxc_language_server::run_server;
use std::path::{Path, PathBuf};

use oxc_language_server::{LanguageId, run_server};
use tower_lsp_server::ls_types::Uri;

use crate::core::ExternalFormatter;

Expand All @@ -8,6 +11,41 @@ mod server_formatter;
mod tester;
const FORMAT_CONFIG_FILES: &[&str; 2] = &[".oxfmtrc.json", ".oxfmtrc.jsonc"];

fn get_file_extension_from_language_id(language_id: &LanguageId) -> Option<&'static str> {
match language_id.as_str() {
"javascript" => Some("js"),
"typescript" => Some("ts"),
"javascriptreact" => Some("jsx"),
"typescriptreact" => Some("tsx"),
"toml" => Some("toml"),
"css" => Some("css"),
"graphql" => Some("graphql"),
"handlebars" => Some("handlebars"),
"json" => Some("json"),
"jsonc" => Some("jsonc"),
"json5" => Some("json5"),
"markdown" => Some("md"),
"mdx" => Some("mdx"),
"mjml" => Some("mjml"),
"html" => Some("html"),
"scss" => Some("scss"),
"less" => Some("less"),
"vue" => Some("vue"),
"yaml" => Some("yaml"),
_ => None,
}
}

pub fn create_fake_file_path_from_language_id(
language_id: &LanguageId,
root: &Path,
uri: &Uri,
) -> Option<PathBuf> {
let file_extension = get_file_extension_from_language_id(language_id)?;
let file_name = format!("{}.{}", uri.authority()?, file_extension);
Some(root.join(file_name))
}

/// Run the language server
pub async fn run_lsp(external_formatter: ExternalFormatter) {
run_server(
Expand Down
105 changes: 80 additions & 25 deletions apps/oxfmt/src/lsp/server_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::core::{
ConfigResolver, ExternalFormatter, FormatFileStrategy, FormatResult, SourceFormatter,
resolve_editorconfig_path, resolve_oxfmtrc_path, utils,
};
use crate::lsp::create_fake_file_path_from_language_id;
use crate::lsp::{FORMAT_CONFIG_FILES, options::FormatOptions as LSPFormatOptions};

pub struct ServerFormatterBuilder {
Expand Down Expand Up @@ -74,7 +75,12 @@ impl ServerFormatterBuilder {
let source_formatter = SourceFormatter::new(num_of_threads)
.with_external_formatter(Some(self.external_formatter.clone()));

ServerFormatter::new(source_formatter, config_resolver, gitignore_glob)
ServerFormatter::new(
root_path.to_path_buf(),
source_formatter,
config_resolver,
gitignore_glob,
)
}
}

Expand Down Expand Up @@ -152,6 +158,7 @@ impl ServerFormatterBuilder {
// ---

pub struct ServerFormatter {
root_path: PathBuf,
source_formatter: SourceFormatter,
config_resolver: ConfigResolver,
gitignore_glob: Option<Gitignore>,
Expand Down Expand Up @@ -246,35 +253,35 @@ impl Tool for ServerFormatter {
fn run_format(
&self,
uri: &Uri,
_language_id: &LanguageId,
language_id: &LanguageId,
content: Option<&str>,
) -> Result<Vec<TextEdit>, String> {
let Some(path) = uri.to_file_path() else { return Err("Invalid file URI".to_string()) };
let file_content;
let (result, source_text) = if uri.as_str().starts_with("untitled:") {
let source_text =
content.ok_or_else(|| "In-memory formatting requires content".to_string())?;

if self.is_ignored(&path) {
debug!("File is ignored: {}", path.display());
return Ok(Vec::new());
}
let Some(result) = self.format_in_memory(uri, source_text, language_id) else {
return Ok(vec![]); // currently not supported
};
(result, source_text)
} else {
let Some(path) = uri.to_file_path() else { return Err("Invalid file URI".to_string()) };

// Determine format strategy from file path (supports JS/TS, JSON, YAML, CSS, etc.)
let Ok(strategy) = FormatFileStrategy::try_from(path.to_path_buf()) else {
debug!("Unsupported file type for formatting: {}", path.display());
return Ok(Vec::new());
};
let source_text = match content {
Some(c) => c,
None => {
&utils::read_to_string(&path).map_err(|e| format!("Failed to read file: {e}"))?
}
};
let source_text = if let Some(c) = content {
c
} else {
file_content = utils::read_to_string(&path)
.map_err(|e| format!("Failed to read file: {e}"))?;
&file_content
};

// Resolve options for this file
let resolved_options = self.config_resolver.resolve(&strategy);
debug!("resolved_options = {resolved_options:?}");
let Some(result) = self.format_file(&path, source_text) else {
return Ok(vec![]); // No formatting for this file (unsupported or ignored)
};

let result = tokio::task::block_in_place(|| {
self.source_formatter.format(&strategy, source_text, resolved_options)
});
(result, source_text)
};

// Handle result
match result {
Expand Down Expand Up @@ -307,11 +314,12 @@ impl Tool for ServerFormatter {

impl ServerFormatter {
pub fn new(
root_path: PathBuf,
source_formatter: SourceFormatter,
config_resolver: ConfigResolver,
gitignore_glob: Option<Gitignore>,
) -> Self {
Self { source_formatter, config_resolver, gitignore_glob }
Self { root_path, source_formatter, config_resolver, gitignore_glob }
}

fn is_ignored(&self, path: &Path) -> bool {
Expand All @@ -325,6 +333,53 @@ impl ServerFormatter {
false
}
}

fn format_file(&self, path: &Path, source_text: &str) -> Option<FormatResult> {
if self.is_ignored(path) {
debug!("File is ignored: {}", path.display());
return None;
}

// Determine format strategy from file path (supports JS/TS, JSON, YAML, CSS, etc.)
let Ok(strategy) = FormatFileStrategy::try_from(path.to_path_buf()) else {
debug!("Unsupported file type for formatting: {}", path.display());
return None;
};

// Resolve options for this file
let resolved_options = self.config_resolver.resolve(&strategy);
debug!("resolved_options = {resolved_options:?}");

Some(tokio::task::block_in_place(|| {
self.source_formatter.format(&strategy, source_text, resolved_options)
}))
}

fn format_in_memory(
&self,
uri: &Uri,
source_text: &str,
language_id: &LanguageId,
) -> Option<FormatResult> {
let Some(path) = create_fake_file_path_from_language_id(language_id, &self.root_path, uri)
else {
debug!("Unsupported language id for in-memory formatting: {language_id:?}");
return None;
};

let Ok(strategy) = FormatFileStrategy::try_from(path.clone()) else {
debug!("Unsupported file type for formatting: {}", path.display());
return None;
};

// Resolve options for this file
let resolved_options = self.config_resolver.resolve(&strategy);
debug!("resolved_options = {resolved_options:?}");

Some(tokio::task::block_in_place(|| {
self.source_formatter.format(&strategy, source_text, resolved_options)
}))
}
}

// ---
Expand Down
78 changes: 78 additions & 0 deletions apps/oxfmt/test/lsp/format/__snapshots__/format.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,81 @@ debugger

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/formatted.ts 1`] = `
"--- FILE -----------
format/formatted.ts
--- BEFORE ---------
const x = 1;

--- AFTER ----------
const x = 1;

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/test.json 1`] = `
"--- FILE -----------
format/test.json
--- BEFORE ---------
{"name":"test","version":"1.0.0"}

--- AFTER ----------
{ "name": "test", "version": "1.0.0" }

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/test.toml 1`] = `
"--- FILE -----------
format/test.toml
--- BEFORE ---------
[package]
name="test"
version="1.0.0"

--- AFTER ----------
[package]
name = "test"
version = "1.0.0"

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/test.tsx 1`] = `
"--- FILE -----------
format/test.tsx
--- BEFORE ---------
const App: React.FC = () => <div>Hello</div>

--- AFTER ----------
const App: React.FC = () => <div>Hello</div>;

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/test.txt 1`] = `
"--- FILE -----------
format/test.txt
--- BEFORE ---------
hello world

--- AFTER ----------
hello world

--------------------"
`;

exports[`LSP formatting > unsaved document > should format unsaved file format/test.vue 1`] = `
"--- FILE -----------
format/test.vue
--- BEFORE ---------
<script>const x = 1;</script>

--- AFTER ----------
<script>
const x = 1;
</script>

--------------------"
`;
22 changes: 21 additions & 1 deletion apps/oxfmt/test/lsp/format/format.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { formatFixture } from "../utils";
import { formatFixture, formatFixtureContent } from "../utils";

const FIXTURES_DIR = join(import.meta.dirname, "fixtures");

Expand Down Expand Up @@ -33,6 +33,26 @@ describe("LSP formatting", () => {
});
});

describe("unsaved document", () => {
it.each([
["format/test.tsx", "typescriptreact"],
["format/test.json", "json"],
["format/test.vue", "vue"],
["format/test.toml", "toml"],
["format/formatted.ts", "typescript"],
["format/test.txt", "plaintext"],
])("should format unsaved file %s", async (path, languageId) => {
expect(
await formatFixtureContent(
FIXTURES_DIR,
path,
"untitled://Untitled-" + languageId,
languageId,
),
).toMatchSnapshot();
});
});

describe("ignore patterns", () => {
it.each([
["ignore-prettierignore/ignored.ts", "typescript"],
Expand Down
24 changes: 22 additions & 2 deletions apps/oxfmt/test/lsp/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ import type {
const CLI_PATH = join(import.meta.dirname, "..", "..", "dist", "cli.js");

export function createLspConnection() {
const proc = spawn("node", [CLI_PATH, "--lsp"]);
const proc = spawn("node", [CLI_PATH, "--lsp"], {
// env: { ...process.env, OXC_LOG: "info" }, for debugging
});

const connection = createMessageConnection(
new StreamMessageReader(proc.stdout),
Expand Down Expand Up @@ -107,8 +109,26 @@ export async function formatFixture(
initializationOptions?: OxfmtLSPConfig,
): Promise<string> {
const filePath = join(fixturesDir, fixturePath);
const dirPath = dirname(filePath);
const fileUri = pathToFileURL(filePath).href;

return await formatFixtureContent(
fixturesDir,
fixturePath,
fileUri,
languageId,
initializationOptions,
);
}

export async function formatFixtureContent(
fixturesDir: string,
fixturePath: string,
fileUri: string,
languageId: string,
initializationOptions?: OxfmtLSPConfig,
): Promise<string> {
const filePath = join(fixturesDir, fixturePath);
const dirPath = dirname(filePath);
const content = await fs.readFile(filePath, "utf-8");

await using client = createLspConnection();
Expand Down
4 changes: 4 additions & 0 deletions crates/oxc_language_server/src/language_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ impl LanguageId {
pub fn new(id: String) -> Self {
Self(id)
}

pub fn as_str(&self) -> &str {
&self.0
}
}
Loading