diff --git a/main.go b/main.go index b3fe9f4..828539d 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "io/ioutil" "log" "os" @@ -21,10 +22,10 @@ func main() { } cmd.Run = func(cmd *cli.Command, args []string) error { - if err := neatifyDir(args[0]); err != nil { + if err := statAndNeatifyPath(args[0]); err != nil { return err } - if err := neatifyDir(args[1]); err != nil { + if err := statAndNeatifyPath(args[1]); err != nil { return err } @@ -39,6 +40,28 @@ func main() { } } +func statAndNeatifyPath(path string) error { + // Stat evaluates symlinks so they are supported (if they lead to dirs or regular files). + fi, err := os.Stat(path) + if err != nil { + return err + } + return neatify(path, fi.Mode()) +} + +// neatify calls the appropriate function for the file based on FileMode +// neatify does not call Stat() because neatifyDir() aleady has FileInfo for the passed file +func neatify(path string, fm os.FileMode) error { + if fm.IsDir() { + return neatifyDir(path) + } + if fm.IsRegular() { + return neatifyFile(path, fm) + } + return fmt.Errorf("Found file '%s' which is neither directory nor a regular file. "+ + "Special files like named pipes or device files are not supported.", path) +} + func neatifyDir(dir string) error { fis, err := ioutil.ReadDir(dir) if err != nil { @@ -47,20 +70,27 @@ func neatifyDir(dir string) error { for _, fi := range fis { filename := filepath.Join(dir, fi.Name()) - data, err := ioutil.ReadFile(filename) - if err != nil { + if err = neatify(filename, fi.Mode()); err != nil { return err } + } - n, err := neat.NeatYAMLOrJSON(data) - if err != nil { - return err - } + return nil +} - if err := ioutil.WriteFile(filename, []byte(n), fi.Mode()); err != nil { - return err - } +func neatifyFile(filename string, fm os.FileMode) error { + data, err := ioutil.ReadFile(filename) + if err != nil { + return err } + n, err := neat.NeatYAMLOrJSON(data) + if err != nil { + return err + } + + if err := ioutil.WriteFile(filename, []byte(n), fm); err != nil { + return err + } return nil }