From 2430ff09ac9ad953938653b152c3db4edde4b48d Mon Sep 17 00:00:00 2001 From: Aditya Dani Date: Wed, 23 Oct 2019 11:21:21 -0700 Subject: [PATCH] Handle trailing comments on a valid /etc/hosts entry. --- txeh.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/txeh.go b/txeh.go index ae41125..5129332 100644 --- a/txeh.go +++ b/txeh.go @@ -45,6 +45,7 @@ type HostFileLine struct { Hostnames []string Raw string Trimed string + Comment string } // NewHostsDefault returns a hosts object with @@ -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 { @@ -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, " ")) }