launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/names/relation.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  const RelationSnippet = "[a-z][a-z0-9]*([_-][a-z0-9]+)*"
    13  
    14  // Relation keys have the format "service1:relName1 service2:relName2".
    15  // Except the peer relations, which have the format "service:relName"
    16  // Relation tags have the format "relation-service1.rel1#service2.rel2".
    17  // For peer relations, the format is "relation-service.rel"
    18  
    19  var (
    20  	validRelation     = regexp.MustCompile("^" + ServiceSnippet + ":" + RelationSnippet + " " + ServiceSnippet + ":" + RelationSnippet + "$")
    21  	validPeerRelation = regexp.MustCompile("^" + ServiceSnippet + ":" + RelationSnippet + "$")
    22  )
    23  
    24  // IsRelation returns whether key is a valid relation key.
    25  func IsRelation(key string) bool {
    26  	return validRelation.MatchString(key) || validPeerRelation.MatchString(key)
    27  }
    28  
    29  // RelationTag returns the tag for the relation with the given key.
    30  func RelationTag(relationKey string) string {
    31  	if !IsRelation(relationKey) {
    32  		panic(fmt.Sprintf("%q is not a valid relation key", relationKey))
    33  	}
    34  	// Replace both ":" with "." and the " " with "#".
    35  	relationKey = strings.Replace(relationKey, ":", ".", 2)
    36  	relationKey = strings.Replace(relationKey, " ", "#", 1)
    37  	return makeTag(RelationTagKind, relationKey)
    38  }
    39  
    40  func relationTagSuffixToKey(s string) string {
    41  	// Replace both "." with ":" and the "#" with " ".
    42  	s = strings.Replace(s, ".", ":", 2)
    43  	return strings.Replace(s, "#", " ", 1)
    44  }