-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (79 loc) · 2.29 KB
/
Copy pathmain.go
File metadata and controls
97 lines (79 loc) · 2.29 KB
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
91
92
93
94
95
96
97
package main
import (
"archive/tar"
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/tarball"
)
func main() {
img, err := crane.Pull("devopps/read-file-and-write-to-sdout:latest")
if err != nil {
panic(err)
}
var b bytes.Buffer
tw := tar.NewWriter(&b)
err = addFileToTarWriter("/Users/batuhan.apaydin/workspace/projects/personal/poc/manipulate-docker-image-layers-with-crane/layer",
"/app",
"/Users/batuhan.apaydin/workspace/projects/personal/poc/manipulate-docker-image-layers-with-crane/layer/hello-world.txt", tw)
if err != nil {
panic(err)
}
addLayer, err := tarball.LayerFromReader(&b)
if err != nil {
panic(err)
}
newImg, err := mutate.AppendLayers(img, addLayer)
if err != nil {
panic(err)
}
tag, err := name.NewTag("devopps/read-file-and-write-to-sdout:foo")
if err != nil {
panic(err)
}
//if s, err := daemon.Write(tag, newImg); err != nil {
// panic(err)
//} else {
// fmt.Println(s)
//}
// push to remote registry
if err := crane.Push(newImg, tag.String()); err != nil {
panic(err)
}
log.Printf("image %s pushed to the registry succesfully\n", tag.String())
}
func addFileToTarWriter(root, targetPath, filePath string, tarWriter *tar.Writer) error {
file, err := os.Open(filePath)
if err != nil {
return errors.New(fmt.Sprintf("Could not open file '%s', got error '%s'", filePath, err.Error()))
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return errors.New(fmt.Sprintf("Could not get stat for file '%s', got error '%s'", filePath, err.Error()))
}
rel, err := filepath.Rel(root, filePath)
header := &tar.Header{
Name: path.Join(targetPath, filepath.ToSlash(rel)),
Size: stat.Size(),
Mode: int64(stat.Mode()),
ModTime: stat.ModTime(),
}
err = tarWriter.WriteHeader(header)
if err != nil {
return errors.New(fmt.Sprintf("Could not write header for file '%s', got error '%s'", filePath, err.Error()))
}
_, err = io.Copy(tarWriter, file)
if err != nil {
return errors.New(fmt.Sprintf("Could not copy the file '%s' data to the tarball, got error '%s'", filePath, err.Error()))
}
return nil
}