Upgrade contentreplace to use real argparse.

This commit is contained in:
Ethan Dalool 2019-04-18 18:49:44 -07:00
parent 71670f3c99
commit e26c8abcee

View file

@ -1,34 +1,22 @@
import glob import argparse
import codecs import codecs
import glob
import sys import sys
filenames = glob.glob(sys.argv[1])
replace_from = sys.argv[2]
replace_to = sys.argv[3]
try:
automatic = sys.argv[4] == '-y'
except IndexError:
automatic = False
replace_from = codecs.decode(replace_from, 'unicode_escape') def contentreplace(filename, replace_from, replace_to, autoyes=False):
replace_to = codecs.decode(replace_to, 'unicode_escape')
def contentreplace(filename):
f = open(filename, 'r', encoding='utf-8') f = open(filename, 'r', encoding='utf-8')
with f: with f:
content = f.read() content = f.read()
occurances = content.count(replace_from) occurances = content.count(replace_from)
print(f'{filename}: Found {occurances} occurences.')
if occurances == 0: if occurances == 0:
print('No occurences')
return return
print('Found %d occurences.' % occurances) permission = autoyes or (input('Replace? ').lower() in ('y', 'yes'))
if automatic: if not permission:
permission = 'y' return
else:
permission = input('Replace? ')
if permission.lower() not in ['y', 'yes']:
exit()
content = content.replace(replace_from, replace_to) content = content.replace(replace_from, replace_to)
@ -36,5 +24,27 @@ def contentreplace(filename):
with f: with f:
f.write(content) f.write(content)
def contentreplace_argparse(args):
filenames = glob.glob(args.filename_glob)
for filename in filenames: for filename in filenames:
contentreplace(filename) contentreplace(
filename,
codecs.decode(args.replace_from, 'unicode_escape'),
codecs.decode(args.replace_to, 'unicode_escape'),
autoyes=args.autoyes,
)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('filename_glob')
parser.add_argument('replace_from')
parser.add_argument('replace_to')
parser.add_argument('-y', '--yes', dest='autoyes', action='store_true', help='accept results without confirming')
parser.set_defaults(func=contentreplace_argparse)
args = parser.parse_args(argv)
args.func(args)
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))