Ejemplo n.º 1
0
    def codesToIdName(self, language, script, country, variant=''):
        """Maps each code to the appropriate ID and name.

        Returns a 4-tuple of (ID, name) pairs corresponding to the
        language, script, country and variant given.  Raises a
        suitable error if any of them is unknown, indicating all that
        are unknown plus suitable names for any that could sensibly be
        added to enumdata.py to make them known.

        Until we implement variant support (QTBUG-81051), the fourth
        member of the returned tuple is always 0 paired with a string
        that should not be used."""
        enum = self.__enumMap
        try:
            return (enum('language')[language], enum('script')[script],
                    enum('country')[country], enum('variant')[variant])
        except KeyError:
            pass

        parts, values = [], [language, script, country, variant]
        for index, key in enumerate(
            ('language', 'script', 'country', 'variant')):
            naming, enums = self.__codeMap(key), enum(key)
            value = values[index]
            if value not in enums:
                text = '{} code {}'.format(key, value)
                name = naming.get(value)
                if name and value != 'POSIX':
                    text += u' (could add {})'.format(name)
                parts.append(text)
        if len(parts) > 1:
            parts[-1] = 'and ' + parts[-1]
        assert parts
        raise Error('Unknown ' + ', '.join(parts), language, script, country,
                    variant)
Ejemplo n.º 2
0
    def numberSystem(self, system):
        """Get a description of a numbering system.

        Returns a mapping, with keys u'digits', u'type' and u'id'; the
        value for this last is system. Raises KeyError for unknown
        number system, ldml.Error on failure to load data."""
        try:
            return self.__numberSystems[system]
        except KeyError:
            raise Error('Unsupported number system: {}'.format(system))
Ejemplo n.º 3
0
    def __localeAsDoc(self, name: str, aliasFor = None):
        path = f'common/main/{name}.xml'
        if self.root.joinpath(path).exists():
            elt = self.__xml(path)
            for child in Node(elt).findAllChildren('alias'):
                try:
                    alias = child.dom.attributes['source'].nodeValue
                except (KeyError, AttributeError):
                    pass
                else:
                    return self.__localeAsDoc(alias, aliasFor or name)
            # No alias child with a source:
            return elt

        if aliasFor:
            raise Error(f'Fatal error: found an alias "{aliasFor}" -> "{name}", '
                        'but found no file for the alias')
Ejemplo n.º 4
0
    def __localeAsDoc(self, name, aliasFor = None,
                      joinPath = os.path.join, exists = os.path.isfile):
        path = ('common', 'main', name + '.xml')
        if exists(joinPath(self.root, *path)):
            elt = self.__xml(path)
            for child in Node(elt).findAllChildren('alias'):
                try:
                    alias = child.dom.attributes['source'].nodeValue
                except (KeyError, AttributeError):
                    pass
                else:
                    return self.__localeAsDoc(alias, aliasFor or name)
            # No alias child with a source:
            return elt

        if aliasFor:
            raise Error('Fatal error: found an alias "{}" -> "{}", but found no file for the alias'
                        .format(aliasFor, name))
Ejemplo n.º 5
0
    def readWindowsTimeZones(self, lookup): # For use by cldr2qtimezone.py
        """Digest CLDR's MS-Win time-zone name mapping.

        MS-Win have their own eccentric names for time-zones.  CLDR
        helpfully provides a translation to more orthodox names.

        Singe argument, lookup, is a mapping from known MS-Win names
        for locales to a unique integer index (starting at 1).

        The XML structure we read has the form:

 <supplementalData>
     <windowsZones>
         <mapTimezones otherVersion="..." typeVersion="...">
             <!-- (UTC-08:00) Pacific Time (US & Canada) -->
             <mapZone other="Pacific Standard Time" territory="001" type="America/Los_Angeles"/>
             <mapZone other="Pacific Standard Time" territory="CA" type="America/Vancouver America/Dawson America/Whitehorse"/>
             <mapZone other="Pacific Standard Time" territory="US" type="America/Los_Angeles America/Metlakatla"/>
             <mapZone other="Pacific Standard Time" territory="ZZ" type="PST8PDT"/>
         </mapTimezones>
     </windowsZones>
 </supplementalData>
"""
        zones = self.supplement('windowsZones.xml')
        enum = self.__enumMap('country')
        badZones, unLands, defaults, windows = set(), set(), {}, {}

        for name, attrs in zones.find('windowsZones/mapTimezones'):
            if name != 'mapZone':
                continue

            wid, code = attrs['other'], attrs['territory']
            data = dict(windowsId = wid,
                        countryCode = code,
                        ianaList = attrs['type'])

            try:
                key = lookup[wid]
            except KeyError:
                badZones.add(wid)
                key = 0
            data['windowsKey'] = key

            if code == u'001':
                defaults[key] = data['ianaList']
            else:
                try:
                    cid, name = enum[code]
                except KeyError:
                    unLands.append(code)
                    continue
                data.update(countryId = cid, country = name)
                windows[key, cid] = data

        if unLands:
            raise Error('Unknown country codes, please add to enumdata.py: '
                        + ', '.join(sorted(unLands)))

        if badZones:
            raise Error('Unknown Windows IDs, please add to cldr2qtimezone.py: '
                        + ', '.join(sorted(badZones)))

        return self.cldrVersion, defaults, windows