Home | History | Annotate | Download | only in tempfile
      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 or directory 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 or directories selected for deferred cleaning.
     38 // Similar to defer semantics, the nodes are deleted in LIFO order.
     39 func Cleanup() {
     40 	tempFilesMu.Lock()
     41 	for i := len(tempFiles) - 1; i >= 0; i-- {
     42 		os.Remove(tempFiles[i])
     43 	}
     44 	tempFiles = nil
     45 	tempFilesMu.Unlock()
     46 }
     47