Skip to content

Commit

Permalink
fix addition of empty newline to end of known_hosts
Browse files Browse the repository at this point in the history
when cleaning the known_hosts file we are adding a newline to the
end of the file, since the scanner returns the lines without '\n'
character we are adding it to properly recreate the  known_hosts
file, but this ends up adding an extra newline at the end of the
file

this commit changes the splitFunc for bufio.Scanner which returns
the lines with the '\n' character so that we don't have to add it
so the extra newline at the end of the file is not added

the splitFunc is a modified version of the ScanLines function from
the bufio package with the change to return lines along with '\n'
  • Loading branch information
anjannath authored and openshift-merge-robot committed Apr 10, 2023
1 parent afe9670 commit a4e4e24
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion pkg/crc/ssh/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ssh

import (
"bufio"
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
Expand Down Expand Up @@ -98,15 +99,30 @@ func RemoveCRCHostEntriesFromKnownHosts() error {
return fmt.Errorf("Error trying to change permissions for temp file: %w", err)
}

// return each line along with the newline '\n' marker
var splitFunc = func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
return i + 1, data[0 : i+1], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}

var foundCRCEntries bool
scanner := bufio.NewScanner(f)
scanner.Split(splitFunc)
writer := bufio.NewWriter(tempHostsFile)
for scanner.Scan() {
if strings.Contains(scanner.Text(), "[127.0.0.1]:2222") || strings.Contains(scanner.Text(), "192.168.130.11") {
foundCRCEntries = true
continue
}
if _, err := writer.WriteString(fmt.Sprintf("%s\n", scanner.Text())); err != nil {
if _, err := writer.WriteString(scanner.Text()); err != nil {
return fmt.Errorf("Error while writing hostsfile content to temp file: %w", err)
}
}
Expand Down

0 comments on commit a4e4e24

Please sign in to comment.