github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/utils/archive/hash.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package archive
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  
    21  	// in some env, there maybe a panic of crypto/sha256 is not imported
    22  	_ "crypto/sha256"
    23  
    24  	"github.com/opencontainers/go-digest"
    25  )
    26  
    27  const emptySHA256TarDigest = "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"
    28  
    29  func TarCanonicalDigest(path string) (digest.Digest, int64, error) {
    30  	tarReader, err := TarWithoutRootDir(path)
    31  	if err != nil {
    32  		return "", 0, fmt.Errorf("unable to tar on %s, err: %s", path, err)
    33  	}
    34  	defer tarReader.Close()
    35  
    36  	digester := digest.Canonical.Digester()
    37  	size, err := io.Copy(digester.Hash(), tarReader)
    38  	if err != nil {
    39  		return "", 0, err
    40  	}
    41  	layerDigest := digester.Digest()
    42  	if layerDigest == emptySHA256TarDigest {
    43  		return "", 0, nil
    44  	}
    45  
    46  	return layerDigest, size, nil
    47  }