Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add flag clear_tag_comment to clear the tag comment #55

Merged
merged 1 commit into from
Aug 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Usage of protoc-go-inject-tag:
pattern to match input file(s)
-verbose
verbose logging
-clear_tag_comment
clear tag comment
```

Add a comment with the following syntax before fields, and these will be
Expand Down Expand Up @@ -102,3 +104,4 @@ Since **v1.3.0**, we recommend using `@gotags:` rather than `@inject_tags:`,
as `@gotags` is more indicative of the language the comment is for. We don't
plan on removing `@inject_tags:` support anytime soon, however we strongly
recommend switching to `@gotags`.

25 changes: 15 additions & 10 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ var (
rComment = regexp.MustCompile(`^//.*?@(?i:gotags?|inject_tags?):\s*(.*)$`)
rInject = regexp.MustCompile("`.+`$")
rTags = regexp.MustCompile(`[\w_]+:"[^"]+"`)
rAll = regexp.MustCompile(".*")
)

type textArea struct {
Start int
End int
CurrentTag string
InjectTag string
Start int
End int
CurrentTag string
InjectTag string
CommentStart int
CommentEnd int
}

func parseFile(inputPath string, xxxSkip []string) (areas []textArea, err error) {
Expand Down Expand Up @@ -112,10 +115,12 @@ func parseFile(inputPath string, xxxSkip []string) (areas []textArea, err error)

currentTag := field.Tag.Value
area := textArea{
Start: int(field.Pos()),
End: int(field.End()),
CurrentTag: currentTag[1 : len(currentTag)-1],
InjectTag: tag,
Start: int(field.Pos()),
End: int(field.End()),
CurrentTag: currentTag[1 : len(currentTag)-1],
InjectTag: tag,
CommentStart: int(comment.Pos()),
CommentEnd: int(comment.End()),
}
areas = append(areas, area)
}
Expand All @@ -125,7 +130,7 @@ func parseFile(inputPath string, xxxSkip []string) (areas []textArea, err error)
return
}

func writeFile(inputPath string, areas []textArea) (err error) {
func writeFile(inputPath string, areas []textArea, clearTagCommon bool) (err error) {
f, err := os.Open(inputPath)
if err != nil {
return
Expand All @@ -144,7 +149,7 @@ func writeFile(inputPath string, areas []textArea) (err error) {
for i := range areas {
area := areas[len(areas)-i-1]
logf("inject custom tag %q to expression %q", area.InjectTag, string(contents[area.Start-1:area.End-1]))
contents = injectTag(contents, area)
contents = injectTag(contents, area, clearTagCommon)
}
if err = ioutil.WriteFile(inputPath, contents, 0644); err != nil {
return
Expand Down
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ import (

func main() {
var inputFiles, xxxTags string
var clearTagCommon bool
flag.StringVar(&inputFiles, "input", "", "pattern to match input file(s)")
flag.StringVar(&xxxTags, "XXX_skip", "", "tags that should be skipped (applies 'tag:\"-\"') for unknown fields (deprecated since protoc-gen-go v1.4.0)")
flag.BoolVar(&clearTagCommon, "clear_tag_comment", false, "clear tag comment")
flag.BoolVar(&verbose, "verbose", false, "verbose logging")

flag.Parse()

var xxxSkipSlice []string
Expand Down Expand Up @@ -54,7 +57,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
if err = writeFile(path, areas); err != nil {
if err = writeFile(path, areas, clearTagCommon); err != nil {
log.Fatal(err)
}
}
Expand Down
61 changes: 59 additions & 2 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,64 @@ func TestParseWriteFile(t *testing.T) {
}
defer os.Remove(testInputFileTemp)

if err = writeFile(testInputFileTemp, areas); err != nil {
if err = writeFile(testInputFileTemp, areas, false); err != nil {
t.Fatal(err)
}

newAreas, err := parseFile(testInputFileTemp, []string{})
if len(newAreas) != len(areas) {
t.Errorf("the comment tag has error")
}
if err != nil {
t.Fatal(err)
}

// check if file contains custom tag
contents, err = ioutil.ReadFile(testInputFileTemp)
if err != nil {
t.Fatal(err)
}
expectedExpr := "Address[ \t]+string[ \t]+`protobuf:\"bytes,1,opt,name=Address,proto3\" json:\"overrided\" valid:\"ip\" yaml:\"ip\"`"
matched, err := regexp.Match(expectedExpr, contents)
if err != nil || matched != true {
t.Error("file doesn't contains custom tag after writing")
t.Log(string(contents))
}
}

func TestParseWriteFileClearCommon(t *testing.T) {
expectedTag := `valid:"ip" yaml:"ip" json:"overrided"`

areas, err := parseFile(testInputFile, []string{})
if err != nil {
t.Fatal(err)
}
if len(areas) != 9 {
t.Fatalf("expected 9 areas to replace, got: %d", len(areas))
}
area := areas[0]
if area.InjectTag != expectedTag {
t.Errorf("expected tag: %q, got: %q", expectedTag, area.InjectTag)
}

// make a copy of test file
contents, err := ioutil.ReadFile(testInputFile)
if err != nil {
t.Fatal(err)
}
if err = ioutil.WriteFile(testInputFileTemp, contents, 0644); err != nil {
t.Fatal(err)
}
defer os.Remove(testInputFileTemp)

if err = writeFile(testInputFileTemp, areas, true); err != nil {
t.Fatal(err)
}
newAreas, err := parseFile(testInputFileTemp, []string{})
if newAreas != nil {
t.Errorf("not clear tag")
}
if err != nil {
t.Fatal(err)
}

Expand Down Expand Up @@ -148,7 +205,7 @@ func TestContinueParsingWhenSkippingFields(t *testing.T) {
}
defer os.Remove(testInputFileTemp)

if err = writeFile(testInputFileTemp, areas); err != nil {
if err = writeFile(testInputFileTemp, areas, false); err != nil {
t.Fatal(err)
}

Expand Down
28 changes: 24 additions & 4 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,35 @@ func newTagItems(tag string) tagItems {
return items
}

func injectTag(contents []byte, area textArea) (injected []byte) {
func injectTag(contents []byte, area textArea, clearTagCommon bool) (injected []byte) {
expr := make([]byte, area.End-area.Start)
copy(expr, contents[area.Start-1:area.End-1])
cti := newTagItems(area.CurrentTag)
iti := newTagItems(area.InjectTag)
ti := cti.override(iti)
expr = rInject.ReplaceAll(expr, []byte(fmt.Sprintf("`%s`", ti.format())))
injected = append(injected, contents[:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:]...)
if clearTagCommon {
black := make([]byte, area.CommentEnd-area.CommentStart)
copy(black, contents[area.CommentStart-1:area.CommentEnd-1])
black = rAll.ReplaceAll(expr, []byte(" "))
if area.CommentStart < area.Start {
injected = append(injected, contents[:area.CommentStart-1]...)
injected = append(injected, black...)
injected = append(injected, contents[area.CommentEnd-1:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:]...)
} else {
injected = append(injected, contents[:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:area.CommentStart-1]...)
injected = append(injected, black...)
injected = append(injected, contents[area.CommentEnd-1:]...)
}
} else {
injected = append(injected, contents[:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:]...)
}

return
}