"""Some i18n/gettext utilities.:organization: Logilab:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2.:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses"""__docformat__="restructuredtext en"importreimportosfromos.pathimportjoin,basename,splitext,existsfromglobimportglobfromcubicweb.toolsutilsimportcreate_dirdefextract_from_tal(files,output_file):"""extract i18n strings from tal and write them into the given output file using standard python gettext marker (_) """output=open(output_file,'w')forfilepathinfiles:formatchinre.finditer('i18n:(content|replace)="([^"]+)"',open(filepath).read()):print>>output,'_("%s")'%match.group(2)output.close()defadd_msg(w,msgid):"""write an empty pot msgid definition"""ifisinstance(msgid,unicode):msgid=msgid.encode('utf-8')msgid=msgid.replace('"',r'\"').splitlines()iflen(msgid)>1:w('msgid ""\n')forlineinmsgid:w('"%s"'%line.replace('"',r'\"'))else:w('msgid "%s"\n'%msgid[0])w('msgstr ""\n\n')defexecute(cmd):"""display the command, execute it and raise an Exception if returned status != 0 """printcmd.replace(os.getcwd()+os.sep,'')status=os.system(cmd)ifstatus!=0:raiseException()defavailable_catalogs(i18ndir=None):ifi18ndirisNone:wildcard='*.po'else:wildcard=join(i18ndir,'*.po')forpopathinglob(wildcard):lang=splitext(basename(popath))[0]yieldlang,popathdefcompile_i18n_catalogs(sourcedirs,destdir,langs):"""generate .mo files for a set of languages into the `destdir` i18n directory """fromlogilab.common.fileutilsimportensure_fs_modeprint'-> compiling %s catalogs...'%destdirerrors=[]forlanginlangs:langdir=join(destdir,lang,'LC_MESSAGES')ifnotexists(langdir):create_dir(langdir)pofiles=[join(path,'%s.po'%lang)forpathinsourcedirs]pofiles=[pofforpofinpofilesifexists(pof)]mergedpo=join(destdir,'%s_merged.po'%lang)try:# merge instance/cubes messages catalogs with the stdlib's oneexecute('msgcat --use-first --sort-output --strict %s > %s'%(' '.join(pofiles),mergedpo))# make sure the .mo file is writeable and compile with *msgfmt*applmo=join(destdir,lang,'LC_MESSAGES','cubicweb.mo')try:ensure_fs_mode(applmo)exceptOSError:pass# suppose not existsexecute('msgfmt %s -o %s'%(mergedpo,applmo))exceptException,ex:errors.append('while handling language %s: %s'%(lang,ex))try:# clean everythingos.unlink(mergedpo)exceptException:continuereturnerrors