| 223 | fd.write("\n") |
| 224 | |
| 225 | def append_reload_and_write( |
| 226 | self, s: str, filename: Path, encoding: str |
| 227 | ) -> None: |
| 228 | if not self.hist_size: |
| 229 | return self.append(s) |
| 230 | |
| 231 | try: |
| 232 | fd = os.open( |
| 233 | filename, |
| 234 | os.O_APPEND | os.O_RDWR | os.O_CREAT, |
| 235 | stat.S_IRUSR | stat.S_IWUSR, |
| 236 | ) |
| 237 | with open(fd, "a+", encoding=encoding, errors="ignore") as hfile: |
| 238 | with FileLock(hfile, filename=str(filename)): |
| 239 | # read entries |
| 240 | hfile.seek(0, os.SEEK_SET) |
| 241 | entries = self.load_from(hfile) |
| 242 | self.append_to(entries, s) |
| 243 | |
| 244 | # write new entries |
| 245 | hfile.seek(0, os.SEEK_SET) |
| 246 | hfile.truncate() |
| 247 | self.save_to(hfile, entries, self.hist_size) |
| 248 | |
| 249 | self.entries = entries |
| 250 | except OSError as err: |
| 251 | raise RuntimeError( |
| 252 | _("Error occurred while writing to file %s (%s)") |
| 253 | % (filename, err.strerror) |
| 254 | ) |
| 255 | else: |
| 256 | if len(self.entries) == 0: |
| 257 | # Make sure that entries contains at least one element. If the |
| 258 | # file and s are empty, this can occur. |
| 259 | self.entries = [""] |