Skip to content

Commit

Permalink
Fix etchosts.Update to not target hosts with given hostname as prefix
Browse files Browse the repository at this point in the history
Signed-off-by: Travis Thieman <travis.thieman@gmail.com>
  • Loading branch information
thieman committed Dec 6, 2015
1 parent 077b076 commit cebc4fb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
4 changes: 2 additions & 2 deletions etchosts/etchosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,6 @@ func Update(path, IP, hostname string) error {
if err != nil {
return err
}
var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)", regexp.QuoteMeta(hostname)))
return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2")), 0644)
var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname)))
return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644)
}
49 changes: 49 additions & 0 deletions etchosts/etchosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,55 @@ func TestUpdate(t *testing.T) {
}
}

// Regression test for GitHub issue #603
func TestUpdateIgnoresPrefixedHostname(t *testing.T) {
file, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())

if err := Build(file.Name(), "10.11.12.13", "testhostname", "testdomainname", []Record{
Record{
Hosts: "prefix",
IP: "2.2.2.2",
},
Record{
Hosts: "prefixAndMore",
IP: "3.3.3.3",
},
Record{
Hosts: "unaffectedHost",
IP: "4.4.4.4",
},
}); err != nil {
t.Fatal(err)
}

content, err := ioutil.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}

if expected := "2.2.2.2\tprefix\n3.3.3.3\tprefixAndMore\n4.4.4.4\tunaffectedHost\n"; !bytes.Contains(content, []byte(expected)) {
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
}

if err := Update(file.Name(), "5.5.5.5", "prefix"); err != nil {
t.Fatal(err)
}

content, err = ioutil.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}

if expected := "5.5.5.5\tprefix\n3.3.3.3\tprefixAndMore\n4.4.4.4\tunaffectedHost\n"; !bytes.Contains(content, []byte(expected)) {
t.Fatalf("Expected to find '%s' got '%s'", expected, content)
}

}

func TestAddEmpty(t *testing.T) {
file, err := ioutil.TempFile("", "")
if err != nil {
Expand Down

0 comments on commit cebc4fb

Please sign in to comment.