Skip to content

Commit

Permalink
Handle trailing comments on a valid /etc/hosts entry.
Browse files Browse the repository at this point in the history
  • Loading branch information
adityadani committed Oct 23, 2019
1 parent 01dac41 commit 2430ff0
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions txeh.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type HostFileLine struct {
Hostnames []string
Raw string
Trimed string
Comment string
}

// NewHostsDefault returns a hosts object with
Expand Down Expand Up @@ -322,6 +323,12 @@ func ParseHosts(path string) ([]HostFileLine, error) {
continue
}

curLineSplit := strings.SplitN(curLine.Trimed, "#", 2)
if len(curLineSplit) > 1 {
curLine.Comment = curLineSplit[1]
}
curLine.Trimed = curLineSplit[0]

curLine.Parts = strings.Fields(curLine.Trimed)

if len(curLine.Parts) > 1 {
Expand Down Expand Up @@ -361,5 +368,8 @@ func lineFormatter(hfl HostFileLine) string {
return hfl.Raw
}

if len(hfl.Comment) > 0 {
return fmt.Sprintf("%-16s %s #%s", hfl.Address, strings.Join(hfl.Hostnames, " "), hfl.Comment)
}
return fmt.Sprintf("%-16s %s", hfl.Address, strings.Join(hfl.Hostnames, " "))
}

0 comments on commit 2430ff0

Please sign in to comment.