From 04851aceb8b4668aece48a5fc2ae42929bc5a617 Mon Sep 17 00:00:00 2001 From: Kyle Brennan Date: Sun, 7 Nov 2021 16:30:18 +0000 Subject: [PATCH] Fixes #852 optionally add last newline Signed-off-by: Kyle Brennan --- commands/new_function.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/commands/new_function.go b/commands/new_function.go index 61cfcd1c..b631e09b 100644 --- a/commands/new_function.go +++ b/commands/new_function.go @@ -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 { @@ -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 +}