Skip to content

Commit

Permalink
lang/go: Add Context.FieldType{PackageName,ImportPath}
Browse files Browse the repository at this point in the history
  • Loading branch information
rvolosatovs committed Aug 7, 2020
1 parent 2fb4b63 commit 394b726
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lang/go/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ type Context interface {

// OutputPath returns the output path relative to the plugin's output destination
OutputPath(entity pgs.Entity) pgs.FilePath

// FieldTypeImportPath returns name of the Field type's package as it would appear in
// Go source generated by the official protoc-gen-go plugin.
// For builtin types empty Name will be returned.
FieldTypePackageName(field pgs.Field) pgs.Name

// FieldTypeImportPath returns the Go import path of the type of the Field
// as it would be included in an import block in a Go file.
// For builtin types empty FilePath will be returned.
FieldTypeImportPath(field pgs.Field) pgs.FilePath
}

type context struct{ p pgs.Parameters }
Expand Down
33 changes: 33 additions & 0 deletions lang/go/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,45 @@ func (c context) PackageName(node pgs.Node) pgs.Name {
return pgs.Name(pkg)
}

func fieldEntity(f pgs.Field) (pgs.Entity, bool) {
switch ft := f.Type(); {
case ft.IsEmbed():
return ft.Embed(), true
case ft.IsEnum():
return ft.Enum(), true
case ft.IsRepeated(), ft.IsMap():
switch el := ft.Element(); {
case el.IsEmbed():
return el.Embed(), true
case el.IsEnum():
return el.Enum(), true
}
}
return nil, false
}

func (c context) FieldTypePackageName(f pgs.Field) pgs.Name {
en, ok := fieldEntity(f)
if !ok {
return pgs.Name("")
}
return c.PackageName(en)
}

func (c context) ImportPath(e pgs.Entity) pgs.FilePath {
path, _ := c.optionPackage(e)
path = c.p.Str("import_prefix") + path
return pgs.FilePath(path)
}

func (c context) FieldTypeImportPath(f pgs.Field) pgs.FilePath {
en, ok := fieldEntity(f)
if !ok {
return pgs.FilePath("")
}
return c.ImportPath(en)
}

func (c context) OutputPath(e pgs.Entity) pgs.FilePath {
out := e.File().InputPath().SetExt(".pb.go")

Expand Down

0 comments on commit 394b726

Please sign in to comment.