Skip to content

Commit

Permalink
fix hostctl header and skip consecutive empty lines.
Browse files Browse the repository at this point in the history
  • Loading branch information
guumaster committed Apr 21, 2020
1 parent e621991 commit fa9ae14
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
14 changes: 13 additions & 1 deletion pkg/host/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,15 @@ func Parse(r io.Reader) (*Content, error) {

default:
row := parseToDefault(b, currProfile)
data.DefaultProfile = append(data.DefaultProfile, row)

// When hostctl banner line is detected, remove previous and next line
if isBannerLine(row) {
data.DefaultProfile = data.DefaultProfile[0 : len(data.DefaultProfile)-1]

s.Scan() // skip next line
} else {
data.DefaultProfile = append(data.DefaultProfile, row)
}
}

if err := s.Err(); err != nil {
Expand All @@ -67,6 +75,10 @@ func Parse(r io.Reader) (*Content, error) {
return data, nil
}

func isBannerLine(r *render.Row) bool {
return strings.Contains(r.Comment, "# Content under this line is handled by hostctl. DO NOT EDIT.")
}

func appendLine(p *Profile, line string) {
if line == "" {
return
Expand Down
37 changes: 27 additions & 10 deletions pkg/host/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net"
"strings"

"github.com/guumaster/hostctl/pkg/host/errors"
"github.com/guumaster/hostctl/pkg/host/render"
Expand Down Expand Up @@ -167,17 +168,17 @@ func (p *Profile) Render(w io.StringWriter) error {
func (d DefaultProfile) Render(w io.StringWriter) error {
tmp := bytes.NewBufferString("")

for _, row := range d {
line := ""
if row.Comment != "" {
line = row.Comment
} else {
prefix := ""
if row.Status == string(Disabled) {
prefix = "# "
}
for i, row := range d {
line := getLine(row)
nextLine := ""

line = fmt.Sprintf("%s%s %s", prefix, row.IP, row.Host)
if i+1 < len(d) {
nextLine = getLine(d[i+1])
}

// skips two consecutive empty lines
if line == "" && nextLine == "" {
continue
}

_, err := tmp.WriteString(line + "\n")
Expand All @@ -192,6 +193,22 @@ func (d DefaultProfile) Render(w io.StringWriter) error {
return err
}

func getLine(row *render.Row) string {
line := ""
if row.Comment != "" {
line = row.Comment
} else {
prefix := ""
if row.Status == string(Disabled) {
prefix = "# "
}

line = fmt.Sprintf("%s%s %s", prefix, row.IP, row.Host)
}

return strings.TrimSpace(line)
}

func remove(s []string, n string) []string {
list := []string{}

Expand Down

0 comments on commit fa9ae14

Please sign in to comment.