github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/names/unit.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package names
     5  
     6  import (
     7  	"fmt"
     8  	"regexp"
     9  	"strings"
    10  )
    11  
    12  var validUnit = regexp.MustCompile("^" + ServiceSnippet + "/" + NumberSnippet + "$")
    13  
    14  // UnitTag returns the tag for the unit with the given name.
    15  // It will panic if the given unit name is not valid.
    16  func UnitTag(unitName string) string {
    17  	// Replace only the last "/" with "-".
    18  	i := strings.LastIndex(unitName, "/")
    19  	if i <= 0 || !IsUnit(unitName) {
    20  		panic(fmt.Sprintf("%q is not a valid unit name", unitName))
    21  	}
    22  	unitName = unitName[:i] + "-" + unitName[i+1:]
    23  	return makeTag(UnitTagKind, unitName)
    24  }
    25  
    26  // IsUnit returns whether name is a valid unit name.
    27  func IsUnit(name string) bool {
    28  	return validUnit.MatchString(name)
    29  }
    30  
    31  // UnitService returns the name of the service that the unit is
    32  // associated with. It panics if unitName is not a valid unit name.
    33  func UnitService(unitName string) string {
    34  	s := validUnit.FindStringSubmatch(unitName)
    35  	if s == nil {
    36  		panic(fmt.Sprintf("%q is not a valid unit name", unitName))
    37  	}
    38  	return s[1]
    39  }
    40  
    41  func unitTagSuffixToId(s string) string {
    42  	// Replace only the last "-" with "/", as it is valid for service
    43  	// names to contain hyphens.
    44  	if i := strings.LastIndex(s, "-"); i > 0 {
    45  		s = s[:i] + "/" + s[i+1:]
    46  	}
    47  	return s
    48  }