trpc.group/trpc-go/trpc-cmdline@v1.0.9/util/style/gofmt.go (about)

     1  // Tencent is pleased to support the open source community by making tRPC available.
     2  //
     3  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     4  // All rights reserved.
     5  //
     6  // If you have downloaded a copy of the tRPC source code from Tencent,
     7  // please note that tRPC source code is licensed under the  Apache 2.0 License,
     8  // A copy of the Apache 2.0 License is included in this file.
     9  
    10  // Package style provides formatting functions.
    11  package style
    12  
    13  import (
    14  	"fmt"
    15  	"go/format"
    16  	"os"
    17  	"path/filepath"
    18  	"strings"
    19  
    20  	"trpc.group/trpc-go/trpc-cmdline/util/log"
    21  )
    22  
    23  // Format the code in place.
    24  func Format(fpath string, lang string) error {
    25  	switch lang {
    26  	case "go":
    27  		return GoFmt(fpath)
    28  	default:
    29  		return nil
    30  	}
    31  }
    32  
    33  // GoFmt formats go code in place.
    34  func GoFmt(fpath string) error {
    35  	fin, err := os.ReadFile(fpath)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	buf, err := format.Source(fin)
    41  	if err != nil {
    42  		return fmt.Errorf("format error: %v", err)
    43  	}
    44  	return os.WriteFile(fpath, buf, 0644)
    45  }
    46  
    47  // GoFmtDir formats Go code in-place in a directory.
    48  func GoFmtDir(dir string) error {
    49  	err := filepath.Walk(dir, func(fpath string, info os.FileInfo, err error) error {
    50  		if strings.HasSuffix(fpath, ".go") && !info.IsDir() {
    51  			err := GoFmt(fpath)
    52  			if err != nil {
    53  				log.Error("Warn: style file:%s error:%v", fpath, err)
    54  			}
    55  		}
    56  		if info.IsDir() && dir != fpath {
    57  			return GoFmtDir(fpath)
    58  		}
    59  		return nil
    60  	})
    61  	return err
    62  }