فهرست منبع

fix(goctl): api format with reader input (#1722)

resolves #1721
Fyn 3 سال پیش
والد
کامیت
500bd87c85
2فایلهای تغییر یافته به همراه38 افزوده شده و 7 حذف شده
  1. 8 6
      tools/goctl/api/format/format.go
  2. 30 1
      tools/goctl/api/format/format_test.go

+ 8 - 6
tools/goctl/api/format/format.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"go/format"
 	"go/scanner"
+	"io"
 	"io/ioutil"
 	"os"
 	"path/filepath"
@@ -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")
 		}
@@ -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
 	}

+ 30 - 1
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"` + "`" + `
@@ -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)
+}