pogrep/pogrep.py

77 lines
1.6 KiB
Python
Raw Normal View History

2019-11-01 19:21:22 +00:00
#!/usr/bin/env python3
2019-11-01 19:30:15 +00:00
"""Find translations exemples by grepping in .po files.
"""
2019-11-22 08:21:59 +00:00
__version__ = "0.1.1"
2019-11-01 19:21:22 +00:00
import argparse
2019-11-01 22:17:44 +00:00
import curses
2019-11-01 19:21:22 +00:00
from glob import glob
import os
from textwrap import fill
import regex
import polib
from tabulate import tabulate
2019-11-01 22:17:44 +00:00
def red_color():
"""Just returns the CSI codes for red and reset color.
"""
2019-11-01 19:21:22 +00:00
try:
2019-11-01 22:17:44 +00:00
curses.setupterm()
fg_color = curses.tigetstr("setaf") or curses.tigetstr("setf") or ""
red = str(curses.tparm(fg_color, 1), "ascii")
no_color = str(curses.tigetstr("sgr0"), "ascii")
except Exception:
red = ""
no_color = ""
return red, no_color
RED, NO_COLOR = red_color()
def get_term_width():
scr = curses.initscr()
width = scr.getmaxyx()[1]
curses.endwin()
return width
2019-11-01 19:21:22 +00:00
2019-11-01 22:17:44 +00:00
WIDTH = get_term_width()
def colorize(text, pattern):
return regex.sub(pattern, RED + r"\g<0>" + NO_COLOR, text)
2019-11-01 22:17:44 +00:00
def find_in_po(pattern):
table = []
2019-11-01 19:21:22 +00:00
for file in glob("**/*.po"):
pofile = polib.pofile(file)
for entry in pofile:
if entry.msgstr and regex.search(pattern, entry.msgid):
table.append(
[
2019-11-01 22:17:44 +00:00
fill(entry.msgid, width=(WIDTH - 7) // 2),
fill(entry.msgstr, width=(WIDTH - 7) // 2),
2019-11-01 19:21:22 +00:00
]
)
2019-11-01 22:17:44 +00:00
print(colorize(tabulate(table, tablefmt="fancy_grid"), pattern))
2019-11-01 19:21:22 +00:00
def parse_args():
parser = argparse.ArgumentParser(description="Find translated words.")
parser.add_argument("pattern")
return parser.parse_args()
def main():
args = parse_args()
find_in_po(args.pattern)
if __name__ == "__main__":
main()