cuelang.org/go@v0.10.1/mod/modregistry/metadata.go (about)

     1  package modregistry
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  // Metadata holds extra information that can be associated with
    10  // a module. It is stored in the module's manifest inside
    11  // the annotations field. All fields must JSON-encode to
    12  // strings.
    13  type Metadata struct {
    14  	VCSType       string    `json:"org.cuelang.vcs-type"`
    15  	VCSCommit     string    `json:"org.cuelang.vcs-commit"`
    16  	VCSCommitTime time.Time `json:"org.cuelang.vcs-commit-time"`
    17  }
    18  
    19  func newMetadataFromAnnotations(annotations map[string]string) (*Metadata, error) {
    20  	// TODO if this ever turned out to be a bottleneck we could
    21  	// improve performance by avoiding the round-trip through JSON.
    22  	raw, err := json.Marshal(annotations)
    23  	if err != nil {
    24  		// Should never happen.
    25  		return nil, err
    26  	}
    27  	var m Metadata
    28  	if err := json.Unmarshal(raw, &m); err != nil {
    29  		return nil, err
    30  	}
    31  	return &m, nil
    32  }
    33  
    34  func (m *Metadata) annotations() (map[string]string, error) {
    35  	// The "is-empty" checks don't work for time.Time
    36  	// so check explicitly.
    37  	if m.VCSCommitTime.IsZero() {
    38  		return nil, fmt.Errorf("no commit time in metadata")
    39  	}
    40  	// TODO if this ever turned out to be a bottleneck we could
    41  	// improve performance by avoiding the round-trip through JSON.
    42  	data, err := json.Marshal(m)
    43  	if err != nil {
    44  		// Should never happen.
    45  		return nil, err
    46  	}
    47  	var annotations map[string]string
    48  	if err := json.Unmarshal(data, &annotations); err != nil {
    49  		// Should never happen.
    50  		return nil, err
    51  	}
    52  	for field, val := range annotations {
    53  		if val == "" {
    54  			return nil, fmt.Errorf("empty metadata value for field %q", field)
    55  		}
    56  	}
    57  	return annotations, nil
    58  }