leases: add WithLabel

This adds a new WithLabel function, which allows to set a single label on
a lease, without having to first construct an intermediate map[string]string.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-09-11 18:39:57 +02:00
parent 1480e3bd4f
commit f7089ba225
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
3 changed files with 45 additions and 14 deletions

View File

@ -75,9 +75,7 @@ When you are done, use the unmount command.
ctx, done, err := client.WithLease(ctx,
leases.WithID(target),
leases.WithExpiration(24*time.Hour),
leases.WithLabels(map[string]string{
"containerd.io/gc.ref.snapshot." + snapshotter: target,
}),
leases.WithLabel("containerd.io/gc.ref.snapshot."+snapshotter, target),
)
if err != nil && !errdefs.IsAlreadyExists(err) {
return err

View File

@ -65,6 +65,19 @@ func SynchronousDelete(ctx context.Context, o *DeleteOptions) error {
return nil
}
// WithLabel sets a label on a lease, and merges it with existing labels.
// It overwrites the existing value of the given label (if present).
func WithLabel(label, value string) Opt {
return func(l *Lease) error {
if l.Labels == nil {
l.Labels = map[string]string{label: value}
return nil
}
l.Labels[label] = value
return nil
}
}
// WithLabels merges labels on a lease
func WithLabels(labels map[string]string) Opt {
return func(l *Lease) error {

View File

@ -26,13 +26,12 @@ import (
func TestWithLabels(t *testing.T) {
testcases := []struct {
name string
uut *Lease
initialLabels map[string]string
labels map[string]string
expected map[string]string
}{
{
name: "AddLabelsToEmptyMap",
uut: &Lease{},
labels: map[string]string{
"containerd.io/gc.root": "2015-12-04T00:00:00Z",
},
@ -42,11 +41,9 @@ func TestWithLabels(t *testing.T) {
},
{
name: "AddLabelsToNonEmptyMap",
uut: &Lease{
Labels: map[string]string{
initialLabels: map[string]string{
"containerd.io/gc.expire": "2015-12-05T00:00:00Z",
},
},
labels: map[string]string{
"containerd.io/gc.root": "2015-12-04T00:00:00Z",
"containerd.io/gc.ref.snapshot.overlayfs": "sha256:87806a591ce894ff5c699c28fe02093d6cdadd6b1ad86819acea05ccb212ff3d",
@ -62,9 +59,32 @@ func TestWithLabels(t *testing.T) {
for _, tc := range testcases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
err := WithLabels(tc.labels)(tc.uut)
lease := newLease(tc.initialLabels)
err := WithLabels(tc.labels)(lease)
require.NoError(t, err)
assert.Equal(t, tc.uut.Labels, tc.expected)
assert.Equal(t, lease.Labels, tc.expected)
})
}
for _, tc := range testcases {
tc := tc
t.Run(tc.name+"-WithLabel", func(t *testing.T) {
lease := newLease(tc.initialLabels)
for k, v := range tc.labels {
err := WithLabel(k, v)(lease)
require.NoError(t, err)
}
assert.Equal(t, lease.Labels, tc.expected)
})
}
}
func newLease(labels map[string]string) *Lease {
lease := &Lease{}
if labels != nil {
lease.Labels = map[string]string{}
for k, v := range labels {
lease.Labels[k] = v
}
}
return lease
}