github.com/ddev/ddev@v1.23.2-0.20240519125000-d824ffe36ff3/pkg/ddevhosts/ddevhosts.go (about)

     1  package ddevhosts
     2  
     3  // This package is a simple wrapper on goodhosts.
     4  // Its only current purpose is to provide GetIPPosition as an
     5  // exported function.
     6  
     7  import (
     8  	goodhosts "github.com/goodhosts/hostsfile"
     9  )
    10  
    11  const WSL2WindowsHostsFile = `/mnt/c/Windows/system32/drivers/etc/hosts`
    12  
    13  // DdevHosts uses composition to absorb all exported functions of goodhosts
    14  type DdevHosts struct {
    15  	*goodhosts.Hosts // provides all exported functions from goodhosts
    16  }
    17  
    18  // GetIPPosition is the same as the unexported getIpPosition,
    19  // providing the position of the line in the hosts file that
    20  // supports the IP address we're looking for.
    21  // Or it returns -1 if none is found yet.
    22  func (h DdevHosts) GetIPPosition(ip string) int {
    23  	for i := range h.Lines {
    24  		line := h.Lines[i]
    25  		if !line.IsComment() && line.Raw != "" {
    26  			if line.IP == ip {
    27  				return i
    28  			}
    29  		}
    30  	}
    31  
    32  	return -1
    33  }
    34  
    35  // New is a simple wrapper on goodhosts.NewHosts()
    36  func New() (*DdevHosts, error) {
    37  	h, err := goodhosts.NewHosts()
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  
    42  	return &DdevHosts{h}, nil
    43  }
    44  
    45  func NewCustomHosts(osHostsFilePath string) (*DdevHosts, error) {
    46  	h, err := goodhosts.NewCustomHosts(osHostsFilePath)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	return &DdevHosts{h}, nil
    52  }