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
This commit is contained in:
per1234 2022-08-02 21:42:20 -07:00
parent ce273adf77
commit 676eb2f588

View File

@ -1,3 +1,4 @@
import * as os from 'os';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { MaybePromise } from '@theia/core/lib/common/types';
import { FileUri } from '@theia/core/lib/node/file-uri';
@ -123,10 +124,23 @@ function toClangOptions(
// See: https://releases.llvm.org/11.0.1/tools/clang/docs/ClangFormatStyleOptions.html
export function style({ TabWidth, UseTab }: ClangFormatOptions): string {
return JSON.stringify(styleJson({ TabWidth, UseTab })).replace(
let styleArgument = JSON.stringify(styleJson({ TabWidth, UseTab })).replace(
/[\\"]/g,
'\\$&'
);
if (os.platform() === 'win32') {
// Windows command interpreter does not use backslash escapes. This causes the argument to have alternate quoted and
// unquoted sections.
// Special characters in the unquoted sections must be caret escaped.
const styleArgumentSplit = styleArgument.split('"');
for (let i = 1; i < styleArgumentSplit.length; i += 2) {
styleArgumentSplit[i] = styleArgumentSplit[i].replace(/[<>^|]/g, '^$&');
}
styleArgument = styleArgumentSplit.join('"');
}
return styleArgument;
}
function styleJson({