File: load.go

package info (click to toggle)
docker.io 26.1.5%2Bdfsg1-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 68,576 kB
  • sloc: sh: 5,748; makefile: 912; ansic: 664; asm: 228; python: 162
file content (71 lines) | stat: -rw-r--r-- 1,607 bytes parent folder | download | duplicates (4)
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
package specialimage

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"strings"
	"testing"

	"github.com/docker/docker/client"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/jsonmessage"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"gotest.tools/v3/assert"
)

type SpecialImageFunc func(string) (*ocispec.Index, error)

func Load(ctx context.Context, t *testing.T, apiClient client.APIClient, imageFunc SpecialImageFunc) string {
	tempDir := t.TempDir()

	_, err := imageFunc(tempDir)
	assert.NilError(t, err)

	rc, err := archive.TarWithOptions(tempDir, &archive.TarOptions{})
	assert.NilError(t, err)

	defer rc.Close()

	resp, err := apiClient.ImageLoad(ctx, rc, true)
	assert.NilError(t, err, "Failed to load dangling image")

	defer resp.Body.Close()

	if !assert.Check(t, err) {
		respBody, err := io.ReadAll(resp.Body)
		if err != nil {
			t.Fatalf("Failed to read response body: %v", err)
			return ""
		}
		t.Fatalf("Failed load: %s", string(respBody))
	}

	all, err := io.ReadAll(resp.Body)
	assert.NilError(t, err)

	decoder := json.NewDecoder(bytes.NewReader(all))
	for {
		var msg jsonmessage.JSONMessage
		err := decoder.Decode(&msg)
		if errors.Is(err, io.EOF) {
			break
		} else {
			assert.NilError(t, err)
		}

		msg.Stream = strings.TrimSpace(msg.Stream)

		if _, imageID, hasID := strings.Cut(msg.Stream, "Loaded image ID: "); hasID {
			return imageID
		}
		if _, imageRef, hasRef := strings.Cut(msg.Stream, "Loaded image: "); hasRef {
			return imageRef
		}
	}

	t.Fatalf("failed to read image ID\n%s", string(all))
	return ""
}