Skip to content

Commit

Permalink
feat: format cmd implement
Browse files Browse the repository at this point in the history
  • Loading branch information
joyme123 committed Nov 22, 2023
1 parent 7d46dff commit c8b100e
Show file tree
Hide file tree
Showing 16 changed files with 2,379 additions and 11 deletions.
6 changes: 5 additions & 1 deletion format/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package format

import (
"bytes"
"strings"

"github.com/joyme123/thrift-ls/parser"
)
Expand Down Expand Up @@ -64,8 +65,11 @@ func FormatDocument(doc *parser.Document) (string, error) {
}
buf.WriteString(MustFormatComments(doc.Comments, ""))
}
res := buf.String()

return buf.String(), nil
res = strings.TrimSpace(res)

return res, nil
}

var (
Expand Down
70 changes: 70 additions & 0 deletions format/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package format

import (
"flag"
"strconv"
"strings"
)

var Indent = " "

type Options struct {
// Do not print reformatted sources to standard output.
// If a file's formatting is different from thriftls's, overwrite it
// with thrfitls's version.
Write bool `yaml:"rewrite"`

// Indent to use. Support: nspace(s), ntab(s). example: 4spaces, 1tab, tab
// if indent format is invalid or not specified, default is 4spaces
Indent string `yaml:"indent"`

// Do not print reformatted sources to standard output.
// If a file's formatting is different than gofmt's, print diffs
// to standard output.
Diff bool `yaml:"Diff"`
}

func (o *Options) SetFlags() {
flag.BoolVar(&o.Write, "w", false, "Do not print reformatted sources to standard output. If a file's formatting is different from thriftls's, overwrite it with thrfitls's version.")
flag.BoolVar(&o.Diff, "d", false, "Do not print reformatted sources to standard output. If a file's formatting is different than gofmt's, print diffs to standard output.")
flag.StringVar(&o.Indent, "indent", "4spaces", "Indent to use. Support: num*space, num*tab. example: 4spaces, 1tab, tab")
}

func (o *Options) InitDefaultIndent() {
Indent = o.GetIndent()
}

func (o *Options) GetIndent() string {
if o.Indent == "" {
o.Indent = "4spaces"
}

indent := o.Indent
suffixes := []string{"spaces", "space", "tabs", "tab"}
for _, suffix := range suffixes {
if strings.HasSuffix(indent, suffix) {
char := ""
if strings.HasPrefix(suffix, "tab") {
char = " "
} else {
char = " "
}
num := 1
numStr := strings.TrimSuffix(indent, suffix)
if len(numStr) == 0 {
num = 1
} else {
num, _ = strconv.Atoi(numStr)
if num == 0 {
num = 4
char = " "
}
}

return strings.Repeat(char, num)
}
}

return " "

}
71 changes: 71 additions & 0 deletions format/options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package format

import (
"testing"

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

func TestOptions_GetIndent(t *testing.T) {
type fields struct {
Write bool
Indent string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "4spaces",
fields: fields{
Indent: "4spaces",
},
want: " ",
},
{
name: "1space",
fields: fields{
Indent: "1spaces",
},
want: " ",
},
{
name: "space",
fields: fields{
Indent: "space",
},
want: " ",
},
{
name: "2tabs",
fields: fields{
Indent: "2tabs",
},
want: "\t\t",
},
{
name: "1tab",
fields: fields{
Indent: "1tab",
},
want: "\t",
},
{
name: "tab",
fields: fields{
Indent: "tab",
},
want: "\t",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
o := &Options{
Write: tt.fields.Write,
Indent: tt.fields.Indent,
}
assert.Equal(t, tt.want, o.GetIndent())
})
}
}
4 changes: 0 additions & 4 deletions format/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,6 @@ import (
"github.com/joyme123/thrift-ls/parser"
)

const (
Indent = " "
)

func MustFormat(tplText string, formatter any) string {
tpl, err := template.New("default").Parse(tplText)
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ go 1.19

require (
github.com/cloudwego/thriftgo v0.2.11
github.com/sergi/go-diff v1.3.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.7.0
go.lsp.dev/jsonrpc2 v0.10.0
go.lsp.dev/pkg v0.0.0-20210717090340-384b27a52fb2
go.lsp.dev/protocol v0.12.0
go.lsp.dev/uri v0.3.0
go.uber.org/zap v1.21.0
gopkg.in/yaml.v2 v2.2.8
gopkg.in/yaml.v2 v2.4.0
)

require (
Expand Down
10 changes: 8 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@ github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.3.4 h1:WM4IBnxH8B9TakiM2QD5LyNl9JSndh88QbHqVC+Pauc=
github.com/segmentio/encoding v0.3.4/go.mod h1:n0JeuIqEQrQoPDGsjo8UNd1iA0U8d8+oHAA4E3G3OxM=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
Expand Down Expand Up @@ -89,10 +92,13 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
77 changes: 74 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@ import (
"context"
"errors"
"flag"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"time"

"github.com/joyme123/thrift-ls/log"
"github.com/joyme123/thrift-ls/format"
tlog "github.com/joyme123/thrift-ls/log"
"github.com/joyme123/thrift-ls/lsp"
"github.com/joyme123/thrift-ls/parser"
"github.com/joyme123/thrift-ls/utils/diff"

"go.lsp.dev/jsonrpc2"
"go.lsp.dev/pkg/fakenet"
"gopkg.in/yaml.v2"
Expand All @@ -20,11 +26,75 @@ type Options struct {
LogLevel int `yaml:"logLevel"` // 1: fatal, 2: error, 3: warn, 4: info, 5: debug, 6: trace
}

func main_format(opt format.Options, file string) error {
opt.InitDefaultIndent()

if file == "" {
err := errors.New("must specified a thrift file to format")
fmt.Println(err)
return err
}

content, err := os.ReadFile(file)
if err != nil {
fmt.Println(err)
return err
}

thrift_file := filepath.Base(file)
ast, err := parser.Parse(thrift_file, content)
if err != nil {
fmt.Println(err)
return err
}
formated, err := format.FormatDocument(ast.(*parser.Document))
if opt.Write {
var perms os.FileMode
fileInfo, err := os.Stat(file)
if err != nil {
fmt.Println(err)
return err
}
perms = fileInfo.Mode() // 使用原文件的权限

// overwrite
err = os.WriteFile(file, []byte(formated), perms)
if err != nil {
fmt.Println(err)
return err
}
} else {
if opt.Diff {
diffLines := diff.Diff("old", content, "new", []byte(formated))
fmt.Print(string(diffLines))
} else {
fmt.Print(formated)
}
return err
}

return nil

}

func main() {
rand.Seed(time.Now().UnixMilli())

formatter := false
formatFile := ""
flag.BoolVar(&formatter, "formatter", false, "use thrift-ls as a format tool")
flag.StringVar(&formatFile, "file", "", "file path to format")
formatOpts := format.Options{}
formatOpts.SetFlags()

opts := configInit()
log.Init(opts.LogLevel)
tlog.Init(opts.LogLevel)

if formatter {
main_format(formatOpts, formatFile)
os.Exit(1)
return
}

ctx := context.Background()
// server := &lsp.Server{}
Expand All @@ -46,6 +116,8 @@ func main() {
}

func configInit() *Options {
opts := &Options{}

logLevel := -1
flag.IntVar(&logLevel, "logLevel", -1, "set log level")
flag.Parse()
Expand All @@ -56,7 +128,6 @@ func configInit() *Options {
}
dir = dir + "/.thriftls"
configFile := dir + "/config.yaml"
opts := &Options{}

data, err := os.ReadFile(configFile)
if err == nil {
Expand Down
7 changes: 7 additions & 0 deletions tests/galaxy-thrift-api/io/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
RSFile格式定义
============

RSFile(Record Sequence File)是基于记录的顺序文件。其基础文件格式定义了一个
二进制记录的序列,然后在此基础上定义了上层服务的专有文件格式(如结构化存储表文件)。

文件格式定义参考io/RSFile.thrift和sds/SLFile.thrift。
Loading

0 comments on commit c8b100e

Please sign in to comment.