Skip to content

Commit

Permalink
Read from stdin when no file names are passed. (#41)
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Moran <danxmoran@gmail.com>
  • Loading branch information
danxmoran authored Nov 12, 2021
1 parent 59beec6 commit c86b884
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
9 changes: 8 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,21 @@ func main() {
DoDiff: doDiff,
}

if len(paths) == 0 {
if err := gci.ProcessFile("<standard input>", os.Stdin, os.Stdout, flagSet); err != nil {
report(err)
}
os.Exit(exitCode)
}

for _, path := range paths {
switch dir, err := os.Stat(path); {
case err != nil:
report(err)
case dir.IsDir():
report(gci.WalkDir(path, flagSet))
default:
if err := gci.ProcessFile(path, os.Stdout, flagSet); err != nil {
if err := gci.ProcessFile(path, nil, os.Stdout, flagSet); err != nil {
report(err)
}
}
Expand Down
21 changes: 12 additions & 9 deletions pkg/gci/gci.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
func visitFile(set *FlagSet) filepath.WalkFunc {
return func(path string, f os.FileInfo, err error) error {
if err == nil && isGoFile(f) {
err = processFile(path, os.Stdout, set)
err = processFile(path, nil, os.Stdout, set)
}
return err
}
Expand All @@ -274,20 +274,23 @@ func isGoFile(f os.FileInfo) bool {
return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
}

func ProcessFile(filename string, out io.Writer, set *FlagSet) error {
return processFile(filename, out, set)
func ProcessFile(filename string, in io.Reader, out io.Writer, set *FlagSet) error {
return processFile(filename, in, out, set)
}

func processFile(filename string, out io.Writer, set *FlagSet) error {
func processFile(filename string, in io.Reader, out io.Writer, set *FlagSet) error {
var err error

f, err := os.Open(filename)
if err != nil {
return err
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
in = f
}
defer f.Close()

src, err := ioutil.ReadAll(f)
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
Expand Down

0 comments on commit c86b884

Please sign in to comment.