github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/engine/docker/tarfile.go (about) 1 package docker 2 3 import ( 4 "archive/tar" 5 "context" 6 "os" 7 "path/filepath" 8 9 "github.com/projecteru2/core/log" 10 ) 11 12 func withTarfileDump(ctx context.Context, target string, content []byte, uid, gid int, mode int64, f func(target, tarfile string) error) error { 13 tarfile, err := tempTarFile(target, content, uid, gid, mode) 14 15 defer func(tarfile string) { 16 if err := os.RemoveAll(tarfile); err != nil { 17 log.WithFunc("engine.docker.withTarfileDump").Warnf(ctx, "clean dump files failed: %+v", err) 18 } 19 }(tarfile) 20 21 if err != nil { 22 return err 23 } 24 return f(target, tarfile) 25 } 26 27 func tempTarFile(path string, data []byte, uid, gid int, mode int64) (string, error) { 28 filename := filepath.Base(path) 29 f, err := os.CreateTemp(os.TempDir(), filename) 30 if err != nil { 31 return "", err 32 } 33 name := f.Name() 34 defer f.Close() 35 36 tw := tar.NewWriter(f) 37 defer tw.Close() 38 hdr := &tar.Header{ 39 Name: filename, 40 Size: int64(len(data)), 41 Mode: mode, 42 Uid: uid, 43 Gid: gid, 44 } 45 if err := tw.WriteHeader(hdr); err != nil { 46 return name, err 47 } 48 _, err = tw.Write(data) 49 return name, err 50 }