You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/util/util.go

85 lines
1.9 KiB
Go

4 years ago
package util
import (
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/util/pathx"
4 years ago
)
// MaybeCreateFile creates file if not exists
4 years ago
func MaybeCreateFile(dir, subdir, file string) (fp *os.File, created bool, err error) {
logx.Must(pathx.MkdirIfNotExist(path.Join(dir, subdir)))
4 years ago
fpath := path.Join(dir, subdir, file)
if pathx.FileExists(fpath) {
4 years ago
fmt.Printf("%s exists, ignored generation\n", fpath)
return nil, false, nil
}
fp, err = pathx.CreateIfNotExist(fpath)
4 years ago
created = err == nil
return
}
// WrapErr wraps an error with message
4 years ago
func WrapErr(err error, message string) error {
return errors.New(message + ", " + err.Error())
}
// Copy calls io.Copy if the source file and destination file exists
4 years ago
func Copy(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, err
}
if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
// ComponentName returns component name for typescript
4 years ago
func ComponentName(api *spec.ApiSpec) string {
name := api.Service.Name
if strings.HasSuffix(name, "-api") {
return name[:len(name)-4] + "Components"
}
return name + "Components"
}
// WriteIndent writes tab spaces
func WriteIndent(writer io.Writer, indent int) {
for i := 0; i < indent; i++ {
fmt.Fprint(writer, "\t")
}
}
// RemoveComment filters comment content
func RemoveComment(line string) string {
commentIdx := strings.Index(line, "//")
if commentIdx >= 0 {
return strings.TrimSpace(line[:commentIdx])
}
return strings.TrimSpace(line)
}