@@ -16,6 +16,7 @@ type HostEntry struct {
1616 idx int
1717 IP string
1818 Hostname string
19+ Comment string
1920}
2021
2122// HostsAPI data structure
@@ -35,25 +36,37 @@ func parseHostfileLine(idx int, line string) ([]*HostEntry, error) {
3536 return nil , errors .New ("comment line" )
3637 }
3738 fields := strings .Fields (line )
38- var validfields []string
39- for _ , f := range fields {
40- if len (f ) <= 0 {
39+ var ip string
40+ var hostnames []string
41+ var comment string
42+ var commentidx int
43+ for i , f := range fields {
44+ if f == "" {
4145 continue
4246 }
4347 if f [0 ] == '#' { // inline comment
48+ commentidx = i + 1
4449 break // don't process any more
4550 }
46- validfields = append (validfields , f )
51+ if i == 0 {
52+ ip = f
53+ } else {
54+ hostnames = append (hostnames , f )
55+ }
56+ }
57+ if commentidx > 0 {
58+ comment = strings .Join (fields [commentidx :], " " )
4759 }
48- if len (validfields ) <= 1 {
60+ if ip == "" || len (hostnames ) == 0 {
4961 return nil , fmt .Errorf ("invalid fields for line: %q" , line )
5062 }
5163 var entries []* HostEntry
52- for _ , hostname := range validfields [ 1 :] {
64+ for _ , hostname := range hostnames {
5365 entries = append (entries , & HostEntry {
5466 idx : idx ,
55- IP : validfields [ 0 ] ,
67+ IP : ip ,
5668 Hostname : hostname ,
69+ Comment : comment ,
5770 })
5871 }
5972
@@ -72,7 +85,7 @@ func (h *HostsAPI) loadAndParse() error {
7285 continue
7386 }
7487 for _ , e := range entries {
75- if h .filter == "" || strings .Contains (e .Hostname , h .filter ) {
88+ if h .filter == "" || strings .Contains (e .Comment , h .filter ) {
7689 h .entries [e .Hostname ] = e
7790 h .remidxs [e .idx ] = nil
7891 }
@@ -155,10 +168,13 @@ func (h *HostsAPI) Write() error {
155168
156169 // append entries to file
157170 for _ , e := range h .entries {
158- outbuf .WriteString (fmt .Sprintf ("%s %s # managed by wsl2-host\r \n " , e .IP , e .Hostname ))
171+ var comment string
172+ if e .Comment != "" {
173+ comment = fmt .Sprintf (" # %s" , e .Comment )
174+ }
175+ outbuf .WriteString (fmt .Sprintf ("%s %s%s\r \n " , e .IP , e .Hostname , comment ))
159176 }
160177
161- fmt .Println (string (outbuf .Bytes ()))
162178 f , err := os .OpenFile (hostspath , os .O_WRONLY | os .O_TRUNC , 0600 )
163179 if err != nil {
164180 return fmt .Errorf ("failed to open hosts file for writing: %w" , err )
0 commit comments