|
| 1 | +import argparse |
| 2 | +import difflib |
| 3 | +import subprocess |
| 4 | + |
| 5 | + |
| 6 | +def get_file_lines(filename): |
| 7 | + with open(filename) as file: |
| 8 | + lines = file.readlines() |
| 9 | + return lines |
| 10 | + |
| 11 | + |
| 12 | +def get_readme_text(lines, start_pattern, end_pattern): |
| 13 | + start_index = lines.index(start_pattern) + 1 |
| 14 | + end_index = lines.index(end_pattern) |
| 15 | + sublines = lines[start_index:end_index] |
| 16 | + # remove backticks |
| 17 | + sublines = [line for line in sublines if line != "```\n"] |
| 18 | + text = "".join(sublines) |
| 19 | + return text |
| 20 | + |
| 21 | + |
| 22 | +def get_command_output(command): |
| 23 | + cmd = command.split(" ") |
| 24 | + out = None |
| 25 | + run = subprocess.run(cmd, stdout=subprocess.PIPE) |
| 26 | + if run.returncode == 0: |
| 27 | + out = run.stdout.decode("utf-8") |
| 28 | + return out |
| 29 | + raise ValueError("could not get the help text") |
| 30 | + |
| 31 | + |
| 32 | +def check_if_equal(command_output, readme_text): |
| 33 | + equal = command_output == readme_text |
| 34 | + if not equal: |
| 35 | + d1 = command_output.splitlines(keepends=True) |
| 36 | + d2 = readme_text.splitlines(keepends=True) |
| 37 | + print("".join(difflib.ndiff(d1, d2))) |
| 38 | + print("* * *") |
| 39 | + raise ValueError("readme text is not up-to-date") |
| 40 | + print("help output in readme is up-to-date") |
| 41 | + |
| 42 | + |
| 43 | +def get_cli_args(): |
| 44 | + parser = argparse.ArgumentParser( |
| 45 | + description="Check a block of text in a file against an output returned by a command or any other piped output." |
| 46 | + ) |
| 47 | + parser.add_argument("--file", required=True, help="file to check the block") |
| 48 | + parser.add_argument("--pattern_start", required=True, help="start pattern") |
| 49 | + parser.add_argument("--pattern_end", required=True, help="end pattern") |
| 50 | + parser.add_argument("--command", required=True, help="command to check the output") |
| 51 | + parsed_args = parser.parse_args() |
| 52 | + # this solution isn't great as it also removes the other unicode characters |
| 53 | + # but so far, I don't have any use case so fine. |
| 54 | + parsed_args.pattern_start = bytes(parsed_args.pattern_start, "utf-8").decode( |
| 55 | + "unicode_escape" |
| 56 | + ) |
| 57 | + parsed_args.pattern_end = bytes(parsed_args.pattern_end, "utf-8").decode( |
| 58 | + "unicode_escape" |
| 59 | + ) |
| 60 | + return parsed_args |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + args = get_cli_args() |
| 65 | + lines = get_file_lines(args.file) |
| 66 | + readme_text = get_readme_text(lines, args.pattern_start, args.pattern_end) |
| 67 | + command_output = get_command_output(args.command) |
| 68 | + check_if_equal(command_output, readme_text) |
| 69 | + return 0 |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments