From 4bf807ef6ac85cba927e06e30c91eb733a2f6aa1 Mon Sep 17 00:00:00 2001 From: riacataquian Date: Fri, 27 May 2022 20:13:33 +0800 Subject: [PATCH] shfmt: state -ln=auto on posix parse errors 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 --- cmd/shfmt/main.go | 9 ++++++--- cmd/shfmt/testdata/scripts/flags.txt | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/cmd/shfmt/main.go b/cmd/shfmt/main.go index 798e3eb69..30f69b0f9 100644 --- a/cmd/shfmt/main.go +++ b/cmd/shfmt/main.go @@ -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 { diff --git a/cmd/shfmt/testdata/scripts/flags.txt b/cmd/shfmt/testdata/scripts/flags.txt index 50278a29c..b5f842972 100644 --- a/cmd/shfmt/testdata/scripts/flags.txt +++ b/cmd/shfmt/testdata/scripts/flags.txt @@ -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 @@ -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() {