import os
import re
import subprocess
import sys
from itertools import zip_longest
def read_olds(reader):
for line in reader:
if re.search(r'^```$', line):
break
yield line
def read_news():
command = ['rpn', '--command', 'help']
process = subprocess.Popen(command, stdout=subprocess.PIPE, text=True)
for line in process.stdout:
yield f' {line}'
def replace_help(reader, writer):
dirty = False
olds = read_olds(reader)
news = read_news()
for old, new in zip_longest(olds, news):
if new is not None:
print(new, end='', file=writer)
dirty |= (new != old)
elif old is not None:
dirty = True
print('```', file=writer)
return dirty
def modify_stream(reader, writer):
dirty = False
quoted = False
for line in reader:
print(line, end='', file=writer)
if quoted:
if re.search(r'^dec> help$', line):
dirty |= replace_help(reader, writer)
quoted = False
elif re.search(r'^```$', line):
quoted = False
else:
if re.search(r'^```$', line):
quoted = True
return dirty
def modify_paths(paths):
if paths:
for path in paths:
temp = f'{path}.___'
with open(path, 'r') as reader:
with open(temp, 'w') as writer:
dirty = modify_stream(reader, writer)
if dirty:
print(path)
os.rename(temp, path)
else:
os.remove(temp)
else:
modify_stream(sys.stdin, sys.stdout)
paths = sys.argv[1:]
modify_paths(paths)