| 41 | |
| 42 | |
| 43 | def replace(filename, blockname, language, content): |
| 44 | start, stop = comment_style[language] |
| 45 | |
| 46 | tempfile = f"{filename}.tmp" |
| 47 | |
| 48 | with open(filename, 'r') as i, open(tempfile, 'w') as o: |
| 49 | lines = i.readlines() |
| 50 | # Read lines up to the marker |
| 51 | while lines != []: |
| 52 | l = lines.pop(0) |
| 53 | o.write(l) |
| 54 | if l.strip() == start.format(blockname=blockname): |
| 55 | break |
| 56 | |
| 57 | o.write(content) |
| 58 | |
| 59 | # Skip lines until we get the end marker |
| 60 | while lines != []: |
| 61 | l = lines.pop(0) |
| 62 | if l.strip() == stop.format(blockname=blockname): |
| 63 | o.write(l) |
| 64 | break |
| 65 | |
| 66 | # Now flush the rest of the file |
| 67 | for l in lines: |
| 68 | o.write(l) |
| 69 | |
| 70 | # Move the temp file over the old one for an atomic replacement |
| 71 | os.rename(tempfile, filename) |
| 72 | |
| 73 | |
| 74 | def main(args): |