def _remove_mo_cache(path=None):
    """Remove the mo cache."""
    if path is not None and os.path.exists(path):
        if not os.access(path, os.W_OK):
            log("No write permission on folder %s" % path, logging.INFO)
            return False
        shutil.rmtree(path)
 def addCatalog(self, catalog):
     try:
         self._delObject(catalog.id)
     except:
         pass
     lang = catalog.getLanguage()
     if not _checkLanguage(lang):
         return
     self._setObject(catalog.id, catalog, set_owner=False)
     log('adding %s: %s' % (catalog.id, catalog.title))
     self._registerMessageCatalog(catalog)
 def addCatalog(self, catalog):
     try:
         self._delObject(catalog.id)
     except:
         pass
     lang = catalog.getLanguage()
     if not _checkLanguage(lang):
         return
     self._setObject(catalog.id, catalog, set_owner=False)
     log('adding %s: %s' % (catalog.id, catalog.title))
     self._registerMessageCatalog(catalog)
def _updateMoFile(name, msgpath, lang, domain, mofile):
    """
    Creates or updates a mo file in the locales folder. Returns True if a
    new file was created.
    """
    pofile = join(msgpath, name)
    create = False
    update = False

    try:
        po_mtime = os.stat(pofile)[ST_MTIME]
    except (IOError, OSError):
        po_mtime = 0

    if os.path.exists(mofile):
        # Update mo file?
        try:
            mo_mtime = os.stat(mofile)[ST_MTIME]
        except (IOError, OSError):
            mo_mtime = 0

        if po_mtime > mo_mtime:
            # Update mo file
            update = True
        else:
            # Mo file is current
            return
    else:
        # Create mo file
        create = True

    if create or update:
        try:
            mo = Msgfmt(pofile, domain).getAsFile()
            fd = open(mofile, 'wb')
            fd.write(mo.read())
            fd.close()

        except (IOError, OSError, PoSyntaxError):
            log('Error while compiling %s' % pofile, logging.WARNING)
            return

        if create:
            return True

    return None
Example #5
0
 def reload(self, REQUEST=None):
     """ Forcibly re-read the file """
     # get pts
     pts = aq_parent(self)
     name = self.getId()
     pofile = self._getPoFile()
     pts._delObject(name)
     try: pts.addCatalog(GettextMessageCatalog(name, pofile))
     except OSError:
         # XXX TODO
         # remove a catalog if it cannot be loaded from the old location
         raise
     except:
         exc=sys.exc_info()
         log('Message Catalog has errors', logging.WARNING, name, exc)
     self = pts._getOb(name)
     if hasattr(REQUEST, 'RESPONSE'):
         if not REQUEST.form.has_key('noredir'):
             REQUEST.RESPONSE.redirect(self.absolute_url())
Example #6
0
 def reload(self, REQUEST=None):
     """ Forcibly re-read the file """
     # get pts
     pts = aq_parent(self)
     name = self.getId()
     pofile = self._getPoFile()
     pts._delObject(name)
     try:
         pts.addCatalog(GettextMessageCatalog(name, pofile))
     except OSError:
         # XXX TODO
         # remove a catalog if it cannot be loaded from the old location
         raise
     except:
         exc = sys.exc_info()
         log('Message Catalog has errors', logging.WARNING, name, exc)
     self = pts._getOb(name)
     if hasattr(REQUEST, 'RESPONSE'):
         if not REQUEST.form.has_key('noredir'):
             REQUEST.RESPONSE.redirect(self.absolute_url())
Example #7
0
def initialize2(context):
    # allow for disabling PTS entirely by setting an environment variable.
    if bool(os.getenv('DISABLE_PTS')):
        log('Disabled by environment variable "DISABLE_PTS".', logging.WARNING)
        return

    cp = getattr(getattr(context, '_ProductContext__app', None),
                 'Control_Panel', None)  # argh
    if cp is not None and cp_id in cp.objectIds():
        cp_ts = getattr(cp, cp_id, None)
        # Clean up ourselves
        if cp_ts is not None:
            cp._delObject(cp_id)
            _remove_mo_cache(CACHE_PATH)

    # load translation files from all packages and products
    loaded = {}

    import Products
    packages = get_registered_packages()
    for package in packages:
        name = package.__name__
        path = package.__path__[0]
        loaded[name] = True
        i18n_dir = os.path.join(path, 'i18n')
        if isdir(i18n_dir):
            _load_i18n_dir(i18n_dir)

    for product in get_products():
        name = product[1]
        if name in IGNORED:
            continue
        basepath = product[3]
        fullname = 'Products.' + name
        # Avoid loading products registered as packages twice
        if loaded.get(fullname):
            continue
        loaded[fullname] = True
        i18n_dir = os.path.join(basepath, name, 'i18n')
        if isdir(i18n_dir):
            _load_i18n_dir(i18n_dir)
Example #8
0
 def reload(self, REQUEST=None):
     """Forcibly re-read the file
     """
     if self.getId() in translationRegistry.keys():
         del translationRegistry[self.getId()]
     if hasattr(self, '_v_tro'):
         del self._v_tro
     name = self.getId()
     pts = aq_parent(self)
     pofile=self._getPoFile()
     try:
         self._prepareTranslations(0)
         log('reloading %s: %s' % (name, self.title), severity=logging.DEBUG)
     except:
         pts._delObject(name)
         exc=sys.exc_info()
         log('Message Catalog has errors', logging.WARNING, name, exc)
     self = pts._getOb(name)
     if hasattr(REQUEST, 'RESPONSE'):
         if not REQUEST.form.has_key('noredir'):
             REQUEST.RESPONSE.redirect(self.absolute_url())
Example #9
0
def initialize2(context):
    # allow for disabling PTS entirely by setting an environment variable.
    if bool(os.getenv('DISABLE_PTS')):
        log('Disabled by environment variable "DISABLE_PTS".', logging.WARNING)
        return

    cp = getattr(getattr(context, '_ProductContext__app', None), 'Control_Panel', None) # argh
    if cp is not None and cp_id in cp.objectIds():
        cp_ts = getattr(cp, cp_id, None)
        # Clean up ourselves
        if cp_ts is not None:
            cp._delObject(cp_id)
            _remove_mo_cache(CACHE_PATH)

    # load translation files from all packages and products
    loaded = {}

    import Products
    packages = get_registered_packages()
    for package in packages:
        name = package.__name__
        path = package.__path__[0]
        loaded[name] = True
        i18n_dir = os.path.join(path, 'i18n')
        if isdir(i18n_dir):
            _load_i18n_dir(i18n_dir)

    for product in get_products():
        name = product[1]
        if name in IGNORED:
            continue
        basepath = product[3]
        fullname = 'Products.' + name
        # Avoid loading products registered as packages twice
        if loaded.get(fullname):
            continue
        loaded[fullname] = True
        i18n_dir = os.path.join(basepath, name, 'i18n')
        if isdir(i18n_dir):
            _load_i18n_dir(i18n_dir)
Example #10
0
 def reload(self, REQUEST=None):
     """Forcibly re-read the file
     """
     if self.getId() in translationRegistry.keys():
         del translationRegistry[self.getId()]
     if hasattr(self, '_v_tro'):
         del self._v_tro
     name = self.getId()
     pts = aq_parent(self)
     pofile = self._getPoFile()
     try:
         self._prepareTranslations(0)
         log('reloading %s: %s' % (name, self.title),
             severity=logging.DEBUG)
     except:
         pts._delObject(name)
         exc = sys.exc_info()
         log('Message Catalog has errors', logging.WARNING, name, exc)
     self = pts._getOb(name)
     if hasattr(REQUEST, 'RESPONSE'):
         if not REQUEST.form.has_key('noredir'):
             REQUEST.RESPONSE.redirect(self.absolute_url())
    def _load_catalog_file(self, name, popath, language=None, domain=None):
        """Create catalog instances in ZODB"""
        id = self.calculatePoId(name, popath, language=language, domain=domain)

        # validate id
        try:
            self._checkId(id, 1)
        except:
            id = name  # fallback mode for borked paths

        # the po file path
        pofile = os.path.join(popath, name)

        ob = self._getOb(id, _marker)
        try:
            if isinstance(ob, BrokenMessageCatalog):
                # remove broken catalog
                self._delObject(id)
                ob = _marker
        except:
            pass
        try:
            if ob is _marker:
                self.addCatalog(
                    GettextMessageCatalog(id, pofile, language, domain))
            else:
                self.reloadCatalog(ob)
        except IOError:
            # io error probably cause of missing or not accessable
            try:
                # remove false catalog from PTS instance
                self._delObject(id)
            except:
                pass
        except KeyboardInterrupt:
            raise
        except:
            exc = sys.exc_info()
            log('Message Catalog has errors', logging.WARNING, pofile, exc)
    def _load_catalog_file(self, name, popath, language=None, domain=None):
        """Create catalog instances in ZODB"""
        id = self.calculatePoId(name, popath, language=language, domain=domain)

        # validate id
        try:
            self._checkId(id, 1)
        except:
            id=name # fallback mode for borked paths

        # the po file path
        pofile = os.path.join(popath, name)

        ob = self._getOb(id, _marker)
        try:
            if isinstance(ob, BrokenMessageCatalog):
                # remove broken catalog
                self._delObject(id)
                ob = _marker
        except:
            pass
        try:
            if ob is _marker:
                self.addCatalog(GettextMessageCatalog(id, pofile, language, domain))
            else:
                self.reloadCatalog(ob)
        except IOError:
            # io error probably cause of missing or not accessable
            try:
                # remove false catalog from PTS instance
                self._delObject(id)
            except:
                pass
        except KeyboardInterrupt:
            raise
        except:
            exc=sys.exc_info()
            log('Message Catalog has errors', logging.WARNING, pofile, exc)
def _load_i18n_dir(basepath):
    """
    Loads an i18n directory (Zope3 PTS format)
    Format:
        Products/MyProduct/i18n/*.po
    The language and domain are stored in the po file
    """
    # load po files
    basepath = os.path.normpath(basepath)
    log('Looking for po files in ' + basepath, logging.DEBUG)
    names = fnmatch.filter(os.listdir(basepath), '*.po')
    if not names:
        log('Nothing found in ' + basepath, logging.DEBUG)
        return

    registered = []

    for name in names:
        lang = None
        domain = None
        pofile = join(basepath, name)
        po = Msgfmt(pofile, None)
        po.read(header_only=True)
        header = po.messages.get('', None)
        if header is not None:
            mime_header = {}
            pairs = [l.split(':', 1) for l in header.split('\n') if l]
            for key, value in pairs:
                mime_header[key.strip().lower()] = value.strip()
            lang = mime_header.get('language-code', None)
            domain = mime_header.get('domain', None)
            if lang is not None and domain is not None:
                if _checkLanguage(lang):
                    reg = (name, basepath, lang, domain, True)
                    _register_catalog_file(*reg)
                    registered.append(name)

    log('Initialized:', detail = str(len(registered)) +
        (' message catalogs in %s\n' % basepath))