summaryrefslogtreecommitdiff
path: root/save.go
blob: b035e7cf41d958ceadb2aa5e32f59cb9179aeba0 (plain)
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
76
77
package config

import (
	"fmt"
	"os"
	"path/filepath"

	"go.wit.com/log"
	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/proto"
)

var ErrProtoFilename error = log.Errorf("proto does not have Filename")

func ConfigSave(pb proto.Message) error {
	// get pb.Filename if it is there in the .proto file
	fullname, ok := GetFilename(pb)
	if !ok {
		return ErrProtoFilename
	}

	// Unmarshal()
	data, err := prototext.Marshal(pb)
	if err != nil {
		return err
	}

	log.Infof("ConfigSave() filename=%s %d\n", fullname, len(data))
	return configWrite(fullname, data)
}

func configWrite(fullname string, data []byte) error {
	if _, base := filepath.Split(fullname); base == "" {
		return fmt.Errorf("--config option not set")
	}
	cfgfile, err := os.OpenFile(fullname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	defer cfgfile.Close()
	if err != nil {
		log.Warn("open config file :", err)
		return err
	}
	_, err = cfgfile.Write(data)
	return err
}

/*

func (e *Events) Save() {
	var fullname string
	base, _ := filepath.Split(argv.Config)
	fullname = filepath.Join(base, "events.pb")

	data, err := e.Marshal()
	if err != nil {
		log.Info("proto.Marshal() failed", err)
		return
	}
	log.Info("proto.Marshal() worked len", len(data))
	configWrite(fullname, data)
}



func (m *Portmaps) configWrite(fullname string, data []byte) error {
	if _, base := filepath.Split(fullname); base == "" {
		return fmt.Errorf("--config option not set")
	}
	cfgfile, err := os.OpenFile(fullname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	defer cfgfile.Close()
	if err != nil {
		log.Warn("open config file :", err)
		return err
	}
	cfgfile.Write(data)
	return nil
}
*/