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.14k stars 338 forks source link

syntax: Minify discards shebangs #833

Closed cilki closed 2 years ago

cilki commented 2 years ago

Running a simple script like:

#!/bin/bash
echo a

through shfmt -mn yields:

echo a

The shebang is stripped out (like a comment) which isn't ideal.

Thanks for the otherwise great library!

mvdan commented 2 years ago

Ah, good catch. This sounds like an easy one if someone wants to send their first PR. We should teach the printer's "minify" mode to not omit a leading comment if it looks like a shebang.

cilki commented 2 years ago

If no one picks this up for a while, I'll eventually send a PR. Also might send you a PR for some dead code optimizations I made to the simplifier if anyone is interested. Basically we do constant inlining and end up with a bunch of dead code like:

if [ "1" = "0" ]; then
    ...
fi

Then shfmt -s removes dead branches as part of our build process to keep scripts as small as possible (it actually makes a big difference in our case). Not sure if anyone else is crazy enough to do something similar.

mvdan commented 2 years ago

Eliminating dead branches seems like an interesting idea, though I would say shfmt -s is not the right place :) It's only meant to apply simple syntactic simplifications, and not anything beyond that like trying to understand what code is dead. One could certainly build another Go program that rewrote shell code to do more aggressive transformations like these, though - note how shfmt is just a relatively light layer on top of https://pkg.go.dev/mvdan.cc/sh/v3/syntax, so you wouldn't have to reimplement much at all.

cilki commented 2 years ago

Indeed. Those changes landed in shfmt -s because it was super convenient, but it would make sense to move it into a separate tool eventually. The AST in the syntax module is so nice it would be a shame not to take full advantage of it. Well done!