Skip to content

Commit 0236e3d

Browse files
Copilotntotten
andcommitted
Add working directory support for external executables
Co-authored-by: ntotten <282782+ntotten@users.noreply.github.com>
1 parent b946d96 commit 0236e3d

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/PrettierExecutableInstance.ts

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { execFile, spawn } from "child_process";
2+
import * as path from "path";
23
import { promisify } from "util";
4+
import { workspace } from "vscode";
35
import { FileInfoOptions, Options, ResolveConfigOptions } from "prettier";
46
import {
57
PrettierInstance,
@@ -20,10 +22,12 @@ function execWithStdin(
2022
executable: string,
2123
args: string[],
2224
input: string,
25+
cwd?: string,
2326
): Promise<string> {
2427
return new Promise((resolve, reject) => {
2528
const process = spawn(executable, args, {
2629
stdio: ["pipe", "pipe", "pipe"],
30+
cwd,
2731
});
2832

2933
let stdout = "";
@@ -190,8 +194,29 @@ export const PrettierExecutableInstance: PrettierInstanceConstructor =
190194
}
191195
}
192196

197+
// Determine working directory from the file being formatted
198+
// This allows relative paths in prettierExecutable to work correctly
199+
let cwd: string | undefined;
200+
if (options?.filepath) {
201+
// Try to find the workspace folder for this file
202+
const workspaceFolder = workspace.workspaceFolders?.find((folder) =>
203+
options.filepath!.startsWith(folder.uri.fsPath),
204+
);
205+
if (workspaceFolder) {
206+
cwd = workspaceFolder.uri.fsPath;
207+
} else {
208+
// Fall back to the file's directory
209+
cwd = path.dirname(options.filepath);
210+
}
211+
}
212+
193213
try {
194-
const formattedText = await execWithStdin(this.executable, args, source);
214+
const formattedText = await execWithStdin(
215+
this.executable,
216+
args,
217+
source,
218+
cwd,
219+
);
195220
return formattedText;
196221
} catch (error: any) {
197222
// If prettier exits with error, the stderr will contain the error message

0 commit comments

Comments
 (0)