github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/output/get_writer.go (about)

     1  package output
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
     8  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/utils"
     9  )
    10  
    11  // GetOutputFileWriter returns a writer which either the default one (same as passed
    12  // to this function) or, if filePath is non-empty, one that writes to that file.
    13  // If there is an error, logger.Fatal is called, because there really is no good way
    14  // to recover. Plus, output file is disabled in server, so it is safe to exit.
    15  func (opts *OutputOptions) GetOutputFileWriter() io.Writer {
    16  	if opts.OutputFn == "" {
    17  		// If there's no output filename, we return the default writer (standard out).
    18  		return opts.Writer
    19  	}
    20  
    21  	var file *os.File
    22  	var err error
    23  	if opts.Append {
    24  		file, err = os.OpenFile(opts.OutputFn, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
    25  	} else {
    26  		file, err = os.OpenFile(opts.OutputFn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    27  	}
    28  	if err != nil {
    29  		// TODO: - what happens in the server case?
    30  		// TODO: In API mode, --output is disallowed, but we should check
    31  		logger.Fatal(err)
    32  	}
    33  	return file
    34  }
    35  
    36  // IsApiMode return true if `w` is successfully cast into a `http.ResponseWriter`
    37  func (opts *OutputOptions) IsApiMode() bool {
    38  	w, ok := opts.Writer.(*JsonWriter)
    39  	if !ok {
    40  		return utils.IsServerWriter(opts.Writer)
    41  	}
    42  
    43  	return utils.IsServerWriter(*w.GetOutputWriter())
    44  }