Skip to content

Commit 04851ac

Browse files
committed
Fixes #852 optionally add last newline
Signed-off-by: Kyle Brennan <[email protected]>
1 parent b562392 commit 04851ac

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

commands/new_function.go

+35
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ Download templates:
152152
}
153153

154154
fileName = appendFile
155+
156+
newLineErr := addLastNewline("./" + fileName)
157+
if newLineErr != nil {
158+
return newLineErr
159+
}
155160
outputMsg = fmt.Sprintf("Stack file updated: %s\n", fileName)
156161

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

347352
return nil
348353
}
354+
355+
func addLastNewline(fileName string) error {
356+
// open a file as read write
357+
file, err := os.OpenFile(fileName, os.O_RDWR, 0600)
358+
defer file.Close()
359+
if err != nil {
360+
return fmt.Errorf("could not open '%s' to check for new lines %s", fileName, err)
361+
}
362+
363+
// read the last byte of the file (excludes EOF)
364+
buffer := make([]byte, 1)
365+
fileStats, _ := file.Stat()
366+
bytesRead, err := file.ReadAt(buffer, fileStats.Size()-1)
367+
368+
// handle I/O errors
369+
if err != nil {
370+
return fmt.Errorf("could not read the last byte of '%s' %s", fileName, err)
371+
} else if bytesRead != 1 {
372+
return fmt.Errorf("read unexpected # of bytes in '%s'", fileName)
373+
}
374+
375+
hasTrailingNewline := string(buffer) == "\n"
376+
if !hasTrailingNewline {
377+
// add 2 trailing newlines
378+
// this is consistent with append behavior when last byte is already \n
379+
file.Seek(0, 2)
380+
file.Write([]byte("\n\n"))
381+
}
382+
return nil
383+
}

0 commit comments

Comments
 (0)