github.com/anjalikarhana/fabric@v2.1.1+incompatible/integration/nwo/package.go (about) 1 /* 2 Copyright IBM Corp All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package nwo 8 9 import ( 10 "archive/tar" 11 "compress/gzip" 12 "encoding/json" 13 "io" 14 "io/ioutil" 15 "os" 16 17 . "github.com/onsi/gomega" 18 ) 19 20 // PackageChaincodeBinary is a helper function to package 21 // an already built chaincode and write it to the location 22 // specified by Chaincode.PackageFile. 23 func PackageChaincodeBinary(c Chaincode) { 24 file, err := os.Create(c.PackageFile) 25 Expect(err).NotTo(HaveOccurred()) 26 defer file.Close() 27 writeTarGz(c, file) 28 } 29 30 func writeTarGz(c Chaincode, w io.Writer) { 31 gw := gzip.NewWriter(w) 32 tw := tar.NewWriter(gw) 33 defer closeAll(tw, gw) 34 35 writeMetadataJSON(tw, c.Path, c.Lang, c.Label) 36 37 writeCodeTarGz(tw, c.CodeFiles) 38 } 39 40 // packageMetadata holds the path, type, and label for a chaincode package 41 type packageMetadata struct { 42 Path string `json:"path"` 43 Type string `json:"type"` 44 Label string `json:"label"` 45 } 46 47 func writeMetadataJSON(tw *tar.Writer, path, ccType, label string) { 48 metadata, err := json.Marshal(&packageMetadata{ 49 Path: path, 50 Type: ccType, 51 Label: label, 52 }) 53 Expect(err).NotTo(HaveOccurred()) 54 55 // write it to the package as metadata.json 56 err = tw.WriteHeader(&tar.Header{ 57 Name: "metadata.json", 58 Size: int64(len(metadata)), 59 Mode: 0100644, 60 }) 61 _, err = tw.Write(metadata) 62 Expect(err).NotTo(HaveOccurred()) 63 } 64 65 func writeCodeTarGz(tw *tar.Writer, codeFiles map[string]string) { 66 // create temp file to hold code.tar.gz 67 tempfile, err := ioutil.TempFile("", "code.tar.gz") 68 Expect(err).NotTo(HaveOccurred()) 69 defer os.Remove(tempfile.Name()) 70 71 gzipWriter := gzip.NewWriter(tempfile) 72 tarWriter := tar.NewWriter(gzipWriter) 73 74 for source, target := range codeFiles { 75 file, err := os.Open(source) 76 Expect(err).NotTo(HaveOccurred()) 77 writeFileToTar(tarWriter, file, target) 78 file.Close() 79 } 80 81 // close down the inner tar 82 closeAll(tarWriter, gzipWriter) 83 84 writeFileToTar(tw, tempfile, "code.tar.gz") 85 } 86 87 func writeFileToTar(tw *tar.Writer, file *os.File, name string) { 88 _, err := file.Seek(0, 0) 89 Expect(err).NotTo(HaveOccurred()) 90 91 fi, err := file.Stat() 92 Expect(err).NotTo(HaveOccurred()) 93 header, err := tar.FileInfoHeader(fi, "") 94 Expect(err).NotTo(HaveOccurred()) 95 96 header.Name = name 97 err = tw.WriteHeader(header) 98 Expect(err).NotTo(HaveOccurred()) 99 100 _, err = io.Copy(tw, file) 101 Expect(err).NotTo(HaveOccurred()) 102 } 103 104 func closeAll(closers ...io.Closer) { 105 for _, c := range closers { 106 Expect(c.Close()).To(Succeed()) 107 } 108 }