#! /usr/bin/env python

"""
Searches in the MoinMoin sources for calls of get_text() or _() and tries to
extract the parameter. Then it checks the language modules if those parameters
are in the dictionary.

usage:

  check_i18n.py [lang1 lang2]

If no parameter is given check_i18n.py checks all languages. This script
assumes that it is called from MoinMoin/scripts. Please adjust the path if
needed below.
"""

import sys, re, os.path

MoinMoin_dir = ".."
sys.path.append(os.path.join(MoinMoin_dir, ".."))

from MoinMoin import i18n
from MoinMoin.util import pysupport

one_line_re = r"(_|get_text) *\( *(('[^']*')|(\"[^\"]*\")) *\)"
multi_line_re = r'(_|get_text)\s*\(\s*"""((\s|.)*?)"""\s*\)'

def search(file_name):
    text_dict = {}
    f = open(file_name, 'r')
    text = f.read()
    f.close()
    for match in re.finditer(one_line_re, text):
        found = match.group(2)[1:-1]
        if text_dict.has_key(found):
            text_dict[found].append(file_name)
        else:
            text_dict[found] = [file_name]
    for match in re.finditer(multi_line_re, text):
        found = match.group(2)
        if text_dict.has_key(found):
            text_dict[found].append(file_name)
        else:
            text_dict[found] = [file_name]
    return text_dict

def visitor(text_dict, dirname, names):
    for file_name in names:
        if file_name[-3:] == ".py":
            tmp_dict = search(os.path.join(dirname, file_name))
            for text, files in tmp_dict.items():
                if text_dict.has_key(text):
                    text_dict[text].extend(files)
                else:
                    text_dict[text] = files
            
def process_files(path):
    text_dict = {}
    os.path.walk('..', visitor, text_dict)
    return text_dict


def check_language(text_dict, lang):
    language = pysupport.importName("MoinMoin.i18n." + lang, "text")
    if not language:
        print "Language %s not found!" % lang
        return

    print "\n\nCHECKING LANGUAGE : ", lang
    print "========================\n"
    for text in text_dict:
        if not language.has_key(text):
            print "%r\nnot found. It's used in" % text,
            for file in text_dict[text]:
                print file,
            print "\n"
    #for text in language:
    #    if not text_dict.has_key(text):
    #        print "%r\n defined but not found in source\n" % text

def main():
    text = {}
    text_dict = process_files(MoinMoin_dir)
    if len(sys.argv) > 1:
        for lang in sys.argv[1:]:
            check_language(text_dict, lang)            
    else:
        for lang in i18n.languages:
            check_language(text_dict, lang)

    #for text in text_dict:
    #    print text
    #    print

main()
