1
// Copyright 2012, 2013 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
15
"launchpad.net/goyaml"
18
// WriteYaml marshals obj as yaml and then writes it to a file, atomically,
19
// by first writing a sibling with the suffix ".preparing" and then moving
20
// the sibling to the real path.
21
func WriteYaml(path string, obj interface{}) error {
22
data, err := goyaml.Marshal(obj)
26
prep := path + ".preparing"
27
f, err := os.OpenFile(prep, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
32
if _, err = f.Write(data); err != nil {
35
return os.Rename(prep, path)
38
// ReadYaml unmarshals the yaml contained in the file at path into obj. See
40
func ReadYaml(path string, obj interface{}) error {
41
data, err := ioutil.ReadFile(path)
45
return goyaml.Unmarshal(data, obj)
48
// ErrorContextf prefixes any error stored in err with text formatted
49
// according to the format specifier. If err does not contain an error,
50
// ErrorContextf does nothing.
51
func ErrorContextf(err *error, format string, args ...interface{}) {
53
*err = errors.New(fmt.Sprintf(format, args...) + ": " + (*err).Error())
57
// ShQuote quotes s so that when read by bash, no metacharacters
58
// within s will be interpreted as such.
59
func ShQuote(s string) string {
60
// single-quote becomes single-quote, double-quote, single-quote, double-quote, single-quote
61
return `'` + strings.Replace(s, `'`, `'"'"'`, -1) + `'`
64
// Gzip compresses the given data.
65
func Gzip(data []byte) []byte {
67
w := gzip.NewWriter(&buf)
68
if _, err := w.Write(data); err != nil {
69
// Compression should never fail unless it fails
70
// to write to the underlying writer, which is a bytes.Buffer
74
if err := w.Close(); err != nil {
80
// Gunzip uncompresses the given data.
81
func Gunzip(data []byte) ([]byte, error) {
82
r, err := gzip.NewReader(bytes.NewReader(data))
86
return ioutil.ReadAll(r)