github.com/chainguard-dev/yam@v0.0.7/pkg/yam/format.go (about) 1 package yam 2 3 import ( 4 "fmt" 5 "io/fs" 6 "path/filepath" 7 8 "github.com/chainguard-dev/yam/pkg/rwfs" 9 "github.com/chainguard-dev/yam/pkg/util" 10 ) 11 12 func Format(fsys rwfs.FS, paths []string, options FormatOptions) error { 13 // "No paths" means "look at all files in the current directory". 14 if len(paths) == 0 { 15 paths = append(paths, ".") 16 } 17 18 for _, p := range paths { 19 stat, err := fs.Stat(fsys, p) 20 if err != nil { 21 return fmt.Errorf("unable to stat %q: %w", p, err) 22 } 23 24 if stat.IsDir() { 25 err := formatDir(fsys, p, options) 26 if err != nil { 27 return fmt.Errorf("unable to format directory %q: %w", p, err) 28 } 29 30 continue 31 } 32 33 err = formatSingleFile(fsys, p, options) 34 if err != nil { 35 return err 36 } 37 } 38 39 return nil 40 } 41 42 func formatDir(fsys rwfs.FS, dirPath string, options FormatOptions) error { 43 dirEntries, err := fs.ReadDir(fsys, dirPath) 44 if err != nil { 45 return err 46 } 47 48 for _, file := range dirEntries { 49 if !file.Type().IsRegular() { 50 continue 51 } 52 53 p := filepath.Join(dirPath, file.Name()) 54 err := formatSingleFile(fsys, p, options) 55 if err != nil { 56 return err 57 } 58 } 59 60 return nil 61 } 62 63 func formatSingleFile(fsys rwfs.FS, path string, options FormatOptions) error { 64 // Immediately skip files that aren't YAML files 65 if !util.IsYAML(path) { 66 return nil 67 } 68 69 p := filepath.Clean(path) 70 file, err := fsys.Open(p) 71 if err != nil { 72 return err 73 } 74 75 defer file.Close() 76 77 formatted, err := applyFormatting(file, options) 78 if err != nil { 79 return fmt.Errorf("unable to format %q: %w", path, err) 80 } 81 82 err = fsys.Truncate(p, 0) 83 if err != nil { 84 return err 85 } 86 writeableFile, err := fsys.OpenRW(p) 87 if err != nil { 88 return err 89 } 90 91 _, err = formatted.WriteTo(writeableFile) 92 if err != nil { 93 return err 94 } 95 96 writeableFile.Close() 97 98 return nil 99 }