Debian Codegraph @

cmd/shfmt/main.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright (c) 2016, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 // shfmt formats shell programs.
5 package main
6
7 import (
8 "bytes"
9 "errors"
10 "flag"
11 "fmt"
12 "io"
13 "io/fs"
14 "os"
15 "path/filepath"
16 "regexp"
17 "runtime/debug"
18 "strings"
19
20 maybeio "github.com/google/renameio/v2/maybe"
21 diffpkg "github.com/rogpeppe/go-internal/diff"
22 "golang.org/x/term"
23 "mvdan.cc/editorconfig"
24
25 "mvdan.cc/sh/v3/fileutil"
26 "mvdan.cc/sh/v3/syntax"
27 "mvdan.cc/sh/v3/syntax/typedjson"
28 )
29
30 type boolStringValue string
31
32 func (b *boolStringValue) Set(val string) error {
33 *b = boolStringValue(val)
34 return nil
35 }
36
37 func (b *boolStringValue) String() string {
38 return string(*b)
39 }
40 func (*boolStringValue) IsBoolFlag() bool { return true }
41
42 func boolStringVar(p *string, name string, value string, usage string) {
43 *p = value
44 flag.Var((*boolStringValue)(p), name, usage)
45 }
46
47 func langVariantVar(p *syntax.LangVariant, name string, value syntax.LangVariant, usage string) {
48 *p = value
49 flag.Var(p, name, usage)
50 }
51
52 type multiFlag[T any] struct {
53 short, long string
54 val T
55 }
56
57 func flagVal[T any](short, long string, val T, register func(*T, string, T, string)) *multiFlag[T] {
58 f := &multiFlag[T]{short, long, val}
59 if short != "" {
60 register(&f.val, short, val, "")
61 }
62 if long != "" {
63 register(&f.val, long, val, "")
64 }
65 return f
66 }
67
68 var (
69 // Generic flags.
70 versionFlag = flagVal("", "version", false, flag.BoolVar)
71 list = flagVal("l", "list", "false", boolStringVar)
72 write = flagVal("w", "write", false, flag.BoolVar)
73 diff = flagVal("d", "diff", false, flag.BoolVar)
74 applyIgnore = flagVal("", "apply-ignore", false, flag.BoolVar)
75 detect = flagVal("", "detect", "default", flag.StringVar)
76 filename = flagVal("", "filename", "", flag.StringVar)
77
78 // Parser flags.
79 lang = flagVal("ln", "language-dialect", syntax.LangAuto, langVariantVar)
80 posix = flagVal("p", "posix", false, flag.BoolVar)
81 simplify = flagVal("s", "simplify", false, flag.BoolVar)
82 // TODO: when promoting exp.recover to a stable flag, add it as an EditorConfig knob too, and perhaps rename to recover-errors
83 expRecover = flagVal("", "exp.recover", 0, flag.IntVar)
84
85 // Printer flags.
86 indent = flagVal("i", "indent", 0, flag.UintVar)
87 binNext = flagVal("bn", "binary-next-line", false, flag.BoolVar)
88 caseIndent = flagVal("ci", "case-indent", false, flag.BoolVar)
89 spaceRedirs = flagVal("sr", "space-redirects", false, flag.BoolVar)
90 keepPadding = flagVal("kp", "keep-padding", false, flag.BoolVar)
91 funcNext = flagVal("fn", "func-next-line", false, flag.BoolVar)
92 minify = flagVal("mn", "minify", false, flag.BoolVar)
93
94 // Utility flags.
95 find = flagVal("f", "find", "false", boolStringVar)
96 toJSON = flagVal("tojson", "to-json", false, flag.BoolVar) // TODO(v4): remove "tojson" for consistency
97 fromJSON = flagVal("", "from-json", false, flag.BoolVar)
98
99 // useEditorConfig will be false if any parser or printer flags were used.
100 useEditorConfig = true
101
102 parser *syntax.Parser
103 printer *syntax.Printer
104 readBuf, writeBuf bytes.Buffer
105 color bool
106
107 copyBuf = make([]byte, 32*1024)
•108
109 version = "(devel)"
110 )
111
112 func main() {
113 flag.Usage = func() {
114 fmt.Fprint(os.Stderr, `usage: shfmt [flags] [path ...]
115
116 shfmt formats shell programs. If the only argument is a dash ('-') or no
117 arguments are given, standard input will be used. If a given path is a
118 directory, all shell scripts found under that directory will be used.
119
120 --version show version and exit
121
122 -l[=0], --list[=0] error with a list of files whose formatting differs from shfmt;
123 paths are separated by a newline or a null character if -l=0
124 -w, --write write result to file instead of stdout
125 -d, --diff error with a diff when the formatting differs
126 --apply-ignore always apply EditorConfig ignore rules
127 --detect str how to detect shell files when walking: default, exec, or all
128 --filename str provide a name for the standard input file
129
130 Parser options:
131
132 -ln, --language-dialect str bash/posix/mksh/bats/zsh, default "auto"
133 -p, --posix shorthand for -ln=posix
134 -s, --simplify simplify the code
135
136 Printer options:
137
138 -i, --indent uint 0 for tabs (default), >0 for number of spaces
139 -bn, --binary-next-line binary ops like && and | may start a line
140 -ci, --case-indent switch cases will be indented
141 -sr, --space-redirects redirect operators will be followed by a space
142 -kp, --keep-padding keep column alignment paddings
143 -fn, --func-next-line function opening braces are placed on a separate line
144 -mn, --minify minify the code to reduce its size (implies -s)
145
146 Utilities:
147
148 -f[=0], --find[=0] recursively find all shell files and print the paths;
149 paths are separated by a newline or a null character if -f=0
150 --to-json print syntax tree to stdout as a typed JSON
151 --from-json read syntax tree from stdin as a typed JSON
152
153 Formatting options can also be read from EditorConfig files; see 'man shfmt'
154 for a detailed description of the tool's behavior.
155 For more information and to report bugs, see https://github.com/mvdan/sh.
156 `)
157 }
158 flag.Parse()
159
160 if versionFlag.val {
•161 if info, ok := debug.ReadBuildInfo(); ok && version == "(devel)" {
162 mod := &info.Main
163 if mod.Replace != nil {
164 mod = mod.Replace
165 }
166 version = mod.Version
167 }
168 fmt.Println(version)
169 return
170 }
171 if posix.val && lang.val != syntax.LangAuto {
172 fmt.Fprintf(os.Stderr, "-p and -ln=lang cannot coexist\n")
173 os.Exit(1)
174 }
175 if list.val != "true" && list.val != "false" && list.val != "0" {
176 fmt.Fprintf(os.Stderr, "only -l and -l=0 allowed\n")
177 os.Exit(1)
178 }
179 if find.val != "true" && find.val != "false" && find.val != "0" {
180 fmt.Fprintf(os.Stderr, "only -f and -f=0 allowed\n")
181 os.Exit(1)
182 }
183 switch detect.val {
184 case "default", "exec", "all":
185 default:
186 fmt.Fprintf(os.Stderr, "--detect only allows default, exec, or all\n")
187 os.Exit(1)
188 }
189 simplify.val = simplify.val || minify.val
190 flag.Visit(func(f *flag.Flag) {
191 // This list should be in sync with the grouping of parser and printer options
192 // as shown by ./shfmt.1.scd.
193 switch f.Name {
194 case lang.short, lang.long,
195 posix.short, posix.long,
196 simplify.short, simplify.long,
197 indent.short, indent.long,
198 binNext.short, binNext.long,
199 caseIndent.short, caseIndent.long,
200 spaceRedirs.short, spaceRedirs.long,
201 keepPadding.short, keepPadding.long,
202 funcNext.short, funcNext.long,
203 minify.short, minify.long:
204 useEditorConfig = false
205 }
206 })
207 parser = syntax.NewParser(syntax.KeepComments(true))
208 printer = syntax.NewPrinter(syntax.Minify(minify.val))
209
210 syntax.RecoverErrors(expRecover.val)(parser)
211
212 if !useEditorConfig {
213 if posix.val {
214 // -p equals -ln=posix
215 lang.val = syntax.LangPOSIX
216 }
217
218 syntax.Indent(indent.val)(printer)
219 syntax.BinaryNextLine(binNext.val)(printer)
220 syntax.SwitchCaseIndent(caseIndent.val)(printer)
221 syntax.SpaceRedirects(spaceRedirs.val)(printer)
222 syntax.KeepPadding(keepPadding.val)(printer)
223 syntax.FunctionNextLine(funcNext.val)(printer)
224 }
225
226 // Decide whether or not to use color for the diff output,
227 // as described in shfmt.1.scd.
228 if os.Getenv("FORCE_COLOR") != "" {
229 color = true
230 } else if os.Getenv("NO_COLOR") != "" || os.Getenv("TERM") == "dumb" {
231 } else if term.IsTerminal(int(os.Stdout.Fd())) {
232 color = true
233 }
234 // TODO(v4): show the help text on zero arguments,
235 // having the user run `shfmt -` if they want to format stdin.
236 // Using a dash is more explicit, and new users can easily be
237 // confused by `shfmt` seemingly hanging forever.
238 if flag.NArg() == 0 || (flag.NArg() == 1 && flag.Arg(0) == "-") {
239 name := "<standard input>"
240 if toJSON.val {
241 name = "" // the default is not useful there
242 }
243 if filename.val != "" {
244 name = filename.val
245 }
246 if err := formatStdin(name); err != nil {
247 if err != errFormattingDiffers {
248 fmt.Fprintln(os.Stderr, err)
249 }
250 os.Exit(1)
251 }
252 return
253 }
254 if filename.val != "" {
255 fmt.Fprintln(os.Stderr, "-filename can only be used with stdin")
256 os.Exit(1)
257 }
258 if toJSON.val {
259 fmt.Fprintln(os.Stderr, "--to-json can only be used with stdin")
260 os.Exit(1)
261 }
262 if fromJSON.val {
263 fmt.Fprintln(os.Stderr, "--from-json can only be used with stdin")
264 os.Exit(1)
265 }
266 status := 0
267 for _, path := range flag.Args() {
268 explicit := true
269 if err := filepath.WalkDir(path, func(path string, entry fs.DirEntry, err error) error {
270 defer func() { explicit = false }()
271 if err != nil {
272 return err
273 }
274 if entry.IsDir() && vcsDir.MatchString(entry.Name()) {
275 return filepath.SkipDir
276 }
277 // If the path is not an explicit arg, or if --apply-ignore is set,
278 // we find and apply EditorConfig ignore rules.
279 if !explicit || applyIgnore.val {
280 // We don't know the language variant at this point yet, as we are walking directories
281 // and we first want to tell if we should skip a path entirely.
282 //
283 // TODO: Should the call to Find with the language name check "ignore" too, then?
284 // Otherwise, a [[bash]] section with ignore=true is effectively never used.
285 //
286 // TODO: Should there be a way to explicitly turn off ignore rules when walking?
287 // Perhaps swapping the default to --apply-ignore=auto and allowing --apply-ignore=false?
288 // I don't imagine it's a particularly useful scenario for now.
289 props, err := ecQuery.Find(path, []string{"shell"})
290 if err != nil {
291 return err
292 }
293 if props.Get("ignore") == "true" {
294 if entry.IsDir() {
295 return filepath.SkipDir
296 } else {
297 return nil
298 }
299 }
300 }
301 conf := fileutil.ConfIsScript
302 // If the path is an explicit arg and it points to a symlink,
303 // resolve that symlink so that we don't try to format non-regular files.
304 if explicit && entry.Type()&fs.ModeSymlink != 0 {
305 info, err := os.Stat(path)
306 if err != nil {
307 return err
308 }
309 entry = fs.FileInfoToDirEntry(info)
310 }
311 // If the path is not an explicit arg, or it's not regular, or --find is set,
312 // then we check for extensions and shebangs.
313 if !explicit || !entry.Type().IsRegular() || find.val != "false" {
314 conf = fileutil.CouldBeScript2(entry)
315 // A regular file discarded for its non-shell extension may
316 // still have its shebang read, depending on --detect.
317 // TODO(v4): perhaps the non-default modes should include hidden files.
318 if conf == fileutil.ConfNotScript && entry.Type().IsRegular() && entry.Name()[0] != '.' {
319 switch detect.val {
320 case "exec":
321 info, err := entry.Info()
322 if err != nil {
323 return err
324 }
325 if info.Mode()&0o111 != 0 {
326 conf = fileutil.ConfIfShebang
327 }
328 case "all":
329 conf = fileutil.ConfIfShebang
330 }
331 }
332 if conf == fileutil.ConfNotScript {
333 return nil
334 }
335 }
336 err = formatPath(path, conf == fileutil.ConfIfShebang)
337 if err == errFormattingDiffers {
338 status = 1
339 err = nil
340 } else if err != nil {
341 fmt.Fprintln(os.Stderr, err)
342 status = 1
343 }
344 return nil
345 }); err != nil {
346 fmt.Fprintln(os.Stderr, err)
347 status = 1
348 }
349 }
350 os.Exit(status)
351 }
352
353 var vcsDir = regexp.MustCompile(`^\.(git|svn|hg)$`)
354
355 var errFormattingDiffers = fmt.Errorf("")
356
357 func formatStdin(name string) error {
358 if write.val {
359 return fmt.Errorf("-w cannot be used on standard input")
360 }
361 if applyIgnore.val {
362 // Mimic the logic from walkPath to apply the ignore rules.
363 props, err := ecQuery.Find(name, []string{"shell"})
364 if err != nil {
365 return err
366 }
367 if props.Get("ignore") == "true" {
368 return nil
369 }
370 }
371 src, err := io.ReadAll(os.Stdin)
372 if err != nil {
373 return err
374 }
375 l := lang.val
376 if l == syntax.LangAuto {
377 if l = langFromFilename(name); l == syntax.LangAuto {
378 shebangLang := fileutil.Shebang(src)
379 if err := l.Set(shebangLang); err != nil {
380 // Fall back to bash.
381 l = syntax.LangBash
382 }
383 }
384 }
385 return formatBytes(src, name, l)
386 }
387
388 func langFromFilename(name string) syntax.LangVariant {
389 // Detect shell config files, which typically have no extension nor shebang.
390 // Note that these are not matched by [fileutil.CouldBeScript2],
391 // because these files are typically not part of source code projects,
392 // so finding these files when formatting entire directories is unnecessary.
393 switch strings.TrimPrefix(filepath.Base(name), ".") {
394 case "bash_profile", "bashrc", "bash_logout":
395 // Same as the usual fallback, but we can avoid trying to read a shebang.
396 return syntax.LangBash
397 case "zshenv", "zprofile", "zshrc", "zlogin", "zlogout":
398 return syntax.LangZsh
399 }
400
401 lang := syntax.LangAuto // fallback when none is found
402 if ext := strings.TrimPrefix(filepath.Ext(name), "."); ext != "sh" {
403 // Note that ".sh" doesn't mean it's POSIX Shell for sure.
404 // A shebang in the file contents could say Bash or some other POSIX-like shell.
405 lang.Set(ext)
406 }
407 return lang
408 }
409
410 var ecQuery = editorconfig.Query{
411 FileCache: make(map[string]*editorconfig.File),
412 RegexpCache: make(map[string]*regexp.Regexp),
413 }
414
415 func propsOptions(lang syntax.LangVariant, props editorconfig.Section) (_ syntax.LangVariant, validLang bool) {
416 // if shell_variant is set to a valid string, it will take precedence
417 langErr := lang.Set(props.Get("shell_variant"))
418 syntax.Variant(lang)(parser)
419
420 size := uint(0)
421 if props.Get("indent_style") == "space" {
422 size = 8
423 if n := props.IndentSize(); n > 0 {
424 size = uint(n)
425 }
426 }
427 syntax.Indent(size)(printer)
428
429 syntax.BinaryNextLine(props.Get("binary_next_line") == "true")(printer)
430 // TODO(v4): rename to case_indent for consistency with flags
431 syntax.SwitchCaseIndent(props.Get("switch_case_indent") == "true")(printer)
432 syntax.SpaceRedirects(props.Get("space_redirects") == "true")(printer)
433 syntax.KeepPadding(props.Get("keep_padding") == "true")(printer)
434 // TODO(v4): rename to func_next_line for consistency with flags
435 syntax.FunctionNextLine(props.Get("function_next_line") == "true")(printer)
436
437 minify := props.Get("minify") == "true"
438 syntax.Minify(minify)(printer)
439 // Note that --simplify is not actually a parser option, so we use a global var.
440 // Just like the CLI flags, minify=true implies simplify=true.
441 simplify.val = minify || props.Get("simplify") == "true"
442
443 return lang, langErr == nil
444 }
445
446 func formatPath(path string, checkShebang bool) error {
447 f, err := os.Open(path)
448 if err != nil {
449 return err
450 }
451 defer f.Close()
452
453 l := lang.val
454 shebangForAuto := false
455 if l == syntax.LangAuto {
456 if l = langFromFilename(path); l == syntax.LangAuto {
457 shebangForAuto = true
458 }
459 }
460 readBuf.Reset()
461 if checkShebang || shebangForAuto {
462 n, err := io.ReadAtLeast(f, copyBuf[:32], len("#!/bin/sh"))
463 switch {
464 case !checkShebang:
465 // only wanted the shebang for LangAuto
466 case err == io.EOF, errors.Is(err, io.ErrUnexpectedEOF):
467 return nil // too short to have a shebang
468 case err != nil:
469 return err // some other read error
470 }
471 shebangLang := fileutil.Shebang(copyBuf[:n])
472 if checkShebang && shebangLang == "" {
473 return nil // not a shell script
474 }
475 if shebangForAuto {
476 if err := l.Set(shebangLang); err != nil {
477 // Fall back to bash.
478 l = syntax.LangBash
479 }
480 }
481 readBuf.Write(copyBuf[:n])
482 }
483 switch find.val {
484 case "true":
485 fmt.Println(path)
486 return nil
487 case "0":
488 fmt.Print(path)
489 fmt.Print("\000")
490 return nil
491 }
492 if _, err := io.CopyBuffer(&readBuf, f, copyBuf); err != nil {
493 return err
494 }
495 f.Close()
496 return formatBytes(readBuf.Bytes(), path, l)
497 }
498
499 func editorConfigLangs(l syntax.LangVariant) []string {
500 // All known shells match [[shell]].
501 // As a special case, bash and the bash-like bats also match [[bash]],
502 // and zsh also matches [[zsh]].
503 // We can later consider others like [[mksh]] or [[posix-shell]],
504 // just consider what list of languages the EditorConfig spec might eventually use.
505 switch l {
506 case syntax.LangBash, syntax.LangBats:
507 return []string{"shell", "bash"}
508 case syntax.LangZsh:
509 return []string{"shell", "zsh"}
510 case syntax.LangPOSIX, syntax.LangMirBSDKorn, syntax.LangAuto:
511 return []string{"shell"}
512 }
513 return nil
514 }
515
516 func formatBytes(src []byte, path string, fileLang syntax.LangVariant) error {
517 fileLangFromEditorConfig := false
518 if useEditorConfig {
519 props, err := ecQuery.Find(path, editorConfigLangs(fileLang))
520 if err != nil {
521 return err
522 }
523 fileLang, fileLangFromEditorConfig = propsOptions(fileLang, props)
524 } else {
525 syntax.Variant(fileLang)(parser)
526 }
527 var node syntax.Node
528 var err error
529 if fromJSON.val {
530 node, err = typedjson.Decode(bytes.NewReader(src))
531 if err != nil {
532 return err
533 }
534 } else {
535 node, err = parser.Parse(bytes.NewReader(src), path)
536 if err != nil {
537 if s, ok := err.(syntax.LangError); ok && lang.val == syntax.LangAuto {
538 if fileLangFromEditorConfig {
539 return fmt.Errorf("%w (parsed as %s via EditorConfig)", s, fileLang)
540 }
541 return fmt.Errorf("%w (parsed as %s via -%s=%s)", s, fileLang, lang.short, lang.val)
542 }
543 return err
544 }
545 }
546 // Note that --simplify is treated as a parser option as it happens
547 // immediately after parsing, even if it's not a [syntax.ParserOption] today.
548 if simplify.val {
549 syntax.Simplify(node)
550 }
551 if toJSON.val {
552 // must be standard input; fine to return
553 // TODO: change the default behavior to be compact,
554 // and allow using --to-json=pretty or --to-json=indent.
555 return typedjson.EncodeOptions{Indent: "\t"}.Encode(os.Stdout, node)
556 }
557 writeBuf.Reset()
558 printer.Print(&writeBuf, node)
559 res := writeBuf.Bytes()
560 if !bytes.Equal(src, res) {
561 switch list.val {
562 case "true":
563 fmt.Println(path)
564 case "0":
565 fmt.Print(path)
566 fmt.Print("\000")
567 }
568 if write.val {
569 info, err := os.Lstat(path)
570 if err != nil {
571 return err
572 }
573 if !info.Mode().IsRegular() {
574 return fmt.Errorf("refusing to atomically replace %q with a regular file as it is not one already", path)
575 }
576 perm := info.Mode().Perm()
577 // TODO: support atomic writes on Windows?
578 if err := maybeio.WriteFile(path, res, perm); err != nil {
579 return err
580 }
581 }
582 if diff.val {
583 diffBytes := diffpkg.Diff(path+".orig", src, path, res)
584 if !color {
585 os.Stdout.Write(diffBytes)
586 return errFormattingDiffers
587 }
588 // The first three lines are the header with the filenames, including --- and +++,
589 // and are marked in bold.
590 current := terminalBold
591 os.Stdout.WriteString(current)
592 for i, line := range bytes.SplitAfter(diffBytes, []byte("\n")) {
593 last := current
594 switch {
595 case i < 3: // the first three lines are bold
596 case bytes.HasPrefix(line, []byte("@@")):
597 current = terminalCyan
598 case bytes.HasPrefix(line, []byte("-")):
599 current = terminalRed
600 case bytes.HasPrefix(line, []byte("+")):
601 current = terminalGreen
602 default:
603 current = terminalReset
604 }
605 if current != last {
606 os.Stdout.WriteString(current)
607 }
608 os.Stdout.Write(line)
609 }
610 return errFormattingDiffers
611 }
612 if list.val != "false" && !write.val {
613 return errFormattingDiffers
614 }
615 }
616 if list.val == "false" && !write.val && !diff.val {
617 os.Stdout.Write(res)
618 }
619 return nil
620 }
621
622 const (
623 terminalGreen = "\u001b[32m"
624 terminalRed = "\u001b[31m"
625 terminalCyan = "\u001b[36m"
626 terminalReset = "\u001b[0m"
627 terminalBold = "\u001b[1m"
628 )