Skip to content

Commit

Permalink
code quality; cleanup; comments etc. (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
bobiverse authored Sep 17, 2024
1 parent 551ce15 commit 487b309
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 112 deletions.
2 changes: 1 addition & 1 deletion Param.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ type Param struct {
Formatter *ParamFormatter

RowPlaceholder string
Index int //slice data index,expandPlaceholders function needs
Index int // slice data index,expandPlaceholders function needs
}

// NewParam ..
Expand Down
6 changes: 3 additions & 3 deletions ParamFormatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ const (
FormatCapitalize = ":capitalize"
)

// ParamFormatter ..
type ParamFormatter struct {
raw string

raw string
Format string
}

Expand Down Expand Up @@ -51,7 +51,7 @@ func NewFormatter(raw []byte) *ParamFormatter {
return f
}

// applyFormat - apply formatting to the given content based on the formatter
// ApplyFormat - apply formatting to the given content based on the formatter
func (p *ParamFormatter) ApplyFormat(format string, content []byte) []byte {
switch format {
case FormatLower:
Expand Down
78 changes: 44 additions & 34 deletions ParamList.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
type ParamList []*Param

// Get method returns the value associated with the given name
func (plist ParamList) Get(key string) any {
for _, p := range plist {
func (params ParamList) Get(key string) any {
for _, p := range params {
if p.Key == key {
return p.Value
}
Expand All @@ -22,8 +22,8 @@ func (plist ParamList) Get(key string) any {
}

// Len ..
func (p ParamList) Len() int {
return len(p)
func (params ParamList) Len() int {
return len(params)
}

// AnyToParams - load params from given any struct
Expand Down Expand Up @@ -234,16 +234,16 @@ func rowParams(row []byte) ParamList {
return nil
}

var list []*Param
var params ParamList
for _, match := range matches {
p := NewParam(string(match[2]))
p.RowPlaceholder = string(match[0])
p.Separator = string(match[3])
p.Trigger = NewParamTrigger(match[4])
p.Formatter = NewFormatter(match[4])
list = append(list, p)
params = append(params, p)
}
return list
return params
}

// Walk through params
Expand All @@ -255,6 +255,7 @@ func (params ParamList) Walk(fn func(*Param)) {
}
}

// WalkWithEnd - recursively apply fn to each Param in the list
func (params ParamList) WalkWithEnd(fn func(*Param) bool) {
for _, p := range params {
if fn(p) {
Expand All @@ -264,53 +265,62 @@ func (params ParamList) WalkWithEnd(fn func(*Param) bool) {
}
}

func (p ParamList) FindAllByKey(key string) []*Param {
// FindAllByKey - returns all Params matching the given key
func (params ParamList) FindAllByKey(key string) ParamList {
keySlice := strings.Split(key, ".")
var ret []*Param
p.findAllByKey(nil, nil, 0, 1, keySlice, &ret)
var ret ParamList
params.findAllByKey(nil, nil, 0, 1, keySlice, &ret)
return ret
}

func (p ParamList) findAllByKey(privParamList, paramList []int, offset, depth int, key []string, params *[]*Param) ([]int, int) {
func (params ParamList) findAllByKey(privParamList, paramList []int, offset, depth int, key []string, paramsIn *ParamList) ([]int, int) {
if depth > len(key) {
return nil, 0
}
currLev := strings.Join(key[:depth], ".")
for i, param := range p {
for i, param := range params {
curr := make([]int, len(paramList))
copy(curr, paramList)

if param.parent != nil && param.parent.Type == SliceParam {
curr = append(curr, i+1)
}

if param.Type == StructParam {
privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth+1, key, params)
} else {
if param.CompactKey == currLev || param.AbsoluteKey == currLev {
if param.Type == SliceParam {
privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth, key, params)
continue
}
if depth == len(key) {
index := 1
if len(curr) > 0 {
index = curr[len(curr)-1]
if len(curr) == len(privParamList) {
for i := range curr[:len(curr)-1] {
if privParamList[i] != curr[i] {
offset += privParamList[len(privParamList)-1]
break
}
privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth+1, key, paramsIn)
continue
}

if param.CompactKey == currLev || param.AbsoluteKey == currLev {

if param.Type == SliceParam {
privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth, key, paramsIn)
continue
}

if depth == len(key) {
index := 1
if len(curr) > 0 {
index = curr[len(curr)-1]
if len(curr) == len(privParamList) {
for i := range curr[:len(curr)-1] {
if privParamList[i] != curr[i] {
offset += privParamList[len(privParamList)-1]
break
}
}
}
param.Index = index + offset
privParamList = curr
*params = append(*params, param)
} else {
privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth+1, key, params)
}
param.Index = index + offset
privParamList = curr
*paramsIn = append(*paramsIn, param)
continue
}

privParamList, offset = param.Params.findAllByKey(privParamList, curr, offset, depth+1, key, paramsIn)

}

}
return privParamList, offset
}
14 changes: 10 additions & 4 deletions Template.helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,29 +119,35 @@ func (t *Template) matchBrokenLeftPlaceholder(content string) bool {
return t.matchBrokenPlaceholder(content, true)
}

// Match right placeholder part `}}`
func (t *Template) matchBrokenRightPlaceholder(content string) bool {
return t.matchBrokenPlaceholder(content, false)
}
// UNUSED
// // Match right placeholder part `}}`
// func (t *Template) matchBrokenRightPlaceholder(content string) bool {
// return t.matchBrokenPlaceholder(content, false)
// }

// GetAttrParam - extracts and returns substrings enclosed in double curly braces "{{...}}" from the given string
func (t Template) GetAttrParam(attr string) []string {
var ret []string
var record strings.Builder
start := false
length := len(attr)
for i := 1; i < length-1; i++ {

if attr[i] == '{' && attr[i-1] == '{' {
start = true
continue
}

if start && (attr[i] == ' ' || (attr[i] == '}' && length-1 > i && attr[i+1] == '}')) {
ret = append(ret, record.String())
record.Reset()
start = false
}

if start {
record.WriteByte(attr[i])
}
}

return ret
}
7 changes: 2 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
module github.com/bobiverse/docxplate

go 1.22
go 1.23.0

require (
github.com/logrusorgru/aurora/v4 v4.0.0
golang.org/x/text v0.16.0
)
require golang.org/x/text v0.18.0
14 changes: 2 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,12 +1,2 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/logrusorgru/aurora/v4 v4.0.0 h1:sRjfPpun/63iADiSvGGjgA1cAYegEWMPCJdUpJYn9JA=
github.com/logrusorgru/aurora/v4 v4.0.0/go.mod h1:lP0iIa2nrnT/qoFXcOZSrZQpJ1o6n2CUf/hyHi2Q4ZQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
2 changes: 1 addition & 1 deletion t.params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestAnyToParamsMapStringString(t *testing.T) {
}

// check if all params exists
for k, _ := range inParams {
for k := range inParams {
if p := outParams.Get(k); p == nil {
t.Fatalf("param `%s` not found", k)
}
Expand Down
106 changes: 54 additions & 52 deletions xml.node.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"regexp"
"slices"
"strings"

"github.com/logrusorgru/aurora/v4"
)

// NodeSingleTypes - NB! sequence is important
Expand Down Expand Up @@ -144,7 +142,9 @@ func (xnode *xmlNode) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
// MarshalXML ..
func (xnode *xmlNode) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
// n.Attrs = start.Attr
defer e.Close()
defer func() {
_ = e.Close()
}()
return xnode.XMLEncode(e)

}
Expand Down Expand Up @@ -346,7 +346,7 @@ func (xnode *xmlNode) cloneAndAppend() *xmlNode {
return xnode
}
// new copy node
nnew := xnode.clone(xnode.parent) //set parent
nnew := xnode.clone(xnode.parent) // set parent
nnew.isNew = true

tmp := xnode.next
Expand Down Expand Up @@ -473,65 +473,67 @@ func (xnode *xmlNode) String() string {
return s
}

// Print tree of node and down
func (xnode *xmlNode) printTree(label string) {
fmt.Printf("[ %s ]", label)
fmt.Println("|" + strings.Repeat("-", 80))
// UNUSED - but kept for debugging
// // Print tree of node and down
// func (xnode *xmlNode) printTree(label string) {
// fmt.Printf("[ %s ]", label)
// fmt.Println("|" + strings.Repeat("-", 80))

if xnode == nil {
aurora.Red("Empty node.")
return
}
fmt.Printf("|%s |%p| %s\n", xnode.XMLName.Local, xnode, xnode.Content)
// if xnode == nil {
// aurora.Red("Empty node.")
// return
// }
// fmt.Printf("|%s |%p| %s\n", xnode.XMLName.Local, xnode, xnode.Content)

xnode.WalkTree(0, func(depth int, n *xmlNode) {
s := "|"
s += strings.Repeat(" ", depth*4)
// xnode.WalkTree(0, func(depth int, n *xmlNode) {
// s := "|"
// s += strings.Repeat(" ", depth*4)

// tag
s += fmt.Sprintf("%-10s", n.XMLName.Local)
if xnode.isNew {
s = aurora.Cyan(s).String()
}
// // tag
// s += fmt.Sprintf("%-10s", n.XMLName.Local)
// if xnode.isNew {
// s = aurora.Cyan(s).String()
// }

// pointers
s += fmt.Sprintf("|%p|", n)
sptr := fmt.Sprintf("|%p| ", n.parent)
if n.parent == nil {
sptr = aurora.Red(sptr).String()
}
s += sptr
// // pointers
// s += fmt.Sprintf("|%p|", n)
// sptr := fmt.Sprintf("|%p| ", n.parent)
// if n.parent == nil {
// sptr = aurora.Red(sptr).String()
// }
// s += sptr

if isListItem, listID := n.IsListItem(); isListItem {
s += fmt.Sprintf(" (List:%s) ", aurora.Blue(listID))
}
// if isListItem, listID := n.IsListItem(); isListItem {
// s += fmt.Sprintf(" (List:%s) ", aurora.Blue(listID))
// }

if bytes.TrimSpace(n.Content) != nil {
s += fmt.Sprintf("[%s]", aurora.Yellow(n.Content))
} else if n.HaveParams() {
s += aurora.Magenta("<< empty param value >>").String()
}
// if bytes.TrimSpace(n.Content) != nil {
// s += fmt.Sprintf("[%s]", aurora.Yellow(n.Content))
// } else if n.HaveParams() {
// s += aurora.Magenta("<< empty param value >>").String()
// }

// s += aurora.Cyan(" -- %s", n.StylesString())
// // s += aurora.Cyan(" -- %s", n.StylesString())

fmt.Println(s)
})
// fmt.Println(s)
// })

fmt.Println("|" + strings.Repeat("-", 80))
}
// fmt.Println("|" + strings.Repeat("-", 80))
// }

func (xnode *xmlNode) attrID() string {
if xnode == nil {
return ""
}
// UNUSED
// func (xnode *xmlNode) attrID() string {
// if xnode == nil {
// return ""
// }

for _, attr := range xnode.Attrs {
if attr.Name.Local == "id" {
return attr.Value
}
}
return ""
}
// for _, attr := range xnode.Attrs {
// if attr.Name.Local == "id" {
// return attr.Value
// }
// }
// return ""
// }

// ^ > w-p > w-pPr > w-numPr > w-numId
func (xnode *xmlNode) nodeBySelector(selector string) *xmlNode {
Expand Down

0 comments on commit 487b309

Please sign in to comment.