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 Oct 9, 2015
1 parent d4989a6 commit 069c342
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
4 changes: 2 additions & 2 deletions etchosts/etchosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,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)
}
10 changes: 7 additions & 3 deletions etchosts/etchosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ func TestUpdateIgnoresPrefixedHostname(t *testing.T) {
Hosts: "prefixAndMore",
IP: "3.3.3.3",
},
Record{
Hosts: "unaffectedHost",
IP: "4.4.4.4",
},
}); err != nil {
t.Fatal(err)
}
Expand All @@ -161,11 +165,11 @@ func TestUpdateIgnoresPrefixedHostname(t *testing.T) {
t.Fatal(err)
}

if expected := "2.2.2.2\tprefix\n3.3.3.3\tprefixAndMore\n"; !bytes.Contains(content, []byte(expected)) {
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(), "4.4.4.4", "prefix"); err != nil {
if err := Update(file.Name(), "5.5.5.5", "prefix"); err != nil {
t.Fatal(err)
}

Expand All @@ -174,7 +178,7 @@ func TestUpdateIgnoresPrefixedHostname(t *testing.T) {
t.Fatal(err)
}

if expected := "4.4.4.4\tprefix\n3.3.3.3\tprefixAndMore\n"; !bytes.Contains(content, []byte(expected)) {
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)
}

Expand Down

0 comments on commit 069c342

Please sign in to comment.