Skip to content
This repository has been archived by the owner on Nov 18, 2021. It is now read-only.

cue: add function for Value.Attributes() #529

Closed
wants to merge 5 commits into from
Closed
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
34 changes: 34 additions & 0 deletions cue/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2151,11 +2151,45 @@ func (v Value) Attribute(key string) Attribute {
return Attribute{internal.NewNonExisting(key)}
}

// Attributes reports all field attributes for the Value.
func (v Value) Attributes() []Attribute {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See CL-level comment.

attrs := []Attribute{}

// return empty when vertex is nil
if v.v == nil {
return attrs
}

// collect attribues
for _, a := range export.ExtractFieldAttrs(v.v.Conjuncts) {
key, body := a.Split()
A := Attribute{internal.ParseAttrBody(token.NoPos, body)}
A.attr.Name = key
attrs = append(attrs, A)
}

return attrs
}

// An Attribute contains meta data about a field.
type Attribute struct {
attr internal.Attr
}

// Name returns the '@name(...)' for the Attribute.
func (a *Attribute) Name() string {
return a.attr.Name
}

// Map returns all key/value pairs for the attribute as a map
func (a *Attribute) Map() map[string]string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method should be removed.

ret := map[string]string{}
for _, F := range a.attr.Fields {
ret[F.Key()] = F.Value()
}
return ret
}

// Err returns the error associated with this Attribute or nil if this
// attribute is valid.
func (a *Attribute) Err() error {
Expand Down
11 changes: 10 additions & 1 deletion internal/attrs.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

// Attr holds positional information for a single Attr.
type Attr struct {
Name string
Fields []keyValue
Err error
}
Expand All @@ -42,8 +43,16 @@ type keyValue struct {
}

func (kv *keyValue) Text() string { return kv.data }
func (kv *keyValue) Key() string { return kv.data[:kv.equal] }
func (kv *keyValue) Key() string {
if kv.equal == 0 {
return kv.data
}
return kv.data[:kv.equal]
}
func (kv *keyValue) Value() string {
if kv.equal == 0 {
return ""
}
return strings.TrimSpace(kv.data[kv.equal+1:])
}

Expand Down