Ran black on branc

This commit is contained in:
Griatch 2019-12-16 20:31:42 +01:00
parent 6effb6f456
commit 4ea6209123
230 changed files with 7108 additions and 2395 deletions

View file

@ -23,7 +23,7 @@ USE_COLOR = True
FAKE_MODE = False
# if these words are longer than output word, retain given case
CASE_WORD_EXCEPTIONS = ('an', )
CASE_WORD_EXCEPTIONS = ("an",)
_HELP_TEXT = """This program interactively renames words in all files of your project. It's
currently renaming {sources} to {targets}.
@ -80,6 +80,7 @@ def _case_sensitive_replace(string, old, new):
`old` has been replaced with `new`, retaining case.
"""
def repl(match):
current = match.group()
# treat multi-word sentences word-by-word
@ -99,15 +100,21 @@ def _case_sensitive_replace(string, old, new):
all_upper = False
# special cases - keep remaing case)
if new_word.lower() in CASE_WORD_EXCEPTIONS:
result.append(new_word[ind + 1:])
result.append(new_word[ind + 1 :])
# append any remaining characters from new
elif all_upper:
result.append(new_word[ind + 1:].upper())
result.append(new_word[ind + 1 :].upper())
else:
result.append(new_word[ind + 1:].lower())
result.append(new_word[ind + 1 :].lower())
out.append("".join(result))
# if we have more new words than old ones, just add them verbatim
out.extend([new_word for ind, new_word in enumerate(new_words) if ind >= len(old_words)])
out.extend(
[
new_word
for ind, new_word in enumerate(new_words)
if ind >= len(old_words)
]
)
return " ".join(out)
regex = re.compile(re.escape(old), re.I)
@ -147,7 +154,9 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
print("%s skipped (excluded)." % full_path)
continue
if not fileend_list or any(file.endswith(ending) for ending in fileend_list):
if not fileend_list or any(
file.endswith(ending) for ending in fileend_list
):
rename_in_file(full_path, in_list, out_list, is_interactive)
# rename file - always ask
@ -155,8 +164,10 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
for src, dst in repl_mapping:
new_file = _case_sensitive_replace(new_file, src, dst)
if new_file != file:
inp = input(_green("Rename %s\n -> %s\n Y/[N]? > " % (file, new_file)))
if inp.upper() == 'Y':
inp = input(
_green("Rename %s\n -> %s\n Y/[N]? > " % (file, new_file))
)
if inp.upper() == "Y":
new_full_path = os.path.join(root, new_file)
try:
os.rename(full_path, new_full_path)
@ -171,8 +182,10 @@ def rename_in_tree(path, in_list, out_list, excl_list, fileend_list, is_interact
for src, dst in repl_mapping:
new_root = _case_sensitive_replace(new_root, src, dst)
if new_root != root:
inp = input(_green("Dir Rename %s\n -> %s\n Y/[N]? > " % (root, new_root)))
if inp.upper() == 'Y':
inp = input(
_green("Dir Rename %s\n -> %s\n Y/[N]? > " % (root, new_root))
)
if inp.upper() == "Y":
try:
os.rename(root, new_root)
except OSError as err:
@ -201,7 +214,7 @@ def rename_in_file(path, in_list, out_list, is_interactive):
print("%s is a directory. You should use the --recursive option." % path)
sys.exit()
with open(path, 'r') as fil:
with open(path, "r") as fil:
org_text = fil.read()
repl_mapping = list(zip(in_list, out_list))
@ -215,7 +228,7 @@ def rename_in_file(path, in_list, out_list, is_interactive):
if FAKE_MODE:
print(" ... Saved changes to %s. (faked)" % path)
else:
with open(path, 'w') as fil:
with open(path, "w") as fil:
fil.write(new_text)
print(" ... Saved changes to %s." % path)
else:
@ -239,18 +252,24 @@ def rename_in_file(path, in_list, out_list, is_interactive):
while True:
for iline, renamed_line in sorted(list(renamed.items()), key=lambda tup: tup[0]):
for iline, renamed_line in sorted(
list(renamed.items()), key=lambda tup: tup[0]
):
print("%3i orig: %s" % (iline + 1, org_lines[iline]))
print(" new : %s" % (_yellow(renamed_line)))
print(_green("%s (%i lines changed)" % (path, len(renamed))))
ret = input(_green("Choose: "
"[q]uit, "
"[h]elp, "
"[s]kip file, "
"[i]gnore lines, "
"[c]lear ignores, "
"[a]ccept/save file: ".lower()))
ret = input(
_green(
"Choose: "
"[q]uit, "
"[h]elp, "
"[s]kip file, "
"[i]gnore lines, "
"[c]lear ignores, "
"[a]ccept/save file: ".lower()
)
)
if ret == "s":
# skip file entirely
@ -267,7 +286,7 @@ def rename_in_file(path, in_list, out_list, is_interactive):
if FAKE_MODE:
print(" ... Saved file %s (faked)" % path)
return
with open(path, 'w') as fil:
with open(path, "w") as fil:
fil.writelines("\n".join(org_lines))
print(" ... Saved file %s" % path)
return
@ -278,7 +297,11 @@ def rename_in_file(path, in_list, out_list, is_interactive):
input(_HELP_TEXT.format(sources=in_list, targets=out_list))
elif ret.startswith("i"):
# ignore one or more lines
ignores = [int(ind) - 1 for ind in ret[1:].split(',') if ind.strip().isdigit()]
ignores = [
int(ind) - 1
for ind in ret[1:].split(",")
if ind.strip().isdigit()
]
if not ignores:
input("Ignore example: i 2,7,34,133\n (return to continue)")
continue
@ -291,36 +314,57 @@ if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Rename text in a source tree, or a single file")
description="Rename text in a source tree, or a single file"
)
parser.add_argument('-i', '--input', action='append',
help="Source word to rename (quote around multiple words)")
parser.add_argument('-o', '--output', action='append',
help="Word to rename a matching src-word to")
parser.add_argument('-x', '--exc', action='append',
help="File path patterns to exclude")
parser.add_argument('-a', '--auto', action='store_true',
help="Automatic mode, don't ask to rename")
parser.add_argument('-r', '--recursive', action='store_true',
help="Recurse subdirs")
parser.add_argument('-f', '--fileending', action='append',
help="Change which file endings to allow (default .py and .html)")
parser.add_argument('--nocolor', action='store_true',
help="Turn off in-program color")
parser.add_argument('--fake', action='store_true',
help="Simulate run but don't actually save")
parser.add_argument('path',
help="File or directory in which to rename text")
parser.add_argument(
"-i",
"--input",
action="append",
help="Source word to rename (quote around multiple words)",
)
parser.add_argument(
"-o", "--output", action="append", help="Word to rename a matching src-word to"
)
parser.add_argument(
"-x", "--exc", action="append", help="File path patterns to exclude"
)
parser.add_argument(
"-a", "--auto", action="store_true", help="Automatic mode, don't ask to rename"
)
parser.add_argument(
"-r", "--recursive", action="store_true", help="Recurse subdirs"
)
parser.add_argument(
"-f",
"--fileending",
action="append",
help="Change which file endings to allow (default .py and .html)",
)
parser.add_argument(
"--nocolor", action="store_true", help="Turn off in-program color"
)
parser.add_argument(
"--fake", action="store_true", help="Simulate run but don't actually save"
)
parser.add_argument("path", help="File or directory in which to rename text")
args = parser.parse_args()
in_list, out_list, exc_list, fileend_list = args.input, args.output, args.exc, args.fileending
in_list, out_list, exc_list, fileend_list = (
args.input,
args.output,
args.exc,
args.fileending,
)
if not (in_list and out_list):
print('At least one source- and destination word must be given.')
print("At least one source- and destination word must be given.")
sys.exit()
if len(in_list) != len(out_list):
print('Number of sources must be identical to the number of destination arguments.')
print(
"Number of sources must be identical to the number of destination arguments."
)
sys.exit()
exc_list = exc_list or []
@ -332,6 +376,8 @@ if __name__ == "__main__":
FAKE_MODE = args.fake
if is_recursive:
rename_in_tree(args.path, in_list, out_list, exc_list, fileend_list, is_interactive)
rename_in_tree(
args.path, in_list, out_list, exc_list, fileend_list, is_interactive
)
else:
rename_in_file(args.path, in_list, out_list, is_interactive)