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.28k stars 346 forks source link

How do I force removal of empty lines around the body of a function? #808

Closed joeljuca closed 2 years ago

joeljuca commented 2 years ago

Hi! This is more of a question than a bug or feature request. How could I force the removal of empty lines between the inner lines of a function?

For instance, the following function:

# hello.sh
function hello {

  if [ -n "$1" ]; then
  echo "Hello, ${1}!"
  else
  echo "Hello, World!"
  fi

}

When formatted (with shfmt -w hello.sh), results in:

# hello.sh
function greet {

  if [ -n "$1" ]; then
    echo "Hello, ${1}!"
  else
    echo "Hello, World!"
  fi

}

I would like to force the removal of these empty lines at the beginning and ending of the function body, resulting in:

# hello.sh
function greet {
  if [ -n "$1" ]; then
    echo "Hello, ${1}!"
  else
    echo "Hello, World!"
  fi
}

Is it currently possible with shfmt? :-)

mvdan commented 2 years ago

This is currently not supported by shfmt out of the box, but it's certainly doable if you modify its code. In particular, one could modify syntax.Printer to not allow any empty lines at the start or end of a function body.

This is probably a good idea for shfmt in general, as I've implemented the same in https://github.com/mvdan/gofumpt.

joeljuca commented 2 years ago

@mvdan it would be nice to have it indeed. Unfortunately, I don't know much of Go, so I can't patch it, but I'm happy with what shfmt does already! It's a pretty nice tool - thank you for it!