github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/pipes/file/file.go (about)

     1  package file
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/lmorg/murex/lang/stdio"
     7  )
     8  
     9  func init() {
    10  	stdio.RegisterPipe("file", NewFile)
    11  }
    12  
    13  // Stats returns bytes written and read. As File is a write-only interface bytes read will always equal 0
    14  func (f *File) Stats() (bytesWritten, bytesRead uint64) {
    15  	f.mutex.Lock()
    16  	bytesWritten = f.bWritten
    17  	bytesRead = 0
    18  	f.mutex.Unlock()
    19  	return
    20  }
    21  
    22  // NewFile writer stream.Io pipe
    23  func NewFile(name string) (_ stdio.Io, err error) {
    24  	f := new(File)
    25  	f.file, err = os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	//f.dependents++
    30  	return f, err
    31  }
    32  
    33  func (f *File) File() *os.File {
    34  	return f.file
    35  }
    36  
    37  // Open file writer
    38  func (f *File) Open() {
    39  	f.mutex.Lock()
    40  	f.dependents++
    41  	f.mutex.Unlock()
    42  }
    43  
    44  // Close file writer
    45  func (f *File) Close() {
    46  	f.mutex.Lock()
    47  
    48  	f.dependents--
    49  	if f.dependents == 0 {
    50  		f.file.Close()
    51  	}
    52  
    53  	if f.dependents < 0 {
    54  		panic("more closed dependents than open")
    55  	}
    56  
    57  	f.mutex.Unlock()
    58  }
    59  
    60  // ForceClose forces the stream.Io interface to close.
    61  func (f *File) ForceClose() {
    62  	f.file.Close()
    63  }