Skip to content

Commit 676eb2f

Browse files
committed
Escape special characters in formatter configuration for Windows
The sketch code formatter configuration is passed to the ClangFormat tool as a string representing a JSON object via a command line argument. Previously, the contents of this string were not given any special treatment to ensure compatibility with the command interpreter used on Windows machines. That did not result in problems only because the configuration didn't contain problematic combinations of characters. This good fortune will not persist through updates to the configuration, so the command must be properly processed. The Windows command interpreter does not use the POSIX style backslash escaping. For this reason, escaped quotes in the argument are recognized as normal quotes, meaning that the string alternates between quoted and unquoted states at random. When a character with special significance to the Windows command interpreter happens to occur outside a quoted section, an error results. The solution is to use the Windows command interpreter's caret escaping on these characters. Since such an escaping system is not recognized by POSIX shells, this is only done when the application is running on a Windows machine. References: - https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/echo#remarks - https://en.wikipedia.org/wiki/Escape_character#Windows_Command_Prompt
1 parent ce273ad commit 676eb2f

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

arduino-ide-extension/src/node/clang-formatter.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as os from 'os';
12
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
23
import { MaybePromise } from '@theia/core/lib/common/types';
34
import { FileUri } from '@theia/core/lib/node/file-uri';
@@ -123,10 +124,23 @@ function toClangOptions(
123124

124125
// See: https://releases.llvm.org/11.0.1/tools/clang/docs/ClangFormatStyleOptions.html
125126
export function style({ TabWidth, UseTab }: ClangFormatOptions): string {
126-
return JSON.stringify(styleJson({ TabWidth, UseTab })).replace(
127+
let styleArgument = JSON.stringify(styleJson({ TabWidth, UseTab })).replace(
127128
/[\\"]/g,
128129
'\\$&'
129130
);
131+
if (os.platform() === 'win32') {
132+
// Windows command interpreter does not use backslash escapes. This causes the argument to have alternate quoted and
133+
// unquoted sections.
134+
// Special characters in the unquoted sections must be caret escaped.
135+
const styleArgumentSplit = styleArgument.split('"');
136+
for (let i = 1; i < styleArgumentSplit.length; i += 2) {
137+
styleArgumentSplit[i] = styleArgumentSplit[i].replace(/[<>^|]/g, '^$&');
138+
}
139+
140+
styleArgument = styleArgumentSplit.join('"');
141+
}
142+
143+
return styleArgument;
130144
}
131145

132146
function styleJson({

0 commit comments

Comments
 (0)