Skip to content

Commit

Permalink
Fixes openfaas#852 optionally add last newline
Browse files Browse the repository at this point in the history
Signed-off-by: Kyle Brennan <[email protected]>
  • Loading branch information
kylos101 committed Nov 7, 2021
1 parent b562392 commit 04851ac
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions commands/new_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ Download templates:
}

fileName = appendFile

newLineErr := addLastNewline("./" + fileName)
if newLineErr != nil {
return newLineErr
}
outputMsg = fmt.Sprintf("Stack file updated: %s\n", fileName)

} else {
Expand Down Expand Up @@ -346,3 +351,33 @@ Cannot have duplicate function names in same yaml file`, functionName, appendFil

return nil
}

func addLastNewline(fileName string) error {
// open a file as read write
file, err := os.OpenFile(fileName, os.O_RDWR, 0600)
defer file.Close()
if err != nil {
return fmt.Errorf("could not open '%s' to check for new lines %s", fileName, err)
}

// read the last byte of the file (excludes EOF)
buffer := make([]byte, 1)
fileStats, _ := file.Stat()
bytesRead, err := file.ReadAt(buffer, fileStats.Size()-1)

// handle I/O errors
if err != nil {
return fmt.Errorf("could not read the last byte of '%s' %s", fileName, err)
} else if bytesRead != 1 {
return fmt.Errorf("read unexpected # of bytes in '%s'", fileName)
}

hasTrailingNewline := string(buffer) == "\n"
if !hasTrailingNewline {
// add 2 trailing newlines
// this is consistent with append behavior when last byte is already \n
file.Seek(0, 2)
file.Write([]byte("\n\n"))
}
return nil
}

0 comments on commit 04851ac

Please sign in to comment.