コード例 #1
0
	def translate(self, key: str, args: tuple, kwargs: dict, *, allow_failure: bool, language: Optional[str] = None, fallback_language: Optional[str] = None, plugin_translations: Optional[TranslationStorage] = None) -> MessageText:
		if language is None:
			language = self.language
		if plugin_translations is None:
			plugin_translations = {}

		# Translating
		try:
			translated_formatter = translation_util.translate_from_dict(self.translations.get(key, {}), language, fallback_language=fallback_language)
		except KeyError:
			try:
				translated_formatter = translation_util.translate_from_dict(plugin_translations.get(key, {}), language, fallback_language=fallback_language, default=None)
			except KeyError:
				translated_formatter = None

		# Check if there's any rtext inside args and kwargs
		use_rtext = any([isinstance(e, RTextBase) for e in list(args) + list(kwargs.values())])

		# Processing
		if translated_formatter is not None:
			translated_formatter = translated_formatter.strip('\n\r')
			try:
				if use_rtext:
					translated_formatter = RTextBase.format(translated_formatter, *args, **kwargs)
				else:
					translated_formatter = translated_formatter.format(*args, **kwargs)
			except Exception as e:
				raise ValueError('Failed to apply args {} and kwargs {} to translated_text {}: {}'.format(args, kwargs, translated_formatter, e))
			return translated_formatter
		else:
			if not allow_failure:
				raise KeyError('Translation key "{}" not found with language {}, fallback_language {}'.format(key, language, fallback_language))
			self.logger.error('Error translate text "{}" to language {}'.format(key, language))
			return key if not use_rtext else RTextBase.from_any(key)
コード例 #2
0
 def to_rtext(self) -> RTextBase:
     return RTextBase.format(
         '{}: {}{}{}',
         RTextBase.from_any(self.__message).copy().set_color(RColor.red),
         RText(self._parsed_command, RColor.dark_red),
         RText(self._error_command, RColor.red),
         RText('<--', RColor.dark_red))
コード例 #3
0
 def __detail_hint(self, text: RTextBase, pref_name: str) -> RTextBase:
     return (text.h(
         self.tr('mcdr_command.preference.list.detail_hint',
                 RText(pref_name, PREF_COLOR))).c(
                     RAction.run_command,
                     '{} preference {}'.format(self.control_command_prefix,
                                               pref_name)))
コード例 #4
0
    def __init__(self, plugin: 'AbstractPlugin', prefix: str,
                 message: Union[MessageText,
                                TranslationKeyDictRich], permission: int):
        self.plugin = plugin
        self.prefix = prefix

        self.message: TranslationKeyDictRich = {}
        if isinstance(message, dict):
            for lang, msg in message.items():
                self.message[lang] = RTextBase.from_any(msg)
        else:
            self.message[core_constant.DEFAULT_LANGUAGE] = RTextBase.from_any(
                message)

        self.permission = permission
        self.__prefix_lower = self.prefix.lower()
コード例 #5
0
    def __init__(self, plugin: 'AbstractPlugin', prefix: str,
                 message: Union[MessageText,
                                TranslationKeyDictRich], permission: int):
        self.plugin = plugin
        self.prefix = prefix

        self.message: RTextBase
        if isinstance(message, RTextMCDRTranslation):
            self.message = message
        elif isinstance(message, dict):
            self.message = RTextMCDRTranslation.from_translation_dict(message)
        else:
            self.message = RTextBase.from_any(message)

        self.permission = permission
        self.__prefix_lower = self.prefix.lower()
コード例 #6
0
 def __get_translated_text(self) -> RTextBase:
     language = getattr(self.__TLS, 'language', None)
     if language is None:
         from mcdreforged.plugin.server_interface import ServerInterface
         server: Optional[ServerInterface] = ServerInterface.get_instance()
         if server is not None:
             language = server.get_mcdr_language()
         else:
             language = core_constant.DEFAULT_LANGUAGE
     processed_text = self.__translator(self.translation_key,
                                        *self.args,
                                        **self.kwargs,
                                        language=language)
     processed_text = RTextBase.from_any(processed_text)
     for process in self.__post_process:
         processed_text = process(processed_text)
     return processed_text
コード例 #7
0
 def __init__(self, plugin: 'AbstractPlugin', prefix: str, message: str
              or RTextBase, permission: int):
     self.plugin = plugin
     self.prefix = prefix
     self.message = RTextBase.from_any(message)
     self.permission = permission
コード例 #8
0
ファイル: misc_util.py プロジェクト: DeSireFire/MCDReforged
def print_text_to_console(logger, text):
    for line in RTextBase.from_any(text).to_colored_text().splitlines():
        logger.info(line)
コード例 #9
0
    def __init__(self, plugin: 'AbstractPlugin', data: dict):
        """
		:param AbstractPlugin plugin: the plugin which this metadata is belong to
		:param dict or None data: a dict with information of the plugin
		"""
        if not isinstance(data, dict):
            data = {}
        logger = plugin.mcdr_server.logger

        use_fallback_id_reason = None
        self.id = data.get('id')
        if self.id is None:
            use_fallback_id_reason = 'Plugin ID of {} not found'.format(plugin)
        elif not isinstance(self.id, str) or re.fullmatch(
                r'[a-z0-9_]{1,64}', self.id) is None:
            use_fallback_id_reason = 'Plugin ID "{}" of {} is invalid'.format(
                self.id, plugin)
        if use_fallback_id_reason is not None:
            self.id = plugin.get_fallback_metadata_id()
            logger.warning('{}, use fallback id {} instead'.format(
                use_fallback_id_reason, self.id))

        self.name = RTextBase.from_any(data.get('name', self.id))

        self.description = data.get('description')
        if self.description is not None:
            self.description = RTextBase.from_any(self.description)

        self.author = data.get('author')
        if isinstance(self.author, str):
            self.author = [self.author]
        if isinstance(self.author, list):
            for i in range(len(self.author)):
                self.author[i] = str(self.author[i])
            if len(self.author) == 0:
                self.author = None

        self.link = data.get('link')
        if not isinstance(self.link, str):
            self.link = None

        version_str = data.get('version')
        if version_str:
            try:
                self.version = Version(version_str, allow_wildcard=False)
            except VersionParsingError as e:
                logger.warning(
                    'Version "{}" of {} is invalid ({}), ignore and use fallback version instead {}'
                    .format(version_str, plugin, e, self.FALLBACK_VERSION))
                version_str = None
        else:
            logger.warning(
                '{} doesn\'t specific a version, use fallback version {}'.
                format(plugin, self.FALLBACK_VERSION))
        if version_str is None:
            self.version = Version(self.FALLBACK_VERSION)

        self.dependencies = {}
        for plugin_id, requirement in data.get('dependencies', {}).items():
            try:
                self.dependencies[plugin_id] = VersionRequirement(requirement)
            except VersionParsingError as e:
                logger.warning(
                    'Dependency "{}: {}" of {} is invalid ({}), ignore'.format(
                        plugin_id, requirement, plugin.get_name(), e))