file.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  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 debug
  14. import (
  15. "io"
  16. "os"
  17. "path"
  18. "sync"
  19. )
  20. // FileProvider implements a debugging provider that creates a real file for
  21. // every call to NewFile. It maintains a list of all files that it creates,
  22. // such that it can close them when its Flush function is called.
  23. type FileProvider struct {
  24. Path string
  25. mu sync.Mutex
  26. files []*os.File
  27. }
  28. func (fp *FileProvider) NewFile(p string) io.WriteCloser {
  29. f, err := os.Create(path.Join(fp.Path, p))
  30. if err != nil {
  31. panic(err)
  32. }
  33. fp.mu.Lock()
  34. defer fp.mu.Unlock()
  35. fp.files = append(fp.files, f)
  36. return NewFileWriterCloser(f, p)
  37. }
  38. func (fp *FileProvider) Flush() {
  39. fp.mu.Lock()
  40. defer fp.mu.Unlock()
  41. for _, f := range fp.files {
  42. f.Close()
  43. }
  44. }
  45. type FileWriterCloser struct {
  46. f *os.File
  47. p string
  48. }
  49. func NewFileWriterCloser(f *os.File, p string) *FileWriterCloser {
  50. return &FileWriterCloser{
  51. f,
  52. p,
  53. }
  54. }
  55. func (fwc *FileWriterCloser) Write(p []byte) (n int, err error) {
  56. return fwc.f.Write(Scrub(p))
  57. }
  58. func (fwc *FileWriterCloser) Close() error {
  59. return fwc.f.Close()
  60. }