github.com/mondo192/jfrog-client-go@v1.0.0/utils/io/fileutils/temp.go (about)

     1  package fileutils
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"strconv"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/mondo192/jfrog-client-go/utils/errorutils"
    11  	"github.com/mondo192/jfrog-client-go/utils/log"
    12  )
    13  
    14  var (
    15  	tempPrefix = "jfrog.cli.temp."
    16  
    17  	// Max temp file age in hours
    18  	maxFileAge = 24.0
    19  
    20  	// Path to the root temp dir
    21  	tempDirBase string
    22  )
    23  
    24  func init() {
    25  	tempDirBase = os.TempDir()
    26  }
    27  
    28  // Creates the temp dir at tempDirBase.
    29  // Set tempDirPath to the created directory path.
    30  func CreateTempDir() (string, error) {
    31  	if tempDirBase == "" {
    32  		return "", errorutils.CheckErrorf("Temp dir cannot be created in an empty base dir.")
    33  	}
    34  	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
    35  	dirPath, err := os.MkdirTemp(tempDirBase, tempPrefix+"-"+timestamp+"-")
    36  	if err != nil {
    37  		return "", errorutils.CheckError(err)
    38  	}
    39  	return dirPath, nil
    40  }
    41  
    42  // Change the containing directory of temp dir.
    43  func SetTempDirBase(dirPath string) {
    44  	tempDirBase = dirPath
    45  }
    46  
    47  func RemoveTempDir(dirPath string) error {
    48  	exists, err := IsDirExists(dirPath, false)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	if !exists {
    53  		return nil
    54  	}
    55  	err = os.RemoveAll(dirPath)
    56  	if err == nil {
    57  		return nil
    58  	}
    59  	// Sometimes removing the directory fails (in Windows) because it's locked by another process.
    60  	// That's a known issue, but its cause is unknown (golang.org/issue/30789).
    61  	// In this case, we'll only remove the contents of the directory, and let CleanOldDirs() remove the directory itself at a later time.
    62  	return RemoveDirContents(dirPath)
    63  }
    64  
    65  // Create a new temp file named "tempPrefix+timeStamp".
    66  func CreateTempFile() (*os.File, error) {
    67  	if tempDirBase == "" {
    68  		return nil, errorutils.CheckErrorf("Temp File cannot be created in an empty base dir.")
    69  	}
    70  	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
    71  	fd, err := os.CreateTemp(tempDirBase, tempPrefix+"-"+timestamp+"-")
    72  	return fd, err
    73  }
    74  
    75  // Old runs/tests may leave junk at temp dir.
    76  // Each temp file/Dir is named with prefix+timestamp, search for all temp files/dirs that match the common prefix and validate their timestamp.
    77  func CleanOldDirs() error {
    78  	// Get all files at temp dir
    79  	files, err := os.ReadDir(tempDirBase)
    80  	if err != nil {
    81  		log.Error(err)
    82  		return errorutils.CheckError(err)
    83  	}
    84  	now := time.Now()
    85  	// Search for files/dirs that match the template.
    86  	for _, file := range files {
    87  		if strings.HasPrefix(file.Name(), tempPrefix) {
    88  			timeStamp, err := extractTimestamp(file.Name())
    89  			if err != nil {
    90  				return err
    91  			}
    92  			// Delete old file/dirs.
    93  			if now.Sub(timeStamp).Hours() > maxFileAge {
    94  				if err := os.RemoveAll(path.Join(tempDirBase, file.Name())); err != nil {
    95  					return errorutils.CheckError(err)
    96  				}
    97  			}
    98  		}
    99  	}
   100  	return nil
   101  }
   102  
   103  func extractTimestamp(item string) (time.Time, error) {
   104  	// Get timestamp from file/dir.
   105  	endTimestampIdx := strings.LastIndex(item, "-")
   106  	beginningTimestampIdx := strings.LastIndex(item[:endTimestampIdx], "-")
   107  	timestampStr := item[beginningTimestampIdx+1 : endTimestampIdx]
   108  	// Convert to int.
   109  	timeStampInt, err := strconv.ParseInt(timestampStr, 10, 64)
   110  	if err != nil {
   111  		return time.Time{}, errorutils.CheckError(err)
   112  	}
   113  	// Convert to time type.
   114  	return time.Unix(timeStampInt, 0), nil
   115  }