github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/ociinstaller/tempdir.go (about)

     1  package ociinstaller
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/google/uuid"
    10  	"github.com/turbot/steampipe/pkg/error_helpers"
    11  )
    12  
    13  type tempDir struct {
    14  	Path string
    15  }
    16  
    17  // NewTempDir creates a directory under the given parent directory.
    18  func NewTempDir(parent string) *tempDir {
    19  	return &tempDir{
    20  		Path: getOrCreateTempDir(parent),
    21  	}
    22  }
    23  
    24  func getOrCreateTempDir(parent string) string {
    25  	cacheDir := filepath.Join(parent, safeDirName(fmt.Sprintf("tmp-%s", generateTempDirName())))
    26  
    27  	if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
    28  		err = os.MkdirAll(cacheDir, 0755)
    29  		error_helpers.FailOnErrorWithMessage(err, "could not create cache directory")
    30  	}
    31  	return cacheDir
    32  }
    33  
    34  func (d *tempDir) Delete() error {
    35  	return os.RemoveAll(d.Path)
    36  }
    37  
    38  func safeDirName(dirName string) string {
    39  	newName := strings.ReplaceAll(dirName, "/", "_")
    40  	newName = strings.ReplaceAll(newName, ":", "@")
    41  
    42  	return newName
    43  }
    44  
    45  func generateTempDirName() string {
    46  	u, err := uuid.NewRandom()
    47  	if err != nil {
    48  		// Should never happen?
    49  		panic(err)
    50  	}
    51  	s := u.String()
    52  	return s[9:23]
    53  }