temp.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package watch
  14. import (
  15. "os"
  16. "path/filepath"
  17. )
  18. // TempDir holds a temp directory and allows easy access to new temp directories.
  19. type TempDir struct {
  20. dir string
  21. }
  22. // NewDir creates a new TempDir in the default location (typically $TMPDIR)
  23. func NewDir(prefix string) (*TempDir, error) {
  24. return NewDirAtRoot("", prefix)
  25. }
  26. // NewDir creates a new TempDir at the given root.
  27. func NewDirAtRoot(root, prefix string) (*TempDir, error) {
  28. tmpDir, err := os.MkdirTemp(root, prefix)
  29. if err != nil {
  30. return nil, err
  31. }
  32. realTmpDir, err := filepath.EvalSymlinks(tmpDir)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &TempDir{dir: realTmpDir}, nil
  37. }
  38. // NewDirAtSlashTmp creates a new TempDir at /tmp
  39. func NewDirAtSlashTmp(prefix string) (*TempDir, error) {
  40. fullyResolvedPath, err := filepath.EvalSymlinks("/tmp")
  41. if err != nil {
  42. return nil, err
  43. }
  44. return NewDirAtRoot(fullyResolvedPath, prefix)
  45. }
  46. // d.NewDir creates a new TempDir under d
  47. func (d *TempDir) NewDir(prefix string) (*TempDir, error) {
  48. d2, err := os.MkdirTemp(d.dir, prefix)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return &TempDir{d2}, nil
  53. }
  54. func (d *TempDir) NewDeterministicDir(name string) (*TempDir, error) {
  55. d2 := filepath.Join(d.dir, name)
  56. err := os.Mkdir(d2, 0o700)
  57. if os.IsExist(err) {
  58. return nil, err
  59. } else if err != nil {
  60. return nil, err
  61. }
  62. return &TempDir{d2}, nil
  63. }
  64. func (d *TempDir) TearDown() error {
  65. return os.RemoveAll(d.dir)
  66. }
  67. func (d *TempDir) Path() string {
  68. return d.dir
  69. }
  70. // Possible extensions:
  71. // temp file
  72. // named directories or files (e.g., we know we want one git repo for our object, but it should be temporary)