-
Notifications
You must be signed in to change notification settings - Fork 9
/
instantiation.go
61 lines (50 loc) · 1.56 KB
/
instantiation.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package core
import (
"context"
"strings"
"namespacelabs.dev/foundation/schema"
)
type ctxKey struct{}
type InstantiationPath struct {
// TODO this can collide (e.g. if a service instantiates two dbs of the same type).
// Consider adding a way to differentiate.
path []schema.PackageName
}
func (ip *InstantiationPath) Last() schema.PackageName {
if len(ip.path) == 0 {
return ""
}
return ip.path[len(ip.path)-1]
}
func (ip *InstantiationPath) String() string {
var a []string
for _, step := range ip.path {
a = append(a, step.String())
}
return strings.Join(a, ",")
}
// InstantiationPathFromContext returns the InstantiationPath associated with the ctx.
// If no logger is associated, nil is returned
func InstantiationPathFromContext(ctx context.Context) *InstantiationPath {
v := ctx.Value(ctxKey{})
if v == nil {
return nil
}
return v.(*InstantiationPath)
}
// WithContext returns a copy of ctx with ip associated. If an instance of InstantiationPath
// is already in the context, the value is overwritten.
func (ip *InstantiationPath) WithContext(ctx context.Context) context.Context {
return context.WithValue(ctx, ctxKey{}, ip)
}
func (ip *InstantiationPath) Append(pkg schema.PackageName) *InstantiationPath {
if ip == nil {
return &InstantiationPath{path: []schema.PackageName{pkg}}
}
copy := *ip
copy.path = append(copy.path, pkg)
return ©
}