forked from sweetpad-dev/sweetpad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter.ts
69 lines (61 loc) · 1.7 KB
/
formatter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import type * as vscode from "vscode";
import { getWorkspaceConfig } from "../common/config.js";
import { exec } from "../common/exec.js";
import { Timer } from "../common/timer.js";
import { formatLogger } from "./logger.js";
/**
* Get formatter command parameters from workspace configuration.
*/
function getFormatterCommand(filename: string): {
command: string;
args: string[];
} {
const path = getWorkspaceConfig("format.path");
// We use "swift-format" as default command if no path is provided,
// "args" config are ignored in this case
if (!path) {
return {
command: "swift-format",
args: ["--in-place", filename],
};
}
// By default we use "swift-format" arguments
const args: string[] | undefined = getWorkspaceConfig("format.args") ?? ["--in-place", "${file}"];
const replacedArgs = args.map((arg) => (arg === "${file}" ? filename : arg));
return {
command: path,
args: replacedArgs,
};
}
/**
* Format given document using swift-format executable.
*/
export async function formatDocument(document: vscode.TextDocument) {
if (document.languageId !== "swift") {
return;
}
const filename = document.fileName;
const { command, args } = getFormatterCommand(filename);
const timer = new Timer();
try {
await exec({
command: command,
args: args,
});
} catch (error) {
formatLogger.error("Failed to format code", {
executable: command,
args: args,
filename: filename,
execTime: `${timer.elapsed}ms`,
error: error,
});
return;
}
formatLogger.log("Code successfully formatted", {
executable: command,
args: args,
filename: filename,
execTime: `${timer.elapsed}ms`,
});
}