Skip to content

Commit

Permalink
Ensure added host entries are sorted
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaumerose committed Nov 25, 2020
1 parent 3a1d7cb commit 2f8a4c1
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 3 additions & 0 deletions pkg/hosts/hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package hosts

import (
"fmt"
"sort"
"strings"

"github.com/goodhosts/hostsfile"
Expand Down Expand Up @@ -35,6 +36,8 @@ func (h *Hosts) Add(ip string, hosts []string) error {
hostEntries = append(hostEntries, key)
}

sort.Strings(hostEntries)

if err := h.File.Add(ip, hostEntries...); err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/hosts/hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ func TestAdd(t *testing.T) {

host := hosts(t, hostsFile)

assert.NoError(t, host.Add("127.0.0.1", []string{"entry1", "entry2"}))
assert.NoError(t, host.Add("127.0.0.2", []string{"entry3"}))
assert.NoError(t, host.Add("127.0.0.1", []string{"entry1", "entry2", "entry3"}))
assert.NoError(t, host.Add("127.0.0.2", []string{"entry4"}))

content, err := ioutil.ReadFile(hostsFile)
assert.NoError(t, err)
assert.Equal(t, "127.0.0.1 entry1 entry2\n127.0.0.2 entry3\n", string(content))
assert.Equal(t, "127.0.0.1 entry1 entry2 entry3\n127.0.0.2 entry4\n", string(content))
}

func TestRemove(t *testing.T) {
Expand Down

0 comments on commit 2f8a4c1

Please sign in to comment.