Skip to content

Commit

Permalink
fix(goctl): api format with reader input (#1722)
Browse files Browse the repository at this point in the history
resolves #1721
  • Loading branch information
fynxiu committed Mar 30, 2022
1 parent e9620c8 commit 500bd87
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
14 changes: 8 additions & 6 deletions tools/goctl/api/format/format.go
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"go/format"
"go/scanner"
"io"
"io/ioutil"
"os"
"path/filepath"
Expand All @@ -29,14 +30,14 @@ const (
func GoFormatApi(c *cli.Context) error {
useStdin := c.Bool("stdin")
skipCheckDeclare := c.Bool("declare")
dir := c.String("dir")

var be errorx.BatchError
if useStdin {
if err := apiFormatByStdin(skipCheckDeclare); err != nil {
if err := apiFormatReader(os.Stdin, dir, skipCheckDeclare); err != nil {
be.Add(err)
}
} else {
dir := c.String("dir")
if len(dir) == 0 {
return errors.New("missing -dir")
}
Expand Down Expand Up @@ -65,13 +66,14 @@ func GoFormatApi(c *cli.Context) error {
return be.Err()
}

func apiFormatByStdin(skipCheckDeclare bool) error {
data, err := ioutil.ReadAll(os.Stdin)
// apiFormatReader
// filename is needed when there are `import` literals.
func apiFormatReader(reader io.Reader, filename string, skipCheckDeclare bool) error {
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}

result, err := apiFormat(string(data), skipCheckDeclare)
result, err := apiFormat(string(data), skipCheckDeclare, filename)
if err != nil {
return err
}
Expand Down
31 changes: 30 additions & 1 deletion tools/goctl/api/format/format_test.go
@@ -1,15 +1,21 @@
package format

import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const (
notFormattedStr = `
type Request struct {
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
}
type Response struct {
Message string ` + "`" + `json:"message"` + "`" + `
Expand Down Expand Up @@ -45,3 +51,26 @@ func TestFormat(t *testing.T) {
_, err = apiFormat(notFormattedStr, false)
assert.Errorf(t, err, " line 7:13 can not found declaration 'Student' in context")
}

func Test_apiFormatReader_issue1721(t *testing.T) {
dir, err := os.MkdirTemp("", "goctl-api-format")
require.NoError(t, err)
defer os.RemoveAll(dir)
subDir := path.Join(dir, "sub")
err = os.MkdirAll(subDir, fs.ModePerm)
require.NoError(t, err)

importedFilename := path.Join(dir, "foo.api")
err = ioutil.WriteFile(importedFilename, []byte{}, fs.ModePerm)
require.NoError(t, err)

filename := path.Join(subDir, "bar.api")
err = ioutil.WriteFile(filename, []byte(fmt.Sprintf(`import "%s"`, importedFilename)), 0644)
require.NoError(t, err)

f, err := os.Open(filename)
require.NoError(t, err)

err = apiFormatReader(f, filename, false)
assert.NoError(t, err)
}

0 comments on commit 500bd87

Please sign in to comment.