Skip to content

Commit

Permalink
fixing multiple calls to add and hostsperline from being destructive
Browse files Browse the repository at this point in the history
  • Loading branch information
luthermonson committed Oct 29, 2023
1 parent 6570bd5 commit efb40e8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
13 changes: 8 additions & 5 deletions hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ func (h *Hosts) Add(ip string, hosts ...string) error {
})
} else {
// add new host to the first one we find
hostsCopy := h.Lines[position[0]].Hosts
loc := position[len(position)-1] // last element
hostsCopy := make([]string, len(h.Lines[position[loc]].Hosts))
copy(hostsCopy, h.Lines[position[loc]].Hosts)

for _, addHost := range hosts {
if h.Has(ip, addHost) {
continue // this combo already exists
Expand All @@ -186,10 +189,10 @@ func (h *Hosts) Add(ip string, hosts ...string) error {
}

hostsCopy = append(hostsCopy, addHost)
h.hosts.add(addHost, position[0])
h.hosts.add(addHost, position[loc])
}
h.Lines[position[0]].Hosts = hostsCopy
h.Lines[position[0]].Raw = h.Lines[position[0]].ToRaw() // reset raw
h.Lines[position[loc]].Hosts = hostsCopy
h.Lines[position[loc]].RegenRaw()
}

return nil
Expand Down Expand Up @@ -477,7 +480,7 @@ func (h *Hosts) HostsPerLine(count int) {
h.ips.add(line.IP, ln+j)

lineCopy.Hosts = line.Hosts[i:end]
lineCopy.Raw = lineCopy.ToRaw()
lineCopy.RegenRaw()
h.Lines = append(h.Lines, lineCopy)
}
}
Expand Down
14 changes: 13 additions & 1 deletion hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,19 @@ func TestHosts_HostsPerLine(t *testing.T) {
assert.Len(t, hosts.ips.l, 1)
assert.Len(t, hosts.hosts.l, 10)

assert.Nil(t, hosts.Add("127.0.0.2", "host1", "host2", "host3", "host4", "host5", "host6", "host7", "host8", "host9", "hosts10"))
// test if multiple calls to HostsPerLine doesn't create havoc and has identical output as calling it once
hosts = newHosts()
for i := 1; i <= 50; i++ {
assert.Nil(t, hosts.Add("127.0.0.1", fmt.Sprintf("a%d.ddev.site", i)))
hosts.HostsPerLine(8) // 8
}

hosts2 := newHosts()
for i := 1; i <= 50; i++ {
assert.Nil(t, hosts2.Add("127.0.0.1", fmt.Sprintf("a%d.ddev.site", i)))
}
hosts2.HostsPerLine(8) // 8
assert.Equal(t, hosts.String(), hosts2.String())
}

func BenchmarkHosts_Add(b *testing.B) {
Expand Down

0 comments on commit efb40e8

Please # to comment.