From d614eb6a9c883ac7cb551084fb520adcca8a4ae6 Mon Sep 17 00:00:00 2001 From: Guillaume Rose Date: Tue, 16 Mar 2021 09:35:08 +0100 Subject: [PATCH] Verify hosts to delete instead of suffixes when cleaning hosts file Clean(".crc.testing") is rejected by the hosts filter. This is a mistake. Without adding a second filter function, we can verify hosts to be deleted before writing the file. --- pkg/hosts/hosts.go | 8 ++++---- pkg/hosts/hosts_test.go | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/pkg/hosts/hosts.go b/pkg/hosts/hosts.go index 79ca9e96..c0f2cd8e 100644 --- a/pkg/hosts/hosts.go +++ b/pkg/hosts/hosts.go @@ -97,10 +97,6 @@ func (h *Hosts) Remove(hosts []string) error { } func (h *Hosts) Clean(rawSuffixes []string) error { - if err := h.verifyHosts(rawSuffixes); err != nil { - return err - } - if err := h.checkIsWritable(); err != nil { return err } @@ -125,6 +121,10 @@ func (h *Hosts) Clean(rawSuffixes []string) error { } } + if err := h.verifyHosts(toDelete); err != nil { + return err + } + for _, host := range toDelete { if err := h.File.RemoveByHostname(host); err != nil { return err diff --git a/pkg/hosts/hosts_test.go b/pkg/hosts/hosts_test.go index f23a86f7..8c70c0ee 100644 --- a/pkg/hosts/hosts_test.go +++ b/pkg/hosts/hosts_test.go @@ -84,7 +84,7 @@ func TestSuffixFilter(t *testing.T) { defer os.RemoveAll(dir) hostsFile := filepath.Join(dir, "hosts") - assert.NoError(t, ioutil.WriteFile(hostsFile, []byte(`127.0.0.1 localhost`), 0600)) + assert.NoError(t, ioutil.WriteFile(hostsFile, []byte(`127.0.0.1 localhost localhost.localdomain`), 0600)) file, err := hostsfile.NewCustomHosts(hostsFile) assert.NoError(t, err) @@ -99,6 +99,8 @@ func TestSuffixFilter(t *testing.T) { assert.Error(t, host.Add("127.0.0.1", []string{"host.poison"})) assert.Error(t, host.Add("127.0.0.1", []string{"CAPITAL.crc.testing"})) assert.Error(t, host.Remove([]string{"localhost"})) + assert.NoError(t, host.Clean([]string{".crc.testing"})) + assert.Error(t, host.Clean([]string{".localdomain"})) } func hosts(t *testing.T, hostsFile string) Hosts {