github.com/djui/moq@v0.3.3/internal/registry/package.go (about)

     1  package registry
     2  
     3  import (
     4  	"go/types"
     5  	"path"
     6  	"strings"
     7  )
     8  
     9  // Package represents an imported package.
    10  type Package struct {
    11  	pkg *types.Package
    12  
    13  	Alias string
    14  }
    15  
    16  // NewPackage creates a new instance of Package.
    17  func NewPackage(pkg *types.Package) *Package { return &Package{pkg: pkg} }
    18  
    19  // Qualifier returns the qualifier which must be used to refer to types
    20  // declared in the package.
    21  func (p *Package) Qualifier() string {
    22  	if p == nil {
    23  		return ""
    24  	}
    25  
    26  	if p.Alias != "" {
    27  		return p.Alias
    28  	}
    29  
    30  	return p.pkg.Name()
    31  }
    32  
    33  // Path is the full package import path (without vendor).
    34  func (p *Package) Path() string {
    35  	if p == nil {
    36  		return ""
    37  	}
    38  
    39  	return stripVendorPath(p.pkg.Path())
    40  }
    41  
    42  var replacer = strings.NewReplacer(
    43  	"go-", "",
    44  	"-go", "",
    45  	"-", "",
    46  	"_", "",
    47  	".", "",
    48  	"@", "",
    49  	"+", "",
    50  	"~", "",
    51  )
    52  
    53  // uniqueName generates a unique name for a package by concatenating
    54  // path components. The generated name is guaranteed to unique with an
    55  // appropriate level because the full package import paths themselves
    56  // are unique.
    57  func (p Package) uniqueName(lvl int) string {
    58  	pp := strings.Split(p.Path(), "/")
    59  	reverse(pp)
    60  
    61  	var name string
    62  	for i := 0; i < min(len(pp), lvl+1); i++ {
    63  		name = strings.ToLower(replacer.Replace(pp[i])) + name
    64  	}
    65  
    66  	return name
    67  }
    68  
    69  // stripVendorPath strips the vendor dir prefix from a package path.
    70  // For example we might encounter an absolute path like
    71  // github.com/foo/bar/vendor/github.com/pkg/errors which is resolved
    72  // to github.com/pkg/errors.
    73  func stripVendorPath(p string) string {
    74  	parts := strings.Split(p, "/vendor/")
    75  	if len(parts) == 1 {
    76  		return p
    77  	}
    78  	return strings.TrimLeft(path.Join(parts[1:]...), "/")
    79  }
    80  
    81  func min(a, b int) int {
    82  	if a < b {
    83  		return a
    84  	}
    85  	return b
    86  }
    87  
    88  func reverse(a []string) {
    89  	for i := len(a)/2 - 1; i >= 0; i-- {
    90  		opp := len(a) - 1 - i
    91  		a[i], a[opp] = a[opp], a[i]
    92  	}
    93  }