def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser("Check for duplicated accelerators")
    parser.add_argument("-t",
                        "--translate",
                        action='store_true',
                        help="Check translated strings")
    parser.add_argument("-p",
                        "--podir",
                        action='store',
                        type=str,
                        metavar='PODIR',
                        help='Directory containing po files',
                        default='./po')
    parser.add_argument("glade_files",
                        nargs="+",
                        metavar="GLADE-FILE",
                        help='The glade file to check')
    args = parser.parse_args(args=argv)

    # First check the untranslated strings in each file
    for glade_file in args.glade_files:
        check_glade(glade_file)

    # Now loop over all of the translations
    if args.translate:
        import langtable

        podicts = translate_all(args.podir)

        for (lang, po_map) in ((key, podicts[key]) for key in podicts.keys()):
            # Set the locale so that we can use lower() on accelerator keys.
            # If the language is of the form xx_XX, use that as the
            # locale name. Otherwise use the first locale that
            # langtable returns for the language. If that doesn't work,
            # just use C and hope for the best.
            if '_' in lang:
                locale.setlocale(locale.LC_ALL, lang)
            else:
                locale_list = langtable.list_locales(languageId=lang)
                if locale_list:
                    try:
                        locale.setlocale(locale.LC_ALL, locale_list[0])
                    except locale.Error:
                        print("No such locale %s, using C" % locale_list[0])
                        locale.setlocale(locale.LC_ALL, 'C')
                else:
                    locale.setlocale(locale.LC_ALL, 'C')

            for glade_file in args.glade_files:
                check_glade(glade_file, po_map)
Exemplo n.º 2
0
    def configure(self, options, conf):
        super().configure(options, conf)

        # If no glade files were specified, find all of them
        if options.glade_file:
            glade_files = options.glade_file
        else:
            glade_files = testfilelist(lambda x: x.endswith('.glade'))

        # Parse all of the glade files
        log.info("Parsing glade files...")
        for glade_file in glade_files:
            self.glade_trees.append(etree.parse(glade_file))

        if options.translate:
            log.info("Loading translations...")
            podicts = translate_all(options.podir)

            # Loop over each available language
            for lang, langmap in podicts.items():
                self.translated_trees[lang] = []

                # For each language, loop over the parsed glade files
                for tree in self.glade_trees:
                    # Make a copy of the tree to translate and save it to
                    # the list for this language
                    tree = copy.deepcopy(tree)
                    self.translated_trees[lang].append(tree)

                    # Save the language as an attribute of the root of the tree
                    tree.getroot().set("lang", lang)

                    # Look for all properties with translatable=yes and translate them
                    for translatable in tree.xpath(
                            '//property[@translatable="yes"]'):
                        try:
                            xlated_text = langmap.get(
                                translatable.text,
                                context=translatable.get('context'))[0]

                            # Add the untranslated text as an attribute to this node
                            translatable.set("original_text",
                                             translatable.text)

                            # Replace the actual text
                            translatable.text = xlated_text
                        except KeyError:
                            # No translation available for this string in this language
                            pass
Exemplo n.º 3
0
    def configure(self, options, conf):
        super().configure(options, conf)

        # If no glade files were specified, find all of them
        if options.glade_file:
            glade_files = options.glade_file
        else:
            glade_files = testfilelist(lambda x: x.endswith('.glade'))

        # Parse all of the glade files
        log.info("Parsing glade files...")
        for glade_file in glade_files:
            self.glade_trees.append(etree.parse(glade_file))

        if options.translate:
            log.info("Loading translations...")
            podicts = translate_all(options.podir)

            # Loop over each available language
            for lang, langmap in podicts.items():
                self.translated_trees[lang] = []

                # For each language, loop over the parsed glade files
                for tree in self.glade_trees:
                    # Make a copy of the tree to translate and save it to
                    # the list for this language
                    tree = copy.deepcopy(tree)
                    self.translated_trees[lang].append(tree)

                    # Save the language as an attribute of the root of the tree
                    tree.getroot().set("lang", lang)

                    # Look for all properties with translatable=yes and translate them
                    for translatable in tree.xpath('//property[@translatable="yes"]'):
                        try:
                            xlated_text = langmap.get(translatable.text, context=translatable.get('context'))[0]

                            # Add the untranslated text as an attribute to this node
                            translatable.set("original_text", translatable.text)

                            # Replace the actual text
                            translatable.text = xlated_text
                        except KeyError:
                            # No translation available for this string in this language
                            pass
Exemplo n.º 4
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser("Check for duplicated accelerators")
    parser.add_argument("-t", "--translate", action='store_true',
            help="Check translated strings")
    parser.add_argument("-p", "--podir", action='store', type=str,
            metavar='PODIR', help='Directory containing po files', default='./po')
    parser.add_argument("glade_files", nargs="+", metavar="GLADE-FILE",
            help='The glade file to check')
    args = parser.parse_args(args=argv)

    # First check the untranslated strings in each file
    for glade_file in args.glade_files:
        check_glade(glade_file)

    # Now loop over all of the translations
    if args.translate:
        import langtable

        podicts = translate_all(args.podir)

        for (lang, po_map) in ((key, podicts[key]) for key in podicts.keys()):
            # Set the locale so that we can use lower() on accelerator keys.
            # If the language is of the form xx_XX, use that as the
            # locale name. Otherwise use the first locale that
            # langtable returns for the language. If that doesn't work,
            # just use C and hope for the best.
            if '_' in lang:
                locale.setlocale(locale.LC_ALL, lang)
            else:
                locale_list = langtable.list_locales(languageId=lang)
                if locale_list:
                    try:
                        locale.setlocale(locale.LC_ALL, locale_list[0])
                    except locale.Error:
                        print("No such locale %s, using C" % locale_list[0])
                        locale.setlocale(locale.LC_ALL, 'C')
                else:
                    locale.setlocale(locale.LC_ALL, 'C')

            for glade_file in args.glade_files:
                check_glade(glade_file, po_map)
Exemplo n.º 5
0
    def visit_const(self, node):
        if not isinstance(node.value, (str, bytes)):
            return

        if not is_markup(node.value):
            return

        self._validate_pango_markup_string(node, node.value)

        # Check translated versions of the string if requested
        if self.config.translate_markup:
            global podicts

            # Check if this is a translatable string
            curr = node
            i18nFunc = None
            while curr.parent:
                if isinstance(curr.parent, astroid.CallFunc) and \
                        getattr(curr.parent.func, "name", "") in i18n_funcs:
                    i18nFunc = curr.parent
                    break
                curr = curr.parent

            if i18nFunc:
                # If not done already, import polib and read the translations
                if not podicts:
                    try:
                        from pocketlint.translatepo import translate_all
                    except ImportError:
                        print("Unable to load po translation module")
                        sys.exit(99)
                    else:
                        podicts = translate_all(os.path.join(os.environ.get('top_srcdir', '.'), 'po'))

                if i18nFunc.func.name in i18n_ctxt_funcs:
                    msgctxt = i18nFunc.args[0].value
                else:
                    msgctxt = None

                # Loop over all translations for the string
                for podict in podicts.values():
                    try:
                        node_values = podict.get(node.value, msgctxt)
                    except KeyError:
                        continue

                    for value in node_values:
                        self._validate_pango_markup_string(node, value, podict.metadata['Language'])

                        # Check that the markup matches, roughly
                        if not markup_match(node.value, value):
                            self.add_message("W9925", node=node, args=(podict.metadata['Language'],))

        # Check if this the left side of a % operation
        curr = node
        formatOp = None
        while curr.parent:
            if isinstance(curr.parent, astroid.BinOp) and curr.parent.op == "%" and \
                    curr.parent.left == curr:
                formatOp = curr.parent
                break
            curr = curr.parent

        # Check whether the right side of the % operation is escaped
        if formatOp:
            if isinstance(formatOp.right, astroid.CallFunc):
                if getattr(formatOp.right.func, "name", "") not in escapeMethods:
                    self.add_message("W9922", node=formatOp.right)
            # If a tuple, each item in the tuple must be escaped
            elif isinstance(formatOp.right, astroid.Tuple):
                for elt in formatOp.right.elts:
                    if not isinstance(elt, astroid.CallFunc) or\
                            getattr(elt.func, "name", "") not in escapeMethods:
                        self.add_message("W9922", node=elt)
            # If a dictionary, each value must be escaped
            elif isinstance(formatOp.right, astroid.Dict):
                for item in formatOp.right.items:
                    if not isinstance(item[1], astroid.CallFunc) or\
                            getattr(item[1].func, "name", "") not in escapeMethods:
                        self.add_message("W9922", node=item[1])
            else:
                self.add_message("W9922", node=formatOp)
Exemplo n.º 6
0
                                "Translated markup does not contain the same elements and attributes at %s%s:%d"
                                % (glade_file_path, lang_str, label.sourceline)
                            )
                            glade_success = False
    return glade_success


if __name__ == "__main__":
    parser = argparse.ArgumentParser("Check Pango markup validity")
    parser.add_argument("-t", "--translate", action="store_true", help="Check translated strings")
    parser.add_argument(
        "-p", "--podir", action="store", type=str, metavar="PODIR", help="Directory containing po files", default="./po"
    )
    parser.add_argument("glade_files", nargs="+", metavar="GLADE-FILE", help="The glade file to check")
    args = parser.parse_args(args=sys.argv[1:])

    success = True
    for file_path in args.glade_files:
        if not check_glade_file(file_path):
            success = False

    # Now loop over all of the translations
    if args.translate:
        podicts = translate_all(args.podir)
        for po_dict in podicts.values():
            for file_path in args.glade_files:
                if not check_glade_file(file_path, po_dict):
                    success = False

    sys.exit(0 if success else 1)
                        "--translate",
                        action='store_true',
                        help="Check translated strings")
    parser.add_argument("-p",
                        "--podir",
                        action='store',
                        type=str,
                        metavar='PODIR',
                        help='Directory containing po files',
                        default='./po')
    parser.add_argument("glade_files",
                        nargs="+",
                        metavar="GLADE-FILE",
                        help='The glade file to check')
    args = parser.parse_args(args=sys.argv[1:])

    success = True
    for file_path in args.glade_files:
        if not check_glade_file(file_path):
            success = False

    # Now loop over all of the translations
    if args.translate:
        podicts = translate_all(args.podir)
        for po_dict in podicts.values():
            for file_path in args.glade_files:
                if not check_glade_file(file_path, po_dict):
                    success = False

    sys.exit(0 if success else 1)