Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 41 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"io/ioutil"
"log"
"os"
Expand All @@ -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
}

Expand All @@ -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 {
Expand All @@ -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
}