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

     1  package tslib
     2  
     3  import (
     4  	"encoding/binary"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/config"
     9  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
    10  )
    11  
    12  func Append(chain string, tsArray []TimestampRecord) error {
    13  	tsFn := config.PathToTimestamps(chain)
    14  	tmpPath := filepath.Join(config.PathToCache(chain), "tmp")
    15  	if backup, err := file.MakeBackup(tmpPath, tsFn); err == nil {
    16  		ClearCache(chain)
    17  		defer func() {
    18  			backup.Restore()
    19  		}()
    20  
    21  		fp, err := os.OpenFile(tsFn, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
    22  		if err != nil {
    23  			return err
    24  		}
    25  		defer func() {
    26  			fp.Close()
    27  		}()
    28  
    29  		err = binary.Write(fp, binary.LittleEndian, tsArray)
    30  		if err != nil {
    31  			return err
    32  		}
    33  
    34  		backup.Clear()
    35  		return nil
    36  
    37  	} else {
    38  		return err
    39  	}
    40  }