Skip to content

Commit

Permalink
Merge pull request #176 from jmattheis/context-setting
Browse files Browse the repository at this point in the history
Context setting
  • Loading branch information
jmattheis authored Dec 14, 2024
2 parents 2edc4a0 + a59de09 commit b953afb
Show file tree
Hide file tree
Showing 39 changed files with 272 additions and 99 deletions.
2 changes: 1 addition & 1 deletion builder/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ func mapField(
Params: method.ParamsNone,
ContextMatch: config.StructMethodContextRegex,
CustomCall: nextIDCode,
})
}, method.EmptyLocalOpts)
if err != nil {
return nil, nil, nil, nil, false, NewError(err.Error()).Lift(lift...)
}
Expand Down
19 changes: 4 additions & 15 deletions comments/parse_docs.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
package comments

import (
"bufio"
"fmt"
"go/ast"
"go/token"
"go/types"
"strings"

"github.com/jmattheis/goverter/config"
"github.com/jmattheis/goverter/config/parse"
"golang.org/x/tools/go/packages"
)

const (
prefix = "goverter"
delimter = ":"
converterMarker = prefix + delimter + "converter"
variablesMarker = prefix + delimter + "variables"
converterMarker = parse.Prefix + parse.Delimiter + "converter"
variablesMarker = parse.Prefix + parse.Delimiter + "variables"
)

// ParseDocsConfig provides input to the ParseDocs method below.
Expand Down Expand Up @@ -188,16 +186,7 @@ func parseInterfaceMethods(location *token.FileSet, inter *ast.InterfaceType) (m
}

func parseRawLines(location, comment string) config.RawLines {
scanner := bufio.NewScanner(strings.NewReader(comment))
raw := config.RawLines{Location: location}
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, prefix+delimter) {
line := strings.TrimPrefix(line, prefix+delimter)
raw.Lines = append(raw.Lines, line)
}
}
return raw
return config.RawLines{Location: location, Lines: parse.SettingLines(comment)}
}

func fileWithLine(p token.Position) string {
Expand Down
33 changes: 17 additions & 16 deletions config/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"regexp"

"github.com/jmattheis/goverter/config/parse"
"github.com/jmattheis/goverter/enum"
)

Expand Down Expand Up @@ -31,46 +32,46 @@ func parseCommon(c *Common, cmd, rest string) (fieldSetting bool, err error) {
if c.WrapErrorsUsing != "" {
return false, fmt.Errorf("cannot be used in combination with wrapErrorsUsing")
}
c.WrapErrors, err = parseBool(rest)
c.WrapErrors, err = parse.Bool(rest)
case "wrapErrorsUsing":
if c.WrapErrors {
return false, fmt.Errorf("cannot be used in combination with wrapErrors")
}
c.WrapErrorsUsing, err = parseString(rest)
c.WrapErrorsUsing, err = parse.String(rest)
case "ignoreUnexported":
fieldSetting = true
c.IgnoreUnexported, err = parseBool(rest)
c.IgnoreUnexported, err = parse.Bool(rest)
case "update:ignoreZeroValueField":
fieldSetting = true
c.IgnoreBasicZeroValueField, err = parseBool(rest)
c.IgnoreBasicZeroValueField, err = parse.Bool(rest)
c.IgnoreStructZeroValueField = c.IgnoreBasicZeroValueField
c.IgnoreNillableZeroValueField = c.IgnoreBasicZeroValueField
case "update:ignoreZeroValueField:basic":
c.IgnoreBasicZeroValueField, err = parseBool(rest)
c.IgnoreBasicZeroValueField, err = parse.Bool(rest)
case "update:ignoreZeroValueField:struct":
c.IgnoreStructZeroValueField, err = parseBool(rest)
c.IgnoreStructZeroValueField, err = parse.Bool(rest)
case "update:ignoreZeroValueField:nillable":
c.IgnoreNillableZeroValueField, err = parseBool(rest)
c.IgnoreNillableZeroValueField, err = parse.Bool(rest)
case "default:update":
c.DefaultUpdate, err = parseBool(rest)
c.DefaultUpdate, err = parse.Bool(rest)
case "matchIgnoreCase":
fieldSetting = true
c.MatchIgnoreCase, err = parseBool(rest)
c.MatchIgnoreCase, err = parse.Bool(rest)
case "ignoreMissing":
fieldSetting = true
c.IgnoreMissing, err = parseBool(rest)
c.IgnoreMissing, err = parse.Bool(rest)
case "skipCopySameType":
c.SkipCopySameType, err = parseBool(rest)
c.SkipCopySameType, err = parse.Bool(rest)
case "useZeroValueOnPointerInconsistency":
c.UseZeroValueOnPointerInconsistency, err = parseBool(rest)
c.UseZeroValueOnPointerInconsistency, err = parse.Bool(rest)
case "useUnderlyingTypeMethods":
c.UseUnderlyingTypeMethods, err = parseBool(rest)
c.UseUnderlyingTypeMethods, err = parse.Bool(rest)
case "enum":
c.Enum.Enabled, err = parseBool(rest)
c.Enum.Enabled, err = parse.Bool(rest)
case "arg:context:regex":
c.ArgContextRegex, err = parseRegex(rest)
c.ArgContextRegex, err = parse.Regex(rest)
case "enum:unknown":
c.Enum.Unknown, err = parseString(rest)
c.Enum.Unknown, err = parse.String(rest)
if err == nil && IsEnumAction(c.Enum.Unknown) {
err = validateEnumAction(c.Enum.Unknown)
}
Expand Down
3 changes: 2 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"sort"

"github.com/jmattheis/goverter/config/parse"
"github.com/jmattheis/goverter/enum"
"github.com/jmattheis/goverter/pkgload"
)
Expand Down Expand Up @@ -64,7 +65,7 @@ func Parse(raw *Raw) ([]*Converter, error) {
}

func formatLineError(lines RawLines, t, value string, err error) error {
cmd, _ := parseCommand(value)
cmd, _ := parse.Command(value)
msg := `error parsing 'goverter:%s' at
%s
%s
Expand Down
19 changes: 9 additions & 10 deletions config/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"fmt"
"go/types"
"path/filepath"
"regexp"
"strings"

"github.com/jmattheis/goverter/config/parse"
"github.com/jmattheis/goverter/enum"
"github.com/jmattheis/goverter/method"
"github.com/jmattheis/goverter/pkgload"
Expand All @@ -25,8 +25,7 @@ const (
)

var DefaultCommon = Common{
Enum: enum.Config{Enabled: true},
ArgContextRegex: regexp.MustCompile("^ctx|^context"),
Enum: enum.Config{Enabled: true},
}

var DefaultConfigInterface = ConverterConfig{
Expand Down Expand Up @@ -123,12 +122,12 @@ func initConverter(loader *pkgload.PackageLoader, rawConverter *RawConverter) (*

if rawConverter.InterfaceName != "" {
c.ConverterConfig = DefaultConfigInterface
v, err := loader.GetOneRaw(c.Package, rawConverter.InterfaceName)
_, interfaceObj, err := loader.GetOneRaw(c.Package, rawConverter.InterfaceName)
if err != nil {
return nil, err
}

c.typ = v.Type()
c.typ = interfaceObj.Type()
c.Name = rawConverter.InterfaceName + "Impl"
return c, nil
}
Expand All @@ -151,25 +150,25 @@ func parseConverterLines(ctx *context, c *Converter, source string, raw RawLines
}

func parseConverterLine(ctx *context, c *Converter, value string) (err error) {
cmd, rest := parseCommand(value)
cmd, rest := parse.Command(value)
switch cmd {
case "converter", "variables":
// only a marker interface
case "name":
if err = c.requireStruct(); err != nil {
return err
}
c.Name, err = parseString(rest)
c.Name, err = parse.String(rest)
case "output:raw":
c.OutputRaw = append(c.OutputRaw, rest)
case "output:file":
c.OutputFile, err = parseString(rest)
c.OutputFile, err = parse.String(rest)
case "output:format":
if len(c.Extend) != 0 {
return fmt.Errorf("Cannot change output:format after extend functions have been added.\nMove the extend below the output:format setting.")
}

c.OutputFormat, err = parseEnum(false, rest, FormatFunction, FormatStruct, FormatVariable)
c.OutputFormat, err = parse.Enum(false, rest, FormatFunction, FormatStruct, FormatVariable)
if err != nil {
return err
}
Expand All @@ -183,7 +182,7 @@ func parseConverterLine(ctx *context, c *Converter, value string) (err error) {
case "output:package":
c.OutputPackageName = ""
var pkg string
pkg, err = parseString(rest)
pkg, err = parse.String(rest)

parts := strings.SplitN(pkg, ":", 2)
switch len(parts) {
Expand Down
19 changes: 13 additions & 6 deletions config/method.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"strings"

"github.com/jmattheis/goverter/config/parse"
"github.com/jmattheis/goverter/method"
)

Expand All @@ -29,6 +30,7 @@ type Method struct {

Location string
updateParam string
localOpts method.LocalOpts
}

type FieldMapping struct {
Expand Down Expand Up @@ -60,11 +62,11 @@ func parseMethods(ctx *context, rawConverter *RawConverter, c *Converter) error
return nil
}
for name, lines := range rawConverter.Methods {
fun, err := ctx.Loader.GetOneRaw(c.Package, name)
_, fn, err := ctx.Loader.GetOneRaw(c.Package, name)
if err != nil {
return err
}
def, err := parseMethod(ctx, c, fun, lines)
def, err := parseMethod(ctx, c, fn, lines)
if err != nil {
return err
}
Expand All @@ -79,6 +81,7 @@ func parseMethod(ctx *context, c *Converter, obj types.Object, rawMethod RawLine
Fields: map[string]*FieldMapping{},
Location: rawMethod.Location,
EnumMapping: &EnumMapping{Map: map[string]string{}},
localOpts: method.LocalOpts{Context: map[string]bool{}},
}

for _, value := range rawMethod.Lines {
Expand All @@ -96,15 +99,15 @@ func parseMethod(ctx *context, c *Converter, obj types.Object, rawMethod RawLine
ContextMatch: m.ArgContextRegex,
Generated: true,
UpdateParam: m.updateParam,
})
}, m.localOpts)

m.Definition = def

return m, err
}

func parseMethodLine(ctx *context, c *Converter, m *Method, value string) (err error) {
cmd, rest := parseCommand(value)
cmd, rest := parse.Command(value)
fieldSetting := false
switch cmd {
case configMap:
Expand Down Expand Up @@ -135,7 +138,11 @@ func parseMethodLine(ctx *context, c *Converter, m *Method, value string) (err e
m.Field(f).Ignore = true
}
case "update":
m.updateParam, err = parseString(rest)
m.updateParam, err = parse.String(rest)
case "context":
var key string
key, err = parse.String(rest)
m.localOpts.Context[key] = true
case "enum:map":
fields := strings.Fields(rest)
if len(fields) != 2 {
Expand All @@ -161,7 +168,7 @@ func parseMethodLine(ctx *context, c *Converter, m *Method, value string) (err e
case "autoMap":
fieldSetting = true
var s string
s, err = parseString(rest)
s, err = parse.String(rest)
m.AutoMap = append(m.AutoMap, strings.TrimSpace(s))
case configDefault:
opts := &method.ParseOpts{
Expand Down
5 changes: 3 additions & 2 deletions config/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
"strings"

"github.com/jmattheis/goverter/config/parse"
"github.com/jmattheis/goverter/pkgload"
)

Expand All @@ -27,7 +28,7 @@ func getPackages(raw *Raw) []string {

func registerConverterLines(lookup map[string]struct{}, cwd string, lines RawLines) {
for _, line := range lines.Lines {
cmd, rest := parseCommand(line)
cmd, rest := parse.Command(line)
if cmd == configExtend {
for _, fullMethod := range strings.Fields(rest) {
registerFullMethod(lookup, cwd, fullMethod)
Expand All @@ -38,7 +39,7 @@ func registerConverterLines(lookup map[string]struct{}, cwd string, lines RawLin

func registerMethodLines(lookup map[string]struct{}, cwd string, lines RawLines) {
for _, line := range lines.Lines {
cmd, rest := parseCommand(line)
cmd, rest := parse.Command(line)
switch cmd {
case configMap:
if _, _, custom, err := parseMethodMap(rest); err == nil && custom != "" {
Expand Down
23 changes: 23 additions & 0 deletions config/parse/line.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package parse

import (
"bufio"
"strings"
)

const (
Prefix = "goverter"
Delimiter = ":"
)

func SettingLines(comment string) (lines []string) {
scanner := bufio.NewScanner(strings.NewReader(comment))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, Prefix+Delimiter) {
line := strings.TrimPrefix(line, Prefix+Delimiter)
lines = append(lines, line)
}
}
return lines
}
16 changes: 8 additions & 8 deletions config/primitive.go → config/parse/parse.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package config
package parse

import (
"fmt"
"regexp"
"strings"
)

func parseCommand(value string) (string, string) {
func Command(value string) (string, string) {
parts := strings.SplitN(value, " ", 2)
if len(parts) == 2 {
return parts[0], parts[1]
}
return parts[0], ""
}

func parseEnum[T ~string](empty bool, remaining string, values ...T) (T, error) {
func Enum[T ~string](empty bool, remaining string, values ...T) (T, error) {
fields := strings.Fields(remaining)

switch {
Expand All @@ -41,21 +41,21 @@ func formatValues[T ~string](values []T) string {
return strings.Join(strs, ", ")
}

func parseBool(remaining string) (bool, error) {
val, err := parseEnum(true, remaining, "yes", "no")
func Bool(remaining string) (bool, error) {
val, err := Enum(true, remaining, "yes", "no")
return val == "" || val == "yes", err
}

func parseString(remaining string) (string, error) {
func String(remaining string) (string, error) {
fields := strings.Fields(remaining)
if len(fields) != 1 {
return "", fmt.Errorf("must have one value but got %d: %#v", len(fields), remaining)
}
return fields[0], nil
}

func parseRegex(remaining string) (*regexp.Regexp, error) {
value, err := parseString(remaining)
func Regex(remaining string) (*regexp.Regexp, error) {
value, err := String(remaining)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit b953afb

Please sign in to comment.