Skip to content

Instantly share code, notes, and snippets.

@kanazux
Created May 24, 2018 16:02
Show Gist options
  • Save kanazux/c639c87b7a38ad2d0b6b4f51d0eb088c to your computer and use it in GitHub Desktop.
Save kanazux/c639c87b7a38ad2d0b6b4f51d0eb088c to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python3.6
# -*- coding: utf-8 -*-
"""
Generate pot file for xml language.
This script will create a pot file only for xml files.
To update another file create with other language use poedit to that.
"""
import re
from subprocess import check_output
from argparse import ArgumentParser
from collections import defaultdict
class potfile():
"""Class to return data for pot file."""
def __init__(self, _tags):
self.datapot = defaultdict(lambda: False)
self.no_tags = re.compile(r"<[^>]+>")
self.str_tag = r"<{}>.*<\/{}>"
self.tags = _tags
def check_tag(self, _line):
"""Check if is a tag line to translate."""
for _tag in self.tags:
if bool(re.match(self.str_tag.format(_tag, _tag), _line.strip())):
return self.no_tags.sub("", _line.strip())
return False
def list_files(self):
"""List xml files to get tags to translate."""
_files = list(filter(None, check_output(
["find ./ -name '*.xml'"], shell=True).decode().split("\n")))
if len(_files) > 1:
return _files
else:
return None
def index_file(self, _file):
"""Create an index , with line description and text to translate."""
with open(_file, 'r') as _read_file:
_lines = list(filter(None, _read_file.read().split("\n")))
for _idx, _line in enumerate(_lines):
_line_tag = self.check_tag(_line)
if _line_tag:
if self.datapot[_line_tag]:
self.datapot[_line_tag].add("{}:{}".format(
_file[2:], _idx))
else:
self.datapot[_line_tag] = set(["{}:{}".format(
_file[2:], _idx)])
def index_cdata(self, _file):
"""Index cdata on files to translate."""
_list_text = []
_append = False
with open(_file, 'r') as _read_file:
_lines = list(filter(None, _read_file.read().split("\n")))
for _idx, _line in enumerate(_lines):
if _line.strip() == "<![CDATA[":
_list_text.append(_idx)
_list_text.append(_line.strip())
_append = True
elif _line.strip() == "]]>":
_list_text.append(_line.strip())
_join_text = "".join(_list_text[1:])
if not bool(re.match(r".*netgate.*", _join_text, re.I)):
if self.datapot[_join_text]:
self.datapot[_join_text].add("{}:{}".format(
_file[2:], _list_text[0]))
else:
self.datapot[_join_text] = set(["{}:{}".format(
_file[2:], _list_text[0])])
_append = False
_list_text = []
elif _append:
_list_text.append(_line)
def run(self):
"""Create pot data to save file."""
_get_files = self.list_files()
if len(_get_files) >= 1:
for _f in _get_files:
self.index_file(_f)
self.index_cdata(_f)
return self.datapot
def parse_opts():
"""Return argument parser."""
parser = ArgumentParser(add_help=True,
description="Create pot file for xml lang.")
parser.add_argument("-t", dest="tags", action="store",
help="Get tags to translate. Comma separeted.")
parser.add_argument("-n", dest="name", action="store",
help="Get a name to save the pot file.")
return parser.parse_args()
def main():
opts = parse_opts()
pot_data = potfile(opts.tags.split(',')).run()
with open(opts.name, 'a') as pot_file:
for item in pot_data:
for line in pot_data[item]:
pot_file.write("#: {}\n".format(line))
pot_file.write("msgid \"{}\"\n".format(item))
pot_file.write("msgstr \"\"\n\n")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment