mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
7.2k stars 340 forks source link

syntax: keep inline comments inside test clauses in place #1019

Open Freed-Wu opened 1 year ago

Freed-Wu commented 1 year ago
if [[ $- != *i* && # . ./main.sh
    $- != *c* # sh -c '. ./main.sh'
    ]]; then
    echo $-
fi

will be formatted to

if [[ $- != *i* &&
    $- != *c* ]] \
    ; then # . ./main.sh
    # sh -c '. ./main.sh'
    echo $-
fi

I don't like the formatted code. I want $- != *i* means this script is run by . ./main.sh, $- != *c* means sh -c '. ./main.sh'. so I hope to keep the comment on the same line as the code. How to avoid this behavior?

mvdan commented 1 year ago

The formatter tries to keep comments where they are on a best-effort basis. This is probably an edge case that we should improve, although I admit it's the first time I ever see it, so it doesn't seem high priority. Patches with tests are always welcome, as long as you don't break the other test cases :)