-
Notifications
You must be signed in to change notification settings - Fork 9
/
maketar.go
90 lines (71 loc) · 1.94 KB
/
maketar.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
84
85
86
87
88
89
90
// 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 binary
import (
"compress/gzip"
"context"
"io"
"os"
"path/filepath"
"github.com/google/go-containerregistry/pkg/v1/empty"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"namespacelabs.dev/foundation/internal/artifacts/oci"
"namespacelabs.dev/foundation/internal/build"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/std/pkggraph"
)
type makeTarImage struct {
spec build.Spec
target string
compress bool
}
func (m makeTarImage) BuildImage(ctx context.Context, env pkggraph.SealedContext, conf build.Configuration) (compute.Computable[oci.Image], error) {
inner, err := m.spec.BuildImage(ctx, env, conf)
if err != nil {
return nil, err
}
return compute.Transform("binary.make_tar", inner, func(ctx context.Context, img oci.Image) (oci.Image, error) {
dir, err := os.MkdirTemp("", "squashfs")
if err != nil {
return nil, err
}
x := filepath.Join(dir, m.target)
if err := os.MkdirAll(filepath.Dir(x), 0755); err != nil {
return nil, err
}
defer os.RemoveAll(dir)
f, err := os.Create(x)
if err != nil {
return nil, err
}
defer f.Close()
r := mutate.Extract(img)
defer r.Close()
var w io.WriteCloser = f
if m.compress {
gw, err := gzip.NewWriterLevel(f, 6)
if err != nil {
return nil, err
}
w = gw
}
if _, err := io.Copy(w, r); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
if w != f {
if err := f.Close(); err != nil {
return nil, err
}
}
layer, err := oci.LayerFromFS(ctx, os.DirFS(dir))
if err != nil {
return nil, err
}
return mutate.AppendLayers(empty.Image, layer)
}), nil
}
func (m makeTarImage) PlatformIndependent() bool { return m.spec.PlatformIndependent() }