github.com/koko1123/flow-go-1@v0.29.6/utils/io/write.go (about)

     1  package io
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"os"
     8  	"path/filepath"
     9  	"syscall"
    10  )
    11  
    12  // WriteFile writes a byte array to the file at the given path.
    13  // This method will also create the directory and file as needed.
    14  func WriteFile(path string, data []byte) error {
    15  	err := os.MkdirAll(filepath.Dir(path), 0755)
    16  	if err != nil {
    17  		return fmt.Errorf("could not create output dir: %w", err)
    18  	}
    19  
    20  	err = os.WriteFile(path, data, 0644)
    21  	if err != nil {
    22  		return fmt.Errorf("could not write file: %w", err)
    23  	}
    24  
    25  	return nil
    26  }
    27  
    28  // WriteText writes a byte array to the file at the given path.
    29  func WriteText(path string, data []byte) error {
    30  	err := os.WriteFile(path, data, 0644)
    31  	if err != nil {
    32  		return fmt.Errorf("could not write file: %w", err)
    33  	}
    34  
    35  	return nil
    36  }
    37  
    38  // WriteJSON marshals the given interface into JSON and writes it to the given path
    39  func WriteJSON(path string, data interface{}) error {
    40  	bz, err := json.MarshalIndent(data, "", "  ")
    41  	if err != nil {
    42  		return fmt.Errorf("could not marshal json: %w", err)
    43  	}
    44  
    45  	return WriteFile(path, bz)
    46  }
    47  
    48  // TerminateOnFullDisk panics if the input error is (or wraps) the system "out of disk
    49  // space" error. It's a no-op for any other error, or nil.
    50  func TerminateOnFullDisk(err error) error {
    51  	if err != nil && errors.Is(err, syscall.ENOSPC) {
    52  		panic(fmt.Sprintf("disk full, terminating node: %s", err.Error()))
    53  	}
    54  	return err
    55  }