github.com/jfrog/jfrog-client-go@v1.40.2/utils/archiveutils.go (about)

     1  package utils
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"strings"
     7  
     8  	"github.com/jfrog/gofrog/unarchive"
     9  	"github.com/jfrog/jfrog-client-go/utils/errorutils"
    10  	"github.com/jfrog/jfrog-client-go/utils/log"
    11  )
    12  
    13  // localPath - The path of the downloaded archive file.
    14  // localFileName - The name of the archive file.
    15  // originFileName - The name of the archive file in Artifactory.
    16  // logMsgPrefix - A prefix to the log message.
    17  // bypassInspection - Set to true to bypass archive inspection against ZipSlip
    18  // Extract an archive file to the 'localPath'.
    19  func ExtractArchive(localPath, localFileName, originFileName, logMsgPrefix string, bypassInspection bool) error {
    20  	unarchiver := &unarchive.Unarchiver{
    21  		BypassInspection: bypassInspection,
    22  	}
    23  	if !unarchiver.IsSupportedArchive(originFileName) {
    24  		return nil
    25  	}
    26  	extractionPath, err := getExtractionPath(localPath)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	var archivePath string
    31  	if !strings.HasPrefix(localFileName, localPath) {
    32  		archivePath = filepath.Join(localPath, localFileName)
    33  	} else {
    34  		archivePath = localFileName
    35  	}
    36  	archivePath, err = filepath.Abs(archivePath)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	err = os.MkdirAll(extractionPath, 0755)
    41  	if errorutils.CheckError(err) != nil {
    42  		return err
    43  	}
    44  	log.Info(logMsgPrefix+"Extracting archive:", archivePath, "to", extractionPath)
    45  	return errorutils.CheckError(extract(archivePath, originFileName, extractionPath, unarchiver))
    46  }
    47  
    48  func extract(localFilePath, originArchiveName, extractionPath string, unarchiver *unarchive.Unarchiver) error {
    49  	if err := unarchiver.Unarchive(localFilePath, originArchiveName, extractionPath); err != nil {
    50  		return errorutils.CheckError(err)
    51  	}
    52  	// If the file was extracted successfully, remove it from the file system
    53  	return errorutils.CheckError(os.Remove(localFilePath))
    54  }
    55  
    56  func getExtractionPath(localPath string) (string, error) {
    57  	// The local path to which the file is going to be extracted,
    58  	// needs to be absolute.
    59  	absolutePath, err := filepath.Abs(localPath)
    60  	if err != nil {
    61  		return "", errorutils.CheckError(err)
    62  	}
    63  	// Add a trailing slash to the local path, since it has to be a directory.
    64  	return absolutePath + string(os.PathSeparator), nil
    65  }