File: files.go

package info (click to toggle)
golang-github-canonical-go-dqlite 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 712 kB
  • sloc: sh: 380; makefile: 5
file content (81 lines) | stat: -rw-r--r-- 1,886 bytes parent folder | download | duplicates (4)
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
78
79
80
81
package app

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

	"gopkg.in/yaml.v2"
	"github.com/google/renameio"
)

const (
	// Store the node ID and address.
	infoFile = "info.yaml"

	// The node store file.
	storeFile = "cluster.yaml"

	// This is a "flag" file to signal when a brand new node needs to join
	// the cluster. In case the node doesn't successfully make it to join
	// the cluster first time it's started, it will re-try the next time.
	joinFile = "join"
)

// Return true if the given file exists in the given directory.
func fileExists(dir, file string) (bool, error) {
	path := filepath.Join(dir, file)

	if _, err := os.Stat(path); err != nil {
		if !os.IsNotExist(err) {
			return false, fmt.Errorf("check if %s exists: %w", file, err)
		}
		return false, nil
	}

	return true, nil
}

// Write a file in the given directory.
func fileWrite(dir, file string, data []byte) error {
	path := filepath.Join(dir, file)

	if err := renameio.WriteFile(path, data, 0600); err != nil {
		return fmt.Errorf("write %s: %w", file, err)
	}

	return nil
}

// Marshal the given object as YAML into the given file.
func fileMarshal(dir, file string, object interface{}) error {
	data, err := yaml.Marshal(object)
	if err != nil {
		return fmt.Errorf("marshall %s: %w", file, err)
	}
	if err := fileWrite(dir, file, data); err != nil {
		return err
	}
	return nil
}

// Unmarshal the given YAML file into the given object.
func fileUnmarshal(dir, file string, object interface{}) error {
	path := filepath.Join(dir, file)

	data, err := ioutil.ReadFile(path)
	if err != nil {
		return fmt.Errorf("read %s: %w", file, err)
	}
	if err := yaml.Unmarshal(data, object); err != nil {
		return fmt.Errorf("unmarshall %s: %w", file, err)
	}

	return nil
}

// Remove a file in the given directory.
func fileRemove(dir, file string) error {
	return os.Remove(filepath.Join(dir, file))
}