goctl add stdin flag (#170)

* add stdin flag to use stdin receive api doc and use stdout output formatted result

* optimize code and output error through stderr

* fix mistake

* add dir parameter legality verify
master v1.0.23
codingfanlt 4 years ago committed by GitHub
parent 033525fea8
commit a13b48c33e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"go/format" "go/format"
"go/scanner"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -22,39 +23,79 @@ var (
) )
func GoFormatApi(c *cli.Context) error { func GoFormatApi(c *cli.Context) error {
useStdin := c.Bool("stdin")
var be errorx.BatchError
if useStdin {
if err := ApiFormatByStdin(); err != nil {
be.Add(err)
}
} else {
dir := c.String("dir") dir := c.String("dir")
if len(dir) == 0 { if len(dir) == 0 {
return errors.New("missing -dir") return errors.New("missing -dir")
} }
printToConsole := c.Bool("p") _, err := os.Lstat(dir)
if err != nil {
return errors.New(dir + ": No such file or directory")
}
var be errorx.BatchError err = filepath.Walk(dir, func(path string, fi os.FileInfo, errBack error) (err error) {
err := filepath.Walk(dir, func(path string, fi os.FileInfo, errBack error) (err error) {
if strings.HasSuffix(path, ".api") { if strings.HasSuffix(path, ".api") {
err := ApiFormat(path, printToConsole) if err := ApiFormatByPath(path); err != nil {
if err != nil {
be.Add(util.WrapErr(err, fi.Name())) be.Add(util.WrapErr(err, fi.Name()))
} }
} }
return nil return nil
}) })
be.Add(err) be.Add(err)
}
if be.NotNil() { if be.NotNil() {
errs := be.Err().Error() scanner.PrintError(os.Stderr, be.Err())
fmt.Println(errs)
os.Exit(1) os.Exit(1)
} }
return be.Err() return be.Err()
} }
func ApiFormat(path string, printToConsole bool) error { func ApiFormatByStdin() error {
data, err := ioutil.ReadFile(path) data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
result, err := apiFormat(string(data))
if err != nil {
return err
}
_, err = fmt.Print(result)
if err != nil { if err != nil {
return err return err
} }
return nil
}
r := reg.ReplaceAllStringFunc(string(data), func(m string) string { func ApiFormatByPath(apiFilePath string) error {
data, err := ioutil.ReadFile(apiFilePath)
if err != nil {
return err
}
result, err := apiFormat(string(data))
if err != nil {
return err
}
if err := ioutil.WriteFile(apiFilePath, []byte(result), os.ModePerm); err != nil {
return err
}
return nil
}
func apiFormat(data string) (string, error) {
r := reg.ReplaceAllStringFunc(data, func(m string) string {
parts := reg.FindStringSubmatch(m) parts := reg.FindStringSubmatch(m)
if len(parts) < 2 { if len(parts) < 2 {
return m return m
@ -67,11 +108,11 @@ func ApiFormat(path string, printToConsole bool) error {
apiStruct, err := parser.ParseApi(r) apiStruct, err := parser.ParseApi(r)
if err != nil { if err != nil {
return err return "", err
} }
info := strings.TrimSpace(apiStruct.Info) info := strings.TrimSpace(apiStruct.Info)
if len(apiStruct.Service) == 0 { if len(apiStruct.Service) == 0 {
return nil return data, nil
} }
fs, err := format.Source([]byte(strings.TrimSpace(apiStruct.StructBody))) fs, err := format.Source([]byte(strings.TrimSpace(apiStruct.StructBody)))
@ -81,16 +122,16 @@ func ApiFormat(path string, printToConsole bool) error {
if lineNumber > 0 { if lineNumber > 0 {
ln, err := strconv.ParseInt(str[:lineNumber], 10, 64) ln, err := strconv.ParseInt(str[:lineNumber], 10, 64)
if err != nil { if err != nil {
return err return "", err
} }
pn := 0 pn := 0
if len(info) > 0 { if len(info) > 0 {
pn = countRune(info, '\n') + 1 pn = countRune(info, '\n') + 1
} }
number := int(ln) + pn + 1 number := int(ln) + pn + 1
return errors.New(fmt.Sprintf("line: %d, %s", number, str[lineNumber+1:])) return "", errors.New(fmt.Sprintf("line: %d, %s", number, str[lineNumber+1:]))
} }
return err return "", err
} }
var result string var result string
@ -107,11 +148,7 @@ func ApiFormat(path string, printToConsole bool) error {
result += strings.TrimSpace(apiStruct.Service) + "\n\n" result += strings.TrimSpace(apiStruct.Service) + "\n\n"
} }
if printToConsole { return result, nil
_, err := fmt.Print(result)
return err
}
return ioutil.WriteFile(path, []byte(result), os.ModePerm)
} }
func countRune(s string, r rune) int { func countRune(s string, r rune) int {

@ -66,7 +66,7 @@ func DoGenProject(apiFile, dir string, force bool) error {
return err return err
} }
if err = apiformat.ApiFormat(apiFile, false); err != nil { if err := apiformat.ApiFormatByPath(apiFile); err != nil {
return err return err
} }

@ -51,15 +51,16 @@ var (
Name: "dir", Name: "dir",
Usage: "the format target dir", Usage: "the format target dir",
}, },
cli.BoolFlag{
Name: "p",
Usage: "print result to console",
},
cli.BoolFlag{ cli.BoolFlag{
Name: "iu", Name: "iu",
Usage: "ignore update", Usage: "ignore update",
Required: false, Required: false,
}, },
cli.BoolFlag{
Name: "stdin",
Usage: "use stdin to input api doc content, press \"ctrl + d\" to send EOF",
Required: false,
},
}, },
Action: format.GoFormatApi, Action: format.GoFormatApi,
}, },

Loading…
Cancel
Save