@@ -153,10 +153,10 @@ Download templates:
153153
154154 fileName = appendFile
155155
156- newLineErr := addLastNewline ("./" + fileName )
157- if newLineErr != nil {
158- return newLineErr
156+ if err := addLastNewline ("./" + fileName ); err != nil {
157+ return err
159158 }
159+
160160 outputMsg = fmt .Sprintf ("Stack file updated: %s\n " , fileName )
161161
162162 } else {
@@ -353,31 +353,26 @@ Cannot have duplicate function names in same yaml file`, functionName, appendFil
353353}
354354
355355func 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 ()
356+ bytes , err := os .ReadFile (fileName )
359357 if err != nil {
360358 return fmt .Errorf ("could not open '%s' to check for new lines %s" , fileName , err )
361359 }
362360
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 )
361+ content := string (bytes )
362+ hasLastNewline := strings .HasSuffix (content , "\n " )
363+ if hasLastNewline {
364+ return nil
365+ }
367366
368- // handle I/O errors
367+ file , err := os . OpenFile ( fileName , os . O_APPEND | os . O_WRONLY | os . O_CREATE , 0600 )
369368 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 )
369+ return fmt .Errorf ("could not open '%s' to append new lines %s" , fileName , err )
373370 }
371+ defer file .Close ()
374372
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 " ))
373+ if _ , err = file .WriteString ("\n \n " ); err != nil {
374+ return fmt .Errorf ("could not write to '%s' to append new lines %s" , fileName , err )
381375 }
376+
382377 return nil
383378}
0 commit comments