github.phpd.cn/thought-machine/please@v12.2.0+incompatible/src/core/subrepo.go (about)

     1  package core
     2  
     3  import (
     4  	"cli"
     5  	"fmt"
     6  	"path"
     7  	"strings"
     8  )
     9  
    10  // A Subrepo stores information about a registered subrepository, typically one
    11  // that we have downloaded somehow to bring in third-party deps.
    12  type Subrepo struct {
    13  	// The name of the subrepo.
    14  	Name string
    15  	// The root directory to load it from.
    16  	Root string
    17  	// If this repo is output by a target, this is the target that creates it. Can be nil.
    18  	Target *BuildTarget
    19  	// If this repo has a different configuration (e.g. it's for a different architecture), it's stored here
    20  	State *BuildState
    21  	// True if this subrepo was created for a different architecture
    22  	IsCrossCompile bool
    23  }
    24  
    25  // SubrepoForArch creates a new subrepo for the given architecture.
    26  func SubrepoForArch(state *BuildState, arch cli.Arch) *Subrepo {
    27  	return &Subrepo{
    28  		Name:           arch.String(),
    29  		State:          state.ForArch(arch),
    30  		IsCrossCompile: true,
    31  	}
    32  }
    33  
    34  // MakeRelative makes a build label that is within this subrepo relative to it (i.e. strips the leading name part).
    35  // The caller should already know that it is within this repo, otherwise this will panic.
    36  func (s *Subrepo) MakeRelative(label BuildLabel) BuildLabel {
    37  	return BuildLabel{s.MakeRelativeName(label.PackageName), label.Name}
    38  }
    39  
    40  // MakeRelativeName is as MakeRelative but operates only on the package name.
    41  func (s *Subrepo) MakeRelativeName(name string) string {
    42  	// Check for nil, makes it easier to call this without having so many conditionals.
    43  	if s == nil {
    44  		return name
    45  	} else if !strings.HasPrefix(name, s.Name) {
    46  		panic(fmt.Errorf("cannot make label %s relative, it is not within this subrepo (%s)", name, s.Name))
    47  	}
    48  	return strings.TrimPrefix(name[len(s.Name):], "/")
    49  }
    50  
    51  // Dir returns the directory for a package of this name.
    52  func (s *Subrepo) Dir(dir string) string {
    53  	return path.Join(s.Root, s.MakeRelativeName(dir))
    54  }