File: dump.go

package info (click to toggle)
distrobuilder 3.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,468 kB
  • sloc: sh: 204; makefile: 75
file content (82 lines) | stat: -rw-r--r-- 1,735 bytes parent folder | download | duplicates (2)
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
82
package generators

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

	"github.com/lxc/distrobuilder/image"
	"github.com/lxc/distrobuilder/shared"
)

type dump struct {
	common
}

// RunLXC dumps content to a file.
func (g *dump) RunLXC(img *image.LXCImage, target shared.DefinitionTargetLXC) error {
	content := g.defFile.Content

	err := g.run(content)
	if err != nil {
		return fmt.Errorf("Failed to dump content: %w", err)
	}

	if g.defFile.Templated {
		err = img.AddTemplate(g.defFile.Path)
		if err != nil {
			return fmt.Errorf("Failed to add template: %w", err)
		}
	}

	return nil
}

// RunIncus dumps content to a file.
func (g *dump) RunIncus(img *image.IncusImage, target shared.DefinitionTargetIncus) error {
	content := g.defFile.Content

	return g.run(content)
}

// Run dumps content to a file.
func (g *dump) Run() error {
	return g.run(g.defFile.Content)
}

func (g *dump) run(content string) error {
	path := filepath.Join(g.sourceDir, g.defFile.Path)

	// Create any missing directory
	err := os.MkdirAll(filepath.Dir(path), 0o755)
	if err != nil {
		return fmt.Errorf("Failed to create directory %q: %w", filepath.Dir(path), err)
	}

	// Open the target file (create if needed)
	file, err := os.Create(path)
	if err != nil {
		return fmt.Errorf("Failed to create file %q: %w", path, err)
	}

	defer file.Close()

	// Append final new line if missing
	if !strings.HasSuffix(content, "\n") {
		content += "\n"
	}

	// Write the content
	_, err = file.WriteString(content)
	if err != nil {
		return fmt.Errorf("Failed to write string to file %q: %w", path, err)
	}

	err = updateFileAccess(file, g.defFile)
	if err != nil {
		return fmt.Errorf("Failed to update file access of %q: %w", path, err)
	}

	return nil
}