설명 없음

tempfile.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. package driver
  15. import (
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "sync"
  20. )
  21. // newTempFilePath returns an unused path for output files.
  22. func newTempFilePath(dir, prefix, suffix string) (string, error) {
  23. for index := 1; index < 10000; index++ {
  24. path := filepath.Join(dir, fmt.Sprintf("%s%03d%s", prefix, index, suffix))
  25. if _, err := os.Stat(path); err != nil {
  26. return path, nil
  27. }
  28. }
  29. // Give up
  30. return "", fmt.Errorf("could not create file of the form %s%03d%s", prefix, 1, suffix)
  31. }
  32. // newTempFile returns a new file with a random name for output files.
  33. func newTempFile(dir, prefix, suffix string) (*os.File, error) {
  34. path, err := newTempFilePath(dir, prefix, suffix)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return os.Create(path)
  39. }
  40. var tempFiles []string
  41. var tempFilesMu = sync.Mutex{}
  42. // deferDeleteTempFile marks a file to be deleted by next call to Cleanup()
  43. func deferDeleteTempFile(path string) {
  44. tempFilesMu.Lock()
  45. tempFiles = append(tempFiles, path)
  46. tempFilesMu.Unlock()
  47. }
  48. // cleanupTempFiles removes any temporary files selected for deferred cleaning.
  49. func cleanupTempFiles() {
  50. tempFilesMu.Lock()
  51. for _, f := range tempFiles {
  52. os.Remove(f)
  53. }
  54. tempFiles = nil
  55. tempFilesMu.Unlock()
  56. }