fsutil.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 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 fsutil
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path"
  20. )
  21. // Create a temporary file with the same semantics as ioutil.TempFile, but
  22. // ensure that it is unlinked before returning so that it does not persist
  23. // after the process exits.
  24. //
  25. // Warning: this is not production-quality code, and should only be used for
  26. // testing purposes. In particular, there is a race between creating and
  27. // unlinking by name.
  28. func AnonymousFile(dir string) (f *os.File, err error) {
  29. // Choose a prefix based on the binary name.
  30. prefix := path.Base(os.Args[0])
  31. // Create the file.
  32. f, err = ioutil.TempFile(dir, prefix)
  33. if err != nil {
  34. err = fmt.Errorf("TempFile: %v", err)
  35. return
  36. }
  37. // Unlink it.
  38. err = os.Remove(f.Name())
  39. if err != nil {
  40. err = fmt.Errorf("Remove: %v", err)
  41. return
  42. }
  43. return
  44. }
  45. // Call fdatasync on the supplied file.
  46. //
  47. // REQUIRES: FdatasyncSupported is true.
  48. func Fdatasync(f *os.File) error {
  49. return fdatasync(f)
  50. }