github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/cmd/cmd_fmt.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"path"
     8  	"strings"
     9  
    10  	"github.com/spf13/cobra"
    11  
    12  	"github.com/artisanhe/tools/format"
    13  )
    14  
    15  func LoadFiles(dir string, filter func(filename string) bool) (filenames []string) {
    16  	files, err := ioutil.ReadDir(dir)
    17  	if err != nil {
    18  		panic(err)
    19  	}
    20  	for _, file := range files {
    21  		filename := path.Join(dir, file.Name())
    22  		if file.IsDir() {
    23  			filenames = append(filenames, LoadFiles(filename, filter)...)
    24  		} else {
    25  			if filter(filename) {
    26  				filenames = append(filenames, filename)
    27  			}
    28  		}
    29  	}
    30  	return
    31  }
    32  
    33  var cmdFormat = &cobra.Command{
    34  	Use:   "fmt",
    35  	Short: "format",
    36  	Run: func(cmd *cobra.Command, args []string) {
    37  		cwd, _ := os.Getwd()
    38  		files := LoadFiles(cwd, func(filename string) bool {
    39  			return path.Ext(filename) == ".go" && !strings.Contains(filename, "/vendor/")
    40  		})
    41  
    42  		for _, filename := range files {
    43  			fileInfo, _ := os.Stat(filename)
    44  			bytes, _ := ioutil.ReadFile(filename)
    45  			nextBytes, err := format.Process(filename, bytes)
    46  			if err != nil {
    47  				panic(fmt.Errorf("errors %s in %s", filename, err.Error()))
    48  			}
    49  			if string(nextBytes) != string(bytes) {
    50  				fmt.Printf("reformatted %s\n", filename)
    51  				err := ioutil.WriteFile(filename, nextBytes, fileInfo.Mode())
    52  				if err != nil {
    53  					panic(err)
    54  				}
    55  			}
    56  		}
    57  	},
    58  }
    59  
    60  func init() {
    61  	cmdRoot.AddCommand(cmdFormat)
    62  }