|
| 1 | +"""Script that checks entries of PO files.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | + |
| 8 | +def maximum_number_of_messages(filenames, max_messages=10000, quiet=False): |
| 9 | + """Check that the maximum number of messages in each PO file is not |
| 10 | + greater than the number passed in the parameter ``max_messages``. |
| 11 | +
|
| 12 | + Parameters |
| 13 | + ---------- |
| 14 | +
|
| 15 | + filenames : list |
| 16 | + Set of file names to check. |
| 17 | +
|
| 18 | + max_messages : int, optional |
| 19 | + Maximum number of messages in each PO file. |
| 20 | +
|
| 21 | + quiet : bool, optional |
| 22 | + Enabled, don't print output to stderr when more messages than allowed |
| 23 | + are found. |
| 24 | +
|
| 25 | + Returns |
| 26 | + ------- |
| 27 | +
|
| 28 | + int: 0 if no more than ``max_messages`` messages found for each file, |
| 29 | + 1 otherwise. |
| 30 | + """ |
| 31 | + exitcode = 0 |
| 32 | + |
| 33 | + for filename in filenames: |
| 34 | + with open(filename) as f: |
| 35 | + content_lines = f.readlines() |
| 36 | + |
| 37 | + number_of_messages = 0 |
| 38 | + for i, line in enumerate(content_lines): |
| 39 | + if line.startswith('msgid "'): |
| 40 | + number_of_messages += 1 |
| 41 | + |
| 42 | + if (number_of_messages - 1) > max_messages: |
| 43 | + exitcode = 1 |
| 44 | + if not quiet: |
| 45 | + sys.stderr.write( |
| 46 | + f"More messages ({number_of_messages}) than allowed" |
| 47 | + f" ({max_messages}) at file {os.path.abspath(filename)}\n" |
| 48 | + ) |
| 49 | + |
| 50 | + return exitcode |
| 51 | + |
| 52 | + |
| 53 | +def main(): |
| 54 | + parser = argparse.ArgumentParser() |
| 55 | + parser.add_argument( |
| 56 | + "filenames", nargs="*", help="Filenames to check for obsolete messages" |
| 57 | + ) |
| 58 | + parser.add_argument("-q", "--quiet", action="store_true", help="Supress output") |
| 59 | + parser.add_argument( |
| 60 | + "-m", |
| 61 | + "--max-messages", |
| 62 | + type=int, |
| 63 | + metavar="NUMBER", |
| 64 | + required=False, |
| 65 | + default=None, |
| 66 | + help=( |
| 67 | + "Check the maximum number of messages in each PO file " |
| 68 | + "is not greater than the number passed in this parameter." |
| 69 | + ), |
| 70 | + ) |
| 71 | + args = parser.parse_args() |
| 72 | + if args.max_messages is not None: |
| 73 | + return maximum_number_of_messages( |
| 74 | + args.filenames, args.max_messages, quiet=args.quiet |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + exit(main()) |
0 commit comments