Debian Codegraph @

cmd/shfmt/main.go

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