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