File: hostname.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 (95 lines) | stat: -rw-r--r-- 2,328 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
83
84
85
86
87
88
89
90
91
92
93
94
95
package generators

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

	"github.com/lxc/incus/v6/shared/api"
	incus "github.com/lxc/incus/v6/shared/util"

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

type hostname struct {
	common
}

// RunLXC creates a hostname template.
func (g *hostname) RunLXC(img *image.LXCImage, target shared.DefinitionTargetLXC) error {
	// Skip if the file doesn't exist
	if !incus.PathExists(filepath.Join(g.sourceDir, g.defFile.Path)) {
		return nil
	}

	// Create new hostname file
	file, err := os.Create(filepath.Join(g.sourceDir, g.defFile.Path))
	if err != nil {
		return fmt.Errorf("Failed to create file %q: %w", filepath.Join(g.sourceDir, g.defFile.Path), err)
	}

	defer file.Close()

	// Write LXC specific string to the hostname file
	_, err = file.WriteString("LXC_NAME\n")
	if err != nil {
		return fmt.Errorf("Failed to write to hostname file: %w", err)
	}

	// Add hostname path to LXC's templates file
	err = img.AddTemplate(g.defFile.Path)
	if err != nil {
		return fmt.Errorf("Failed to add template: %w", err)
	}

	return nil
}

// RunIncus creates a hostname template.
func (g *hostname) RunIncus(img *image.IncusImage, target shared.DefinitionTargetIncus) error {
	// Skip if the file doesn't exist
	if !incus.PathExists(filepath.Join(g.sourceDir, g.defFile.Path)) {
		return nil
	}

	templateDir := filepath.Join(g.cacheDir, "templates")

	err := os.MkdirAll(templateDir, 0o755)
	if err != nil {
		return fmt.Errorf("Failed to create directory %q: %w", templateDir, err)
	}

	file, err := os.Create(filepath.Join(templateDir, "hostname.tpl"))
	if err != nil {
		return fmt.Errorf("Failed to create file %q: %w", filepath.Join(templateDir, "hostname.tpl"), err)
	}

	defer file.Close()

	_, err = file.WriteString("{{ container.name }}\n")
	if err != nil {
		return fmt.Errorf("Failed to write to hostname file: %w", err)
	}

	// Add to Incus templates
	img.Metadata.Templates[g.defFile.Path] = &api.ImageMetadataTemplate{
		Template:   "hostname.tpl",
		Properties: g.defFile.Template.Properties,
		When:       g.defFile.Template.When,
	}

	if len(g.defFile.Template.When) == 0 {
		img.Metadata.Templates[g.defFile.Path].When = []string{
			"create",
			"copy",
		}
	}

	return nil
}

// Run does nothing.
func (g *hostname) Run() error {
	return nil
}