/
append.go
43 lines (36 loc) · 941 Bytes
/
append.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package tslib
import (
"encoding/binary"
"os"
"path/filepath"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/config"
"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
)
func Append(chain string, tsArray []TimestampRecord) error {
tsFn := config.PathToTimestamps(chain)
tmpPath := filepath.Join(config.PathToCache(chain), "tmp")
if backupFn, err := file.MakeBackup(tmpPath, tsFn); err == nil {
ClearCache(chain)
defer func() {
if file.FileExists(backupFn) {
_ = os.Rename(backupFn, tsFn)
_ = os.Remove(backupFn) // seems redundant, but may not be on some operating systems
}
}()
fp, err := os.OpenFile(tsFn, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
defer func() {
fp.Close()
}()
err = binary.Write(fp, binary.LittleEndian, tsArray)
if err != nil {
return err
}
os.Remove(backupFn)
return nil
} else {
return err
}
}