1
1
import { spawn } from 'child_process'
2
2
import * as LSP from 'vscode-languageserver/node'
3
3
import { TextDocument , TextEdit } from 'vscode-languageserver-textdocument'
4
+ import { basename } from 'node:path'
4
5
5
6
import { logger } from '../util/logger'
6
7
@@ -41,9 +42,7 @@ export class Formatter {
41
42
formatOptions ?: LSP . FormattingOptions | null ,
42
43
shfmtConfig ?: Record < string , string | boolean > | null ,
43
44
) : Promise < TextEdit [ ] > {
44
- const documentText = document . getText ( )
45
-
46
- const result = await this . runShfmt ( documentText , formatOptions , shfmtConfig )
45
+ const result = await this . runShfmt ( document , formatOptions , shfmtConfig )
47
46
48
47
if ( ! this . _canFormat ) {
49
48
return [ ]
@@ -61,16 +60,20 @@ export class Formatter {
61
60
}
62
61
63
62
private async runShfmt (
64
- documentText : string ,
63
+ document : TextDocument ,
65
64
formatOptions ?: LSP . FormattingOptions | null ,
66
65
shfmtConfig ?: Record < string , string | boolean > | null ,
67
66
) : Promise < string > {
68
- const indentation : number = formatOptions ?. insertSpaces ? formatOptions . tabSize : 0
69
- const args : string [ ] = [ `-i=${ indentation } ` ] // --indent
70
- if ( shfmtConfig ?. binaryNextLine ) args . push ( '-bn' ) // --binary-next-line
71
- if ( shfmtConfig ?. caseIndent ) args . push ( '-ci' ) // --case-indent
72
- if ( shfmtConfig ?. funcNextLine ) args . push ( '-fn' ) // --func-next-line
73
- if ( shfmtConfig ?. spaceRedirects ) args . push ( '-sr' ) // --space-redirects
67
+ // documentText: string,
68
+ const documentText = document . getText ( )
69
+ const documentUri = document . uri
70
+ const filename = basename ( documentUri )
71
+
72
+ // Do not pass any Parser and Printer options like -i/-p/-bn/-l. It will cause the .editorconfig not to be loaded.
73
+ // See https://github.com/mvdan/sh/blob/23633a432f903599a4ce46c30c4337e413a26ef1/cmd/shfmt/main.go#L186-L196
74
+ const args : string [ ] = [
75
+ `--filename=${ filename } ` , // Must set filename for matching the rules in .editorconfig.
76
+ ]
74
77
75
78
logger . debug ( `Shfmt: running "${ this . executablePath } ${ args . join ( ' ' ) } "` )
76
79
0 commit comments