Exemplo n.º 1
0
    def merge_upload(self, request, fileobj, overwrite, author_name=None,
                     author_email=None, method='translate', fuzzy=''):
        """Top level handler for file uploads."""
        filecopy = fileobj.read()
        fileobj.close()

        # Strip possible UTF-8 BOM
        if filecopy[:3] == codecs.BOM_UTF8:
            filecopy = filecopy[3:]

        # Load backend file
        store = try_load(
            fileobj.name,
            filecopy,
            self.component.file_format_cls,
            self.component.template_store
        )

        # Check valid plural forms
        if hasattr(store.store, 'parseheader'):
            header = store.store.parseheader()
            try:
                number, equation = Plural.parse_formula(header['Plural-Forms'])
                if not self.plural.same_plural(number, equation):
                    raise Exception('Plural forms do not match the language.')
            except (ValueError, KeyError):
                # Formula wrong or missing
                pass

        # Optionally set authorship
        orig_user = None
        if author_email:
            from weblate.auth.models import User
            orig_user = request.user
            request.user = User.objects.get_or_create(
                email=author_email,
                defaults={
                    'username': author_email,
                    'is_active': False,
                    'full_name': author_name or author_email,
                }
            )[0]

        try:
            if method in ('translate', 'fuzzy', 'approve'):
                # Merge on units level
                with self.component.repository.lock:
                    return self.merge_translations(
                        request,
                        store,
                        overwrite,
                        method,
                        fuzzy,
                    )

            # Add as sugestions
            return self.merge_suggestions(request, store, fuzzy)
        finally:
            if orig_user:
                request.user = orig_user
Exemplo n.º 2
0
    def merge_upload(self, request, fileobj, overwrite, author=None,
                     merge_header=True, method='translate', fuzzy=''):
        """Top level handler for file uploads."""
        filecopy = fileobj.read()
        fileobj.close()

        # Commit pending changes so far
        self.commit_pending(request)

        # Strip possible UTF-8 BOM
        if filecopy[:3] == codecs.BOM_UTF8:
            filecopy = filecopy[3:]

        # Load backend file
        store = try_load(
            fileobj.name,
            filecopy,
            self.component.file_format_cls,
            self.component.template_store
        )

        # Optionally set authorship
        if author is None:
            author = request.user.get_author_name()

        # Check valid plural forms
        if hasattr(store.store, 'parseheader'):
            header = store.store.parseheader()
            try:
                number, equation = Plural.parse_formula(header['Plural-Forms'])
                if not self.plural.same_plural(number, equation):
                    raise Exception('Plural forms do not match the language.')
            except (ValueError, KeyError):
                # Formula wrong or missing
                pass

        if method in ('translate', 'fuzzy'):
            # Merge on units level
            with self.component.repository.lock:
                return self.merge_translations(
                    request,
                    store,
                    overwrite,
                    (method == 'fuzzy'),
                    fuzzy,
                    merge_header,
                )

        # Add as sugestions
        return self.merge_suggestions(request, store, fuzzy)
Exemplo n.º 3
0
    def get_plural(self, language):
        """Return matching plural object."""
        from weblate.lang.models import Plural
        header = self.store.parseheader()
        try:
            number, equation = Plural.parse_formula(header['Plural-Forms'])
        except (ValueError, KeyError):
            return super(PoFormat, self).get_plural(language)

        # Find matching one
        for plural in language.plural_set.all():
            if plural.same_plural(number, equation):
                return plural

        # Create new one
        return Plural.objects.create(
            language=language,
            source=Plural.SOURCE_GETTEXT,
            number=number,
            equation=equation,
        )
Exemplo n.º 4
0
 def test_examples(self):
     plural = Plural(number=2, formula="n!=1")
     self.assertEqual(
         plural.examples,
         {0: ["1"], 1: ["0", "2", "3", "4", "5", "6", "7", "8", "9", "10"]},
     )
Exemplo n.º 5
0
 def test_examples(self):
     plural = Plural(number=2, equation='n!=1')
     self.assertEqual(plural.examples, {
         0: ['1'],
         1: ['0', '2', '3', '4', '5', '6', '7', '8', '9', '10']
     })
Exemplo n.º 6
0
 def __init__(self, code='cs'):
     super().__init__(code=code)
     self.plural = Plural(language=self)
Exemplo n.º 7
0
    def merge_upload(self,
                     request,
                     fileobj,
                     overwrite,
                     author_name=None,
                     author_email=None,
                     method='translate',
                     fuzzy=''):
        """Top level handler for file uploads."""
        filecopy = fileobj.read()
        fileobj.close()

        # Strip possible UTF-8 BOM
        if filecopy[:3] == codecs.BOM_UTF8:
            filecopy = filecopy[3:]

        # Load backend file
        store = try_load(fileobj.name, filecopy,
                         self.component.file_format_cls,
                         self.component.template_store)

        # Check valid plural forms
        if hasattr(store.store, 'parseheader'):
            header = store.store.parseheader()
            try:
                number, equation = Plural.parse_formula(header['Plural-Forms'])
                if not self.plural.same_plural(number, equation):
                    raise Exception('Plural forms do not match the language.')
            except (ValueError, KeyError):
                # Formula wrong or missing
                pass

        # Optionally set authorship
        orig_user = None
        if author_email:
            from weblate.auth.models import User
            orig_user = request.user
            request.user = User.objects.get_or_create(email=author_email,
                                                      defaults={
                                                          'username':
                                                          author_email,
                                                          'is_active':
                                                          False,
                                                          'full_name':
                                                          author_name
                                                          or author_email,
                                                      })[0]

        try:
            if method in ('translate', 'fuzzy', 'approve'):
                # Merge on units level
                with self.component.repository.lock:
                    return self.merge_translations(
                        request,
                        store,
                        overwrite,
                        method,
                        fuzzy,
                    )

            # Add as sugestions
            return self.merge_suggestions(request, store, fuzzy)
        finally:
            if orig_user:
                request.user = orig_user
Exemplo n.º 8
0
    def merge_upload(
        self,
        request,
        fileobj: BinaryIO,
        conflicts: str,
        author_name: Optional[str] = None,
        author_email: Optional[str] = None,
        method: str = "translate",
        fuzzy: str = "",
    ):
        """Top level handler for file uploads."""
        # Optionally set authorship
        orig_user = None
        if author_email:
            from weblate.auth.models import User

            orig_user = request.user
            request.user = User.objects.get_or_create(
                email=author_email,
                defaults={
                    "username": author_email,
                    "is_active": False,
                    "full_name": author_name or author_email,
                },
            )[0]

        try:
            if method == "replace":
                return self.handle_replace(request, fileobj)

            if method == "source":
                return self.handle_source(request, fileobj)

            filecopy = fileobj.read()
            fileobj.close()

            # Strip possible UTF-8 BOM
            if filecopy[:3] == codecs.BOM_UTF8:
                filecopy = filecopy[3:]

            # Load backend file
            store = try_load(
                fileobj.name,
                filecopy,
                self.component.file_format_cls,
                self.component.template_store,
            )

            # Check valid plural forms
            if hasattr(store.store, "parseheader"):
                header = store.store.parseheader()
                try:
                    number, formula = Plural.parse_plural_forms(header["Plural-Forms"])
                    if not self.plural.same_plural(number, formula):
                        raise PluralFormsMismatch()
                except (ValueError, KeyError):
                    # Formula wrong or missing
                    pass

            if method in ("translate", "fuzzy", "approve"):
                # Merge on units level
                with self.component.repository.lock:
                    return self.merge_translations(
                        request, store, conflicts, method, fuzzy
                    )

            # Add as sugestions
            return self.merge_suggestions(request, store, fuzzy)
        finally:
            if orig_user:
                request.user = orig_user