설명 없음

tempfile.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. type VolatileFile struct {
  41. *os.File
  42. }
  43. func (file VolatileFile) Close() error {
  44. if err := file.File.Close(); err != nil {
  45. return err
  46. }
  47. if err := os.Remove(file.Name()); err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. // DeleteOnClose deletes file on Close().
  53. func DeleteOnClose(file *os.File) VolatileFile {
  54. return VolatileFile {
  55. File: file,
  56. }
  57. }
  58. var tempFiles []string
  59. var tempFilesMu = sync.Mutex{}
  60. // deferDeleteTempFile marks a file to be deleted by next call to Cleanup()
  61. func deferDeleteTempFile(path string) {
  62. tempFilesMu.Lock()
  63. tempFiles = append(tempFiles, path)
  64. tempFilesMu.Unlock()
  65. }
  66. // cleanupTempFiles removes any temporary files selected for deferred cleaning.
  67. func cleanupTempFiles() {
  68. tempFilesMu.Lock()
  69. for _, f := range tempFiles {
  70. os.Remove(f)
  71. }
  72. tempFiles = nil
  73. tempFilesMu.Unlock()
  74. }