github.com/Files-com/files-sdk-go/v3@v3.1.81/file/tmpdownloadpath.go (about)

     1  package file
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"os"
     7  	"time"
     8  )
     9  
    10  const TempDownloadExtension = "download"
    11  
    12  // tmpDownloadPath Generates a unique temporary download path for a given file path by appending a ".download" extension and, if necessary, additional identifiers to avoid name conflicts.
    13  func tmpDownloadPath(path string) (string, error) {
    14  	var index int
    15  	randGenerator := rand.New(rand.NewSource(time.Now().UnixNano()))
    16  
    17  	for {
    18  		var tempPath, uniqueness string
    19  		if index == 0 {
    20  			tempPath = fmt.Sprintf("%v.%v", path, TempDownloadExtension)
    21  		} else if index > 25 {
    22  			return "", fmt.Errorf("unable to create a unique temporary path after 25 attempts, consider deleting existing .%v files; attempted path: %v", TempDownloadExtension, path)
    23  		} else {
    24  			if index > 10 {
    25  				for i := 0; i < 4; i++ {
    26  					uniqueness += string(rune(randGenerator.Intn(26) + 'a'))
    27  				}
    28  			} else {
    29  				uniqueness = fmt.Sprintf("%v", index)
    30  			}
    31  			tempPath = fmt.Sprintf("%v (%v).%v", path, uniqueness, TempDownloadExtension)
    32  		}
    33  
    34  		if _, err := os.Stat(tempPath); os.IsNotExist(err) {
    35  			return tmpDownloadPathOnNotExist(path, tempPath)
    36  		}
    37  		index++
    38  	}
    39  }