github.com/akaros/go-akaros@v0.0.0-20181004170632-85005d477eab/src/cmd/pprof/internal/tempfile/tempfile.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package tempfile provides tools to create and delete temporary files
     6  package tempfile
     7  
     8  import (
     9  	"fmt"
    10  	"os"
    11  	"path/filepath"
    12  	"sync"
    13  )
    14  
    15  // New returns an unused filename for output files.
    16  func New(dir, prefix, suffix string) (*os.File, error) {
    17  	for index := 1; index < 10000; index++ {
    18  		path := filepath.Join(dir, fmt.Sprintf("%s%03d%s", prefix, index, suffix))
    19  		if _, err := os.Stat(path); err != nil {
    20  			return os.Create(path)
    21  		}
    22  	}
    23  	// Give up
    24  	return nil, fmt.Errorf("could not create file of the form %s%03d%s", prefix, 1, suffix)
    25  }
    26  
    27  var tempFiles []string
    28  var tempFilesMu = sync.Mutex{}
    29  
    30  // DeferDelete marks a file to be deleted by next call to Cleanup()
    31  func DeferDelete(path string) {
    32  	tempFilesMu.Lock()
    33  	tempFiles = append(tempFiles, path)
    34  	tempFilesMu.Unlock()
    35  }
    36  
    37  // Cleanup removes any temporary files selected for deferred cleaning.
    38  func Cleanup() {
    39  	tempFilesMu.Lock()
    40  	for _, f := range tempFiles {
    41  		os.Remove(f)
    42  	}
    43  	tempFiles = nil
    44  	tempFilesMu.Unlock()
    45  }