File: hosts.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (54 lines) | stat: -rw-r--r-- 1,269 bytes parent folder | download
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
package adminhelper

import (
	"github.com/crc-org/admin-helper/pkg/hosts"
	"github.com/crc-org/admin-helper/pkg/types"
	"github.com/crc-org/crc/v2/pkg/crc/constants"
)

// UpdateHostsFile updates the host's /etc/hosts file with Instance IP.
func UpdateHostsFile(instanceIP string, hostnames ...string) error {
	if err := RemoveFromHostsFile(hostnames...); err != nil {
		return err
	}
	return AddToHostsFile(instanceIP, hostnames...)
}

func AddToHostsFile(instanceIP string, hostnames ...string) error {
	hosts, err := hosts.New()
	if err != nil {
		return err
	}
	var filtered []string
	for _, hostname := range hostnames {
		if !hosts.Contains(instanceIP, hostname) {
			filtered = append(filtered, hostname)
		}
	}
	if len(filtered) == 0 {
		return nil
	}

	return instance().Add(&types.AddRequest{
		IP:    instanceIP,
		Hosts: filtered,
	})
}

func RemoveFromHostsFile(hostnames ...string) error {
	return instance().Remove(&types.RemoveRequest{
		Hosts: hostnames,
	})
}

func CleanHostsFile() error {
	return instance().Clean(&types.CleanRequest{
		Domains: []string{constants.ClusterDomain, constants.AppsDomain},
	})
}

type helper interface {
	Add(req *types.AddRequest) error
	Remove(req *types.RemoveRequest) error
	Clean(req *types.CleanRequest) error
}