AppendLineToFile adds a new line in file
(filename, line string)
| 112 | |
| 113 | // AppendLineToFile adds a new line in file |
| 114 | func (c *OSCommand) AppendLineToFile(filename, line string) error { |
| 115 | msg := utils.ResolvePlaceholderString( |
| 116 | c.Tr.Log.AppendingLineToFile, |
| 117 | map[string]string{ |
| 118 | "line": line, |
| 119 | "filename": filename, |
| 120 | }, |
| 121 | ) |
| 122 | c.LogCommand(msg, false) |
| 123 | |
| 124 | f, err := os.OpenFile(filename, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0o600) |
| 125 | if err != nil { |
| 126 | return utils.WrapError(err) |
| 127 | } |
| 128 | defer f.Close() |
| 129 | |
| 130 | info, err := os.Stat(filename) |
| 131 | if err != nil { |
| 132 | return utils.WrapError(err) |
| 133 | } |
| 134 | |
| 135 | if info.Size() > 0 { |
| 136 | // read last char |
| 137 | buf := make([]byte, 1) |
| 138 | if _, err := f.ReadAt(buf, info.Size()-1); err != nil { |
| 139 | return utils.WrapError(err) |
| 140 | } |
| 141 | |
| 142 | // if the last byte of the file is not a newline, add it |
| 143 | if []byte("\n")[0] != buf[0] { |
| 144 | _, err = f.WriteString("\n") |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | if err == nil { |
| 149 | _, err = f.WriteString(line + "\n") |
| 150 | } |
| 151 | |
| 152 | if err != nil { |
| 153 | return utils.WrapError(err) |
| 154 | } |
| 155 | return nil |
| 156 | } |
| 157 | |
| 158 | // CreateFileWithContent creates a file with the given content |
| 159 | func (c *OSCommand) CreateFileWithContent(path string, content string) error { |