diff --git a/etchosts/etchosts.go b/etchosts/etchosts.go index 256a89dfa8..5f68372b90 100644 --- a/etchosts/etchosts.go +++ b/etchosts/etchosts.go @@ -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) } diff --git a/etchosts/etchosts_test.go b/etchosts/etchosts_test.go index a79b43b6b7..13e3a211d6 100644 --- a/etchosts/etchosts_test.go +++ b/etchosts/etchosts_test.go @@ -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 {