Browse Source

fix commenting on line addition and removal

tags/v3.1.0
Chris Wiegman 5 months ago
parent
commit
f94c3d4851
Signed by: chriswiegman <chris@chriswiegman.com> GPG Key ID: 2B23D7A74FDE2DF4
4 changed files with 23 additions and 14 deletions
  1. +1
    -1
      cmd/main.go
  2. +3
    -2
      hostLine.go
  3. +13
    -9
      hostsFile.go
  4. +6
    -2
      utils.go

+ 1
- 1
cmd/main.go View File

@@ -87,7 +87,7 @@ Options:
os.Exit(1)
}

err = hosts.Add(ip, "", hostEntries...)
err = hosts.Add(ip, "This is a test comment", hostEntries...)
if err != nil {
fmt.Fprintln(os.Stderr, fmt.Sprintf("%s", err.Error()))
os.Exit(2)


+ 3
- 2
hostLine.go View File

@@ -10,7 +10,7 @@ import (
type HostsLine struct {
IP string
Hosts []string
comment string
Comment string
Raw string
Err error
}
@@ -35,7 +35,8 @@ func NewHostsLine(raw string) HostsLine {

for i, field := range fields {
if IsComment(field) {
output.comment = field[i:]
output.Comment = strings.Join(fields[i:], " ")
output.Comment = output.Comment[1:]
break
}
outputFields = append(outputFields, field)


+ 13
- 9
hostsFile.go View File

@@ -56,6 +56,7 @@ func (h *Hosts) Load() error {

// Flush any changes made to hosts file.
func (h Hosts) Flush() error {

file, err := os.Create(h.Path)
if err != nil {
return err
@@ -64,11 +65,7 @@ func (h Hosts) Flush() error {
w := bufio.NewWriter(file)

for _, line := range h.Lines {
var comment string
if len(line.comment) > 0 {
comment = " #" + line.comment
}
fmt.Fprintf(w, "%s%s%s", line.Raw, comment, eol)
fmt.Fprintf(w, "%s%s", line.Raw, eol)
}

err = w.Flush()
@@ -88,16 +85,18 @@ func (h *Hosts) Add(ip, comment string, hosts ...string) error {

for _, host := range hosts {

endLine := NewHostsLine(buildRawLine(ip, host))
endLine.comment = comment
h.Lines = append(h.Lines, endLine)
if !h.Has(ip, host) {
endLine := NewHostsLine(buildRawLine(ip, host, comment))
endLine.Comment = comment
h.Lines = append(h.Lines, endLine)
}
}

return nil
}

// Has Return a bool if ip/host combo in hosts file.
func (h Hosts) Has(ip string, host string) bool {
func (h *Hosts) Has(ip string, host string) bool {
pos := h.getHostPosition(ip, host)

return pos != -1
@@ -133,6 +132,11 @@ func (h *Hosts) Remove(ip string, hosts ...string) error {
for _, host := range newHosts {
newLineRaw = fmt.Sprintf("%s %s", newLineRaw, host)
}

if len(line.Comment) > 0 {
newLineRaw = fmt.Sprintf("%s #%s", newLineRaw, line.Comment)
}

newLine := NewHostsLine(newLineRaw)
outputLines = append(outputLines, newLine)
}


+ 6
- 2
utils.go View File

@@ -15,9 +15,13 @@ func itemInSlice(item string, list []string) bool {
return false
}

func buildRawLine(ip string, host string) string {
func buildRawLine(ip string, host, comment string) string {
output := ip
output = fmt.Sprintf("%s %s", output, host)

if len(comment) > 0 {
comment = "#" + comment
}
output = fmt.Sprintf("%s %s %s", output, host, comment)

return output
}


Loading…
Cancel
Save