Skip to content

Commit fa58af6

Browse files
committed
Merge pull request #950 from thockin/hostname_domainname
Extract hostname from (hostname.domainname)
2 parents 1a8def6 + f0cf480 commit fa58af6

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

etchosts/etchosts.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io/ioutil"
99
"os"
1010
"regexp"
11+
"strings"
1112
"sync"
1213
)
1314

@@ -78,10 +79,17 @@ func Build(path, IP, hostname, domainname string, extraContent []Record) error {
7879
//set main record
7980
var mainRec Record
8081
mainRec.IP = IP
82+
// User might have provided a FQDN in hostname or split it across hostname
83+
// and domainname. We want the FQDN and the bare hostname.
84+
fqdn := hostname
8185
if domainname != "" {
82-
mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname)
86+
fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
87+
}
88+
parts := strings.SplitN(fqdn, ".", 2)
89+
if len(parts) == 2 {
90+
mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
8391
} else {
84-
mainRec.Hosts = hostname
92+
mainRec.Hosts = fqdn
8593
}
8694
if _, err := mainRec.WriteTo(content); err != nil {
8795
return err

etchosts/etchosts_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,28 @@ func TestBuildHostname(t *testing.T) {
8181
}
8282
}
8383

84+
func TestBuildHostnameFQDN(t *testing.T) {
85+
file, err := ioutil.TempFile("", "")
86+
if err != nil {
87+
t.Fatal(err)
88+
}
89+
defer os.Remove(file.Name())
90+
91+
err = Build(file.Name(), "10.11.12.13", "testhostname.testdomainname.com", "", nil)
92+
if err != nil {
93+
t.Fatal(err)
94+
}
95+
96+
content, err := ioutil.ReadFile(file.Name())
97+
if err != nil {
98+
t.Fatal(err)
99+
}
100+
101+
if expected := "10.11.12.13\ttesthostname.testdomainname.com testhostname\n"; !bytes.Contains(content, []byte(expected)) {
102+
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
103+
}
104+
}
105+
84106
func TestBuildNoIP(t *testing.T) {
85107
file, err := ioutil.TempFile("", "")
86108
if err != nil {

0 commit comments

Comments
 (0)