Skip to content

Commit

Permalink
shfmt: state -ln=auto on posix parse errors
Browse files Browse the repository at this point in the history
explicitly state language dialect on `syntax.LangError`s when ln
is set to `auto`

for example, incompatible bash constructs will cause parse errors
due to the parser using posix as language dialect

fixes #803
  • Loading branch information
riacataquian committed May 27, 2022
1 parent 461b535 commit 4bf807e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
9 changes: 6 additions & 3 deletions cmd/shfmt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,18 +426,21 @@ func formatPath(path string, checkShebang bool) error {
return formatBytes(readBuf.Bytes(), path, fileLang)
}

func formatBytes(src []byte, path string, lang syntax.LangVariant) error {
func formatBytes(src []byte, path string, fileLang syntax.LangVariant) error {
if useEditorConfig {
props, err := ecQuery.Find(path)
if err != nil {
return err
}
propsOptions(lang, props)
propsOptions(fileLang, props)
} else {
syntax.Variant(lang)(parser)
syntax.Variant(fileLang)(parser)
}
prog, err := parser.Parse(bytes.NewReader(src), path)
if err != nil {
if s, ok := err.(syntax.LangError); ok && lang.val == syntax.LangAuto {
return fmt.Errorf("%w (parsed as %s via -%s=%s)", s, fileLang, lang.short, lang.val)
}
return err
}
if simplify.val {
Expand Down
15 changes: 15 additions & 0 deletions cmd/shfmt/testdata/scripts/flags.txt
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ stdin input-mksh
shfmt -ln=auto -filename=input.mksh
stdout 'coprocess'

# Explicitly state language on parse errors
stdin input-bash-arrays
! shfmt -ln=auto -filename=input.sh
stderr 'parsed as posix via -ln=auto'

stdin input-bash-extglobs
! shfmt -ln=auto -filename=input.sh
stderr 'parsed as posix via -ln=auto'

stdin flags-input
shfmt -i 2
cmp stdout flags-output.indent-golden
Expand Down Expand Up @@ -151,6 +160,12 @@ coprocess |&
-- input-mksh-shebang --
#!/bin/mksh
coprocess |&
-- input-bash-extglobs --
#!/bin/sh
echo !(a)
-- input-bash-arrays --
#!/bin/sh
foo=(bar)

-- flags-input --
foo() {
Expand Down

0 comments on commit 4bf807e

Please sign in to comment.