github.com/verrazzano/verrazzano@v1.7.0/pkg/os/file.go (about)

     1  // Copyright (c) 2021, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  package os
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"path/filepath"
     9  	"regexp"
    10  
    11  	"go.uber.org/zap"
    12  )
    13  
    14  // CreateTempFile creates a temp file from a filename pattern and data
    15  func CreateTempFile(filenamePattern string, data []byte) (*os.File, error) {
    16  	var tmpFile *os.File
    17  	tmpFile, err := os.CreateTemp(os.TempDir(), filenamePattern)
    18  	if err != nil {
    19  		return tmpFile, fmt.Errorf("Failed to create temporary file: %v", err)
    20  	}
    21  
    22  	if _, err = tmpFile.Write(data); err != nil {
    23  		return tmpFile, fmt.Errorf("Failed to write to temporary file: %v", err)
    24  	}
    25  
    26  	// Close the file
    27  	if err := tmpFile.Close(); err != nil {
    28  		return tmpFile, fmt.Errorf("Failed to close temporary file: %v", err)
    29  	}
    30  	return tmpFile, nil
    31  }
    32  
    33  func RemoveTempFiles(log *zap.SugaredLogger, regexPattern string) error {
    34  	files, err := os.ReadDir(os.TempDir())
    35  	if err != nil {
    36  		log.Errorf("Unable to read temp directory: %v", err)
    37  		return err
    38  	}
    39  	matcher, err := regexp.Compile(regexPattern)
    40  	if err != nil {
    41  		log.Errorf("Unable to compile regex pattern: %s: %v", regexPattern, err)
    42  		return err
    43  	}
    44  	for _, file := range files {
    45  		if !file.IsDir() && matcher.Match([]byte(file.Name())) {
    46  			fullPath := filepath.Join(os.TempDir(), file.Name())
    47  			log.Debugf("Deleting temp file %s", fullPath)
    48  			if err := os.Remove(fullPath); err != nil {
    49  				log.Errorf("Error deleting temp file %s: %v", fullPath, err)
    50  				return err
    51  			}
    52  		}
    53  	}
    54  	return nil
    55  }
    56  
    57  // FileExists returns true if the file at the specified path exists, false otherwise
    58  func FileExists(filePath string) (bool, error) {
    59  	if _, err := os.Stat(filePath); err != nil {
    60  		if os.IsNotExist(err) {
    61  			return false, nil
    62  		}
    63  		return false, err
    64  	}
    65  	return true, nil
    66  }