func GetSASBlob()

in pkg/download/blob.go [75:115]


func GetSASBlob(blobURI, blobSas, targetDir string) (string, error) {
	bloburl, err := url.Parse(blobURI + blobSas)
	loggableBlobUri := GetUriForLogging(blobURI)
	if err != nil {
		return "", errors.Wrapf(err, "unable to parse URL: %q", loggableBlobUri)
	}

	containerRef, err := storage.GetContainerReferenceFromSASURI(*bloburl)
	if err != nil {
		return "", errors.Wrapf(err, "unable to open storage container: %q", loggableBlobUri)
	}

	// Extract the blob path after container name
	fileName, blobPathError := getBlobPathAfterContainerName(blobURI, containerRef.Name)
	if fileName == "" {
		return "", errors.Wrapf(blobPathError, "cannot extract blob path name from URL: %q", loggableBlobUri)
	}

	blobref := containerRef.GetBlobReference(fileName)
	reader, err := blobref.Get(nil)
	if err != nil {
		return "", errors.Wrapf(err, "unable to open storage blob: %q", loggableBlobUri)
	}

	scriptFilePath := filepath.Join(targetDir, fileName)
	const mode = 0500 // scripts should have execute permissions
	file, err := os.OpenFile(scriptFilePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, mode)
	if err != nil {
		return "", errors.Wrapf(err, "failed to open file '%s' for writing: ", scriptFilePath)
	}
	defer file.Close()

	var buff = make([]byte, 1000)
	for numBytes, _ := reader.Read(buff); numBytes > 0; numBytes, _ = reader.Read(buff) {
		writtenBytes, writeErr := file.Write(buff[:numBytes])
		if writtenBytes != numBytes || writeErr != nil {
			return "", errors.Wrapf(writeErr, "failed to write to the file '%s': ", scriptFilePath)
		}
	}
	return scriptFilePath, nil
}