forked from glycerine/sshego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
perjson.go
75 lines (57 loc) · 1.22 KB
/
perjson.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package sshego
import (
"encoding/json"
"fmt"
"io/ioutil"
"os/exec"
"time"
"github.com/glycerine/go-unsnap-stream"
"github.com/mailgun/log"
)
func (s *KnownHosts) saveJSONSnappy(fn string) error {
mkpath(fn)
t0 := time.Now()
by, err := json.Marshal(s)
if err != nil {
panic(err)
}
// don't blow away the last good (fn) until the new version is completely written.
fnNew := fn + ".new"
// for backups
//exec.Command("mv", fn+".prev", fn+".prev.prev").Run()
exec.Command("cp", "-p", fn, fn+".prev").Run()
j, err := unsnap.Create(fnNew)
defer j.Close()
if err != nil {
panic(err)
}
_, err = j.Write(by)
if err != nil {
panic(err)
}
fmt.Fprintf(j, "\n")
j.Close()
exec.Command("mv", fnNew, fn).Run()
log.Infof("saveJSONSnappy() took %v", time.Since(t0))
return err
}
func (s *KnownHosts) readJSONSnappy(fn string) error {
if !fileExists(fn) {
return fmt.Errorf("could not open because no such file: '%s'", fn)
}
log.Infof("readJSONSnappy() is restoring state from file '%s'.", fn)
f, err := unsnap.Open(fn)
if err != nil {
panic(err)
}
defer f.Close()
dat, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
err = json.Unmarshal(dat, s)
if err != nil {
panic(err)
}
return err
}