...

Source file src/cmd/vendor/github.com/google/pprof/internal/driver/tempfile.go

     1	// Copyright 2014 Google Inc. All Rights Reserved.
     2	//
     3	// Licensed under the Apache License, Version 2.0 (the "License");
     4	// you may not use this file except in compliance with the License.
     5	// You may obtain a copy of the License at
     6	//
     7	//     http://www.apache.org/licenses/LICENSE-2.0
     8	//
     9	// Unless required by applicable law or agreed to in writing, software
    10	// distributed under the License is distributed on an "AS IS" BASIS,
    11	// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12	// See the License for the specific language governing permissions and
    13	// limitations under the License.
    14	
    15	package driver
    16	
    17	import (
    18		"fmt"
    19		"os"
    20		"path/filepath"
    21		"sync"
    22	)
    23	
    24	// newTempFile returns a new output file in dir with the provided prefix and suffix.
    25	func newTempFile(dir, prefix, suffix string) (*os.File, error) {
    26		for index := 1; index < 10000; index++ {
    27			path := filepath.Join(dir, fmt.Sprintf("%s%03d%s", prefix, index, suffix))
    28			if _, err := os.Stat(path); err != nil {
    29				return os.Create(path)
    30			}
    31		}
    32		// Give up
    33		return nil, fmt.Errorf("could not create file of the form %s%03d%s", prefix, 1, suffix)
    34	}
    35	
    36	var tempFiles []string
    37	var tempFilesMu = sync.Mutex{}
    38	
    39	// deferDeleteTempFile marks a file to be deleted by next call to Cleanup()
    40	func deferDeleteTempFile(path string) {
    41		tempFilesMu.Lock()
    42		tempFiles = append(tempFiles, path)
    43		tempFilesMu.Unlock()
    44	}
    45	
    46	// cleanupTempFiles removes any temporary files selected for deferred cleaning.
    47	func cleanupTempFiles() {
    48		tempFilesMu.Lock()
    49		for _, f := range tempFiles {
    50			os.Remove(f)
    51		}
    52		tempFiles = nil
    53		tempFilesMu.Unlock()
    54	}
    55	

View as plain text