The stable-sort behaviour is described in the Design decisions section of the README.
52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
# Technical Assignment: Replace Configured Values in a Text File
|
|
# By: Martin Stajnko
|
|
|
|
import argparse
|
|
import sys
|
|
|
|
from config_loader import load_config
|
|
from replacer import prepare_pairs, replace_line
|
|
|
|
|
|
def main() -> None:
|
|
"""Parse CLI arguments, apply configured replacements, and print
|
|
the resulting lines sorted by number of replaced symbols
|
|
(most-changed first)."""
|
|
parser = argparse.ArgumentParser(
|
|
description="Replace configured values in a text file."
|
|
)
|
|
parser.add_argument("config_file", help="Configuration file")
|
|
parser.add_argument("text_file", help="Input text file")
|
|
|
|
args = parser.parse_args()
|
|
|
|
changed_lines = []
|
|
|
|
try:
|
|
# Ordered once here rather than on every line of the text file.
|
|
pairs = prepare_pairs(load_config(args.config_file))
|
|
|
|
with open(args.text_file, "r", encoding="utf-8") as file:
|
|
for line in file:
|
|
# Remove only the newline, preserving all other characters.
|
|
line = line.rstrip("\r\n")
|
|
|
|
changed_line, replaced_symbols = replace_line(line, pairs)
|
|
|
|
changed_lines.append((replaced_symbols, changed_line))
|
|
|
|
except OSError as error:
|
|
sys.exit(f"error: {error.filename}: {error.strerror}")
|
|
except ValueError as error:
|
|
# Also covers UnicodeDecodeError, which is a subclass of ValueError.
|
|
sys.exit(f"error: {error}")
|
|
|
|
changed_lines.sort(key=lambda item: item[0], reverse=True)
|
|
|
|
for _, line in changed_lines:
|
|
print(line)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|