generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
deployment_name.go
83 lines (71 loc) · 1.77 KB
/
deployment_name.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package model
import (
"crypto/rand"
"database/sql"
"database/sql/driver"
"encoding"
"encoding/hex"
"fmt"
"strings"
"github.com/alecthomas/errors"
"github.com/alecthomas/types"
)
type DeploymentName string
type MaybeDeploymentName types.Option[DeploymentName]
var _ interface {
sql.Scanner
driver.Valuer
encoding.TextUnmarshaler
encoding.TextMarshaler
} = (*DeploymentName)(nil)
func NewDeploymentName(module string) DeploymentName {
hash := make([]byte, 5)
_, err := rand.Read(hash)
if err != nil {
panic(err)
}
return DeploymentName(fmt.Sprintf("%s-%010x", module, hash))
}
func ParseDeploymentName(name string) (DeploymentName, error) {
var zero DeploymentName
parts := strings.Split(name, "-")
if len(parts) < 2 {
return zero, errors.Errorf("should be at least <deployment>-<hash>: invalid deployment name %q", name)
}
hash, err := hex.DecodeString(parts[len(parts)-1])
if err != nil {
return zero, errors.Wrapf(err, "invalid deployment name %q", name)
}
if len(hash) != 5 {
return zero, errors.Errorf("hash should be 5 bytes: invalid deployment name %q", name)
}
return DeploymentName(fmt.Sprintf("%s-%010x", strings.Join(parts[0:len(parts)-1], "-"), hash)), nil
}
func (d *DeploymentName) String() string {
return string(*d)
}
func (d *DeploymentName) UnmarshalText(bytes []byte) error {
name, err := ParseDeploymentName(string(bytes))
if err != nil {
return err
}
*d = name
return nil
}
func (d *DeploymentName) MarshalText() ([]byte, error) {
return []byte(*d), nil
}
func (d *DeploymentName) Scan(value any) error {
if value == nil {
return nil
}
name, err := ParseDeploymentName(value.(string))
if err != nil {
return err
}
*d = name
return nil
}
func (d *DeploymentName) Value() (driver.Value, error) {
return d.String(), nil
}