File: relation.go

package info (click to toggle)
golang-github-juju-names 4.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, trixie
  • size: 340 kB
  • sloc: makefile: 14
file content (67 lines) | stat: -rw-r--r-- 2,182 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package names

import (
	"fmt"
	"regexp"
	"strings"
)

const RelationTagKind = "relation"

const RelationSnippet = "[a-z][a-z0-9]*(?:[_-][a-z0-9]+)*"

// Relation keys have the format "application1:relName1 application2:relName2".
// Except the peer relations, which have the format "application:relName"
// Relation tags have the format "relation-application1.rel1#application2.rel2".
// For peer relations, the format is "relation-application.rel"

var (
	validRelation     = regexp.MustCompile("^" + ApplicationSnippet + ":" + RelationSnippet + " " + ApplicationSnippet + ":" + RelationSnippet + "$")
	validPeerRelation = regexp.MustCompile("^" + ApplicationSnippet + ":" + RelationSnippet + "$")
)

// IsValidRelation returns whether key is a valid relation key.
func IsValidRelation(key string) bool {
	return validRelation.MatchString(key) || validPeerRelation.MatchString(key)
}

type RelationTag struct {
	key string
}

func (t RelationTag) String() string { return t.Kind() + "-" + t.key }
func (t RelationTag) Kind() string   { return RelationTagKind }
func (t RelationTag) Id() string     { return relationTagSuffixToKey(t.key) }

// NewRelationTag returns the tag for the relation with the given key.
func NewRelationTag(relationKey string) RelationTag {
	if !IsValidRelation(relationKey) {
		panic(fmt.Sprintf("%q is not a valid relation key", relationKey))
	}
	// Replace both ":" with "." and the " " with "#".
	relationKey = strings.Replace(relationKey, ":", ".", 2)
	relationKey = strings.Replace(relationKey, " ", "#", 1)
	return RelationTag{key: relationKey}
}

// ParseRelationTag parses a relation tag string.
func ParseRelationTag(relationTag string) (RelationTag, error) {
	tag, err := ParseTag(relationTag)
	if err != nil {
		return RelationTag{}, err
	}
	rt, ok := tag.(RelationTag)
	if !ok {
		return RelationTag{}, invalidTagError(relationTag, RelationTagKind)
	}
	return rt, nil
}

func relationTagSuffixToKey(s string) string {
	// Replace both "." with ":" and the "#" with " ".
	s = strings.Replace(s, ".", ":", 2)
	return strings.Replace(s, "#", " ", 1)
}