Skip to content

Commit

Permalink
allow to use field name and tag options together
Browse files Browse the repository at this point in the history
in case when you don't want to duplicate the field name in the
iso8583 tag, you can just skip it and set the rest of the options like
this:

```go
F2 *field.String `iso8583:",keepzero"`
```

then the field id will be derived from the field name and keepzero
option will be used as well
  • Loading branch information
alovak committed Oct 25, 2024
1 parent ec4d932 commit 3f9cf01
Showing 1 changed file with 34 additions and 29 deletions.
63 changes: 34 additions & 29 deletions field/index_tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ type IndexTag struct {
}

func NewIndexTag(field reflect.StructField) IndexTag {
indexTag := extractTagInfo(field)

if indexTag.Tag == "" {
id, tag := extractIdAndTagFromName(field.Name)
indexTag.ID = id
indexTag.Tag = tag
}

return indexTag
}

func extractTagInfo(field reflect.StructField) IndexTag {
// value of the key "index" in the tag
var value string

Expand All @@ -35,41 +47,37 @@ func NewIndexTag(field reflect.StructField) IndexTag {
// format of the value is "id[,keep_zero_value]"
// id is the id of the field
// let's parse it
if value != "" {
tag, opts := parseTag(value)

id, err := strconv.Atoi(tag)
if err != nil {
id = -1
}

if value == "" {
return IndexTag{
ID: id,
Tag: tag,
KeepZero: opts.Contains("keepzero"),
ID: -1,
}
}

dataFieldName := field.Name
if len(dataFieldName) > 0 && fieldNameIndexRe.MatchString(dataFieldName) {
indexStr := dataFieldName[1:]
tag, opts := parseTag(value)
id, err := strconv.Atoi(tag)
if err != nil {
id = -1
}

return IndexTag{
ID: id,
Tag: tag,
KeepZero: opts.Contains("keepzero"),
}
}

func extractIdAndTagFromName(fieldName string) (int, string) {
if len(fieldName) > 0 && fieldNameIndexRe.MatchString(fieldName) {
indexStr := fieldName[1:]
fieldIndex, err := strconv.Atoi(indexStr)
if err != nil {
return IndexTag{
ID: -1,
Tag: indexStr,
}
return -1, indexStr
}

return IndexTag{
ID: fieldIndex,
Tag: indexStr,
}
return fieldIndex, indexStr
}

return IndexTag{
ID: -1,
}
return -1, ""
}

type tagOptions []string
Expand All @@ -78,16 +86,13 @@ type tagOptions []string
// comma-separated options.
func parseTag(tag string) (string, tagOptions) {
tag, opt, _ := strings.Cut(tag, ",")

return tag, tagOptions(strings.Split(opt, ","))
}

// Contains reports whether a comma-separated list of options
// contains a particular substr flag. substr must be surrounded by a
// string boundary or commas.
func (o tagOptions) Contains(optionName string) bool {
if len(o) == 0 {
return false
}

return slices.Contains(o, optionName)
}

0 comments on commit 3f9cf01

Please sign in to comment.