Skip to content

Commit

Permalink
Incorporate code review feedback
Browse files Browse the repository at this point in the history
Signed-off-by: Kyle Brennan <[email protected]>
  • Loading branch information
kylos101 committed Nov 17, 2021
1 parent 04851ac commit 3a2cd9c
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions commands/new_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ Download templates:

fileName = appendFile

newLineErr := addLastNewline("./" + fileName)
if newLineErr != nil {
return newLineErr
if err := addLastNewline("./" + fileName); err != nil {
return err
}

outputMsg = fmt.Sprintf("Stack file updated: %s\n", fileName)

} else {
Expand Down Expand Up @@ -353,31 +353,26 @@ Cannot have duplicate function names in same yaml file`, functionName, appendFil
}

func addLastNewline(fileName string) error {
// open a file as read write
file, err := os.OpenFile(fileName, os.O_RDWR, 0600)
defer file.Close()
bytes, err := os.ReadFile(fileName)
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)
content := string(bytes)
hasLastNewline := strings.HasSuffix(content, "\n")
if hasLastNewline {
return nil
}

// handle I/O errors
file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
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)
return fmt.Errorf("could not open '%s' to append new lines %s", fileName, err)
}
defer file.Close()

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"))
if _, err = file.WriteString("\n\n"); err != nil {
return fmt.Errorf("could not write to '%s' to append new lines %s", fileName, err)
}

return nil
}

0 comments on commit 3a2cd9c

Please sign in to comment.