github.com/sirkon/goproxy@v1.4.8/plugin/apriori/module.go (about)

     1  package apriori
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"sort"
    10  
    11  	"github.com/sirkon/goproxy/internal/errors"
    12  
    13  	"github.com/sirkon/goproxy"
    14  	"github.com/sirkon/goproxy/semver"
    15  )
    16  
    17  type aprioriModule struct {
    18  	path string
    19  	mod  map[string]ModuleInfo
    20  }
    21  
    22  func (s *aprioriModule) ModulePath() string {
    23  	return s.path
    24  }
    25  
    26  func (s *aprioriModule) Versions(ctx context.Context, prefix string) (tags []string, err error) {
    27  	for version := range s.mod {
    28  		tags = append(tags, version)
    29  	}
    30  	for _, tag := range tags {
    31  		if !semver.IsValid(tag) {
    32  			return nil, errors.Newf("apriori invalid semver value %s", tag)
    33  		}
    34  	}
    35  	sort.Slice(tags, func(i, j int) bool {
    36  		return semver.Compare(tags[i], tags[j]) < 0
    37  	})
    38  	return
    39  }
    40  
    41  func (s *aprioriModule) Stat(ctx context.Context, rev string) (*goproxy.RevInfo, error) {
    42  	res, ok := s.mod[rev]
    43  	if !ok {
    44  		return nil, errors.New(s.errMsg("apriori version %s not found", rev))
    45  	}
    46  	return &res.RevInfo, nil
    47  }
    48  
    49  func (s *aprioriModule) GoMod(ctx context.Context, version string) (data []byte, err error) {
    50  	item, ok := s.mod[version]
    51  	if !ok {
    52  		return nil, errors.Newf("apriori module %s: version %s not found", s.path, version)
    53  	}
    54  	data, err = ioutil.ReadFile(item.GoModPath)
    55  	if err != nil {
    56  		return nil, errors.Wrap(err, s.errMsg("getting go.mod file for version %s", version))
    57  	}
    58  	return
    59  }
    60  
    61  func (s *aprioriModule) Zip(ctx context.Context, version string) (file io.ReadCloser, err error) {
    62  	item, ok := s.mod[version]
    63  	if !ok {
    64  		return nil, errors.Newf("apriori module %s: version %s not found", s.path, version)
    65  	}
    66  	file, err = os.Open(item.ArchivePath)
    67  	if err != nil {
    68  		return nil, errors.Wrap(err, s.errMsg("apriori getting archive file for version %s", version))
    69  	}
    70  	return
    71  }
    72  
    73  func (s *aprioriModule) errMsg(format string, a ...interface{}) string {
    74  	head := "module " + s.path + ": "
    75  	return fmt.Sprintf(head+format, a...)
    76  }