Merge pull request #950 from thockin/hostname_domainname

Extract hostname from (hostname.domainname)
This commit is contained in:
aboch 2016-03-01 08:25:58 -08:00
commit 68df121f41
2 changed files with 32 additions and 2 deletions

View file

@ -8,6 +8,7 @@ import (
"io/ioutil"
"os"
"regexp"
"strings"
"sync"
)
@ -78,10 +79,17 @@ func Build(path, IP, hostname, domainname string, extraContent []Record) error {
//set main record
var mainRec Record
mainRec.IP = IP
// User might have provided a FQDN in hostname or split it across hostname
// and domainname. We want the FQDN and the bare hostname.
fqdn := hostname
if domainname != "" {
mainRec.Hosts = fmt.Sprintf("%s.%s %s", hostname, domainname, hostname)
fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
}
parts := strings.SplitN(fqdn, ".", 2)
if len(parts) == 2 {
mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
} else {
mainRec.Hosts = hostname
mainRec.Hosts = fqdn
}
if _, err := mainRec.WriteTo(content); err != nil {
return err

View file

@ -81,6 +81,28 @@ func TestBuildHostname(t *testing.T) {
}
}
func TestBuildHostnameFQDN(t *testing.T) {
file, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
err = Build(file.Name(), "10.11.12.13", "testhostname.testdomainname.com", "", nil)
if err != nil {
t.Fatal(err)
}
content, err := ioutil.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}
if expected := "10.11.12.13\ttesthostname.testdomainname.com testhostname\n"; !bytes.Contains(content, []byte(expected)) {
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
}
}
func TestBuildNoIP(t *testing.T) {
file, err := ioutil.TempFile("", "")
if err != nil {