github.com/vmware/govmomi@v0.37.2/vim25/debug/file.go (about)

     1  /*
     2  Copyright (c) 2014 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package debug
    18  
    19  import (
    20  	"io"
    21  	"os"
    22  	"path"
    23  	"sync"
    24  )
    25  
    26  // FileProvider implements a debugging provider that creates a real file for
    27  // every call to NewFile. It maintains a list of all files that it creates,
    28  // such that it can close them when its Flush function is called.
    29  type FileProvider struct {
    30  	Path string
    31  
    32  	mu    sync.Mutex
    33  	files []*os.File
    34  }
    35  
    36  func (fp *FileProvider) NewFile(p string) io.WriteCloser {
    37  	f, err := os.Create(path.Join(fp.Path, p))
    38  	if err != nil {
    39  		panic(err)
    40  	}
    41  
    42  	fp.mu.Lock()
    43  	defer fp.mu.Unlock()
    44  	fp.files = append(fp.files, f)
    45  
    46  	return NewFileWriterCloser(f, p)
    47  }
    48  
    49  func (fp *FileProvider) Flush() {
    50  	fp.mu.Lock()
    51  	defer fp.mu.Unlock()
    52  	for _, f := range fp.files {
    53  		f.Close()
    54  	}
    55  }
    56  
    57  type FileWriterCloser struct {
    58  	f *os.File
    59  	p string
    60  }
    61  
    62  func NewFileWriterCloser(f *os.File, p string) *FileWriterCloser {
    63  	return &FileWriterCloser{
    64  		f,
    65  		p,
    66  	}
    67  }
    68  
    69  func (fwc *FileWriterCloser) Write(p []byte) (n int, err error) {
    70  	return fwc.f.Write(Scrub(p))
    71  }
    72  
    73  func (fwc *FileWriterCloser) Close() error {
    74  	return fwc.f.Close()
    75  }