github.com/octohelm/cuekit@v0.0.0-20240424021256-e7df8d743066/pkg/mod/modfile/file_ovewrites.go (about)

     1  package modfile
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"sync"
     7  
     8  	"cuelang.org/go/cue"
     9  	"cuelang.org/go/cue/ast"
    10  	"cuelang.org/go/cue/cuecontext"
    11  	"cuelang.org/go/cue/format"
    12  	"cuelang.org/go/mod/module"
    13  )
    14  
    15  type FileOverwrites struct {
    16  	Deps map[string]*DepOverwrite `json:"deps,omitempty"`
    17  
    18  	// Path resolved
    19  	Path string `json:"path,omitempty"`
    20  	// Version resolved
    21  	Version string `json:"version,omitempty"`
    22  
    23  	mu sync.RWMutex
    24  }
    25  
    26  func (f *FileOverwrites) AddDep(mpath string, dep *DepOverwrite) {
    27  	f.mu.Lock()
    28  	defer f.mu.Unlock()
    29  
    30  	if f.Deps == nil {
    31  		f.Deps = map[string]*DepOverwrite{}
    32  	}
    33  	f.Deps[mpath] = dep
    34  }
    35  
    36  func (f *FileOverwrites) GetDep(mpath string) (*DepOverwrite, bool) {
    37  	f.mu.Lock()
    38  	defer f.mu.Unlock()
    39  
    40  	if len(f.Deps) == 0 {
    41  		return nil, false
    42  	}
    43  
    44  	dep, ok := f.Deps[mpath]
    45  	if ok {
    46  		return dep, true
    47  	}
    48  
    49  	for m, dep := range f.Deps {
    50  		base, _, ok := module.SplitPathVersion(m)
    51  		if ok && base == mpath {
    52  			return dep, true
    53  		}
    54  	}
    55  
    56  	return nil, false
    57  }
    58  
    59  func (f *FileOverwrites) Format() ([]byte, error) {
    60  	v := cuecontext.New().Encode(f)
    61  	if err := v.Validate(cue.Concrete(true)); err != nil {
    62  		return nil, err
    63  	}
    64  	n := v.Syntax(cue.Concrete(true)).(*ast.StructLit)
    65  	data, err := format.Node(&ast.File{
    66  		Decls: n.Elts,
    67  	})
    68  	if err != nil {
    69  		return nil, fmt.Errorf("cannot format: %v", err)
    70  	}
    71  	return data, err
    72  }
    73  
    74  func (f *FileOverwrites) Load(data []byte) error {
    75  	v := cuecontext.New().CompileBytes(data)
    76  	if err := v.Validate(); err != nil {
    77  		return err
    78  	}
    79  	if err := v.Decode(f); err != nil {
    80  		return err
    81  	}
    82  	return nil
    83  }
    84  
    85  func (f *FileOverwrites) IsZero() bool {
    86  	return f == nil || (f.Version == "") && len(f.Deps) == 0
    87  }
    88  
    89  type DepOverwrite struct {
    90  	Path    string `json:"path,omitempty"`
    91  	Source  string `json:"source,omitempty"`
    92  	Version string `json:"v,omitempty"`
    93  }
    94  
    95  func (o *DepOverwrite) IsLocalReplacement() bool {
    96  	return o.Path != "" && strings.HasPrefix(o.Path, ".")
    97  }