id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,500
|
getters.py
|
translate_pootle/pootle/apps/virtualfolder/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import search_backend
from pootle.core.plugin import getter
from pootle_app.models import Directory
from pootle_store.models import Store
from .delegate import (
path_matcher, vfolder_finder, vfolders_data_tool, vfolders_data_view)
from .models import VirtualFolder
from .search import VFolderDBSearchBackend
from .utils import (
DirectoryVFDataTool, VirtualFolderFinder, VirtualFolderPathMatcher)
from .views import VFoldersDataView
@getter(search_backend, sender=VirtualFolder)
def get_vfolder_search_backend(**kwargs_):
return VFolderDBSearchBackend
@getter(path_matcher, sender=VirtualFolder)
def vf_path_matcher_getter(**kwargs_):
return VirtualFolderPathMatcher
@getter(vfolder_finder, sender=Store)
def store_vf_finder_getter(**kwargs_):
return VirtualFolderFinder
@getter(vfolders_data_tool, sender=Directory)
def vf_directory_data_tool_getter(**kwargs_):
return DirectoryVFDataTool
@getter(vfolders_data_view, sender=Directory)
def vf_directory_data_view_getter(**kwargs_):
return VFoldersDataView
| 1,348
|
Python
|
.py
| 33
| 38.636364
| 77
| 0.808903
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,501
|
urls.py
|
translate_pootle/pootle/apps/virtualfolder/urls.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf.urls import include, url
from pootle_store.urls import unit_xhr_urlpatterns
from .views import VFolderTPTranslateView, get_vfolder_units
vfolder_urlpatterns = [
# TP Translate
url(r'(?P<language_code>[^/]*)/'
r'(?P<project_code>[^/]*)/translate/(?P<dir_path>(.*/)*)?/?',
VFolderTPTranslateView.as_view(),
name='pootle-vfolder-tp-translate'),
url(r'xhr/units/$',
get_vfolder_units,
name='vfolder-pootle-xhr-units')]
urlpatterns = [
url("^\+\+vfolder/(?P<vfolder_name>[^/]*)/", include(vfolder_urlpatterns)),
url("^\+\+vfolder/(?P<vfolder_name>[^/]*)/", include(unit_xhr_urlpatterns))]
| 943
|
Python
|
.py
| 22
| 38.818182
| 80
| 0.678337
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,502
|
search.py
|
translate_pootle/pootle/apps/virtualfolder/search.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_store.unit.search import DBSearchBackend
class VFolderDBSearchBackend(DBSearchBackend):
def __init__(self, request_user, **kwargs):
self.vfolder = kwargs.pop("vfolder")
super(VFolderDBSearchBackend, self).__init__(request_user, **kwargs)
def filter_qs(self, qs):
filtered = super(VFolderDBSearchBackend, self).filter_qs(qs)
return filtered.filter(store__vfolders=self.vfolder)
| 710
|
Python
|
.py
| 15
| 43.266667
| 77
| 0.735849
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,503
|
apps.py
|
translate_pootle/pootle/apps/virtualfolder/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleVirtualFolderConfig(AppConfig):
name = "virtualfolder"
verbose_name = "Pootle Virtual Folders"
def ready(self):
importlib.import_module("virtualfolder.getters")
importlib.import_module("virtualfolder.receivers")
importlib.import_module("virtualfolder.providers")
importlib.import_module("virtualfolder.getters")
| 700
|
Python
|
.py
| 17
| 37.235294
| 77
| 0.757755
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,504
|
display.py
|
translate_pootle/pootle/apps/virtualfolder/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.functional import cached_property
from pootle.core.views.display import StatsDisplay
class VFolderStatsDisplay(StatsDisplay):
@cached_property
def stats(self):
stats = self.stat_data
for k, item in stats.items():
item["incomplete"] = item["total"] - item["translated"]
item["untranslated"] = item["total"] - item["translated"]
self.localize_stats(item)
return stats
| 732
|
Python
|
.py
| 18
| 35.611111
| 77
| 0.702398
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,505
|
receivers.py
|
translate_pootle/pootle/apps/virtualfolder/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from pootle.core.delegate import revision_updater
from pootle_app.models import Directory
from pootle_store.models import Store
from .delegate import vfolder_finder
from .models import VirtualFolder
@receiver(post_save, sender=Store)
def handle_store_save(sender, instance, created, **kwargs):
if not created:
return
vfolder_finder.get(
instance.__class__)(instance).add_to_vfolders()
@receiver(post_save, sender=VirtualFolder)
def handle_vfolder_save(sender, instance, created, **kwargs):
instance.path_matcher.update_stores()
@receiver(pre_delete, sender=VirtualFolder)
def handle_vfolder_delete(sender, instance, **kwargs):
dirs = set(instance.stores.values_list("parent", flat=True))
for store in instance.stores.all():
instance.stores.remove(store)
if store.priority == instance.priority:
store.set_priority()
updater = revision_updater.get(Directory)(
object_list=Directory.objects.filter(pk__in=dirs))
updater.update(keys=["stats"])
| 1,400
|
Python
|
.py
| 33
| 38.727273
| 77
| 0.752577
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,506
|
utils.py
|
translate_pootle/pootle/apps/virtualfolder/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from fnmatch import fnmatch
from django.db.models import Max, Sum
from pootle.core.decorators import persistent_property
from pootle_data.utils import RelatedStoresDataTool
from pootle_fs.utils import PathFilter
from pootle_store.models import Store
from .models import VirtualFolder
class VirtualFolderFinder(object):
"""Find vfs for a new store"""
def __init__(self, store):
self.store = store
@property
def language(self):
return self.store.translation_project.language
@property
def project(self):
return self.store.translation_project.project
@property
def possible_vfolders(self):
return (
self.project.vfolders.filter(all_languages=True)
| self.language.vfolders.filter(all_projects=True)
| self.project.vfolders.filter(languages=self.language)
| VirtualFolder.objects.filter(
all_languages=True, all_projects=True))
def add_to_vfolders(self):
to_add = []
for vf in self.possible_vfolders:
if vf.path_matcher.should_add_store(self.store):
to_add.append(vf)
if to_add:
self.store.vfolders.add(*to_add)
self.store.set_priority()
class VirtualFolderPathMatcher(object):
tp_path = "/[^/]*/[^/]*/"
def __init__(self, vf):
self.vf = vf
@property
def existing_stores(self):
"""Currently associated Stores"""
return self.vf.stores.all()
@property
def languages(self):
"""The languages associated with this vfolder
If `all_languages` is set then `None` is returned
"""
if self.vf.all_languages:
return None
return self.vf.languages.values_list("pk", flat=True)
@property
def projects(self):
"""The projects associated with this vfolder
If `all_projects` is set then `None` is returned
"""
if self.vf.all_projects:
return None
return self.vf.projects.values_list("pk", flat=True)
@property
def matching_stores(self):
"""Store qs containing all stores that match
project, language, and rules for this vfolder
"""
return self.filter_from_rules(self.store_qs)
@property
def rules(self):
"""Glob matching rules"""
return (
"%s" % r.strip()
for r
in self.vf.filter_rules.split(","))
@property
def store_manager(self):
"""The root object manager for finding/adding stores"""
return Store.objects
@property
def store_qs(self):
"""The stores qs without any rule filtering"""
return self.filter_projects(
self.filter_languages(
self.store_manager))
def add_and_remove_stores(self):
"""Add Stores that should be associated but arent, delete Store
associations for Stores that are associated but shouldnt be
"""
existing_stores = set(self.existing_stores)
matching_stores = set(self.matching_stores)
to_add = matching_stores - existing_stores
to_remove = existing_stores - matching_stores
if to_add:
self.add_stores(to_add)
if to_remove:
self.remove_stores(to_remove)
return to_add, to_remove
def add_stores(self, stores):
"""Associate a Store"""
self.vf.stores.add(*stores)
def filter_from_rules(self, qs):
filtered_qs = qs.none()
for rule in self.rules:
filtered_qs = (
filtered_qs
| qs.filter(pootle_path__regex=self.get_rule_regex(rule)))
return filtered_qs
def filter_languages(self, qs):
if self.languages is None:
return qs
return qs.filter(
translation_project__language_id__in=self.languages)
def filter_projects(self, qs):
if self.projects is None:
return qs
return qs.filter(
translation_project__project_id__in=self.projects)
def get_rule_regex(self, rule):
"""For a given *glob* rule, return a pootle_path *regex*"""
return (
"^%s%s"
% (self.tp_path,
PathFilter().path_regex(rule)))
def path_matches(self, path):
"""Returns bool of whether path is valid for this VF.
"""
for rule in self.rules:
if fnmatch(rule, path):
return True
return False
def remove_stores(self, stores):
self.vf.stores.remove(*stores)
def should_add_store(self, store):
return (
self.store_matches(store)
and not self.store_associated(store))
def store_associated(self, store):
return self.vf.stores.through.objects.filter(
store_id=store.id,
virtualfolder_id=self.vf.id).exists()
def store_matches(self, store):
return self.path_matches(store.path)
def update_stores(self):
"""Add and delete Store associations as necessary, and set the
priority for any affected Stores
"""
added, removed = self.add_and_remove_stores()
for store in added:
if store.priority < self.vf.priority:
store.set_priority(priority=self.vf.priority)
for store in removed:
if store.priority == self.vf.priority:
store.set_priority()
class DirectoryVFDataTool(RelatedStoresDataTool):
group_by = ("store__vfolders__name", )
ns = "virtualfolder"
cache_key_name = "vfolder"
@property
def context_name(self):
return self.context.pootle_path
@property
def max_unit_revision(self):
return VirtualFolder.stores.through.objects.filter(
store__translation_project=self.context.translation_project,
store__pootle_path__startswith=self.context.pootle_path).aggregate(
rev=Max("store__data__max_unit_revision"))
def filter_data(self, qs):
return (
qs.filter(store__translation_project=self.context.translation_project)
.filter(store__pootle_path__startswith=self.context.pootle_path)
.filter(store__vfolders__gt=0))
def vfolder_is_visible(self, vfolder, vfolder_stats):
return (
vfolder_stats["critical"]
or vfolder_stats["suggestions"]
or (vfolder.priority >= 1
and vfolder_stats["total"] != vfolder_stats["translated"]))
@persistent_property
def all_vf_stats(self):
return self.get_vf_stats(self.all_children_stats, show_all=True)
@persistent_property
def vf_stats(self):
return self.get_vf_stats(self.children_stats)
def get_vf_stats(self, stats, show_all=False):
vfolders = {
vf.name: vf
for vf
in VirtualFolder.objects.filter(name__in=stats.keys())}
for k, v in stats.items():
vfolder = vfolders.get(k)
stats[k]["priority"] = vfolder.priority
stats[k]["isVisible"] = (
vfolder.is_public
and self.vfolder_is_visible(vfolder, v))
if not stats[k]["isVisible"] and not show_all:
del stats[k]
continue
stats[k]["name"] = k
stats[k]["code"] = k
stats[k]["title"] = k
return stats
def get_stats(self, user=None):
if self.show_all_to(user):
return self.all_vf_stats
return self.vf_stats
def _group_vf_check_data(self, data):
checks = {}
for vf, name, count in data:
checks[vf] = checks.get(vf, {})
checks[vf][name] = count
return checks
@persistent_property
def all_checks_data(self):
return self._group_vf_check_data(
self.filter_data(self.checks_data_model)
.values_list("store__vfolders", "name")
.annotate(Sum("count")))
@persistent_property
def checks_data(self):
data = self.filter_accessible(
self.filter_data(self.checks_data_model))
return self._group_vf_check_data(
data.values_list("store__vfolders", "name")
.annotate(Sum("count")))
| 8,608
|
Python
|
.py
| 227
| 28.735683
| 82
| 0.611351
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,507
|
__init__.py
|
translate_pootle/pootle/apps/virtualfolder/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'virtualfolder.apps.PootleVirtualFolderConfig'
| 344
|
Python
|
.py
| 8
| 41.875
| 77
| 0.776119
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,508
|
providers.py
|
translate_pootle/pootle/apps/virtualfolder/providers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import panels, url_patterns
from pootle.core.plugin import provider
from pootle_translationproject.views import TPBrowseView
from .panels import VFolderPanel
from .urls import urlpatterns
@provider(url_patterns)
def vf_url_provider(**kwargs_):
return dict(vfolders=urlpatterns)
@provider(panels, sender=TPBrowseView)
def vf_panel_provider(**kwargs_):
return dict(vfolders=VFolderPanel)
| 701
|
Python
|
.py
| 18
| 37.166667
| 77
| 0.799114
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,509
|
panels.py
|
translate_pootle/pootle/apps/virtualfolder/panels.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_app.panels import ChildrenPanel
class VFolderPanel(ChildrenPanel):
panel_name = "vfolder"
@property
def children(self):
if not self.view.vfolders_data_view:
return {}
return self.view.vfolders_data_view.table_items
@property
def vfdata(self):
vfdata = self.view.vfolders_data_view
if not self.view.has_vfolders:
return vfdata
return vfdata
@property
def table(self):
return (
self.vfdata.table_data["children"]
if self.vfdata and self.vfdata.table_data
else "")
| 891
|
Python
|
.py
| 27
| 26.740741
| 77
| 0.668998
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,510
|
views.py
|
translate_pootle/pootle/apps/virtualfolder/views.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import forms
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.functional import cached_property
from pootle.core.browser import get_table_headings
from pootle.core.delegate import search_backend
from pootle.core.exceptions import Http400
from pootle.core.http import JsonResponse
from pootle.core.url_helpers import get_path_parts, split_pootle_path
from pootle.i18n.gettext import ugettext as _
from pootle_misc.util import ajax_required
from pootle_store.forms import UnitSearchForm
from pootle_store.unit.results import GroupedResults
from pootle_translationproject.views import TPTranslateView
from .delegate import vfolders_data_tool
from .display import VFolderStatsDisplay
from .models import VirtualFolder
def make_vfolder_dict(context, vf, stats):
lang_code, proj_code = split_pootle_path(context.pootle_path)[:2]
base_url = reverse(
"pootle-vfolder-tp-translate",
kwargs=dict(
vfolder_name=vf,
language_code=lang_code,
project_code=proj_code))
return {
'href_translate': base_url,
'title': stats["title"],
'code': vf,
'priority': stats.get("priority"),
'is_grayed': not stats["isVisible"],
'stats': stats,
'icon': 'vfolder'}
class VFolderTPTranslateView(TPTranslateView):
display_vfolder_priority = False
@cached_property
def check_data(self):
return self.vfolders_data_view.vfolder_data_tool.get_checks(
user=self.request.user).get(self.vfolder_pk, {})
@cached_property
def vfolder(self):
return VirtualFolder.objects.get(name=self.kwargs["vfolder_name"])
@property
def vfolder_pk(self):
return self.vfolder.pk
def get_context_data(self, *args, **kwargs):
ctx = super(
VFolderTPTranslateView,
self).get_context_data(*args, **kwargs)
ctx["unit_api_root"] = reverse(
"vfolder-pootle-xhr-units",
kwargs=dict(vfolder_name=self.vfolder.name))
ctx["resource_path"] = (
"/".join(
["++vfolder",
self.vfolder.name,
self.object.pootle_path.replace(self.ctx_path, "")]))
ctx["resource_path_parts"] = get_path_parts(ctx["resource_path"])
return ctx
@ajax_required
def get_vfolder_units(request, **kwargs):
"""Gets source and target texts and its metadata.
:return: A JSON-encoded string containing the source and target texts
grouped by the store they belong to.
The optional `count` GET parameter defines the chunk size to
consider. The user's preference will be used by default.
When the `initial` GET parameter is present, a sorted list of
the result set ids will be returned too.
"""
search_form = UnitSearchForm(request.GET, user=request.user)
vfolder = get_object_or_404(
VirtualFolder,
name=kwargs.get("vfolder_name"))
if not search_form.is_valid():
errors = search_form.errors.as_data()
if "path" in errors:
for error in errors["path"]:
if error.code == "max_length":
raise Http400(_('Path too long.'))
elif error.code == "required":
raise Http400(_('Arguments missing.'))
raise Http404(forms.ValidationError(search_form.errors).messages)
search_form.cleaned_data["vfolder"] = vfolder
backend = search_backend.get(VirtualFolder)(
request.user, **search_form.cleaned_data)
total, start, end, units_qs = backend.search()
return JsonResponse(
{'start': start,
'end': end,
'total': total,
'unitGroups': GroupedResults(units_qs).data})
class VFoldersDataView(object):
_table_fields = (
'name', 'progress', 'activity',
'total', 'need-translation',
'suggestions', 'critical', 'priority')
def __init__(self, context, user, has_admin_access=False):
self.context = context
self.user = user
self.has_admin_access = has_admin_access
@cached_property
def vfolder_data_tool(self):
return vfolders_data_tool.get(self.context.__class__)(self.context)
@property
def table_fields(self):
fields = self._table_fields
if self.has_admin_access:
fields += ('last-updated', )
return fields
@cached_property
def table_data(self):
ctx = {}
if len(self.all_stats) > 0:
ctx.update({
'children': {
'id': 'vfolders',
'fields': self.table_fields,
'headings': get_table_headings(self.table_fields),
'rows': self.table_items}})
return ctx
@cached_property
def all_stats(self):
return VFolderStatsDisplay(
self.context,
self.vfolder_data_tool.get_stats(user=self.user)).stats
@cached_property
def stats(self):
return dict(children=self.all_stats)
@property
def table_items(self):
items = [make_vfolder_dict(self.context, *vf)
for vf
in self.all_stats.items()]
items.sort(
lambda x, y: cmp(y['stats']['priority'], x['stats']['priority']))
return items
@cached_property
def has_data(self):
return (
self.vfolder_data_tool.all_stat_data.exists()
if self.vfolder_data_tool.show_all_to(self.user)
else self.vfolder_data_tool.stat_data.exists())
| 5,937
|
Python
|
.py
| 150
| 31.533333
| 77
| 0.642522
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,511
|
delegate.py
|
translate_pootle/pootle/apps/virtualfolder/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin.delegate import Getter
path_matcher = Getter()
vfolders_data_tool = Getter()
vfolder_finder = Getter()
vfolders_data_view = Getter()
| 435
|
Python
|
.py
| 12
| 35
| 77
| 0.766667
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,512
|
0013_set_projects_languages.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0013_set_projects_languages.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pootle.core.url_helpers import split_pootle_path
def parse_vfolder_rules(vf):
languages = set()
projects = set()
new_rules = set()
full_rules = [vf.location.strip() + rule.strip()
for rule in vf.filter_rules.split(",")]
for full_rule in full_rules:
lang_code, proj_code, dir_path, filename = split_pootle_path(full_rule)
if filename:
new_rules.add(dir_path + filename)
else:
new_rules.add(dir_path + "*")
languages.add(lang_code)
projects.add(proj_code)
if "{LANG}" in languages:
languages = set()
if "{PROJ}" in projects:
projects = set()
new_rules=",".join(new_rules)
return languages, projects, new_rules
def set_projects_and_languages(app, schema):
VirtualFolder = app.get_model("virtualfolder.VirtualFolder")
Project = app.get_model("pootle_project.Project")
Language = app.get_model("pootle_language.Language")
for vf in VirtualFolder.objects.all():
languages, projects, new_rules = parse_vfolder_rules(vf)
if projects:
vf.projects.add(*Project.objects.filter(code__in=projects))
if languages:
vf.languages.add(*Language.objects.filter(code__in=languages))
vf.filter_rules = new_rules
vf.all_projects = not projects
vf.all_languages = not languages
vf.save()
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0012_add_all_proj_lang_flags'),
]
operations = [
migrations.RunPython(set_projects_and_languages)
]
| 1,728
|
Python
|
.py
| 45
| 31.222222
| 79
| 0.64907
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,513
|
0002_set_unit_priorities.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0002_set_unit_priorities.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import FieldError
from django.db import models, migrations
def forwards_units(apps, schema_editor):
Unit = apps.get_model("pootle_store", "Unit")
VirtualFolder = apps.get_model("virtualfolder", "VirtualFolder")
db_alias = schema_editor.connection.alias
# first set all Units to a priority of 1.0
Unit.objects.update(priority=1.0)
vf_values = (
VirtualFolder.objects.using(db_alias)
.order_by("-priority")
.values_list("units__pk", "priority"))
unit_prios = {}
for unit, priority in vf_values.iterator():
# As vf_values is ordered -priority we can just grab the first for
# each unit.
if unit_prios.get(unit, None) is None:
unit_prios[unit] = priority
unit_values = (
Unit.objects.using(db_alias)
.values_list("id", "priority"))
for pk, priority, in unit_values.iterator():
new_priority = unit_prios.get(pk, 1.0)
if new_priority != 1.0:
if priority != new_priority:
Unit.objects.filter(pk=pk).update(priority=new_priority)
def forwards(apps, schema_editor):
# as we have no real way of controlling whether this will be
# run before or after priority was moved to store, we need to
# test the field exists
try:
apps.get_model("pootle_store.Unit").objects.filter(priority=1)
except FieldError:
pass
else:
return forwards_units(apps, schema_editor)
class Migration(migrations.Migration):
dependencies = [
('pootle_store', '0005_unit_priority'),
('virtualfolder', '0001_initial'),
]
operations = [migrations.RunPython(forwards)]
| 1,820
|
Python
|
.py
| 44
| 33.454545
| 74
| 0.640749
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,514
|
0014_remove_location.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0014_remove_location.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0013_set_projects_languages'),
]
operations = [
migrations.AlterUniqueTogether(
name='virtualfolder',
unique_together=set([]),
),
migrations.RemoveField(
model_name='virtualfolder',
name='location',
),
]
| 493
|
Python
|
.py
| 17
| 21.588235
| 57
| 0.605096
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,515
|
0011_add_projects_languages.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0011_add_projects_languages.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_language', '0002_case_insensitive_schema'),
('pootle_project', '0010_add_reserved_code_validator'),
('virtualfolder', '0010_remove_virtualfolder_units'),
]
operations = [
migrations.AddField(
model_name='virtualfolder',
name='languages',
field=models.ManyToManyField(related_name='vfolders', to='pootle_language.Language', db_index=True),
),
migrations.AddField(
model_name='virtualfolder',
name='projects',
field=models.ManyToManyField(related_name='vfolders', to='pootle_project.Project', db_index=True),
),
]
| 831
|
Python
|
.py
| 21
| 31.47619
| 112
| 0.638509
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,516
|
0017_rm_vfdata.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0017_rm_vfdata.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-06 10:36
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0016_remove_vfdata_last_updated_unit'),
]
operations = [
migrations.RemoveField(
model_name='vfdata',
name='last_created_unit',
),
migrations.RemoveField(
model_name='vfdata',
name='last_submission',
),
migrations.RemoveField(
model_name='vfdata',
name='vf',
),
migrations.DeleteModel(
name='VFData',
),
]
| 704
|
Python
|
.py
| 25
| 20.08
| 66
| 0.571217
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,517
|
0016_remove_vfdata_last_updated_unit.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0016_remove_vfdata_last_updated_unit.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-19 09:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0015_vfdata'),
]
operations = [
migrations.RemoveField(
model_name='vfdata',
name='last_updated_unit',
),
]
| 397
|
Python
|
.py
| 14
| 22.428571
| 47
| 0.624339
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,518
|
0015_vfdata.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0015_vfdata.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_statistics', '0004_fill_translated_wordcount'),
('pootle_store', '0019_remove_unit_priority'),
('virtualfolder', '0014_remove_location'),
]
operations = [
migrations.CreateModel(
name='VFData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('max_unit_mtime', models.DateTimeField(db_index=True, null=True, blank=True)),
('max_unit_revision', models.IntegerField(default=0, null=True, db_index=True, blank=True)),
('critical_checks', models.IntegerField(default=0, db_index=True)),
('pending_suggestions', models.IntegerField(default=0, db_index=True)),
('total_words', models.IntegerField(default=0, db_index=True)),
('translated_words', models.IntegerField(default=0, db_index=True)),
('fuzzy_words', models.IntegerField(default=0, db_index=True)),
('last_created_unit', models.OneToOneField(related_name='last_created_for_vfdata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('last_submission', models.OneToOneField(related_name='vfdata_stats_data', null=True, blank=True, to='pootle_statistics.Submission', on_delete=models.CASCADE)),
('last_updated_unit', models.OneToOneField(related_name='last_updated_for_vfdata', null=True, blank=True, to='pootle_store.Unit', on_delete=models.CASCADE)),
('vf', models.OneToOneField(related_name='data', to='virtualfolder.VirtualFolder', on_delete=models.CASCADE)),
],
options={
'db_table': 'pootle_vf_data',
},
),
]
| 1,950
|
Python
|
.py
| 31
| 51.290323
| 176
| 0.628527
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,519
|
0009_set_vfolder_stores.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0009_set_vfolder_stores.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_vfolder_stores(app, schema):
VirtualFolder = app.get_model("virtualfolder.VirtualFolder")
Store = app.get_model("pootle_store.Store")
for vf in VirtualFolder.objects.all():
store_pks = vf.units.values_list("store", flat=True).distinct()
stores = Store.objects.filter(pk__in=store_pks)
vf.stores.add(*stores)
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0008_virtualfolder_stores'),
]
operations = [
migrations.RunPython(set_vfolder_stores)
]
| 660
|
Python
|
.py
| 17
| 33.411765
| 71
| 0.691824
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,520
|
0003_case_sensitive_schema.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0003_case_sensitive_schema.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pootle.core.utils.db import set_mysql_collation_for_column
def make_vfti_paths_cs(apps, schema_editor):
cursor = schema_editor.connection.cursor()
set_mysql_collation_for_column(
apps,
cursor,
"virtualfolder.VirtualFolderTreeItem",
"pootle_path",
"utf8_bin",
"varchar(255)")
def make_virtualfolder_paths_cs(apps, schema_editor):
cursor = schema_editor.connection.cursor()
set_mysql_collation_for_column(
apps,
cursor,
"virtualfolder.VirtualFolder",
"name",
"utf8_bin",
"varchar(70)")
set_mysql_collation_for_column(
apps,
cursor,
"virtualfolder.VirtualFolder",
"location",
"utf8_bin",
"varchar(255)")
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0002_set_unit_priorities'),
]
operations = [
migrations.RunPython(make_vfti_paths_cs),
migrations.RunPython(make_virtualfolder_paths_cs),
]
| 1,140
|
Python
|
.py
| 37
| 24.027027
| 63
| 0.645014
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,521
|
0012_add_all_proj_lang_flags.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0012_add_all_proj_lang_flags.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0011_add_projects_languages'),
]
operations = [
migrations.AddField(
model_name='virtualfolder',
name='all_languages',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='virtualfolder',
name='all_projects',
field=models.BooleanField(default=False),
),
]
| 594
|
Python
|
.py
| 19
| 23.263158
| 57
| 0.610526
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,522
|
0018_rm_vfti.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0018_rm_vfti.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def drop_vfti_ctype(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
ContentType.objects.filter(app_label='virtualfolder',
model='virtualfoldertreeitem').delete()
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0017_rm_vfdata'),
]
operations = [
migrations.AlterUniqueTogether(
name='virtualfoldertreeitem',
unique_together=set([]),
),
migrations.RemoveField(
model_name='virtualfoldertreeitem',
name='directory',
),
migrations.RemoveField(
model_name='virtualfoldertreeitem',
name='parent',
),
migrations.RemoveField(
model_name='virtualfoldertreeitem',
name='stores',
),
migrations.RemoveField(
model_name='virtualfoldertreeitem',
name='vfolder',
),
migrations.DeleteModel(
name='VirtualFolderTreeItem',
),
migrations.RunPython(drop_vfti_ctype),
]
| 1,218
|
Python
|
.py
| 37
| 23.648649
| 70
| 0.602215
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,523
|
0001_initial.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import pootle.core.mixins.treeitem
import pootle.core.markup.fields
class Migration(migrations.Migration):
dependencies = [
('pootle_store', '0001_initial'),
('pootle_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='VirtualFolder',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=70, verbose_name='Name')),
('location', models.CharField(help_text='Root path where this virtual folder is applied.', max_length=255, verbose_name='Location')),
('filter_rules', models.TextField(help_text='Filtering rules that tell which stores this virtual folder comprises.', verbose_name='Filter')),
('priority', models.FloatField(default=1, help_text='Number specifying importance. Greater priority means it is more important.', verbose_name='Priority')),
('is_public', models.BooleanField(default=True, help_text='Whether this virtual folder is public or not.', verbose_name='Is public?')),
('description', pootle.core.markup.fields.MarkupField(verbose_name='Description', blank=True)),
('units', models.ManyToManyField(related_name='vfolders', to='pootle_store.Unit', db_index=True)),
],
options={
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='virtualfolder',
unique_together=set([('name', 'location')]),
),
migrations.CreateModel(
name='VirtualFolderTreeItem',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('pootle_path', models.CharField(unique=True, max_length=255, editable=False, db_index=True)),
('directory', models.ForeignKey(related_name='vf_treeitems', to='pootle_app.Directory', on_delete=models.CASCADE)),
('parent', models.ForeignKey(related_name='child_vf_treeitems', to='virtualfolder.VirtualFolderTreeItem', null=True, on_delete=models.CASCADE)),
('stores', models.ManyToManyField(related_name='parent_vf_treeitems', to='pootle_store.Store', db_index=True)),
('vfolder', models.ForeignKey(related_name='vf_treeitems', to='virtualfolder.VirtualFolder', on_delete=models.CASCADE)),
],
options={
},
bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem),
),
migrations.AlterUniqueTogether(
name='virtualfoldertreeitem',
unique_together=set([('directory', 'vfolder')]),
),
]
| 2,907
|
Python
|
.py
| 50
| 46.8
| 172
| 0.629734
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,524
|
0019_change_filter_rules_field_label.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0019_change_filter_rules_field_label.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-07 17:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0018_rm_vfti'),
]
operations = [
migrations.AlterField(
model_name='virtualfolder',
name='filter_rules',
field=models.TextField(help_text='Filtering rules that tell which files this virtual folder comprises.', verbose_name='Filter'),
),
]
| 549
|
Python
|
.py
| 15
| 30.2
| 140
| 0.657845
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,525
|
0004_virtualfolder_title.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0004_virtualfolder_title.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0003_case_sensitive_schema'),
]
operations = [
migrations.AddField(
model_name='virtualfolder',
name='title',
field=models.CharField(max_length=255, null=True, verbose_name='Title', blank=True),
),
]
| 461
|
Python
|
.py
| 14
| 26.142857
| 96
| 0.633484
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,526
|
0010_remove_virtualfolder_units.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0010_remove_virtualfolder_units.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0009_set_vfolder_stores'),
]
operations = [
migrations.RemoveField(
model_name='virtualfolder',
name='units',
),
]
| 364
|
Python
|
.py
| 13
| 21.692308
| 53
| 0.621387
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,527
|
0007_make_vfolder_name_unique.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0007_make_vfolder_name_unique.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0006_cleanup_vfolder_names'),
]
operations = [
migrations.AlterField(
model_name='virtualfolder',
name='name',
field=models.CharField(unique=True, max_length=70, verbose_name='Name'),
),
]
| 450
|
Python
|
.py
| 14
| 25.357143
| 84
| 0.63109
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,528
|
0006_cleanup_vfolder_names.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0006_cleanup_vfolder_names.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import Counter
from django.db import migrations, models
def rename_vf(vfolder):
parts = vfolder.location.split("/")
suffix = "-".join(
[x for x
in parts
if x and x not in ["{LANG}", "{PROJ}"]])
new_name = "-".join([vfolder.name, suffix])
for vfti in vfolder.vf_treeitems.all():
vfti_parts = vfti.pootle_path.split("/")
vfti_parts[vfolder.location.strip("/").count("/") + 2] = new_name
vfti.pootle_path = "/".join(vfti_parts)
vfti.save()
vfolder.name = new_name
vfolder.save()
def cleanup_vfolder_names(app, schema):
VirtualFolder = app.get_model("virtualfolder.VirtualFolder")
names = Counter(VirtualFolder.objects.values_list("name", flat=True))
for name, count in names.items():
if count < 2:
continue
for vf in VirtualFolder.objects.filter(name=name):
rename_vf(vf)
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0005_set_vfolder_titles'),
]
operations = [
migrations.RunPython(cleanup_vfolder_names)
]
| 1,193
|
Python
|
.py
| 33
| 29.757576
| 73
| 0.637631
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,529
|
0008_virtualfolder_stores.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0008_virtualfolder_stores.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pootle_store', '0019_remove_unit_priority'),
('virtualfolder', '0007_make_vfolder_name_unique'),
]
operations = [
migrations.AddField(
model_name='virtualfolder',
name='stores',
field=models.ManyToManyField(related_name='vfolders', to='pootle_store.Store', db_index=True),
),
]
| 530
|
Python
|
.py
| 15
| 28.4
| 106
| 0.637255
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,530
|
0005_set_vfolder_titles.py
|
translate_pootle/pootle/apps/virtualfolder/migrations/0005_set_vfolder_titles.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_vfolder_titles(app, schema):
VirtualFolder = app.get_model("virtualfolder.VirtualFolder")
for vf in VirtualFolder.objects.all():
vf.title = vf.name
vf.save()
class Migration(migrations.Migration):
dependencies = [
('virtualfolder', '0004_virtualfolder_title'),
]
operations = [
migrations.RunPython(set_vfolder_titles)
]
| 496
|
Python
|
.py
| 15
| 27.933333
| 64
| 0.688421
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,531
|
add_vfolders.py
|
translate_pootle/pootle/apps/virtualfolder/management/commands/add_vfolders.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import logging
import os
# This must be run before importing Django.
os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings'
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from pootle.core.url_helpers import split_pootle_path
from pootle_language.models import Language
from pootle_project.models import Project
from virtualfolder.models import VirtualFolder
class Command(BaseCommand):
help = "Add virtual folders from file."
def add_arguments(self, parser):
parser.add_argument(
"vfolder",
nargs=1,
help="JSON vfolder configuration file",
)
def parse_vfolder_rules(self, location, old_rules):
"""Extract languages, projects and new rules from location and rules."""
languages = set()
projects = set()
new_rules = set()
full_rules = [location + old_rule.strip() for old_rule in old_rules]
for full_rule in full_rules:
lang_code, proj_code, dir_path, fname = split_pootle_path(full_rule)
if fname:
new_rules.add(dir_path + fname)
else:
new_rules.add(dir_path + "*")
languages.add(lang_code)
projects.add(proj_code)
if "{LANG}" in languages:
languages = set()
if "{PROJ}" in projects:
projects = set()
new_rules = ",".join(new_rules)
return languages, projects, new_rules
def handle(self, **options):
"""Add virtual folders from file."""
try:
with open(options['vfolder'][0], "r") as inputfile:
vfolders = json.load(inputfile)
except IOError as e:
raise CommandError(e)
except ValueError as e:
raise CommandError("Please check if the JSON file is malformed. "
"Original error:\n%s" % e)
for vfolder_item in vfolders:
try:
temp = ','.join(vfolder_item['filters']['files'])
if not temp:
raise ValueError
except (KeyError, ValueError):
raise CommandError("Virtual folder '%s' has no filtering "
"rules." % vfolder_item['name'])
self.stdout.write("Importing virtual folders...")
added_count = 0
updated_count = 0
errored_count = 0
for vfolder_item in vfolders:
vfolder_item['name'] = vfolder_item['name'].strip().lower()
# Put all the files for each virtual folder as a list and save it
# as its filter rules.
languages, projects, new_rules = self.parse_vfolder_rules(
vfolder_item['location'].strip(),
vfolder_item['filters']['files']
)
vfolder_item['filter_rules'] = new_rules
if 'filters' in vfolder_item:
del vfolder_item['filters']
# Now create or update the virtual folder.
try:
# Retrieve the virtual folder if it exists.
vfolder = VirtualFolder.objects.get(name=vfolder_item['name'])
except VirtualFolder.DoesNotExist:
# If the virtual folder doesn't exist yet then create it.
try:
self.stdout.write(u'Adding new virtual folder %s...' %
vfolder_item['name'])
vfolder_item['all_projects'] = not projects
vfolder_item['all_languages'] = not languages
vfolder = VirtualFolder(**vfolder_item)
vfolder.save()
except ValidationError as e:
errored_count += 1
self.stdout.write('FAILED')
self.stderr.write(e)
else:
if projects:
vfolder.projects.add(
*Project.objects.filter(code__in=projects)
)
if languages:
vfolder.languages.add(
*Language.objects.filter(code__in=languages)
)
self.stdout.write('DONE')
added_count += 1
else:
# Update the already existing virtual folder.
changed = False
if not projects:
vfolder.all_projects = True
changed = True
logging.debug("'All projects' for virtual folder '%s' "
"will be changed.", vfolder.name)
if not languages:
vfolder.all_languages = True
changed = True
logging.debug("'All languages' for virtual folder '%s' "
"will be changed.", vfolder.name)
if projects:
vfolder.projects.set(
*Project.objects.filter(code__in=projects)
)
if languages:
vfolder.languages.set(
*Language.objects.filter(code__in=languages)
)
if vfolder.filter_rules != vfolder_item['filter_rules']:
vfolder.filter_rules = vfolder_item['filter_rules']
changed = True
logging.debug("Filter rules for virtual folder '%s' will "
"be changed.", vfolder.name)
if ('priority' in vfolder_item and
vfolder.priority != vfolder_item['priority']):
vfolder.priority = vfolder_item['priority']
changed = True
logging.debug("Priority for virtual folder '%s' will be "
"changed to %f.", vfolder.name,
vfolder.priority)
if ('is_public' in vfolder_item and
vfolder.is_public != vfolder_item['is_public']):
vfolder.is_public = vfolder_item['is_public']
changed = True
logging.debug("is_public status for virtual folder "
"'%s' will be changed.", vfolder.name)
if ('description' in vfolder_item and
vfolder.description.raw != vfolder_item['description']):
vfolder.description = vfolder_item['description']
changed = True
logging.debug("Description for virtual folder '%s' will "
"be changed.", vfolder.name)
if changed:
try:
self.stdout.write(u'Updating virtual folder %s...' %
vfolder_item['name'])
vfolder.save()
except ValidationError as e:
errored_count += 1
self.stdout.write('FAILED')
self.stderr.write(e)
else:
self.stdout.write('DONE')
updated_count += 1
self.stdout.write("\nErrored: %d\nAdded: %d\n"
"Updated: %d\nUnchanged: %d" %
(errored_count, added_count, updated_count,
len(vfolders) - errored_count - added_count -
updated_count))
| 7,937
|
Python
|
.py
| 169
| 30.331361
| 80
| 0.510735
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,532
|
getters.py
|
translate_pootle/pootle/apps/pootle_terminology/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import terminology, terminology_matcher
from pootle.core.plugin import getter
from pootle_store.models import Unit
from .utils import UnitTerminology, UnitTerminologyMatcher
@getter(terminology, sender=Unit)
def get_unit_terminology(**kwargs_):
return UnitTerminology
@getter(terminology_matcher, sender=Unit)
def get_unit_terminology_matcher(**kwargs_):
return UnitTerminologyMatcher
| 700
|
Python
|
.py
| 17
| 39.352941
| 77
| 0.805022
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,533
|
urls.py
|
translate_pootle/pootle/apps/pootle_terminology/urls.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf.urls import url
from .views import manage
urlpatterns = [
url(r'^(?P<language_code>[^/]*)/(?P<project_code>[^/]*)/terminology/',
manage,
name='pootle-terminology-manage'),
]
| 490
|
Python
|
.py
| 14
| 32.285714
| 77
| 0.707627
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,534
|
apps.py
|
translate_pootle/pootle/apps/pootle_terminology/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleTerminologyConfig(AppConfig):
name = "pootle_terminology"
verbose_name = "Pootle Terminology"
version = "0.1.1"
def ready(self):
importlib.import_module("pootle_terminology.getters")
importlib.import_module("pootle_terminology.receivers")
| 615
|
Python
|
.py
| 16
| 35.0625
| 77
| 0.752108
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,535
|
receivers.py
|
translate_pootle/pootle/apps/pootle_terminology/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db.models.signals import post_save
from django.dispatch import receiver
from pootle.core.delegate import terminology
from pootle_statistics.models import Submission, SubmissionFields
from pootle_store.constants import TRANSLATED
from pootle_store.models import Unit
@receiver(post_save, sender=Unit)
def handle_unit_save(**kwargs):
unit = kwargs["instance"]
if not kwargs.get("created"):
return
if unit.state != TRANSLATED:
return
is_terminology = (
unit.store.name.startswith("pootle-terminology")
or (unit.store.translation_project.project.code
== "terminology"))
if not is_terminology:
return
terminology.get(Unit)(unit).stem()
@receiver(post_save, sender=Submission)
def handle_submission_save(**kwargs):
sub = kwargs["instance"]
if sub.field != SubmissionFields.TARGET:
return
unit = sub.unit
if unit.state != TRANSLATED:
return
is_terminology = (
unit.store.name.startswith("pootle-terminology")
or (unit.store.translation_project.project.code
== "terminology"))
if not is_terminology:
return
terminology.get(Unit)(unit).stem()
| 1,483
|
Python
|
.py
| 42
| 30.452381
| 77
| 0.713589
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,536
|
utils.py
|
translate_pootle/pootle/apps/pootle_terminology/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.utils.functional import cached_property
from pootle.core.decorators import persistent_property
from pootle.core.delegate import revision, text_comparison
from pootle_store.constants import TRANSLATED
from pootle_store.models import Unit
from pootle_translationproject.models import TranslationProject
from pootle_word.utils import TextStemmer
from .apps import PootleTerminologyConfig
class UnitTerminology(TextStemmer):
def __init__(self, context):
super(UnitTerminology, self).__init__(context)
if not self.is_terminology:
raise ValueError("Unit must be a terminology unit")
@property
def is_terminology(self):
return (
self.context.store.name.startswith("pootle-terminology")
or (self.context.store.translation_project.project.code
== "terminology"))
@property
def existing_stems(self):
return set(
self.stem_set.values_list(
"root", flat=True))
@property
def missing_stems(self):
return (
self.stems
- set(self.stem_model.objects.filter(
root__in=self.stems).values_list("root", flat=True)))
@property
def stem_model(self):
return self.stem_set.model
@property
def stem_set(self):
return self.context.stems
@property
def stem_m2m(self):
return self.stem_set.through
def associate_stems(self, stems):
self.stem_m2m.objects.bulk_create(
self.stem_m2m(stem_id=stem_id, unit_id=self.context.id)
for stem_id
in list(
self.stem_model.objects.filter(root__in=stems)
.values_list("id", flat=True)))
def clear_stems(self, stems):
# not sure if this delecetes the m2m or the stem
self.stem_set.filter(root__in=stems).delete()
def create_stems(self, stems):
self.stem_model.objects.bulk_create(
self.stem_model(root=root)
for root
in stems)
def stem(self):
stems = self.stems
existing_stems = self.existing_stems
missing_stems = self.missing_stems
if existing_stems:
self.clear_stems(existing_stems - stems)
if missing_stems:
self.create_stems(missing_stems)
if stems - existing_stems:
self.associate_stems(stems - existing_stems)
class UnitTerminologyMatcher(TextStemmer):
ns = "pootle.terminology.matcher"
sw_version = PootleTerminologyConfig.version
similarity_threshold = .2
max_matches = 10
@property
def revision_context(self):
term_tp = TranslationProject.objects.select_related("directory").filter(
language_id=self.language_id,
project__code="terminology").first()
if term_tp:
return term_tp.directory
@property
def rev_cache_key(self):
rev_context = self.revision_context
return (
revision.get(rev_context.__class__)(rev_context).get(key="stats")
if rev_context
else "")
@property
def cache_key(self):
return (
"%s.%s.%s"
% (self.language_id,
self.rev_cache_key,
hash(self.text)))
@property
def language_id(self):
return self.context.store.translation_project.language.id
@property
def terminology_units(self):
return Unit.objects.filter(
state=TRANSLATED,
store__translation_project__project__code="terminology",
store__translation_project__language_id=self.language_id)
@cached_property
def comparison(self):
return text_comparison.get()(self.text)
def similar(self, results):
matches = []
matched = []
for result in results:
target_pair = (
result.source_f.lower().strip(),
result.target_f.lower().strip())
if target_pair in matched:
continue
similarity = self.comparison.similarity(result.source_f)
if similarity > self.similarity_threshold:
matches.append((similarity, result))
matched.append(target_pair)
return sorted(matches, key=lambda x: -x[0])[:self.max_matches]
@persistent_property
def matches(self):
return self.similar(
self.terminology_units.filter(
stems__root__in=self.stems).distinct())
| 4,808
|
Python
|
.py
| 128
| 28.65625
| 80
| 0.63228
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,537
|
__init__.py
|
translate_pootle/pootle/apps/pootle_terminology/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'pootle_terminology.apps.PootleTerminologyConfig'
| 347
|
Python
|
.py
| 8
| 42.25
| 77
| 0.775148
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,538
|
forms.py
|
translate_pootle/pootle/apps/pootle_terminology/forms.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import forms
from pootle.i18n.gettext import ugettext as _
from pootle_store.forms import MultiStringFormField
from pootle_store.models import Store, Unit
def term_unit_form_factory(terminology_store):
store_pk = terminology_store.pk
# Set store for new terms
qs = Store.objects.filter(pk=store_pk)
class TermUnitForm(forms.ModelForm):
store = forms.ModelChoiceField(queryset=qs, initial=store_pk,
widget=forms.HiddenInput)
index = forms.IntegerField(required=False, widget=forms.HiddenInput)
source_f = MultiStringFormField(required=False, textarea=False)
class Meta(object):
model = Unit # FIXME: terminology should use its own model!
fields = ('index', 'source_f', 'store',)
def clean_index(self):
# Assign new terms an index value
value = self.cleaned_data['index']
if self.instance.id is None:
value = terminology_store.max_index() + 1
return value
def clean_source_f(self):
value = self.cleaned_data['source_f']
if value:
existing = terminology_store.findid(value[0])
if existing and existing.id != self.instance.id:
raise forms.ValidationError(_('This term already exists '
'in this file.'))
self.instance.setid(value[0])
return value
return TermUnitForm
| 1,813
|
Python
|
.py
| 39
| 36.179487
| 77
| 0.632955
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,539
|
views.py
|
translate_pootle/pootle/apps/pootle_terminology/views.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.shortcuts import render
from django.urls import reverse
from pootle.core.decorators import get_path_obj, permission_required
from pootle_app.views.admin import util
from pootle_store.models import Store, Unit
from .forms import term_unit_form_factory
def get_terminology_filename(translation_project):
try:
# See if a terminology store already exists
return translation_project.stores.live().filter(
name__startswith='pootle-terminology.',
).values_list('name', flat=True)[0]
except IndexError:
pass
return (
'pootle-terminology.%s'
% translation_project.project.filetypes.first().extension)
def manage_store(request, ctx, language, term_store):
TermUnitForm = term_unit_form_factory(term_store)
template_name = 'translation_projects/terminology/manage.html'
return util.edit(request, template_name, Unit, ctx,
None, None, queryset=term_store.units, can_delete=True,
form=TermUnitForm)
@get_path_obj
@permission_required('administrate')
def manage(request, translation_project):
ctx = {
'page': 'admin-terminology',
'browse_url': reverse('pootle-tp-browse', kwargs={
'language_code': translation_project.language.code,
'project_code': translation_project.project.code,
}),
'translate_url': reverse('pootle-tp-translate', kwargs={
'language_code': translation_project.language.code,
'project_code': translation_project.project.code,
}),
'translation_project': translation_project,
'language': translation_project.language,
'project': translation_project.project,
'source_language': translation_project.project.source_language,
'directory': translation_project.directory,
}
if translation_project.project.is_terminology:
# Which file should we edit?
stores = list(Store.objects.live().filter(
translation_project=translation_project,
))
if len(stores) == 1:
# There is only one, and we're not going to offer file-level
# activities, so let's just edit the one that is there.
return manage_store(request, ctx, ctx['language'], stores[0])
elif len(stores) > 1:
for store in stores:
path_length = len(translation_project.pootle_path)
store.nice_name = store.pootle_path[path_length:]
ctx['stores'] = stores
return render(request,
"translation_projects/terminology/stores.html", ctx)
try:
terminology_filename = get_terminology_filename(translation_project)
term_store = Store.objects.get(
pootle_path=translation_project.pootle_path + terminology_filename,
)
return manage_store(request, ctx, ctx['language'], term_store)
except Store.DoesNotExist:
return render(request, "translation_projects/terminology/manage.html",
ctx)
| 3,352
|
Python
|
.py
| 74
| 36.932432
| 79
| 0.669016
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,540
|
terminology_tags.py
|
translate_pootle/pootle/apps/pootle_terminology/templatetags/terminology_tags.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import template
register = template.Library()
@register.inclusion_tag('translation_projects/terminology/_term_edit.html',
takes_context=True)
def render_term_edit(context, form):
template_vars = {
'unit': form.instance,
'form': form,
'language': context['language'],
'source_language': context['source_language'],
}
return template_vars
| 697
|
Python
|
.py
| 19
| 31.842105
| 77
| 0.693908
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,541
|
state.py
|
translate_pootle/pootle/apps/pootle_fs/state.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from copy import copy
from django.db.models import Q
from django.utils.functional import cached_property
from django.utils.lru_cache import lru_cache
from pootle.core.state import ItemState, State
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
from .models import StoreFS
from .resources import FSProjectStateResources
FS_STATE = OrderedDict()
FS_STATE["conflict"] = {
"title": "Conflicts",
"description": "Both Pootle Store and file in filesystem have changed"}
FS_STATE["conflict_untracked"] = {
"title": "Untracked conflicts",
"description": (
"Newly created files in the filesystem matching newly created Stores "
"in Pootle")}
FS_STATE["pootle_ahead"] = {
"title": "Changed in Pootle",
"description": "Stores that have changed in Pootle"}
FS_STATE["pootle_untracked"] = {
"title": "Untracked Stores",
"description": "Newly created Stores in Pootle"}
FS_STATE["pootle_staged"] = {
"title": "Added in Pootle",
"description": (
"Stores that have been added in Pootle and are now being tracked")}
FS_STATE["pootle_removed"] = {
"title": "Removed from Pootle",
"description": "Stores that have been removed from Pootle"}
FS_STATE["fs_ahead"] = {
"title": "Changed in filesystem",
"description": "A file has been changed in the filesystem"}
FS_STATE["fs_untracked"] = {
"title": "Untracked files",
"description": "Newly created files in the filesystem"}
FS_STATE["fs_staged"] = {
"title": "Fetched from filesystem",
"description": (
"Files that have been fetched from the filesystem and are now being "
"tracked")}
FS_STATE["fs_removed"] = {
"title": "Removed from filesystem",
"description": "Files that have been removed from the filesystem"}
FS_STATE["merge_pootle_wins"] = {
"title": "Staged for merge (Pootle wins)",
"description": (
"Files or Stores that have been staged for merging on sync - pootle "
"wins where units are both updated")}
FS_STATE["merge_fs_wins"] = {
"title": "Staged for merge (FS wins)",
"description": (
"Files or Stores that have been staged for merging on sync - FS "
"wins where units are both updated")}
FS_STATE["remove"] = {
"title": "Staged for removal",
"description": "Files or Stores that have been staged or removal on sync"}
FS_STATE["both_removed"] = {
"title": "Removed from Pootle and filesystem",
"description": (
"Files or Stores that were previously tracked but have now "
"disappeared")}
class FSItemState(ItemState):
@property
def pootle_path(self):
if "pootle_path" in self.kwargs:
return self.kwargs["pootle_path"]
elif "store" in self.kwargs:
return self.kwargs["store"].pootle_path
@property
def fs_path(self):
return self.kwargs.get("fs_path")
@property
def project(self):
return self.plugin.project
@property
def plugin(self):
return self.state.context
@cached_property
def store_fs(self):
store_fs = self.kwargs.get("store_fs")
if isinstance(store_fs, (int, long)):
return StoreFS.objects.filter(pk=store_fs).first()
return store_fs
@property
def store(self):
return self.kwargs.get("store")
def __gt__(self, other):
if isinstance(other, self.__class__):
return self.pootle_path > other.pootle_path
return object.__gt__(other)
class ProjectFSState(State):
item_state_class = FSItemState
def __init__(self, context, fs_path=None, pootle_path=None, load=True):
self.fs_path = fs_path
self.pootle_path = pootle_path
super(ProjectFSState, self).__init__(
context, fs_path=fs_path, pootle_path=pootle_path,
load=load)
@property
def project(self):
return self.context.project
@property
def states(self):
return FS_STATE.keys()
@cached_property
def resources(self):
return FSProjectStateResources(
self.context,
pootle_path=self.pootle_path,
fs_path=self.fs_path)
@property
def state_conflict(self):
conflict = self.resources.pootle_changed.exclude(
resolve_conflict__gt=0)
for store_fs in conflict.iterator():
pootle_changed_, fs_changed = self._get_changes(store_fs.file)
if fs_changed:
yield dict(
store_fs=store_fs.pk,
pootle_path=store_fs.pootle_path,
fs_path=store_fs.path)
@property
def state_fs_untracked(self):
tracked_fs_paths = self.resources.tracked_paths.keys()
tracked_pootle_paths = self.resources.tracked_paths.values()
trackable_fs_paths = self.resources.trackable_store_paths.values()
trackable_pootle_paths = self.resources.trackable_store_paths.keys()
for pootle_path, fs_path in self.resources.found_file_matches:
fs_untracked = (
fs_path not in tracked_fs_paths
and pootle_path not in tracked_pootle_paths
and fs_path not in trackable_fs_paths
and pootle_path not in trackable_pootle_paths)
if fs_untracked:
yield dict(
pootle_path=pootle_path,
fs_path=fs_path)
@property
def state_pootle_untracked(self):
for store, path in self.resources.trackable_stores:
if path not in self.resources.found_file_paths:
yield dict(
store=store,
fs_path=path)
@property
def state_conflict_untracked(self):
for store, path in self.resources.trackable_stores:
if path in self.resources.found_file_paths:
yield dict(
store=store,
fs_path=path)
@property
def state_remove(self):
to_remove = (
self.resources.tracked.filter(staged_for_removal=True)
.values_list("pk", "pootle_path", "path"))
for pk, pootle_path, path in to_remove.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_unchanged(self):
has_changes = []
for v in self.__state__.values():
if v:
has_changes.extend([p.pootle_path for p in v])
unchanged = (
self.resources.synced.exclude(pootle_path__in=has_changes)
.order_by("pootle_path")
.values_list("pk", "pootle_path", "path"))
for pk, pootle_path, path in unchanged.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_fs_staged(self):
staged = (
self.resources.unsynced
.exclude(path__in=self.resources.missing_file_paths)
.exclude(resolve_conflict=POOTLE_WINS)
| self.resources.synced
.filter(Q(store__isnull=True) | Q(store__obsolete=True))
.exclude(path__in=self.resources.missing_file_paths)
.filter(resolve_conflict=SOURCE_WINS))
staged = staged.values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in staged.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_fs_ahead(self):
all_pootle_changed = list(
self.resources.pootle_changed.values_list("pk", flat=True))
all_fs_changed = list(self.resources.fs_changed)
fs_changed = self.resources.synced.filter(pk__in=all_fs_changed)
fs_changed = (
fs_changed.exclude(pk__in=all_pootle_changed)
| (fs_changed.filter(pk__in=all_pootle_changed)
.filter(resolve_conflict=SOURCE_WINS)))
fs_changed = fs_changed.values_list(
"pk", "pootle_path", "path", "store_id", "store__obsolete")
fs_hashes = self.resources.file_hashes
pootle_revisions = self.resources.pootle_revisions
for changed in fs_changed.iterator():
pk, pootle_path, path, store_id, store_obsolete = changed
if store_obsolete:
continue
if pootle_path not in fs_hashes:
# fs_removed
continue
if store_id not in pootle_revisions:
# pootle_removed
continue
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_fs_removed(self):
removed = (
self.resources.synced
.filter(path__in=self.resources.missing_file_paths)
.exclude(resolve_conflict=POOTLE_WINS)
.exclude(store_id__isnull=True)
.exclude(store__obsolete=True))
all_pootle_changed = list(
self.resources.pootle_changed.values_list("pk", flat=True))
removed = removed.exclude(
pk__in=all_pootle_changed).values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in removed.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_merge_pootle_wins(self):
to_merge = self.resources.tracked.filter(
staged_for_merge=True,
resolve_conflict=POOTLE_WINS)
to_merge = to_merge.values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in to_merge.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_merge_fs_wins(self):
to_merge = self.resources.tracked.filter(
staged_for_merge=True,
resolve_conflict=SOURCE_WINS)
to_merge = to_merge.values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in to_merge.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_pootle_ahead(self):
for store_fs in self.resources.pootle_changed.iterator():
pootle_changed_, fs_changed = self._get_changes(store_fs.file)
pootle_ahead = (
not fs_changed
or store_fs.resolve_conflict == POOTLE_WINS)
if pootle_ahead:
yield dict(
store_fs=store_fs.pk,
pootle_path=store_fs.pootle_path,
fs_path=store_fs.path)
@property
def state_pootle_staged(self):
staged = (
self.resources.unsynced
.exclude(resolve_conflict=SOURCE_WINS)
.exclude(store__isnull=True)
.exclude(store__obsolete=True)
| self.resources.synced
.exclude(store__obsolete=True)
.exclude(store__isnull=True)
.filter(path__in=self.resources.missing_file_paths)
.filter(resolve_conflict=POOTLE_WINS))
for store_fs in staged.iterator():
fs_staged = (
not store_fs.resolve_conflict == POOTLE_WINS
and (store_fs.file
and store_fs.file.file_exists))
if fs_staged:
continue
yield dict(
store_fs=store_fs.pk,
pootle_path=store_fs.pootle_path,
fs_path=store_fs.path)
@property
def state_both_removed(self):
removed = (
self.resources.synced
.filter(Q(store__obsolete=True) | Q(store__isnull=True))
.filter(path__in=self.resources.missing_file_paths))
removed = removed.values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in removed.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@property
def state_pootle_removed(self):
synced = (
self.resources.synced
.exclude(resolve_conflict=SOURCE_WINS)
.exclude(path__in=self.resources.missing_file_paths)
.filter(Q(store__isnull=True) | Q(store__obsolete=True)))
synced = synced.values_list("pk", "pootle_path", "path")
for pk, pootle_path, path in synced.iterator():
yield dict(
store_fs=pk,
pootle_path=pootle_path,
fs_path=path)
@lru_cache()
def _get_changes(self, fs_file):
return fs_file.pootle_changed, fs_file.fs_changed
def clear_cache(self):
for x in dir(self):
x = getattr(self, x)
if callable(x) and hasattr(x, "cache_clear"):
x.cache_clear()
if "resources" in self.__dict__:
del self.__dict__["resources"]
return super(ProjectFSState, self).clear_cache()
def filter(self, fs_paths=None, pootle_paths=None, states=None):
filtered = self.__class__(
self.context,
pootle_path=self.pootle_path,
fs_path=self.fs_path,
load=False)
for k in self.states:
if states and k not in states:
filtered[k] = []
continue
filtered[k] = [
copy(item)
for item in self.__state__[k]
if (not pootle_paths
or item.pootle_path in pootle_paths)
and (not fs_paths
or item.fs_path in fs_paths)]
return filtered
| 14,558
|
Python
|
.py
| 357
| 29.473389
| 84
| 0.574041
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,542
|
signals.py
|
translate_pootle/pootle/apps/pootle_fs/signals.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.dispatch import Signal
fs_pre_push = Signal(providing_args=["plugin"], use_caching=True)
fs_post_push = Signal(providing_args=["plugin"], use_caching=True)
fs_pre_pull = Signal(providing_args=["plugin"], use_caching=True)
fs_post_pull = Signal(providing_args=["plugin"], use_caching=True)
| 580
|
Python
|
.py
| 12
| 47
| 77
| 0.755319
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,543
|
models.py
|
translate_pootle/pootle/apps/pootle_fs/models.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .abstracts import AbstractStoreFS
class StoreFS(AbstractStoreFS):
pass
| 358
|
Python
|
.py
| 10
| 34.1
| 77
| 0.773913
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,544
|
getters.py
|
translate_pootle/pootle/apps/pootle_fs/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.core.exceptions import ValidationError
from pootle.core.delegate import response, state
from pootle.core.plugin import getter
from pootle_config.delegate import (
config_should_not_be_set, config_should_not_be_appended)
from pootle_project.models import Project
from .delegate import (
fs_file, fs_finder, fs_matcher, fs_plugins, fs_resources,
fs_translation_mapping_validator, fs_url_validator)
from .files import FSFile
from .finder import TranslationFileFinder, TranslationMappingValidator
from .localfs import LocalFSPlugin, LocalFSUrlValidator
from .matcher import FSPathMatcher
from .resources import FSProjectResources
from .response import ProjectFSResponse
from .state import ProjectFSState
@getter(state, sender=LocalFSPlugin)
def fs_plugin_state_getter(**kwargs_):
return ProjectFSState
@getter(response, sender=ProjectFSState)
def fs_plugin_response_getter(**kwargs_):
return ProjectFSResponse
@getter(fs_file, sender=LocalFSPlugin)
def fs_file_getter(**kwargs_):
return FSFile
@getter(fs_resources, sender=LocalFSPlugin)
def fs_resources_getter(**kwargs_):
return FSProjectResources
@getter(fs_finder, sender=LocalFSPlugin)
def fs_finder_getter(**kwargs_):
return TranslationFileFinder
@getter(fs_matcher, sender=LocalFSPlugin)
def fs_matcher_getter(**kwargs_):
return FSPathMatcher
@getter(fs_url_validator, sender=LocalFSPlugin)
def fs_url_validator_getter(**kwargs_):
return LocalFSUrlValidator
@getter(fs_translation_mapping_validator)
def fs_translation_mapping_validator_getter(**kwargs_):
return TranslationMappingValidator
@getter([config_should_not_be_set, config_should_not_be_appended], sender=Project)
def fs_url_config_validator(**kwargs):
if kwargs["key"] == "pootle_fs.fs_type":
plugin_class = fs_plugins.gather(Project).get(kwargs["value"])
if not plugin_class:
raise ValidationError("Unrecognised fs_type")
if kwargs["key"] == "pootle_fs.fs_url":
fs_type = kwargs["instance"].config.get("pootle_fs.fs_type")
if not fs_type:
raise ValidationError("You cannot set fs_url until fs_type is set")
plugin_class = fs_plugins.gather(Project).get(fs_type)
if plugin_class:
validator = fs_url_validator.get(plugin_class)
if validator:
validator().validate(kwargs["value"])
if kwargs["key"] == "pootle_fs.translation_mapping":
validator = fs_translation_mapping_validator.get()
for path in kwargs["value"].values():
validator(path).validate()
| 2,866
|
Python
|
.py
| 66
| 39.136364
| 82
| 0.75099
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,545
|
resources.py
|
translate_pootle/pootle/apps/pootle_fs/resources.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
from fnmatch import fnmatch
from django.db.models import F, Max
from django.utils.functional import cached_property
from pootle.core.decorators import persistent_property
from pootle_store.models import Store
from .apps import PootleFSConfig
from .models import StoreFS
from .utils import StoreFSPathFilter, StorePathFilter
class FSProjectResources(object):
def __init__(self, project):
self.project = project
def __str__(self):
return (
"<%s(%s)>"
% (self.__class__.__name__,
self.project))
@property
def excluded_languages(self):
return self.project.config.get("pootle.fs.excluded_languages")
@property
def stores(self):
excluded = self.excluded_languages
stores = Store.objects.filter(
translation_project__project=self.project)
if excluded:
stores = stores.exclude(
translation_project__language__code__in=excluded)
return stores
@property
def tracked(self):
return StoreFS.objects.filter(
project=self.project).select_related("store")
@property
def synced(self):
return (
self.tracked.exclude(last_sync_revision__isnull=True)
.exclude(last_sync_hash__isnull=True))
@property
def unsynced(self):
return (
self.tracked.filter(last_sync_revision__isnull=True)
.filter(last_sync_hash__isnull=True))
@property
def trackable_stores(self):
return self.stores.exclude(obsolete=True).filter(fs__isnull=True)
class FSProjectStateResources(object):
"""Wrap FSPlugin and cache available resources
Accepts `pootle_path` and `fs_path` glob arguments.
If present all resources are filtered accordingly.
"""
sw_version = PootleFSConfig.version
ns = "pootle.fs.resources"
def __init__(self, context, pootle_path=None, fs_path=None):
self.context = context
self.pootle_path = pootle_path
self.fs_path = fs_path
def match_fs_path(self, path):
"""Match fs_paths using file glob if set"""
if not self.fs_path or fnmatch(path, self.fs_path):
return path
def _exclude_staged(self, qs):
return (
qs.exclude(staged_for_removal=True)
.exclude(staged_for_merge=True))
@persistent_property
def found_file_matches(self):
return sorted(self.context.find_translations(
fs_path=self.fs_path, pootle_path=self.pootle_path))
def _found_file_paths(self):
return [x[1] for x in self.found_file_matches]
found_file_paths = persistent_property(
_found_file_paths,
key_attr="fs_cache_key")
@cached_property
def resources(self):
"""Uncached Project resources provided by FSPlugin"""
return self.context.resources
@cached_property
def store_filter(self):
"""Filter Store querysets using file globs"""
return StorePathFilter(
pootle_path=self.pootle_path)
@cached_property
def storefs_filter(self):
"""Filter StoreFS querysets using file globs"""
return StoreFSPathFilter(
pootle_path=self.pootle_path,
fs_path=self.fs_path)
@cached_property
def synced(self):
"""Returns tracked StoreFSs that have sync information, and are not
currently staged for any kind of operation
"""
return self.storefs_filter.filtered(
self._exclude_staged(self.resources.synced))
@cached_property
def trackable_stores(self):
"""Stores that are not currently tracked but could be"""
_trackable = []
stores = self.store_filter.filtered(self.resources.trackable_stores)
for store in stores:
fs_path = self.match_fs_path(
self.context.get_fs_path(store.pootle_path))
if fs_path:
_trackable.append((store, fs_path))
return _trackable
@cached_property
def trackable_store_paths(self):
"""Dictionary of pootle_path, fs_path for trackable Stores"""
return {
store.pootle_path: fs_path
for store, fs_path
in self.trackable_stores}
@persistent_property
def missing_file_paths(self):
return [
path for path in self.tracked_paths.keys()
if path not in self.found_file_paths]
@cached_property
def tracked(self):
"""StoreFS queryset of tracked resources"""
return self.storefs_filter.filtered(self.resources.tracked)
def _tracked_paths(self):
"""Dictionary of fs_path, path for tracked StoreFS"""
return dict(self.tracked.values_list("path", "pootle_path"))
tracked_paths = persistent_property(
_tracked_paths,
key_attr="sync_cache_key")
@cached_property
def unsynced(self):
"""Returns tracked StoreFSs that have NO sync information, and are not
currently staged for any kind of operation
"""
return self.storefs_filter.filtered(
self._exclude_staged(
self.resources.unsynced))
@cached_property
def pootle_changed(self):
"""StoreFS queryset of tracked resources where the Store has changed
since it was last synced.
"""
return (
self.synced.exclude(store_id__isnull=True)
.exclude(store__obsolete=True)
.annotate(max_revision=Max("store__unit__revision"))
.exclude(last_sync_revision=F("max_revision")))
@cached_property
def pootle_revisions(self):
return dict(
self.synced.exclude(store_id__isnull=True)
.exclude(store__obsolete=True)
.values_list("store_id", "store__data__max_unit_revision"))
@cached_property
def file_hashes(self):
hashes = {}
def _get_file_hash(path):
file_path = os.path.join(
self.context.project.local_fs_path,
path.strip("/"))
if os.path.exists(file_path):
return str(os.stat(file_path).st_mtime)
for pootle_path, path in self.found_file_matches:
hashes[pootle_path] = _get_file_hash(path)
return hashes
@cached_property
def fs_changed(self):
"""StoreFS queryset of tracked resources where the Store has changed
since it was last synced.
"""
hashes = self.file_hashes
tracked_files = []
for store_fs in self.synced.iterator():
if store_fs.last_sync_hash == hashes.get(store_fs.pootle_path):
continue
tracked_files.append(store_fs.pk)
return tracked_files
def reload(self):
"""Uncache cached_properties"""
cache_reload = [
"context", "pootle_path", "fs_path",
"cache_key", "sync_revision", "fs_revision"]
for k, v_ in self.__dict__.items():
if k in cache_reload:
continue
del self.__dict__[k]
@cached_property
def fs_revision(self):
return self.context.fs_revision
@cached_property
def sync_revision(self):
return self.context.sync_revision
@cached_property
def cache_key(self):
return self.context.cache_key
@cached_property
def fs_cache_key(self):
return (
"%s.%s"
% (self.context.cache_key, self.fs_revision))
@cached_property
def sync_cache_key(self):
return (
"%s.%s"
% (self.context.cache_key, self.sync_revision))
| 8,028
|
Python
|
.py
| 212
| 28.985849
| 82
| 0.624469
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,546
|
finder.py
|
translate_pootle/pootle/apps/pootle_fs/finder.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import fnmatch
import os
import re
import scandir
from django.core.exceptions import ValidationError
from django.utils.functional import cached_property
from django.utils.lru_cache import lru_cache
from pootle.core.decorators import persistent_property
from .apps import PootleFSConfig
PATH_MAPPING = (
(".", "\."),
("<language_code>", "(?P<language_code>[\w\@\-\.]*)"),
("<filename>", "(?P<filename>[\w\-\.]*)"),
("/<dir_path>/", "/<dir_path>"),
("<dir_path>", "(?P<dir_path>[\w\/\-]*?)"))
DEFAULT_EXTENSIONS = ("po", "pot")
class TranslationFileFinder(object):
ns = "pootle.fs.finder"
sw_version = PootleFSConfig.version
extensions = DEFAULT_EXTENSIONS
path_mapping = PATH_MAPPING
def __init__(self, translation_mapping, path_filters=None,
extensions=None, exclude_languages=None, fs_hash=None):
self.fs_hash = fs_hash
TranslationMappingFinderValidator(translation_mapping).validate()
self.translation_mapping = translation_mapping
if extensions:
self.extensions = extensions
self.path_filters = path_filters
self.exclude_languages = exclude_languages or []
@cached_property
def regex(self):
return re.compile(self._parse_path())
@cached_property
def file_root(self):
"""The deepest directory that can be used from the translation mapping
before the <tags>.
"""
file_root = self.translation_mapping.split("<")[0]
if not file_root.endswith("/"):
file_root = os.sep.join(file_root.split("/")[:-1])
return file_root.rstrip("/")
def match(self, file_path):
"""For a given file_path find translation_mapping matches.
If a match is found `file_path`, `matchdata` is returned.
"""
match = self.regex.match(file_path)
if not match:
return
matched = match.groupdict()
if matched["language_code"] in self.exclude_languages:
return
matched["dir_path"] = matched.get("dir_path", "").strip("/")
if not matched.get("filename"):
matched["filename"] = os.path.splitext(
os.path.basename(file_path))[0]
return file_path, matched
def walk(self):
"""Walk a filesystem"""
for root, dirs_, files in scandir.walk(self.file_root):
for filename in files:
yield os.path.join(root, filename)
def find(self):
"""Find matching files anywhere in file_root"""
for filepath in self.walk():
match = self.match(filepath)
if match:
yield match
@property
def cache_key(self):
if not self.fs_hash:
return
return (
"%s.%s.%s"
% (self.fs_hash,
"::".join(self.exclude_languages),
hash(self.regex.pattern)))
@persistent_property
def found(self):
return list(self.find())
@lru_cache(maxsize=None)
def reverse_match(self, language_code, filename=None,
extension=None, dir_path=None):
"""For given matchdata return the file path that would be
matched.
"""
if language_code in self.exclude_languages:
return
if extension is None:
extension = self.extensions[0]
if extension not in self.extensions:
raise ValueError("ext must be in the list of possible extensions")
if not filename:
filename = language_code
extension = extension.strip(".")
path = (
"%s.%s"
% (os.path.splitext(self.translation_mapping)[0], extension))
if dir_path and "<dir_path>" not in path:
return
path = (path.replace("<language_code>", language_code)
.replace("<filename>", filename))
if "<dir_path>" in path:
if dir_path and dir_path.strip("/"):
path = path.replace("<dir_path>", "/%s/" % dir_path.strip("/"))
else:
path = path.replace("<dir_path>", "")
local_path = path.replace(self.file_root, "")
if "//" in local_path:
path = "/".join([
self.file_root,
local_path.replace("//", "/").lstrip("/")])
return path
def _ext_re(self):
return (
r".(?P<ext>(%s))"
% "|".join(
("%s$" % x)
for x in set(self.extensions)))
def _parse_path_regex(self):
path = self.translation_mapping
for k, v in self.path_mapping:
path = path.replace(k, v)
return r"%s%s$" % (
os.path.splitext(path)[0],
self._ext_re())
def _parse_path(self):
regex = self._parse_path_regex()
if not self.path_filters:
return regex
regex = r"(?=%s)" % regex
filter_regex = "".join(
("(?=^%s)" % fnmatch.translate(path))
for path in self.path_filters)
return r"%s%s" % (regex, filter_regex)
class TranslationMappingValidator(object):
validators = (
"absolute", "lang_code", "ext", "match_tags", "path")
def __init__(self, path):
self.path = path
def validate_absolute(self):
if self.path[0] != '/':
raise ValidationError(
"Translation mapping '%s' should start with '/'" % self.path)
def validate_lang_code(self):
if "<language_code>" not in self.path:
raise ValidationError(
"Translation mapping must contain a <language_code> pattern "
"to match.")
def validate_ext(self):
if not self.path.endswith(".<ext>"):
raise ValidationError(
"Translation mapping must end with <ext>.")
@cached_property
def stripped_path(self):
return (self.path.replace("<language_code>", "")
.replace("<dir_path>", "")
.replace("<ext>", "")
.replace("<filename>", ""))
def validate_match_tags(self):
if "<" in self.stripped_path or ">" in self.stripped_path:
raise ValidationError(
"Only <language_code>, <dir_path>, <filename> and <ext> are valid "
"patterns to match in the translation mapping")
def validate_path(self):
if os.path.sep == "\\":
bad_chars = re.search("[^\w\\\:\-\.]+", self.stripped_path)
else:
bad_chars = re.search("[^\w\/\-\.]+", self.stripped_path)
if bad_chars:
raise ValidationError(
"Invalid character in translation_mapping '%s'"
% self.stripped_path[bad_chars.span()[0]:bad_chars.span()[1]])
def validate(self):
for k in self.validators:
getattr(self, "validate_%s" % k)()
class TranslationMappingFinderValidator(TranslationMappingValidator):
def validate_absolute(self):
if self.path != os.path.abspath(self.path):
raise ValidationError(
"Translation mapping '%s' should be absolute" % self.path)
| 7,487
|
Python
|
.py
| 188
| 30.207447
| 83
| 0.572904
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,547
|
plugin.py
|
translate_pootle/pootle/apps/pootle_fs/plugin.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import os
import shutil
import uuid
from bulk_update.helper import bulk_update
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils.functional import cached_property
from django.utils.lru_cache import lru_cache
from pootle.core.delegate import (
config, response as pootle_response, revision, state as pootle_state)
from pootle_app.models import Directory
from pootle_project.models import Project
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
from pootle_store.models import Store
from .apps import PootleFSConfig
from .decorators import emits_state, responds_to_state
from .delegate import fs_finder, fs_matcher, fs_resources
from .exceptions import FSStateError
from .models import StoreFS
from .signals import fs_post_pull, fs_post_push, fs_pre_pull, fs_pre_push
logger = logging.getLogger(__name__)
class Plugin(object):
"""Base Plugin implementation"""
ns = "pootle.fs.plugin"
sw_version = PootleFSConfig.version
name = None
def __init__(self, project):
if not isinstance(project, Project):
raise TypeError(
"pootle_fs.Plugin expects a Project")
self.project = project
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.project == other.project
and self.name == other.name)
def __str__(self):
return "<%s(%s)>" % (self.__class__.__name__, self.project)
@property
def cache_key(self):
return (
"%s.%s.%s.%s"
% (self.project.code,
self.pootle_revision,
self.sync_revision,
self.fs_revision))
@property
def is_cloned(self):
return os.path.exists(self.project.local_fs_path)
@property
def latest_hash(self):
raise NotImplementedError
@property
def finder_class(self):
return fs_finder.get(self.__class__)
@property
def fs_url(self):
fs_type = self.project.config["pootle_fs.fs_type"]
fs_url = self.project.config["pootle_fs.fs_url"]
parse_placeholder = (
fs_type == "localfs"
and fs_url.startswith("{POOTLE_TRANSLATION_DIRECTORY}"))
if parse_placeholder:
return os.path.join(
settings.POOTLE_TRANSLATION_DIRECTORY,
fs_url[30:])
return fs_url
@property
def fs_revision(self):
return self.latest_hash
@property
def pootle_revision(self):
return revision.get(Directory)(
self.project.directory).get(key="stats")
@property
def response_class(self):
return pootle_response.get(self.state_class)
@property
def sync_revision(self):
return revision.get(
Project)(self.project).get(key="pootle.fs.sync")
@cached_property
def matcher_class(self):
return fs_matcher.get(self.__class__)
@property
def store_fs_class(self):
from .models import StoreFS
return StoreFS
@cached_property
def matcher(self):
return self.matcher_class(self)
@cached_property
def pootle_user(self):
User = get_user_model()
username = config.get(
self.project.__class__,
instance=self.project,
key="pootle_fs.pootle_user")
if username:
try:
return User.objects.get(username=username)
except User.DoesNotExist:
logger.warning(
"Misconfigured pootle_fs user: %s",
username)
@cached_property
def resources(self):
return fs_resources.get(self.__class__)(self.project)
@cached_property
def state_class(self):
return pootle_state.get(self.__class__)
@lru_cache(maxsize=None)
def get_fs_path(self, pootle_path):
"""
Reverse match an FS filepath from a ``Store.pootle_path``.
:param pootle_path: A ``Store.pootle_path``
:returns: An filepath relative to the FS root.
"""
return self.matcher.reverse_match(pootle_path)
def create_store_fs(self, items, **kwargs):
if not items:
return
to_add = []
paths = [
x.pootle_path
for x in items]
stores = dict(
Store.objects.filter(
pootle_path__in=paths).values_list("pootle_path", "pk"))
for item in items:
to_add.append(
self.store_fs_class(
project=self.project,
pootle_path=item.pootle_path,
path=item.fs_path,
store_id=stores.get(item.pootle_path),
**kwargs))
self.store_fs_class.objects.bulk_create(to_add)
def delete_store_fs(self, items, **kwargs):
if not items:
return
self.store_fs_class.objects.filter(
pk__in=[fs.kwargs["store_fs"] for fs in items]).delete()
def update_store_fs(self, items, **kwargs):
if not items:
return
self.store_fs_class.objects.filter(
pk__in=[fs.kwargs["store_fs"] for fs in items]).update(**kwargs)
def clear_repo(self):
if self.is_cloned:
shutil.rmtree(self.project.local_fs_path)
def expire_sync_cache(self):
revision.get(Project)(self.project).set(
keys=["pootle.fs.sync"], value=uuid.uuid4().hex)
def find_translations(self, fs_path=None, pootle_path=None):
"""
Find translation files from the file system
:param fs_path: Path glob to filter translations matching FS path
:param pootle_path: Path glob to filter translations to add matching
``pootle_path``
:yields pootle_path, fs_path: Where `pootle_path` and `fs_path` are
matched paths.
"""
return self.matcher.matches(fs_path, pootle_path)
def fetch(self):
"""
Pull the FS from external source if required.
"""
raise NotImplementedError
def push(self, paths=None, message=None, response=None):
"""
Push the FS to an external source if required.
"""
raise NotImplementedError
def reload(self):
self.project.config.reload()
if "matcher" in self.__dict__:
del self.__dict__["matcher"]
if "pootle_user" in self.__dict__:
del self.__dict__["pootle_user"]
def response(self, state):
return self.response_class(state)
def state(self, fs_path=None, pootle_path=None):
"""
Get a state object for showing current state of FS/Pootle
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
``pootle_path``
:returns state: Where ``state`` is an instance of self.state_class
"""
if not self.is_cloned:
raise FSStateError(
"Filesystem has not been fetched. "
"Use `pootle fs fetch ...` first.")
return self.state_class(
self, fs_path=fs_path, pootle_path=pootle_path)
@responds_to_state
@transaction.atomic
def add(self, state, response, fs_path=None, pootle_path=None, **kwargs):
"""
Stage untracked or removed Stores or files
:param force: Re-add removed Stores or files.
:param update: Add to ``pootle``, ``fs`` or ``all``.
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
force = kwargs.get("force", False)
update = kwargs.get("update", "all")
untracked = []
if update == "all":
untracked = state["fs_untracked"] + state["pootle_untracked"]
elif update == "pootle":
untracked = state["fs_untracked"]
elif update == "fs":
untracked = state["pootle_untracked"]
self.create_store_fs(untracked)
if force:
if update in ["all", "pootle"]:
self.update_store_fs(
state["fs_removed"],
resolve_conflict=POOTLE_WINS)
if update in ["all", "fs"]:
self.update_store_fs(
state["pootle_removed"],
resolve_conflict=SOURCE_WINS)
if update in ["all", "pootle"]:
for fs_state in state["fs_untracked"]:
response.add("added_from_fs", fs_state=fs_state)
if update in ["all", "fs"]:
for fs_state in state["pootle_untracked"]:
response.add("added_from_pootle", fs_state=fs_state)
if force:
if update in ["all", "pootle"]:
for fs_state in state["fs_removed"]:
response.add("readded_from_pootle", fs_state=fs_state)
if update in ["all", "fs"]:
for fs_state in state["pootle_removed"]:
response.add("readded_from_fs", fs_state=fs_state)
if response.made_changes:
self.expire_sync_cache()
return response
@responds_to_state
@transaction.atomic
def resolve(self, state, response, fs_path=None, pootle_path=None,
merge=True, pootle_wins=False):
"""
Resolve conflicting translations
Default is to merge with FS winning
:param merge: Merge Pootle and FS, defaults to True, otherwise overwrite
:param pootle_wins: Use unit from Pootle where conflicting
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
kwargs = {}
if pootle_wins:
kwargs["resolve_conflict"] = POOTLE_WINS
else:
kwargs["resolve_conflict"] = SOURCE_WINS
if merge:
kwargs["staged_for_merge"] = True
self.create_store_fs(state["conflict_untracked"], **kwargs)
self.update_store_fs(state["conflict"], **kwargs)
action_type = (
"staged_for_%s_%s"
% ((merge and "merge" or "overwrite"),
(pootle_wins and "pootle" or "fs")))
for fs_state in state["conflict"] + state["conflict_untracked"]:
response.add(action_type, fs_state=fs_state)
if response.made_changes:
self.expire_sync_cache()
return response
@responds_to_state
@transaction.atomic
def rm(self, state, response, fs_path=None, pootle_path=None, **kwargs):
"""
Stage translations for removal.
If ``force``=``True`` is present it will also:
- stage untracked files from FS
- stage untracked Stores
:param force: Fetch conflicting translations.
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
force = kwargs.get("force", False)
update = kwargs.get("update", "all")
to_create = []
to_update = state["both_removed"]
if update in ["all", "fs"]:
to_update += state["pootle_removed"]
if update in ["all", "pootle"]:
to_update += state["fs_removed"]
if force:
to_update += state["conflict"]
to_create += state["conflict_untracked"]
if update in ["all", "fs"]:
to_create += state["pootle_untracked"]
if update in ["all", "pootle"]:
to_create += state["fs_untracked"]
self.update_store_fs(to_update, staged_for_removal=True)
self.create_store_fs(to_create, staged_for_removal=True)
for fs_state in to_create + to_update:
response.add("staged_for_removal", fs_state=fs_state)
if response.made_changes:
self.expire_sync_cache()
return response
@responds_to_state
@transaction.atomic
def unstage(self, state, response, fs_path=None, pootle_path=None):
"""
Unstage files staged for addition, merge or removal
"""
to_remove = []
to_update = (
state["remove"]
+ state["merge_pootle_wins"]
+ state["merge_fs_wins"]
+ state["pootle_staged"]
+ state["fs_staged"])
for fs_state in state["pootle_ahead"] + state["fs_ahead"]:
if fs_state.store_fs.resolve_conflict in [SOURCE_WINS, POOTLE_WINS]:
to_update.append(fs_state)
for fs_state in to_update:
should_remove = (
fs_state.store_fs
and not fs_state.store_fs.last_sync_revision
and not fs_state.store_fs.last_sync_hash)
if should_remove:
to_remove.append(fs_state)
to_update = list(set(to_update) - set(to_remove))
self.update_store_fs(
to_update,
resolve_conflict=None,
staged_for_merge=False,
staged_for_removal=False)
self.delete_store_fs(to_remove)
updated = sorted(
to_remove + to_update,
key=lambda x: x.pootle_path)
for fs_state in updated:
response.add("unstaged", fs_state=fs_state)
if response.made_changes:
self.expire_sync_cache()
return response
@responds_to_state
def sync_merge(self, state, response, fs_path=None,
pootle_path=None, update="all"):
"""
Perform merge between Pootle and working directory
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
sfs = {}
for fs_state in (state['merge_pootle_wins'] + state['merge_fs_wins']):
sfs[fs_state.kwargs["store_fs"]] = fs_state
_sfs = StoreFS.objects.filter(
id__in=sfs.keys()).select_related("store", "store__data")
for store_fs in _sfs:
fs_state = sfs[store_fs.id]
fs_state.store_fs = store_fs
pootle_wins = (fs_state.state_type == "merge_pootle_wins")
store_fs = fs_state.store_fs
update_revision = store_fs.file.pull(
merge=True,
pootle_wins=pootle_wins,
user=self.pootle_user)
if update == "all":
update_revision = store_fs.file.push()
state.resources.pootle_revisions[
store_fs.store_id] = update_revision
state.resources.file_hashes[
store_fs.pootle_path] = store_fs.file.latest_hash
if pootle_wins:
response.add("merged_from_pootle", fs_state=fs_state)
else:
response.add("merged_from_fs", fs_state=fs_state)
if response.made_changes:
self.expire_sync_cache()
return response
@responds_to_state
@emits_state(pre=fs_pre_pull, post=fs_post_pull)
def sync_pull(self, state, response, fs_path=None, pootle_path=None):
"""
Pull translations from working directory to Pootle
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
sfs = {}
for fs_state in (state['fs_staged'] + state['fs_ahead']):
sfs[fs_state.kwargs["store_fs"]] = fs_state
_sfs = StoreFS.objects.filter(
id__in=sfs.keys()).select_related("store", "store__data")
for store_fs in _sfs:
store_fs.file.pull(user=self.pootle_user)
if store_fs.store and store_fs.store.data:
state.resources.pootle_revisions[
store_fs.store_id] = store_fs.store.data.max_unit_revision
state.resources.file_hashes[
store_fs.pootle_path] = store_fs.file.latest_hash
fs_state = sfs[store_fs.id]
fs_state.store_fs = store_fs
response.add("pulled_to_pootle", fs_state=fs_state)
return response
@responds_to_state
@emits_state(pre=fs_pre_push, post=fs_post_push)
def sync_push(self, state, response, fs_path=None, pootle_path=None):
"""
Push translations from Pootle to working directory.
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
pushable = state['pootle_staged'] + state['pootle_ahead']
stores_fs = StoreFS.objects.filter(
id__in=[
fs_state.store_fs.id
for fs_state
in pushable])
stores_fs = {sfs.id: sfs for sfs in stores_fs.select_related("store")}
for fs_state in pushable:
store_fs = stores_fs[fs_state.store_fs.id]
fs_state.store_fs = store_fs
store_fs.file.push()
state.resources.pootle_revisions[
store_fs.store_id] = store_fs.store.data.max_unit_revision
state.resources.file_hashes[
store_fs.pootle_path] = store_fs.file.latest_hash
response.add('pushed_to_fs', fs_state=fs_state)
return response
@responds_to_state
def sync_rm(self, state, response, fs_path=None, pootle_path=None):
"""
Remove Store and files from working directory that are staged for
removal.
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
sfs = {}
for fs_state in state['remove']:
sfs[fs_state.kwargs["store_fs"]] = fs_state
for store_fs in StoreFS.objects.filter(id__in=sfs.keys()):
fs_state = sfs[store_fs.pk]
store_fs.file.delete()
if store_fs.store and store_fs.store.data:
state.resources.pootle_revisions[
store_fs.store_id] = store_fs.store.data.max_unit_revision
response.add("removed", fs_state=fs_state, store_fs=store_fs)
return response
@responds_to_state
@transaction.atomic
def sync(self, state, response, fs_path=None, pootle_path=None, update="all"):
"""
Synchronize all staged and non-conflicting files and Stores, and push
changes upstream if required.
:param fs_path: FS path glob to filter translations
:param pootle_path: Pootle path glob to filter translations
:returns response: Where ``response`` is an instance of self.respose_class
"""
self.sync_rm(
state, response, fs_path=fs_path, pootle_path=pootle_path)
if update in ["all", "pootle"]:
self.sync_merge(
state, response,
fs_path=fs_path,
pootle_path=pootle_path,
update=update)
self.sync_pull(
state, response, fs_path=fs_path, pootle_path=pootle_path)
if update in ["all", "fs"]:
self.sync_push(
state, response, fs_path=fs_path, pootle_path=pootle_path)
self.push(response)
sync_types = [
"pushed_to_fs", "pulled_to_pootle",
"merged_from_pootle", "merged_from_fs"]
fs_to_update = {}
file_hashes = state.resources.file_hashes
pootle_revisions = state.resources.pootle_revisions
for sync_type in sync_types:
if sync_type in response:
for response_item in response.completed(sync_type):
store_fs = response_item.store_fs
last_sync_revision = None
if store_fs.store_id in pootle_revisions:
last_sync_revision = pootle_revisions[store_fs.store_id]
file_hash = file_hashes.get(
store_fs.pootle_path, store_fs.file.latest_hash)
store_fs.file.on_sync(
file_hash,
last_sync_revision,
save=False)
fs_to_update[store_fs.id] = store_fs
if fs_to_update:
bulk_update(
fs_to_update.values(),
update_fields=[
"last_sync_revision", "last_sync_hash",
"resolve_conflict", "staged_for_merge"])
if response.made_changes:
self.expire_sync_cache()
return response
| 21,449
|
Python
|
.py
| 515
| 31.163107
| 82
| 0.591471
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,548
|
abstracts.py
|
translate_pootle/pootle/apps/pootle_fs/abstracts.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db import models
from django.utils.functional import cached_property
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from pootle_project.models import Project
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
from pootle_store.models import Store
from .delegate import fs_file
from .managers import StoreFSManager, validate_store_fs
from .utils import FSPlugin
class AbstractStoreFS(models.Model):
project = models.ForeignKey(
Project, related_name='store_fs', on_delete=models.CASCADE)
pootle_path = models.CharField(max_length=255, blank=False)
path = models.CharField(max_length=255, blank=False)
store = models.ForeignKey(
Store, related_name='fs', blank=True, null=True,
on_delete=models.SET_NULL)
last_sync_revision = models.IntegerField(blank=True, null=True)
last_sync_mtime = models.DateTimeField(null=True, blank=True)
last_sync_hash = models.CharField(max_length=64, blank=True, null=True)
staged_for_removal = models.BooleanField(default=False)
staged_for_merge = models.BooleanField(default=False)
resolve_conflict = models.IntegerField(
blank=True, null=True,
default=0,
choices=[(0, ""),
(POOTLE_WINS, "pootle"),
(SOURCE_WINS, "fs")])
objects = StoreFSManager()
class Meta(object):
abstract = True
@cached_property
def plugin(self):
try:
return FSPlugin(self.project)
except (NotConfiguredError, MissingPluginError):
return None
@cached_property
def file(self):
if self.plugin:
file_adapter = fs_file.get(self.plugin.__class__)
if file_adapter:
return file_adapter(self)
def save(self, *args, **kwargs):
validated = validate_store_fs(
store=self.store,
project=self.project,
pootle_path=self.pootle_path,
path=self.path)
self.store = validated.get("store")
self.project = validated.get("project")
self.pootle_path = validated.get("pootle_path")
self.path = validated.get("path")
return super(AbstractStoreFS, self).save(*args, **kwargs)
| 2,527
|
Python
|
.py
| 61
| 34.655738
| 77
| 0.686889
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,549
|
response.py
|
translate_pootle/pootle/apps/pootle_fs/response.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from collections import OrderedDict
from django.utils.functional import cached_property
from pootle.core.response import ItemResponse, Response
from pootle_store.models import Store
logger = logging.getLogger(__name__)
FS_RESPONSE = OrderedDict()
FS_RESPONSE["pulled_to_pootle"] = {
"title": "Pulled to Pootle",
"description":
"Stores updated where filesystem version was new or newer"}
FS_RESPONSE["added_from_pootle"] = {
"title": "Added from Pootle",
"description":
"Files staged from Pootle that were new or newer than their files"}
FS_RESPONSE["added_from_fs"] = {
"title": "Added from filesystem",
"description":
("Files staged from the filesystem that were new or newer than their "
"Pootle Stores")}
FS_RESPONSE["pushed_to_fs"] = {
"title": "Pushed to filesystem",
"description":
"Files updated where Pootle Store version was new or newer"}
FS_RESPONSE["staged_for_overwrite_fs"] = {
"title": "Staged for overwrite from filesystem",
"description":
("Files staged to overwrite the corresponding Store")}
FS_RESPONSE["staged_for_overwrite_pootle"] = {
"title": "Staged for overwrite from pootle",
"description":
("Stores staged to overwrite the corresponding file")}
FS_RESPONSE["staged_for_removal"] = {
"title": "Staged for removal",
"description":
("Files or Stores staged for removal where the corresponding "
"file/Store is missing")}
FS_RESPONSE["removed"] = {
"title": "Removed",
"description":
("Files or Stores removed that no longer had corresponding files or "
"Stores")}
FS_RESPONSE["staged_for_merge_fs"] = {
"title": "Staged for merge (FS Wins)",
"description":
("Files or Stores staged for merge where the corresponding "
"file/Store has also been updated or created")}
FS_RESPONSE["staged_for_merge_pootle"] = {
"title": "Staged for merge (Pootle Wins)",
"description":
("Files or Stores staged for merge where the corresponding "
"file/Store has also been updated or created")}
FS_RESPONSE["merged_from_fs"] = {
"title": "Merged from fs",
"description":
("Merged - FS won where unit updates conflicted")}
FS_RESPONSE["merged_from_pootle"] = {
"title": "Merged from pootle",
"description":
("Merged - Pootle won where unit updates conflicted")}
FS_RESPONSE["unstaged"] = {
"title": "Unstaged",
"description":
("Files or Stores that were previously staged for addition, "
"merge or removal were unstaged")}
class ProjectFSItemResponse(ItemResponse):
def __str__(self):
return (
"<%s(%s)%s: %s %s::%s>"
% (self.__class__.__name__,
self.response.context,
self.failed and " FAILED" or "",
self.action_type,
self.pootle_path,
self.fs_path))
@property
def fs_path(self):
return self.fs_state.fs_path
@property
def fs_state(self):
return self.kwargs["fs_state"]
@property
def pootle_path(self):
return self.fs_state.pootle_path
@cached_property
def store(self):
if self.fs_state.store:
return self.fs_state.store
if self.store_fs:
return self.store_fs.store
try:
return Store.objects.get(
pootle_path=self.fs_state.pootle_path)
except Store.DoesNotExist:
return None
@property
def store_fs(self):
return self.fs_state.store_fs
class ProjectFSResponse(Response):
response_class = ProjectFSItemResponse
@property
def response_types(self):
return FS_RESPONSE.keys()
| 4,047
|
Python
|
.py
| 110
| 30.527273
| 78
| 0.654504
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,550
|
apps.py
|
translate_pootle/pootle/apps/pootle_fs/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleFSConfig(AppConfig):
name = "pootle_fs"
verbose_name = "Pootle Filesystem synchronisation"
version = "0.1.3"
def ready(self):
importlib.import_module("pootle_fs.models")
importlib.import_module("pootle_fs.getters")
importlib.import_module("pootle_fs.providers")
importlib.import_module("pootle_fs.receivers")
importlib.import_module("pootle_fs.management.commands.fs")
| 769
|
Python
|
.py
| 19
| 36.210526
| 77
| 0.733871
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,551
|
display.py
|
translate_pootle/pootle/apps/pootle_fs/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.display import Display, ItemDisplay, SectionDisplay
from pootle_fs.response import FS_RESPONSE
from pootle_fs.state import FS_STATE
BOTH_EXISTS_ACTIONS = [
"merged_from_fs", "merged_from_pootle",
"pulled_to_pootle", "pushed_to_fs",
"staged_for_merge_fs", "staged_for_merge_pootle"]
FS_EXISTS_ACTIONS = BOTH_EXISTS_ACTIONS + ["added_from_fs"]
STORE_EXISTS_ACTIONS = BOTH_EXISTS_ACTIONS + ["added_from_pootle"]
BOTH_EXISTS_STATES = [
"fs_ahead", "pootle_ahead",
"conflict", "conflict_untracked",
"merge_fs_wins", "merge_pootle_wins"]
FS_EXISTS_STATES = BOTH_EXISTS_STATES + [
"fs_untracked", "fs_staged", "pootle_removed"]
STORE_EXISTS_STATES = BOTH_EXISTS_STATES + [
"pootle_untracked", "pootle_staged", "fs_removed"]
class FSItemDisplay(ItemDisplay):
def __str__(self):
return (
" %s\n <--> %s\n"
% (self.pootle_path, self.fs_path))
@property
def pootle_path(self):
return (
self.item.pootle_path
if self.store_exists
else "(%s)" % self.item.pootle_path)
@property
def fs_path(self):
return (
self.item.fs_path
if self.file_exists
else "(%s)" % self.item.fs_path)
class ResponseItemDisplay(FSItemDisplay):
@property
def action_type(self):
return self.item.action_type
@property
def file_exists(self):
return (
self.action_type in FS_EXISTS_ACTIONS
or (self.state_type
in ["conflict", "conflict_untracked"])
or (self.action_type == "staged_for_removal"
and (self.state_type
in ["fs_untracked", "pootle_removed"])))
@property
def fs_added(self):
return (
self.action_type == "added_from_fs"
and self.state_type not in ["conflict", "conflict_untracked"])
@property
def pootle_added(self):
return (
self.action_type == "added_from_pootle"
and self.state_type not in ["conflict", "conflict_untracked"])
@property
def state_item(self):
return self.item.fs_state
@property
def state_type(self):
return self.state_item.state_type
@property
def store_exists(self):
return (
self.action_type in STORE_EXISTS_ACTIONS
or (self.state_type
in ["conflict", "conflict_untracked"])
or (self.action_type == "staged_for_removal"
and (self.state_type
in ["pootle_untracked", "fs_removed"])))
class ResponseTypeDisplay(SectionDisplay):
item_class = ResponseItemDisplay
class ResponseDisplay(Display):
context_info = FS_RESPONSE
section_class = ResponseTypeDisplay
no_results_msg = "No changes made"
class StateItemDisplay(FSItemDisplay):
@property
def state_type(self):
return self.item.state_type
@property
def file(self):
if self.item.store_fs:
return self.item.store_fs.file
@property
def file_exists(self):
return (
self.state_type in FS_EXISTS_STATES
or (self.state_type == "remove"
and self.file.file_exists))
@property
def store_exists(self):
return (
self.state_type in STORE_EXISTS_STATES
or (self.state_type == "remove"
and self.file.store_exists))
@property
def tracked(self):
return self.item.store_fs and True or False
class StateTypeDisplay(SectionDisplay):
item_class = StateItemDisplay
class StateDisplay(Display):
context_info = FS_STATE
section_class = StateTypeDisplay
| 4,005
|
Python
|
.py
| 113
| 27.876106
| 77
| 0.631088
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,552
|
localfs.py
|
translate_pootle/pootle/apps/pootle_fs/localfs.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import uuid
from django import forms
from pootle.core import sync
from pootle.core.delegate import revision
from pootle_project.models import Project
from .exceptions import FSFetchError
from .plugin import Plugin
class LocalFSPlugin(Plugin):
fs_type = "localfs"
_pulled = False
@property
def latest_hash(self):
return revision.get(Project)(
self.project).get(key="pootle.fs.fs_hash")
def push(self, response):
sync.sync(
self.project.local_fs_path,
self.fs_url,
"sync",
purge=True,
logger=logging.getLogger(sync.__name__))
return response
def fetch(self):
try:
synced = sync.sync(
self.fs_url,
self.project.local_fs_path,
"sync",
create=True,
purge=True,
logger=logging.getLogger(sync.__name__))
except ValueError as e:
raise FSFetchError(e)
if synced:
revision.get(Project)(self.project).set(
keys=["pootle.fs.fs_hash"], value=uuid.uuid4().hex)
class LocalFSUrlValidator(object):
help_text = "Enter an absolute path to a directory on your filesystem"
def validate(self, url):
is_valid = (
url.startswith("/")
or url.startswith("{POOTLE_TRANSLATION_DIRECTORY}"))
if not is_valid:
raise forms.ValidationError(self.help_text)
| 1,781
|
Python
|
.py
| 52
| 26.211538
| 77
| 0.627988
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,553
|
receivers.py
|
translate_pootle/pootle/apps/pootle_fs/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.dispatch import receiver
from pootle.core.exceptions import NotConfiguredError
from pootle.core.signals import filetypes_changed
from pootle_project.models import Project
from .utils import FSPlugin
@receiver(filetypes_changed, sender=Project)
def handle_project_filetypes_changed(**kwargs):
project = kwargs["instance"]
try:
FSPlugin(project).expire_sync_cache()
except NotConfiguredError:
pass
| 716
|
Python
|
.py
| 19
| 34.947368
| 77
| 0.781792
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,554
|
utils.py
|
translate_pootle/pootle/apps/pootle_fs/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from fnmatch import translate
from django.utils.functional import cached_property
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from .delegate import fs_plugins
class PathFilter(object):
def path_regex(self, path):
return translate(path).replace("\Z(?ms)", "$")
class StorePathFilter(PathFilter):
"""Filters Stores (only pootle_path)
pootle_path should be file a glob
the glob is converted to a regex and used to filter a qs
"""
def __init__(self, pootle_path=None):
self.pootle_path = pootle_path
@cached_property
def pootle_regex(self):
if not self.pootle_path:
return
return self.path_regex(self.pootle_path)
def filtered(self, qs):
if not self.pootle_regex:
return qs
return qs.filter(pootle_path__regex=self.pootle_regex)
class StoreFSPathFilter(StorePathFilter):
"""Filters StoreFS
pootle_path and fs_path should be file globs
these are converted to regexes and used to filter a qs
"""
def __init__(self, pootle_path=None, fs_path=None):
super(StoreFSPathFilter, self).__init__(pootle_path=pootle_path)
self.fs_path = fs_path
@cached_property
def fs_regex(self):
if not self.fs_path:
return
return self.path_regex(self.fs_path)
def filtered(self, qs):
qs = super(StoreFSPathFilter, self).filtered(qs)
if not self.fs_regex:
return qs
return qs.filter(path__regex=self.fs_regex)
class FSPlugin(object):
"""Wraps a Project to access the configured FS plugin"""
def __init__(self, project):
self.project = project
plugins = fs_plugins.gather(self.project.__class__)
fs_type = project.config.get("pootle_fs.fs_type")
fs_url = project.config.get("pootle_fs.fs_url")
if not fs_type or not fs_url:
missing_key = "pootle_fs.fs_url" if fs_type else "pootle_fs.fs_type"
raise NotConfiguredError('Missing "%s" in project configuration.' %
missing_key)
try:
self.plugin = plugins[fs_type](self.project)
except KeyError:
raise MissingPluginError(
"No such plugin: %s" % fs_type)
@property
def __class__(self):
return self.plugin.__class__
def __getattr__(self, k):
return getattr(self.plugin, k)
def __eq__(self, other):
return self.plugin.__eq__(other)
def __str__(self):
return str(self.plugin)
def parse_fs_url(fs_url):
fs_type = 'localfs'
chunks = fs_url.split('+', 1)
if len(chunks) > 1:
if chunks[0] in fs_plugins.gather().keys():
fs_type = chunks[0]
fs_url = chunks[1]
return fs_type, fs_url
| 3,105
|
Python
|
.py
| 81
| 31.024691
| 80
| 0.641761
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,555
|
presets.py
|
translate_pootle/pootle/apps/pootle_fs/presets.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from pootle.i18n.gettext import ugettext_lazy as _
FS_PRESETS = OrderedDict(
gnu=("/po/<language_code>.<ext>", _("GNU style")),
nongnu=(
"/<language_code>/<dir_path>/<filename>.<ext>",
_("non-GNU style")),
django=(
"/locale/<language_code>/LC_MESSAGES/<filename>.<ext>",
_("Django style")),
custom=("", _("Custom")))
| 680
|
Python
|
.py
| 18
| 33.888889
| 77
| 0.665653
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,556
|
__init__.py
|
translate_pootle/pootle/apps/pootle_fs/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'pootle_fs.apps.PootleFSConfig'
| 329
|
Python
|
.py
| 8
| 40
| 77
| 0.7625
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,557
|
providers.py
|
translate_pootle/pootle/apps/pootle_fs/providers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin import provider
from .delegate import fs_plugins
from .localfs import LocalFSPlugin
@provider(fs_plugins)
def localfs_plugin_provider(**kwargs_):
return dict(localfs=LocalFSPlugin)
| 488
|
Python
|
.py
| 13
| 35.923077
| 77
| 0.785563
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,558
|
exceptions.py
|
translate_pootle/pootle/apps/pootle_fs/exceptions.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class FSException(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
self.message = message
class FSFetchError(FSException):
pass
class FSAddError(FSException):
pass
class FSStateError(FSException):
pass
class FSSyncError(FSException):
pass
| 594
|
Python
|
.py
| 19
| 27.789474
| 77
| 0.739362
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,559
|
files.py
|
translate_pootle/pootle/apps/pootle_fs/files.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import os
from translate.storage.factory import getclass
from django.contrib.auth import get_user_model
from django.utils.functional import cached_property
from pootle.core.models import Revision
from pootle.core.proxy import AttributeProxy
from pootle_statistics.models import SubmissionTypes
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
from pootle_store.models import Store
logger = logging.getLogger(__name__)
User = get_user_model()
class FSFile(object):
def __init__(self, store_fs):
"""
:param store_fs: ``StoreFS`` object
"""
self.store_fs = self._validate_store_fs(store_fs)
self.pootle_path = store_fs.pootle_path
self.path = store_fs.path
def _validate_store_fs(self, store_fs):
from .models import StoreFS
if not isinstance(store_fs, StoreFS):
raise TypeError(
"pootle_fs.FSFile expects a StoreFS")
return store_fs
def __str__(self):
return "<%s: %s::%s>" % (
self.__class__.__name__, self.pootle_path, self.path)
def __hash__(self):
return hash(
"%s::%s::%s::%s"
% (self.path,
self.pootle_path,
self.store_fs.last_sync_hash,
self.store_fs.last_sync_revision))
def __eq__(self, other):
return hash(other) == hash(self)
@property
def file_exists(self):
return os.path.exists(self.file_path)
@property
def store_exists(self):
return self.store is not None
@property
def file_path(self):
return os.path.join(
self.store_fs.project.local_fs_path,
self.path.strip("/"))
@property
def fs_changed(self):
return (
self.latest_hash
!= self.store_fs.last_sync_hash)
@property
def latest_hash(self):
if self.file_exists:
return str(os.stat(self.file_path).st_mtime)
@property
def latest_author(self):
return None, None
@property
def plugin(self):
return self.store_fs.plugin
@property
def pootle_changed(self):
return bool(
self.store_exists
and (
(self.store.data.max_unit_revision or 0)
!= self.store_fs.last_sync_revision))
@cached_property
def store(self):
return self.store_fs.store
def create_store(self):
"""
Creates a ```Store``` and if necessary the ```TranslationProject```
parent ```Directories```
"""
store = Store.objects.create_by_path(
self.pootle_path,
project=self.store_fs.project)
self.store_fs.store = store
self.store_fs.save()
self.__dict__["store"] = self.store_fs.store
def delete(self):
"""
Delete the file from FS and Pootle
This does not commit/push
"""
store = self.store
if store and store.pk:
store.makeobsolete()
del self.__dict__["store"]
if self.store_fs.pk:
self.store_fs.delete()
self.remove_file()
def on_sync(self, last_sync_hash, last_sync_revision, save=True):
"""
Called after FS and Pootle have been synced
"""
self.store_fs.resolve_conflict = None
self.store_fs.staged_for_merge = False
self.store_fs.last_sync_hash = last_sync_hash
self.store_fs.last_sync_revision = last_sync_revision
if save:
self.store_fs.save()
@property
def latest_user(self):
author, author_email = self.latest_author
if not author or not author_email:
return self.plugin.pootle_user
try:
return User.objects.get(email=author_email)
except User.DoesNotExist:
try:
return User.objects.get(username=author)
except User.DoesNotExist:
return self.plugin.pootle_user
def pull(self, user=None, merge=False, pootle_wins=None):
"""
Pull FS file into Pootle
"""
if self.store_exists and not self.fs_changed:
return
logger.debug("Pulling file: %s", self.path)
if not self.store_exists:
self.create_store()
if self.store.obsolete:
self.store.resurrect()
return self._sync_to_pootle(
merge=merge, pootle_wins=pootle_wins)
def push(self, user=None):
"""
Push Pootle ``Store`` into FS
"""
dont_push = (
not self.store_exists
or (self.file_exists and not self.pootle_changed))
if dont_push:
return
logger.debug("Pushing file: %s", self.path)
directory = os.path.dirname(self.file_path)
if not os.path.exists(directory):
logger.debug("Creating directory: %s", directory)
os.makedirs(directory)
return self._sync_from_pootle()
def read(self):
if not self.file_exists:
return
with open(self.file_path) as f:
return f.read()
def remove_file(self):
if self.file_exists:
os.unlink(self.file_path)
def deserialize(self, create=False):
if not create and not self.file_exists:
return
if self.file_exists:
with open(self.file_path) as f:
f = AttributeProxy(f)
f.location_root = self.store_fs.project.local_fs_path
store_file = (
self.store.syncer.file_class(f)
if self.store and self.store.syncer.file_class
else getclass(f)(f.read()))
if store_file.units:
return store_file
if self.store_exists:
return self.store.deserialize(self.store.serialize())
def serialize(self):
if not self.store_exists:
return
return self.store.serialize()
def _sync_from_pootle(self):
"""
Update FS file with the serialized content from Pootle ```Store```
"""
disk_store = self.deserialize(create=True)
self.store.syncer.sync(disk_store, self.store.data.max_unit_revision)
with open(self.file_path, "w") as f:
f.write(str(disk_store))
logger.debug("Pushed file: %s", self.path)
return self.store.data.max_unit_revision
def _sync_to_pootle(self, merge=False, pootle_wins=None):
"""
Update Pootle ``Store`` with the parsed FS file.
"""
tmp_store = self.deserialize()
if not tmp_store:
logger.warn("File staged for sync has disappeared: %s", self.path)
return
if pootle_wins is None:
resolve_conflict = (
self.store_fs.resolve_conflict or SOURCE_WINS)
elif pootle_wins:
resolve_conflict = POOTLE_WINS
else:
resolve_conflict = SOURCE_WINS
if merge:
revision = self.store_fs.last_sync_revision or 0
else:
# We set the revision to *anything* higher than the Store's
# This is analogous to the `overwrite` option in
# Store.update_from_disk
revision = Revision.get() + 1
update_revision, __ = self.store.update(
tmp_store,
submission_type=SubmissionTypes.SYSTEM,
user=self.latest_user,
store_revision=revision,
resolve_conflict=resolve_conflict)
logger.debug("Pulled file: %s", self.path)
return update_revision
| 7,935
|
Python
|
.py
| 221
| 26.515837
| 78
| 0.5932
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,560
|
matcher.py
|
translate_pootle/pootle/apps/pootle_fs/matcher.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import os
from fnmatch import fnmatch
from django.utils.functional import cached_property
from django.utils.lru_cache import lru_cache
from pootle.core.delegate import lang_mapper
from pootle.core.url_helpers import split_pootle_path
logger = logging.getLogger(__name__)
class FSPathMatcher(object):
def __init__(self, context):
self.context = context
@cached_property
def lang_mapper(self):
return lang_mapper.get(
self.project.__class__,
instance=self.project)
@cached_property
def excluded_languages(self):
excluded = self.project.config.get(
"pootle.fs.excluded_languages")
return [
self.lang_mapper.get_upstream_code(code) or code
for code
in excluded or []]
@lru_cache(maxsize=None)
def get_finder(self, fs_path=None):
path_filters = []
if fs_path:
path_filters.append(fs_path)
return self.context.finder_class(
self.translation_mapping,
extensions=self.project.filetype_tool.valid_extensions,
path_filters=path_filters,
exclude_languages=self.excluded_languages,
fs_hash=self.context.latest_hash)
@property
def project(self):
return self.context.project
@property
def root_directory(self):
return self.context.project.local_fs_path
@property
def translation_mapping(self):
return os.path.join(
self.project.local_fs_path,
os.path.join(
*self.context.project.config[
"pootle_fs.translation_mappings"]["default"].split("/")))
def make_pootle_path(self, **matched):
language_code = matched.get("language_code")
filename = matched.get("filename")
ext = matched.get("ext")
if not (language_code and filename and ext):
return
return "/".join(
["", language_code,
self.project.code]
+ [m for m in
matched.get('dir_path', '').split("/")
if m]
+ ["%s.%s"
% (filename, ext)])
def match_pootle_path(self, pootle_path_match=None, **matched):
pootle_path = self.make_pootle_path(**matched)
matches = (
pootle_path
and (not pootle_path_match
or fnmatch(pootle_path, pootle_path_match)))
if matches:
return pootle_path
def get_language(self, language_code):
return self.lang_mapper[language_code]
def relative_path(self, path):
if not path.startswith(self.root_directory):
return path
return path[len(self.root_directory):]
def matches(self, fs_path, pootle_path):
missing_langs = []
for file_path, matched in self.get_finder(fs_path).found:
if matched["language_code"] in missing_langs:
continue
language = self.get_language(matched["language_code"])
if not language:
missing_langs.append(matched['language_code'])
continue
matched["language_code"] = language.code
matched_pootle_path = self.match_pootle_path(
pootle_path_match=pootle_path, **matched)
if matched_pootle_path:
yield matched_pootle_path, self.relative_path(file_path)
if missing_langs:
logger.warning(
"Could not import files for languages: %s",
(", ".join(sorted(missing_langs))))
def reverse_match(self, pootle_path):
lang_code, __, dir_path, filename = split_pootle_path(pootle_path)
lang_code = self.lang_mapper.get_upstream_code(lang_code)
fileparts = os.path.splitext(filename)
fs_path = self.get_finder().reverse_match(
lang_code,
filename=fileparts[0],
extension=fileparts[1].lstrip("."),
dir_path=dir_path.strip("/"))
if fs_path:
return "/%s" % self.relative_path(fs_path).lstrip("/")
| 4,402
|
Python
|
.py
| 112
| 29.741071
| 77
| 0.608899
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,561
|
decorators.py
|
translate_pootle/pootle/apps/pootle_fs/decorators.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import functools
def emits_state(pre=None, post=None):
def class_wrapper(f):
@functools.wraps(f)
def method_wrapper(self, state, response, **kwargs):
if pre:
pre.send(
self.__class__,
plugin=self,
state=state,
response=response)
result = f(self, state, response, **kwargs)
if post:
post.send(
self.__class__,
plugin=self,
state=state,
response=response)
return result
return method_wrapper
return class_wrapper
def responds_to_state(f):
@functools.wraps(f)
def method_wrapper(self, *args, **kwargs):
if args:
state = args[0]
elif "state" in kwargs:
state = kwargs["state"]
del kwargs["state"]
else:
state = self.state(
pootle_path=kwargs.get("pootle_path"),
fs_path=kwargs.get("fs_path"))
if len(args) > 1:
response = args[1]
elif "response" in kwargs:
response = kwargs["response"]
del kwargs["response"]
else:
response = self.response(state)
return f(self, state, response, **kwargs)
return method_wrapper
| 1,661
|
Python
|
.py
| 49
| 23.142857
| 77
| 0.53995
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,562
|
delegate.py
|
translate_pootle/pootle/apps/pootle_fs/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin.delegate import Getter, Provider
fs_file = Getter()
fs_finder = Getter()
fs_matcher = Getter()
fs_resources = Getter()
fs_translation_mapping_validator = Getter()
fs_url_validator = Getter()
# File system plugins such as git/mercurial/localfs
fs_plugins = Provider()
fs_pre_pull_handlers = Provider()
fs_post_pull_handlers = Provider()
fs_pre_push_handlers = Provider()
fs_post_push_handlers = Provider()
fs_upstream = Provider()
| 735
|
Python
|
.py
| 21
| 33.714286
| 77
| 0.765537
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,563
|
managers.py
|
translate_pootle/pootle/apps/pootle_fs/managers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.core.exceptions import ValidationError
from django.db import models
from pootle_language.models import Language
from pootle_project.models import Project
from pootle_store.models import Store
def validate_store_fs(**kwargs):
"""When creating or saving a StoreFS, validate that it has the necessary
information.
"""
store = kwargs.get("store")
project = kwargs.get("project")
pootle_path = kwargs.get("pootle_path")
path = kwargs.get("path")
# We must have a pootle_path somehow
if not (store or pootle_path):
raise ValidationError(
"Either store or pootle_path must be set")
# Lets see if there is a Store matching pootle_path
if not store:
try:
store = Store.objects.get(pootle_path=pootle_path)
except Store.DoesNotExist:
pass
if store:
if not project:
project = store.translation_project.project
if not pootle_path:
pootle_path = store.pootle_path
# If store is set then pootle_path should match
if store.pootle_path != pootle_path:
raise ValidationError(
"Store.pootle_path must match pootle_path: %s %s"
% (pootle_path, store.pootle_path))
# We must be able to calculate a pootle_path and path
if not (pootle_path and path):
raise ValidationError(
"StoreFS must be created with at least a pootle_path and path")
# If project is not set then get from the pootle_path
try:
path_project = Project.objects.get(code=pootle_path.split("/")[2])
except (IndexError, Project.DoesNotExist):
raise ValidationError("Unrecognised project in path: %s" % pootle_path)
if not project:
project = path_project
elif project != path_project:
raise ValidationError(
"Path does not match project: %s %s"
% (project, pootle_path))
# Ensure language exists
if not store:
try:
Language.objects.get(code=pootle_path.split("/")[1])
except (IndexError, Language.DoesNotExist):
raise ValidationError(
"Unrecognised language in path: %s"
% pootle_path)
kwargs["project"] = project
kwargs["store"] = store
kwargs["pootle_path"] = pootle_path
return kwargs
class StoreFSManager(models.Manager):
def create(self, *args, **kwargs):
kwargs = validate_store_fs(**kwargs)
return super(StoreFSManager, self).create(*args, **kwargs)
| 2,831
|
Python
|
.py
| 71
| 32.605634
| 79
| 0.66132
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,564
|
fs_tags.py
|
translate_pootle/pootle/apps/pootle_fs/templatetags/fs_tags.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django import template
from pootle.core.delegate import upstream
register = template.Library()
@register.inclusion_tag('includes/upstream_link.html')
def upstream_link(project):
upstream_provider = None
if project.config.get("pootle.fs.upstream"):
upstream_providers = upstream.gather(project.__class__)
upstream_provider = upstream_providers.get(
project.config["pootle.fs.upstream"])
if not upstream_provider:
return dict()
return upstream_provider(project).context_data
@register.inclusion_tag('includes/upstream_link_short.html')
def upstream_link_short(project, location=None):
upstream_provider = None
if project.config.get("pootle.fs.upstream"):
upstream_providers = upstream.gather(project.__class__)
upstream_provider = upstream_providers.get(
project.config["pootle.fs.upstream"])
if not upstream_provider:
return dict()
return upstream_provider(project, location).context_data
| 1,280
|
Python
|
.py
| 30
| 37.933333
| 77
| 0.735105
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,565
|
0001_initial.py
|
translate_pootle/pootle/apps/pootle_fs/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pootle_project', '0004_correct_checkerstyle_options_order'),
('pootle_store', '0008_flush_django_cache'),
]
operations = [
migrations.CreateModel(
name='StoreFS',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('pootle_path', models.CharField(max_length=255)),
('path', models.CharField(max_length=255)),
('last_sync_revision', models.IntegerField(null=True, blank=True)),
('last_sync_mtime', models.DateTimeField(null=True, blank=True)),
('last_sync_hash', models.CharField(max_length=64, null=True, blank=True)),
('staged_for_removal', models.BooleanField(default=False)),
('staged_for_merge', models.BooleanField(default=False)),
('resolve_conflict', models.IntegerField(default=0, null=True, blank=True, choices=[(0, ''), (1, 'pootle'), (2, 'fs')])),
('project', models.ForeignKey(related_name='store_fs', to='pootle_project.Project', on_delete=models.CASCADE)),
('store', models.ForeignKey(related_name='fs', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='pootle_store.Store', null=True)),
],
options={
'abstract': False,
},
),
]
| 1,612
|
Python
|
.py
| 30
| 42.566667
| 158
| 0.600507
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,566
|
0002_convert_localfs.py
|
translate_pootle/pootle/apps/pootle_fs/migrations/0002_convert_localfs.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-17 09:16
from __future__ import unicode_literals
import json
import logging
import os
import posixpath
from functools import partial
from pathlib import PosixPath
import dirsync
from django.conf import settings
from django.db import migrations
from translate.lang.data import langcode_re
logger = logging.getLogger(__name__)
def _file_belongs_to_project(project, filename):
ext = os.path.splitext(filename)[1][1:]
filetype_extensions = list(
project.filetypes.values_list(
"extension__name", flat=True))
template_extensions = list(
project.filetypes.values_list(
"template_extension__name", flat=True))
return (
ext in filetype_extensions
or (ext in template_extensions))
def _detect_treestyle_and_path(Config, Language, project, proj_trans_path):
dirlisting = os.walk(proj_trans_path)
dirpath_, dirnames, filenames = dirlisting.next()
if not dirnames:
# No subdirectories
if filter(partial(_file_belongs_to_project, project), filenames):
# Translation files found, assume gnu
return "gnu", ""
# There are subdirectories
languages = set(
Language.objects.values_list("code", flat=True))
lang_mapping_config = Config.objects.filter(
content_type__model="project",
object_pk=project.pk,
key="pootle.core.lang_mappings").values_list(
"value", flat=True).first()
if lang_mapping_config:
languages |= set(json.loads(lang_mapping_config).keys())
has_subdirs = filter(
(lambda dirname: (
(dirname == 'templates'
or langcode_re.match(dirname))
and dirname in languages)),
dirnames)
if has_subdirs:
return "nongnu", None
# No language subdirs found, look for any translation file
# in subdirs
for dirpath_, dirnames, filenames in os.walk(proj_trans_path):
if filter(partial(_file_belongs_to_project, project), filenames):
return "gnu", dirpath_.replace(proj_trans_path, "")
# Unsure
return "nongnu", None
def _get_translation_mapping(Config, Language, project):
old_translation_path = settings.POOTLE_TRANSLATION_DIRECTORY
proj_trans_path = os.path.join(old_translation_path, project.code)
old_treestyle, old_path = (
_detect_treestyle_and_path(
Config, Language, project, proj_trans_path)
if project.treestyle in ["auto", "gnu"]
else (project.treestyle, None))
project.treestyle = "pootle_fs"
if old_treestyle == "nongnu":
return "/<language_code>/<dir_path>/<filename>.<ext>"
else:
return (
"%s/<language_code>.<ext>"
% (old_path and "/<dir_path>" or ""))
def _set_project_config(Language, Config, project_ct, project):
old_translation_path = settings.POOTLE_TRANSLATION_DIRECTORY
proj_trans_path = os.path.join(old_translation_path, project.code)
configs = Config.objects.filter(
content_type=project_ct,
object_pk=project.pk)
configs.delete()
Config.objects.update_or_create(
content_type=project_ct,
object_pk=project.pk,
key="pootle_fs.fs_url",
defaults=dict(
value=proj_trans_path))
Config.objects.update_or_create(
content_type=project_ct,
object_pk=project.pk,
key="pootle_fs.fs_type",
defaults=dict(
value="localfs"))
if os.path.exists(proj_trans_path):
Config.objects.update_or_create(
content_type=project_ct,
object_pk=project.pk,
key="pootle_fs.translation_mappings",
defaults=dict(
value=dict(default=_get_translation_mapping(
Config, Language, project))))
def convert_to_localfs(apps, schema_editor):
Project = apps.get_model("pootle_project.Project")
Store = apps.get_model("pootle_store.Store")
StoreFS = apps.get_model("pootle_fs.StoreFS")
Config = apps.get_model("pootle_config.Config")
Language = apps.get_model("pootle_language.Language")
ContentType = apps.get_model("contenttypes.ContentType")
project_ct = ContentType.objects.get_for_model(Project)
old_translation_path = settings.POOTLE_TRANSLATION_DIRECTORY
for project in Project.objects.exclude(treestyle="pootle_fs"):
logger.debug("Converting project '%s' to pootle fs", project.code)
proj_trans_path = str(PosixPath().joinpath(old_translation_path, project.code))
proj_stores = Store.objects.filter(
translation_project__project=project).exclude(file="").exclude(obsolete=True)
old_treestyle, old_path = (
_detect_treestyle_and_path(
Config, Language, project, proj_trans_path)
if project.treestyle in ["auto", "gnu"]
else (project.treestyle, None))
_set_project_config(Language, Config, project_ct, project)
project.treestyle = "pootle_fs"
project.save()
if project.disabled:
continue
if not os.path.exists(proj_trans_path):
logger.warn(
"Missing project ('%s') translation directory '%s', "
"skipped adding tracking",
project.code,
proj_trans_path)
continue
store_fs = StoreFS.objects.filter(
store__translation_project__project=project)
store_fs.delete()
sfs = []
templates = []
for store in proj_stores:
filepath = str(store.file)[len(project.code):]
fullpath = str(
PosixPath().joinpath(
proj_trans_path,
filepath.lstrip("/")))
if not os.path.exists(fullpath):
logger.warn(
"No file found at '%s', not adding tracking",
fullpath)
continue
if store.is_template and old_treestyle == "gnu":
templates.append(store)
sfs.append(
StoreFS(
project=project,
store=store,
path=str(filepath),
pootle_path=store.pootle_path,
last_sync_hash=str(os.stat(fullpath).st_mtime),
last_sync_revision=store.last_sync_revision,
last_sync_mtime=store.file_mtime))
if len(sfs):
StoreFS.objects.bulk_create(sfs, batch_size=1000)
if old_treestyle == "gnu" and len(templates) == 1:
template = templates[0]
template_name, __ = posixpath.splitext(template.name)
if template_name != "templates":
try:
mapping = Config.objects.get(
content_type=project_ct,
object_pk=project.pk,
key="pootle.core.lang_mapping")
except Config.DoesNotExist:
mapping = {}
mapping[template_name] = "templates"
Config.objects.update_or_create(
content_type=project_ct,
object_pk=project.pk,
key="pootle.core.lang_mapping",
defaults=dict(value=mapping))
logger.debug(
"Tracking added for %s/%s stores in project '%s'",
len(sfs),
proj_stores.count(),
project.code)
fs_temp = os.path.join(
settings.POOTLE_FS_WORKING_PATH, project.code)
dirsync.sync(
str(proj_trans_path),
fs_temp,
"sync",
create=True,
purge=True,
logger=logging.getLogger(dirsync.__name__))
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('pootle_fs', '0001_initial'),
('pootle_format', '0003_remove_extra_indeces'),
('pootle_config', '0001_initial'),
('pootle_store', '0013_set_store_filetype_again'),
('pootle_project', '0016_change_treestyle_choices_label'),
]
operations = [
migrations.RunPython(convert_to_localfs),
]
| 8,319
|
Python
|
.py
| 203
| 30.70936
| 89
| 0.601285
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,567
|
0003_path_uses_placeholder.py
|
translate_pootle/pootle/apps/pootle_fs/migrations/0003_path_uses_placeholder.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-12 15:17
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
def set_path_with_placeholder(apps, schema_editor):
Config = apps.get_model("pootle_config.Config")
ContentType = apps.get_model("contenttypes.ContentType")
Project = apps.get_model("pootle_project.Project")
project_ct = ContentType.objects.get_for_model(Project)
for project in Project.objects.all():
config = Config.objects.get(
content_type=project_ct,
object_pk=project.pk,
key="pootle_fs.fs_url")
if config.value.startswith(settings.POOTLE_TRANSLATION_DIRECTORY):
config.value = (
"{POOTLE_TRANSLATION_DIRECTORY}%s"
% config.value[
len(settings.POOTLE_TRANSLATION_DIRECTORY.rstrip("/")) + 1:])
config.save()
class Migration(migrations.Migration):
dependencies = [
('pootle_fs', '0002_convert_localfs'),
]
operations = [
migrations.RunPython(set_path_with_placeholder),
]
| 1,143
|
Python
|
.py
| 28
| 33.107143
| 81
| 0.654923
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,568
|
fs.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
import os
from django.utils.termcolors import PALETTES, NOCOLOR_PALETTE
PALETTES[NOCOLOR_PALETTE]["FS_MISSING"] = {}
PALETTES["light"]["FS_MISSING"] = {'fg': 'magenta'}
PALETTES["dark"]["FS_MISSING"] = {'fg': 'magenta'}
PALETTES[NOCOLOR_PALETTE]["POOTLE_MISSING"] = {}
PALETTES["light"]["POOTLE_MISSING"] = {'fg': 'magenta'}
PALETTES["dark"]["POOTLE_MISSING"] = {'fg': 'magenta'}
PALETTES[NOCOLOR_PALETTE]["FS_UNTRACKED"] = {}
PALETTES["light"]["FS_UNTRACKED"] = {'fg': 'red'}
PALETTES["dark"]["FS_UNTRACKED"] = {'fg': 'red'}
PALETTES[NOCOLOR_PALETTE]["FS_STAGED"] = {}
PALETTES["light"]["FS_STAGED"] = {'fg': 'green'}
PALETTES["dark"]["FS_STAGED"] = {'fg': 'green'}
PALETTES[NOCOLOR_PALETTE]["FS_UPDATED"] = {}
PALETTES["light"]["FS_UPDATED"] = {'fg': 'green'}
PALETTES["dark"]["FS_UPDATED"] = {'fg': 'green'}
PALETTES[NOCOLOR_PALETTE]["FS_CONFLICT"] = {}
PALETTES["light"]["FS_CONFLICT"] = {'fg': 'red', 'opts': ('bold',)}
PALETTES["dark"]["FS_CONFLICT"] = {'fg': 'red', 'opts': ('bold',)}
PALETTES[NOCOLOR_PALETTE]["FS_REMOVED"] = {}
PALETTES["light"]["FS_REMOVED"] = {'fg': 'red'}
PALETTES["dark"]["FS_REMOVED"] = {'fg': 'red'}
PALETTES[NOCOLOR_PALETTE]["FS_ERROR"] = {}
PALETTES["light"]["FS_ERROR"] = {'fg': 'red', 'opts': ('bold',)}
PALETTES["dark"]["FS_ERROR"] = {'fg': 'red', 'opts': ('bold',)}
# This must be run before importing the rest of the Django libs.
os.environ["DJANGO_COLORS"] = "light"
os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings'
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from pootle.core.management.subcommands import CommandWithSubcommands
from pootle_fs.utils import FSPlugin
from pootle_project.models import Project
from .fs_commands.add import AddCommand
from .fs_commands.fetch import FetchCommand
from .fs_commands.info import ProjectInfoCommand
from .fs_commands.resolve import ResolveCommand
from .fs_commands.rm import RmCommand
from .fs_commands.state import StateCommand
from .fs_commands.sync import SyncCommand
from .fs_commands.unstage import UnstageCommand
logger = logging.getLogger('pootle.fs')
class Command(CommandWithSubcommands):
help = "Pootle FS."
subcommands = {
"add": AddCommand,
"fetch": FetchCommand,
"info": ProjectInfoCommand,
"rm": RmCommand,
"resolve": ResolveCommand,
"state": StateCommand,
"sync": SyncCommand,
"unstage": UnstageCommand}
def handle(self, *args, **kwargs):
any_configured = False
for project in Project.objects.order_by("pk"):
try:
plugin = FSPlugin(project)
self.stdout.write(
"%s\t%s"
% (project.code, plugin.fs_url))
any_configured = True
except (MissingPluginError, NotConfiguredError):
pass
if not any_configured:
self.stdout.write("No projects configured")
| 3,224
|
Python
|
.py
| 74
| 39.148649
| 77
| 0.67198
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,569
|
init_fs_project.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/init_fs_project.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from django.core.exceptions import ValidationError
from django.core.management import BaseCommand, CommandError
from pootle_format.models import Format
from pootle_fs.exceptions import FSFetchError
from pootle_fs.utils import FSPlugin, parse_fs_url
from pootle_language.models import Language
from pootle_project.models import Project
logger = logging.getLogger('pootle.fs')
class Command(BaseCommand):
help = "Init a new Pootle FS project."
def add_arguments(self, parser):
parser.add_argument(
'code',
metavar='CODE',
help='Project code'
)
parser.add_argument(
'fs',
metavar='FS_URL',
help='FS url "filesystem_type+/repo/path/"'
)
parser.add_argument(
'translation_mapping',
help='Translation mapping "<language_code>/<filename>.<ext>"',
metavar='TRANSLATION_MAPPING'
)
parser.add_argument(
'-n', '--name',
action='store',
dest='name',
nargs='?',
help='Project name',
)
parser.add_argument(
'--filetypes',
action='append',
dest='filetypes',
help='File types',
)
parser.add_argument(
'--checkstyle',
action='store',
dest='checkstyle',
help='Checkstyle',
nargs='?',
default='standard'
)
parser.add_argument(
'-l', '--source-language',
action='store',
dest='source_language',
help="Code for the project's source language",
nargs='?',
default='en'
)
parser.add_argument(
'--nosync',
action='store_false',
dest='sync',
help='Flag if sync is unnecessary',
default=True
)
def handle(self, **options):
source_language_code = options['source_language']
try:
source_language = Language.objects.get(code=source_language_code)
except Language.DoesNotExist as e:
self.stdout.write('%s: Unknown language code.' %
source_language_code)
raise CommandError(e)
fs_type, fs_url = parse_fs_url(options['fs'])
code = options['code']
name = options['name'] or code.capitalize()
try:
project = Project.objects.create(
code=code,
fullname=name,
checkstyle=options['checkstyle'],
source_language=source_language)
except ValidationError as e:
raise CommandError(e)
for filetype in options["filetypes"] or ["po"]:
try:
filetype = Format.objects.get(name=filetype)
project.filetypes.add(filetype)
except Format.DoesNotExist as e:
raise CommandError(e)
project.config['pootle_fs.fs_type'] = fs_type
project.config['pootle_fs.fs_url'] = fs_url
project.config['pootle_fs.translation_mappings'] = {
'default': options['translation_mapping']
}
if options['sync']:
try:
plugin = FSPlugin(project)
plugin.fetch()
plugin.add()
plugin.sync()
except FSFetchError as e:
project.delete()
raise CommandError(e)
| 3,805
|
Python
|
.py
| 109
| 24.33945
| 77
| 0.560956
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,570
|
__init__.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.core.management.base import BaseCommand, CommandError
from django.utils.lru_cache import lru_cache
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from pootle_fs.display import ResponseDisplay
from pootle_fs.exceptions import FSStateError
from pootle_fs.utils import FSPlugin
from pootle_project.models import Project
RESPONSE_COLORMAP = dict(
pootle_added=(None, "MISSING"),
fs_added=("MISSING", None),
remove=("MISSING", "MISSING"))
class BaseSubCommand(BaseCommand):
requires_system_checks = False
class ProjectSubCommand(BaseSubCommand):
def add_arguments(self, parser):
parser.add_argument(
'project',
type=str,
help='Pootle project')
super(ProjectSubCommand, self).add_arguments(parser)
@lru_cache()
def get_fs(self, project_code):
project = self.get_project(project_code)
try:
return FSPlugin(project)
except (NotConfiguredError, MissingPluginError) as e:
raise CommandError(e)
@lru_cache()
def get_project(self, project_code):
try:
return Project.objects.get(code=project_code)
except Project.DoesNotExist as e:
raise CommandError(e)
class FSAPISubCommand(ProjectSubCommand):
def add_arguments(self, parser):
super(FSAPISubCommand, self).add_arguments(parser)
parser.add_argument(
'-p', '--fs-path',
action='store',
dest='fs_path',
help='Filter translations by filesystem path')
parser.add_argument(
'-P', '--pootle-path',
action='store',
dest='pootle_path',
help='Filter translations by Pootle path')
def handle_api_options(self, options):
return {
k: v
for k, v
in options.items()
if k in [
"pootle_path", "fs_path", "merge",
"force", "pootle_wins"]}
def handle_api(self, **options):
api_method = getattr(
self.get_fs(options["project"]),
self.api_method)
try:
return api_method(**self.handle_api_options(options))
except FSStateError as e:
raise CommandError(e)
def display(self, **options):
return ResponseDisplay(
self.handle_api(**options))
@property
def colormap(self):
return RESPONSE_COLORMAP
@lru_cache()
def get_style(self, key):
pootle_style, fs_style = self.colormap.get(key, (None, None))
if pootle_style:
pootle_style = getattr(self.style, "FS_%s" % pootle_style)
if fs_style:
fs_style = getattr(self.style, "FS_%s" % fs_style)
return pootle_style, fs_style
def is_empty(self, display):
return not display.context.made_changes
def handle(self, *args, **options):
display = self.display(**options)
if self.is_empty(display):
self.stdout.write(str(display).strip())
self.stdout.write("")
return
for section in display.sections:
section = display.section(section)
self.stdout.write(section.title, self.style.HTTP_INFO)
self.stdout.write("-" * len(section.title), self.style.HTTP_INFO)
if section.description:
self.stdout.write(section.description)
self.stdout.write("")
for item in section.items:
pootle_style, fs_style = self.get_style(item.section)
self.write_line(
item.pootle_path,
item.fs_path,
pootle_style=pootle_style, fs_style=fs_style)
self.stdout.write("")
self.stdout.write("")
def write_line(self, pootle_path, fs_path,
pootle_style=None, fs_style=None):
self.stdout.write(" %s" % pootle_path, pootle_style)
self.stdout.write(" <--> ", ending="")
self.stdout.write(fs_path, fs_style)
| 4,350
|
Python
|
.py
| 111
| 29.936937
| 77
| 0.615458
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,571
|
state.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/state.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.display import StateDisplay
from pootle_fs.management.commands import FSAPISubCommand
STATE_COLORMAP = {
"conflict": ("CONFLICT", "CONFLICT"),
"conflict_untracked": ("CONFLICT", "CONFLICT"),
"remove": ("MISSING", "MISSING"),
"merge_fs_wins": ("UPDATED", "UPDATED"),
"merge_pootle_wins": ("UPDATED", "UPDATED"),
"fs_ahead": (None, "UPDATED"),
"fs_staged": ("MISSING", "STAGED"),
"fs_untracked": ("MISSING", "UNTRACKED"),
"fs_removed": (None, "REMOVED"),
"pootle_untracked": ("UNTRACKED", "REMOVED"),
"pootle_staged": ("STAGED", "REMOVED"),
"pootle_removed": ("REMOVED", None),
"pootle_ahead": ("UPDATED", None)}
class StateCommand(FSAPISubCommand):
help = ("Show state of tracked and untracked files and Stores for the "
"specified project")
api_method = "state"
def add_arguments(self, parser):
super(StateCommand, self).add_arguments(parser)
parser.add_argument(
'-t', '--type',
action='append',
dest='state_type',
help='State type')
@property
def colormap(self):
return STATE_COLORMAP
def display(self, **options):
return StateDisplay(self.handle_api(**options))
def is_empty(self, display):
return not display.context.has_changed
| 1,612
|
Python
|
.py
| 41
| 33.707317
| 77
| 0.651088
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,572
|
sync.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/sync.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import FSAPISubCommand
class SyncCommand(FSAPISubCommand):
help = "Sync translations from FS into Pootle."
api_method = "sync"
| 448
|
Python
|
.py
| 11
| 38.727273
| 77
| 0.767281
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,573
|
fetch.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/fetch.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import ProjectSubCommand
class FetchCommand(ProjectSubCommand):
help = "Fetch remote filesystems."
def handle(self, **options):
self.get_fs(options["project"]).fetch()
| 498
|
Python
|
.py
| 12
| 38.833333
| 77
| 0.753112
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,574
|
unstage.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/unstage.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import FSAPISubCommand
class UnstageCommand(FSAPISubCommand):
help = "Unstage staged actions."
api_method = "unstage"
| 439
|
Python
|
.py
| 11
| 37.909091
| 77
| 0.769412
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,575
|
add.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/add.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import FSAPISubCommand
class AddCommand(FSAPISubCommand):
help = "Stage untracked stores for sync to the filesystem."
api_method = "add"
def add_arguments(self, parser):
super(AddCommand, self).add_arguments(parser)
parser.add_argument(
"--force",
action="store_true",
dest="force",
help=("Stage conflicting files on the filesystem to be "
"overwritten with the Pootle store"))
| 786
|
Python
|
.py
| 19
| 35.210526
| 77
| 0.684142
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,576
|
rm.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/rm.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import FSAPISubCommand
class RmCommand(FSAPISubCommand):
help = "Stage files and/or stores for removal."
api_method = "rm"
def add_arguments(self, parser):
super(RmCommand, self).add_arguments(parser)
parser.add_argument(
"--force",
action="store_true",
dest="force",
help=("Stage for removal conflicting/untracked files and/or "
"stores"))
| 749
|
Python
|
.py
| 19
| 33.263158
| 77
| 0.674931
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,577
|
resolve.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/resolve.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import FSAPISubCommand
class ResolveCommand(FSAPISubCommand):
help = "Resolve conflicting stores for sync to the filesystem."
api_method = "resolve"
def add_arguments(self, parser):
super(ResolveCommand, self).add_arguments(parser)
parser.add_argument(
"--overwrite",
action="store_false",
dest="merge",
help=("Overwrite the corresponding store or file"))
parser.add_argument(
"--pootle-wins",
action="store_true",
dest="pootle_wins",
help=("Where units are conflicting use the version from Pootle"))
| 947
|
Python
|
.py
| 23
| 34.26087
| 77
| 0.670652
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,578
|
info.py
|
translate_pootle/pootle/apps/pootle_fs/management/commands/fs_commands/info.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.management.commands import ProjectSubCommand
class ProjectInfoCommand(ProjectSubCommand):
help = "Show pootle_fs configuration information for specified project."
def handle(self, *args, **kwargs):
fs = self.get_fs(kwargs['project'])
self.stdout.write("Project: %s" % fs.project.code)
self.stdout.write("type: %s" % fs.fs_type)
self.stdout.write("URL: %s" % fs.fs_url)
| 703
|
Python
|
.py
| 15
| 42.933333
| 77
| 0.717836
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,579
|
models.py
|
translate_pootle/pootle/apps/pootle_config/models.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .abstracts import AbstractConfig
class Config(AbstractConfig):
class Meta(AbstractConfig.Meta):
db_table = "pootle_config"
| 419
|
Python
|
.py
| 11
| 35.636364
| 77
| 0.757426
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,580
|
getters.py
|
translate_pootle/pootle/apps/pootle_config/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import config
from pootle.core.plugin import getter
from .exceptions import ConfigurationError
from .models import Config
@getter(config)
def config_getter(**kwargs):
sender = kwargs["sender"]
instance = kwargs.get("instance")
key = kwargs.get("key")
if sender:
if instance is not None and not isinstance(instance, sender):
raise ConfigurationError(
"'instance' must be an instance of 'sender', when specified")
conf = Config.objects.get_config_queryset(instance or sender)
elif instance:
raise ConfigurationError(
"'sender' must be defined when 'instance' is specified")
else:
conf = Config.objects.site_config()
if key is None:
return conf
if isinstance(key, (list, tuple)):
return conf.list_config(key)
try:
return conf.get_config(key)
except Config.MultipleObjectsReturned as e:
raise ConfigurationError(e)
| 1,264
|
Python
|
.py
| 34
| 31.705882
| 77
| 0.701309
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,581
|
abstracts.py
|
translate_pootle/pootle/apps/pootle_config/abstracts.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import collections
from jsonfield.fields import JSONField
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from .managers import ConfigManager, ConfigQuerySet
class AbstractConfig(models.Model):
content_type = models.ForeignKey(
ContentType,
blank=True,
null=True,
db_index=True,
verbose_name='content type',
related_name="content_type_set_for_%(class)s",
on_delete=models.CASCADE)
object_pk = models.CharField(
'object ID',
max_length=255,
blank=True,
null=True)
content_object = GenericForeignKey(
ct_field="content_type",
fk_field="object_pk")
key = models.CharField(
'Configuration key',
max_length=255,
blank=False,
null=False,
db_index=True)
value = JSONField(
'Configuration value',
default="",
blank=True,
null=False,
load_kwargs={'object_pairs_hook': collections.OrderedDict})
objects = ConfigManager.from_queryset(ConfigQuerySet)()
class Meta(object):
abstract = True
ordering = ['pk']
index_together = ["content_type", "object_pk"]
def save(self, **kwargs):
if not self.key:
raise ValidationError("Config object must have a key")
if self.object_pk and not self.content_type:
raise ValidationError(
"Config object must have content_type when object_pk is set")
super(AbstractConfig, self).save(**kwargs)
| 1,957
|
Python
|
.py
| 55
| 28.890909
| 77
| 0.674591
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,582
|
apps.py
|
translate_pootle/pootle/apps/pootle_config/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleConfigConfig(AppConfig):
name = "pootle_config"
verbose_name = "Pootle Config"
def ready(self):
importlib.import_module("pootle_config.getters")
| 509
|
Python
|
.py
| 14
| 33.5
| 77
| 0.754601
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,583
|
utils.py
|
translate_pootle/pootle/apps/pootle_config/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from django.utils.functional import cached_property
from pootle.core.delegate import config
class ConfigDict(object):
"""Assumes keys for __config__ are unique, uses last instance of key
if not
"""
def __init__(self, context):
self.context = context
@property
def __config__(self):
raise NotImplementedError
@cached_property
def conf(self):
return OrderedDict(self.__config__.list_config())
def reload(self):
if "conf" in self.__dict__:
del self.__dict__["conf"]
def __contains__(self, k):
return self.conf.__contains__(k)
def __getitem__(self, k):
return self.conf.__getitem__(k)
def __iter__(self):
return self.conf.__iter__()
def __setitem__(self, k, v):
self.__config__.set_config(k, v)
self.reload()
def get(self, k, default=None):
return self.conf.get(k, default)
def keys(self):
return self.conf.keys()
def items(self):
return self.conf.items()
def values(self):
return self.conf.values()
class SiteConfig(ConfigDict):
def __init__(self):
pass
@property
def __config__(self):
return config.get()
class ModelConfig(ConfigDict):
@property
def __config__(self):
return config.get(self.context)
class ObjectConfig(ConfigDict):
@property
def __config__(self):
return config.get(
self.context.__class__,
instance=self.context)
| 1,834
|
Python
|
.py
| 58
| 25.534483
| 77
| 0.637507
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,584
|
__init__.py
|
translate_pootle/pootle/apps/pootle_config/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'pootle_config.apps.PootleConfigConfig'
| 337
|
Python
|
.py
| 8
| 41
| 77
| 0.768293
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,585
|
exceptions.py
|
translate_pootle/pootle/apps/pootle_config/exceptions.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
class ConfigurationError(Exception):
"""Problem trying to set a configuration"""
pass
| 372
|
Python
|
.py
| 10
| 35.1
| 77
| 0.752089
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,586
|
delegate.py
|
translate_pootle/pootle/apps/pootle_config/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin.delegate import Getter
config_should_not_be_set = Getter(providing_args=["instance", "key", "value"])
config_should_not_be_appended = Getter(providing_args=["instance", "key", "value"])
| 488
|
Python
|
.py
| 10
| 47.5
| 83
| 0.751579
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,587
|
managers.py
|
translate_pootle/pootle/apps/pootle_config/managers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.base import ModelBase
from django.utils.encoding import force_text
from pootle.core.signals import config_updated
from .delegate import config_should_not_be_appended, config_should_not_be_set
from .exceptions import ConfigurationError
class ConfigQuerySet(models.QuerySet):
def __init__(self, *args, **kwargs):
super(ConfigQuerySet, self).__init__(*args, **kwargs)
self.query_model = None
def _clone(self, **kwargs):
clone = super(ConfigQuerySet, self)._clone(**kwargs)
clone.query_model = self.query_model
return clone
@property
def base_qs(self):
qs = self.__class__(self.model)
qs.query_model = self.query_model
return qs.select_related("content_type")
def append_config(self, key, value="", model=None):
model = self.get_query_model(model)
self.should_append_config(key, value, model)
self.create(
key=key, value=value,
**self.get_model_kwargs(model))
def clear_config(self, key, model=None):
self.get_config_queryset(model).filter(key=key).delete()
def config_for(self, model):
"""
QuerySet for all config for a particular model (either an instance or
a class).
"""
self.query_model = model
return self.base_qs.filter(**self.get_model_kwargs(model))
def get_config(self, key, model=None):
conf = self.get_config_queryset(model)
try:
key = conf.get(key=key)
except self.model.DoesNotExist:
return None
return key.value
def get_config_queryset(self, model):
model = self.get_query_model(model)
if model:
if isinstance(model, models.Model):
return self.config_for(model)
return self.config_for(model).filter(object_pk__isnull=True)
return self.site_config()
def get_model_kwargs(self, model):
model = self.get_query_model(model)
if model is None:
return {}
ct = ContentType.objects.get_for_model(model)
kwargs = dict(content_type=ct)
if isinstance(model, models.Model):
kwargs["object_pk"] = force_text(model._get_pk_val())
return kwargs
def get_query_model(self, model=None):
if model:
self.query_model = model
elif self.query_model:
model = self.query_model
return model
def list_config(self, key=None, model=None):
conf = self.get_config_queryset(model)
conf_list = []
if isinstance(key, (list, tuple)):
if key:
conf = conf.filter(key__in=key)
elif key is not None:
conf = conf.filter(key=key)
for item in conf.order_by("key", "pk"):
# dont use values_list to trigger to_python
conf_list.append((item.key, item.value))
return conf_list
def set_config(self, key, value="", model=None):
model = self.get_query_model(model)
model_conf = self.get_config_queryset(model)
self.should_set_config(key, value, model)
old_value = None
updated = False
try:
conf = model_conf.get(key=key)
except model_conf.model.DoesNotExist:
conf = self.create(
key=key,
value=value,
**self.get_model_kwargs(model))
updated = True
if conf.value != value:
old_value = conf.value
updated = True
conf.value = value
conf.save()
if updated:
if isinstance(model, ModelBase):
sender = model
instance = None
else:
sender = model.__class__
instance = model
config_updated.send(
sender,
instance=instance,
key=key,
value=value,
old_value=old_value)
def should_append_config(self, key, value, model=None):
sender = model
instance = None
if isinstance(model, models.Model):
sender = model.__class__
instance = model
no_append = config_should_not_be_appended.get(
sender,
instance=instance,
key=key,
value=value)
if no_append:
raise ConfigurationError(no_append)
def should_set_config(self, key, value, model=None):
sender = model
instance = None
if isinstance(model, models.Model):
sender = model.__class__
instance = model
no_set = config_should_not_be_set.get(
sender,
instance=instance,
key=key,
value=value)
if no_set:
raise ConfigurationError(no_set)
def site_config(self):
self.query_model = None
return self.base_qs.filter(
content_type__isnull=True, object_pk__isnull=True)
class ConfigManager(models.Manager):
pass
| 5,446
|
Python
|
.py
| 147
| 27.401361
| 77
| 0.594769
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,588
|
0001_initial.py
|
translate_pootle/pootle/apps/pootle_config/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Config',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_pk', models.CharField(max_length=255, null=True, verbose_name='object ID', blank=True)),
('key', models.CharField(max_length=255, verbose_name='Configuration key', db_index=True)),
('value', jsonfield.fields.JSONField(default='', verbose_name='Configuration value', blank=True)),
('content_type', models.ForeignKey(related_name='content_type_set_for_config', verbose_name='content type', blank=True, to='contenttypes.ContentType', null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ['pk'],
'abstract': False,
'db_table': 'pootle_config',
},
),
migrations.AlterIndexTogether(
name='config',
index_together=set([('content_type', 'object_pk')]),
),
]
| 1,343
|
Python
|
.py
| 29
| 35.896552
| 205
| 0.595111
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,589
|
models.py
|
translate_pootle/pootle/apps/pootle_data/models.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db import models
from .abstracts import AbstractPootleChecksData, AbstractPootleData
class StoreData(AbstractPootleData):
class Meta(object):
db_table = "pootle_store_data"
store = models.OneToOneField(
"pootle_store.Store",
on_delete=models.CASCADE,
db_index=True,
related_name="data")
def __unicode__(self):
return self.store.pootle_path
class StoreChecksData(AbstractPootleChecksData):
class Meta(AbstractPootleChecksData.Meta):
db_table = "pootle_store_check_data"
unique_together = ["store", "category", "name"]
index_together = [AbstractPootleChecksData.Meta.index_together]
store = models.ForeignKey(
"pootle_store.Store",
on_delete=models.CASCADE,
db_index=False,
related_name="check_data")
def __unicode__(self):
return self.store.pootle_path
class TPData(AbstractPootleData):
class Meta(object):
db_table = "pootle_tp_data"
tp = models.OneToOneField(
"pootle_translationproject.TranslationProject",
on_delete=models.CASCADE,
db_index=True,
related_name="data")
def __unicode__(self):
return self.tp.pootle_path
class TPChecksData(AbstractPootleChecksData):
class Meta(AbstractPootleChecksData.Meta):
db_table = "pootle_tp_check_data"
unique_together = ["tp", "category", "name"]
index_together = [AbstractPootleChecksData.Meta.index_together]
tp = models.ForeignKey(
"pootle_translationproject.TranslationProject",
on_delete=models.CASCADE,
db_index=False,
related_name="check_data")
def __unicode__(self):
return self.tp.pootle_path
| 2,025
|
Python
|
.py
| 53
| 31.660377
| 77
| 0.690256
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,590
|
language_data.py
|
translate_pootle/pootle/apps/pootle_data/language_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from .utils import RelatedTPsDataTool
class LanguageDataTool(RelatedTPsDataTool):
"""Retrieves aggregate stats for a Language"""
cache_key_name = "language"
def filter_data(self, qs):
return qs.filter(tp__language=self.context)
| 528
|
Python
|
.py
| 13
| 37.692308
| 77
| 0.75098
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,591
|
getters.py
|
translate_pootle/pootle/apps/pootle_data/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import crud, data_tool, data_updater
from pootle.core.plugin import getter
from pootle_app.models import Directory
from pootle_language.models import Language
from pootle_project.models import Project, ProjectResource, ProjectSet
from pootle_store.models import Store
from pootle_translationproject.models import TranslationProject
from .directory_data import DirectoryDataTool
from .language_data import LanguageDataTool
from .models import StoreChecksData, StoreData, TPChecksData, TPData
from .project_data import (
ProjectDataTool, ProjectResourceDataTool, ProjectSetDataTool)
from .store_data import (
StoreChecksDataCRUD, StoreDataCRUD, StoreDataTool, StoreDataUpdater)
from .tp_data import (
TPChecksDataCRUD, TPDataCRUD, TPDataTool, TPDataUpdater, TPUpdater)
CRUD = {
StoreData: StoreDataCRUD(),
StoreChecksData: StoreChecksDataCRUD(),
TPData: TPDataCRUD(),
TPChecksData: TPChecksDataCRUD()}
@getter(crud, sender=(StoreChecksData, StoreData, TPChecksData, TPData))
def data_crud_getter(**kwargs):
return CRUD[kwargs["sender"]]
@getter(data_tool, sender=Store)
def store_data_tool_getter(**kwargs_):
return StoreDataTool
@getter(data_updater, sender=TranslationProject)
def store_updater_getter(**kwargs_):
return TPUpdater
@getter(data_updater, sender=StoreDataTool)
def store_data_tool_updater_getter(**kwargs_):
return StoreDataUpdater
@getter(data_tool, sender=TranslationProject)
def tp_data_tool_getter(**kwargs_):
return TPDataTool
@getter(data_updater, sender=TPDataTool)
def tp_data_tool_updater_getter(**kwargs_):
return TPDataUpdater
@getter(data_tool, sender=Project)
def project_data_tool_getter(**kwargs_):
return ProjectDataTool
@getter(data_tool, sender=ProjectSet)
def project_set_data_tool_getter(**kwargs_):
return ProjectSetDataTool
@getter(data_tool, sender=ProjectResource)
def project_resource_data_tool_getter(**kwargs_):
return ProjectResourceDataTool
@getter(data_tool, sender=Language)
def language_data_tool_getter(**kwargs_):
return LanguageDataTool
@getter(data_tool, sender=Directory)
def directory_data_tool_getter(**kwargs_):
return DirectoryDataTool
| 2,490
|
Python
|
.py
| 61
| 38.213115
| 77
| 0.801082
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,592
|
abstracts.py
|
translate_pootle/pootle/apps/pootle_data/abstracts.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from translate.filters.decorators import Category
from django.db import models
class AbstractPootleData(models.Model):
class Meta(object):
abstract = True
# last untranslated unit created
last_created_unit = models.OneToOneField(
"pootle_store.Unit",
db_index=True,
null=True,
blank=True,
related_name="last_created_for_%(class)s",
on_delete=models.SET_NULL)
# the mtime of the last unit to be changed - used to order Stores
max_unit_mtime = models.DateTimeField(
null=True,
blank=True,
auto_now=False,
db_index=True)
# the revision of the last unit to be changed - used to order Stores
max_unit_revision = models.IntegerField(
null=False,
blank=True,
default=0,
db_index=True)
# last submission made
last_submission = models.OneToOneField(
"pootle_statistics.Submission",
null=True,
blank=True,
db_index=True,
related_name="%(class)s_stats_data",
on_delete=models.SET_NULL)
# the total number of failing critical checks
critical_checks = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
# the number of pending suggestions
pending_suggestions = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
# the total number of words in the store
total_words = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
# the number of translated words
translated_words = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
# the number of fuzzy words
fuzzy_words = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
class AbstractPootleChecksData(models.Model):
class Meta(object):
abstract = True
index_together = ["name", "category"]
name = models.CharField(
max_length=64,
db_index=False)
category = models.IntegerField(
null=False,
default=Category.NO_CATEGORY,
db_index=True)
count = models.IntegerField(
null=False,
blank=False,
default=0,
db_index=True)
| 2,644
|
Python
|
.py
| 86
| 23.72093
| 77
| 0.642857
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,593
|
tp_data.py
|
translate_pootle/pootle/apps/pootle_data/tp_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db.models import Max, Sum
from django.db.models.functions import Coalesce
from pootle.core.bulk import BulkCRUD
from pootle.core.decorators import persistent_property
from pootle.core.delegate import revision
from pootle.core.signals import update_data
from pootle_data.models import StoreChecksData, StoreData
from .models import TPChecksData, TPData
from .utils import DataUpdater, RelatedStoresDataTool
class TPDataCRUD(BulkCRUD):
model = TPData
class TPChecksDataCRUD(BulkCRUD):
model = TPChecksData
class TPDataUpdater(DataUpdater):
related_name = "tp"
aggregate_fields = (
"words",
"critical_checks",
"last_created_unit",
"last_submission",
"max_unit_revision",
"max_unit_mtime",
"pending_suggestions")
@property
def aggregate_critical_checks(self):
return dict(
critical_checks=Coalesce(
Sum("critical_checks"), 0))
@property
def aggregate_last_created_unit(self):
return dict(last_created_unit=Max("last_created_unit"))
@property
def aggregate_last_submission(self):
return dict(last_submission=Max("last_submission"))
@property
def aggregate_max_unit_mtime(self):
return dict(max_unit_mtime=Max("max_unit_mtime"))
@property
def aggregate_max_unit_revision(self):
return dict(
max_unit_revision=Coalesce(
Max("max_unit_revision"), 0))
@property
def aggregate_pending_suggestions(self):
return dict(
pending_suggestions=Coalesce(
Sum("pending_suggestions"), 0))
@property
def aggregate_words(self):
return dict(
total_words=Coalesce(Sum("total_words"), 0),
fuzzy_words=Coalesce(Sum("fuzzy_words"), 0),
translated_words=Coalesce(Sum("translated_words"), 0))
@property
def store_data_qs(self):
return StoreData.objects.filter(
store__translation_project_id=self.tool.context.id)
@property
def store_check_data_qs(self):
return StoreChecksData.objects.filter(
store__translation_project_id=self.tool.context.id)
def get_last_created_unit(self, **kwargs):
return self.get_aggregate_data(
fields=["last_created_unit"])["last_created_unit"]
def get_last_submission(self, **kwargs):
return self.get_aggregate_data(
fields=["last_submission"])["last_submission"]
def get_pending_suggestions(self, **kwargs):
return self.get_aggregate_data(
fields=["pending_suggestions"])["pending_suggestions"]
def get_checks(self, **kwargs):
return self.store_check_data_qs.values(
"category", "name").annotate(count=Sum("count"))
class TPDataTool(RelatedStoresDataTool):
"""Retrieves aggregate stats for a TP"""
group_by = ("store__tp_path", )
cache_key_name = "directory"
def get_root_child_path(self, child):
remainder = child["store__tp_path"].replace(
"/%s" % (self.dir_path), "", 1)
return remainder.split("/")[0]
@property
def rev_cache_key(self):
return revision.get(self.context.directory.__class__)(
self.context.directory).get(key="stats")
@property
def context_name(self):
return self.context.pootle_path.strip("/").replace("/", ".")
@property
def object_stats(self):
stats = {
v: getattr(self.context.data, k)
for k, v in self.stats_mapping.items()}
stats["last_submission"] = self.get_last_submission()
stats["last_created_unit"] = self.get_last_created()
return stats
@property
def stat_data(self):
return self.data_model.filter(
store__translation_project=self.context)
def filter_data(self, qs):
return qs.filter(store__translation_project=self.context)
def get_last_submission(self, **kwargs):
return (
self.context.data.last_submission
and self.context.data.last_submission.get_submission_info()
or None)
def get_last_created(self, **kwargs):
return (
self.context.data.last_created_unit
and self.context.data.last_created_unit.get_last_created_unit_info()
or None)
@persistent_property
def all_checks_data(self):
return dict(self.context.check_data.values_list("name", "count"))
@persistent_property
def checks_data(self):
return dict(self.context.check_data.values_list("name", "count"))
@property
def max_unit_revision(self):
return self.context.data.max_unit_revision
class TPUpdater(object):
def __init__(self, tp, object_list):
self.tp = tp
self.object_list = object_list
def update(self):
for store in self.object_list:
update_data.send(store.__class__, instance=store)
| 5,243
|
Python
|
.py
| 135
| 31.348148
| 80
| 0.657656
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,594
|
apps.py
|
translate_pootle/pootle/apps/pootle_data/apps.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import importlib
from django.apps import AppConfig
class PootleDataConfig(AppConfig):
name = "pootle_data"
verbose_name = "Pootle Data"
version = "0.1.4"
def ready(self):
importlib.import_module("pootle_data.models")
importlib.import_module("pootle_data.getters")
importlib.import_module("pootle_data.receivers")
| 634
|
Python
|
.py
| 17
| 33.588235
| 77
| 0.733224
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,595
|
receivers.py
|
translate_pootle/pootle/apps/pootle_data/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import logging
from django.db.models.signals import post_save
from django.dispatch import receiver
from pootle.core.delegate import crud, data_tool, data_updater
from pootle.core.signals import create, delete, update, update_data
from pootle_store.models import Store
from pootle_translationproject.models import TranslationProject
from .models import StoreChecksData, StoreData, TPChecksData, TPData
logger = logging.getLogger(__name__)
@receiver(create, sender=StoreData)
def handle_store_data_obj_create(**kwargs):
crud.get(StoreData).create(**kwargs)
@receiver(create, sender=TPData)
def handle_tp_data_obj_create(**kwargs):
crud.get(TPData).create(**kwargs)
@receiver(update, sender=StoreData)
def handle_store_data_obj_update(**kwargs):
crud.get(StoreData).update(**kwargs)
@receiver(update, sender=TPData)
def handle_tp_data_obj_update(**kwargs):
crud.get(TPData).update(**kwargs)
@receiver(delete, sender=StoreChecksData)
def handle_store_checks_data_delete(**kwargs):
crud.get(StoreChecksData).delete(**kwargs)
@receiver(create, sender=StoreChecksData)
def handle_store_checks_data_create(**kwargs):
crud.get(StoreChecksData).create(**kwargs)
@receiver(update, sender=StoreChecksData)
def handle_store_checks_data_update(**kwargs):
crud.get(StoreChecksData).update(**kwargs)
@receiver(update, sender=TPChecksData)
def handle_tp_checks_data_update(**kwargs):
crud.get(TPChecksData).update(**kwargs)
@receiver(delete, sender=TPChecksData)
def handle_tp_checks_data_delete(**kwargs):
crud.get(TPChecksData).delete(**kwargs)
@receiver(create, sender=TPChecksData)
def handle_tp_checks_data_create(**kwargs):
crud.get(TPChecksData).create(**kwargs)
@receiver(post_save, sender=StoreData)
def handle_storedata_save(**kwargs):
tp = kwargs["instance"].store.translation_project
update_data.send(tp.__class__, instance=tp)
@receiver(update_data, sender=Store)
def handle_store_data_update(**kwargs):
store = kwargs.get("instance")
data_tool.get(Store)(store).update()
@receiver(update_data, sender=TranslationProject)
def handle_tp_data_update(**kwargs):
tp = kwargs["instance"]
if "object_list" in kwargs:
data_updater.get(TranslationProject)(
tp,
object_list=kwargs["object_list"]).update()
else:
data_tool.get(TranslationProject)(tp).update()
@receiver(post_save, sender=Store)
def handle_store_data_create(sender, instance, created, **kwargs):
if created:
data_updater.get(instance.data_tool.__class__)(instance.data_tool).update()
@receiver(post_save, sender=TranslationProject)
def handle_tp_data_create(sender, instance, created, **kwargs):
if created:
update_data.send(instance.__class__, instance=instance)
| 3,059
|
Python
|
.py
| 71
| 39.71831
| 83
| 0.760163
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,596
|
utils.py
|
translate_pootle/pootle/apps/pootle_data/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.db import models
from django.db.models import Sum
from django.utils.functional import cached_property
from pootle.core.decorators import persistent_property
from pootle.core.delegate import data_updater, revision
from pootle.core.signals import create, delete, update
from pootle.core.url_helpers import split_pootle_path
from pootle_statistics.models import Submission
from pootle_statistics.proxy import SubmissionProxy
from pootle_store.models import Unit
from .apps import PootleDataConfig
from .models import StoreChecksData, StoreData, TPChecksData, TPData
SUM_FIELDS = (
"critical_checks",
"total_words",
"fuzzy_words",
"translated_words",
"pending_suggestions")
class DataTool(object):
stats_mapping = dict(
total_words="total",
fuzzy_words="fuzzy",
translated_words="translated",
critical_checks="critical",
pending_suggestions="suggestions")
def __init__(self, context):
self.context = context
@property
def children_stats(self):
return {}
@property
def object_stats(self):
return {}
@property
def updater(self):
updater = data_updater.get(self.__class__)
if updater:
return updater(self)
def get_checks(self):
return {}
def get_stats(self, include_children=True, user=None):
stats = self.object_stats
if include_children:
stats["children"] = {}
if stats.get("total"):
stats["untranslated"] = stats["total"] - stats["translated"]
stats["incomplete"] = stats["total"] - stats["translated"]
return stats
def update(self, **kwargs):
if self.updater:
return self.updater.update(**kwargs)
class DataUpdater(object):
"""Set data for an object"""
sum_fields = SUM_FIELDS
aggregate_fields = ()
update_fields = (
"checks",
"critical_checks",
"last_created_unit",
"max_unit_mtime",
"max_unit_revision",
"last_submission",
"translated_words",
"total_words",
"fuzzy_words",
"pending_suggestions")
fk_fields = (
"last_created_unit",
"last_submission")
aggregate_defaults = dict(
total_words=0,
fuzzy_words=0,
translated_words=0,
critical_checks=0,
pending_suggestions=0)
def __init__(self, tool):
self.tool = tool
@property
def check_data_field(self):
return self.model._meta.get_field("check_data")
@cached_property
def data(self):
try:
return self.model.data
except self.data_field.related_model.DoesNotExist:
return self.data_field.related_model(
**{self.related_name: self.model})
@property
def data_field(self):
# one2one field
return self.model._meta.get_field("data")
@property
def model(self):
return self.tool.context
def filter_aggregate_fields(self, fields_to_get):
aggregate_fields = list(self.aggregate_fields)
for f in ["max_unit_revision", "max_unit_mtime"]:
if f not in fields_to_get:
aggregate_fields.remove(f)
return aggregate_fields
def filter_fields(self, **kwargs):
if "fields" in kwargs:
return list(
set(kwargs["fields"])
& set(self.update_fields))
return self.update_fields
def get_aggregate_data(self, fields):
fields = self.filter_aggregate_fields(fields)
if not fields:
return {}
data = self.store_data_qs.aggregate(
**self.get_aggregation(fields))
for k, v in data.items():
if v is None and k in self.aggregate_defaults:
data[k] = self.aggregate_defaults[k]
return data
def get_aggregation(self, fields):
agg_fields = self.aggregate_fields
agg = {}
if fields:
agg_fields = [
f for f
in fields
if f in fields]
for field in agg_fields:
agg.update(getattr(self, "aggregate_%s" % field))
return agg
def get_fields(self, fields_to_get):
field_data = {}
kwargs = self.get_aggregate_data(fields_to_get)
kwargs["data"] = {}
for k in fields_to_get:
field_data[k] = (
kwargs[k]
if k in kwargs
else getattr(self, "get_%s" % k)(**kwargs))
kwargs["data"].update(field_data)
return field_data
def get_max_unit_mtime(self, **kwargs):
return self.get_aggregate_data(
fields=["max_unit_mtime"])["max_unit_mtime"]
def get_max_unit_revision(self, **kwargs):
return self.get_aggregate_data(
fields=["max_unit_revision"])["max_unit_revision"]
def get_store_data(self, **kwargs):
data = self.get_fields(self.filter_fields(**kwargs))
data.update(kwargs)
data["max_unit_revision"] = data.get("max_unit_revision") or 0
return data
def set_check_data(self, store_data=None):
checks = {}
existing_checks = self.model.check_data.values_list(
"pk", "category", "name", "count")
for pk, category, name, count in existing_checks:
checks[(category, name)] = (pk, count)
to_update = []
to_add = []
for check in store_data["checks"]:
category = check["category"]
name = check["name"]
count = check["count"]
check_exists = (
checks.get((category, name)))
if not check_exists:
to_add.append(check)
continue
elif checks[(category, name)][1] != count:
to_update.append((checks[(category, name)][0], dict(count=count)))
del checks[(category, name)]
check_data = None
for category, name in checks.keys():
if check_data is None:
check_data = self.model.check_data.filter(
category=category, name=name)
else:
check_data = check_data | self.model.check_data.filter(
category=category, name=name)
if checks:
delete.send(check_data.model, objects=check_data)
if to_update:
to_update = dict(to_update)
update.send(
self.model.check_data.model,
updates=to_update)
if not to_add:
return
create.send(
self.model.check_data.model,
objects=[
self.check_data_field.related_model(
**{self.related_name: self.model,
"category": check["category"],
"name": check["name"],
"count": check["count"]})
for check in to_add])
def set_data(self, k, v):
k = (k in self.fk_fields
and "%s_id" % k
or k)
if not hasattr(self.data, k):
return
existing_value = getattr(self.data, k)
if existing_value != v:
setattr(self.data, k, v)
return k
def update(self, **kwargs):
store_data = self.get_store_data(**kwargs)
data_changed = set(
filter(
None,
[self.set_data(k, store_data[k])
for k
in self.filter_fields(**kwargs)]))
# set the checks
if "checks" in store_data:
self.set_check_data(store_data)
if not self.data.pk:
create.send(
self.data.__class__,
instance=self.data)
self.model.data = self.data
elif data_changed:
self.save_data(fields=data_changed)
def save_data(self, fields=None):
update.send(
self.data.__class__,
instance=self.data,
update_fields=fields)
# this ensures that any calling code gets the
# correct revision. It doesnt refresh the last
# created/updated fks tho
self.model.data = self.data
class RelatedStoresDataTool(DataTool):
ns = "pootle.data"
group_by = (
"store__pootle_path", )
max_fields = (
"last_submission__pk",
"last_created_unit__pk")
sum_fields = SUM_FIELDS
submission_fields = (
("pk", )
+ SubmissionProxy.info_fields)
@property
def aggregate_sum_fields(self):
return list(
models.Sum(f)
for f
in self.sum_fields)
@property
def aggregate_max_fields(self):
return list(
models.Max(f)
for f
in self.max_fields)
@persistent_property
def all_checks_data(self):
return dict(
self.filter_data(self.checks_data_model).values_list(
"name").annotate(Sum("count")))
@persistent_property
def all_children_stats(self):
return self.get_children_stats(self.all_child_stats_qs)
@property
def all_child_stats_qs(self):
"""Aggregates grouped sum/max fields"""
return self.annotate_fields(self.all_stat_data)
@persistent_property
def all_object_stats(self):
return self.get_object_stats(self.all_stat_data)
@property
def all_stat_data(self):
return self.filter_data(self.data_model)
@property
def rev_cache_key(self):
return revision.get(
self.context.__class__)(self.context).get(key="stats")
@property
def sw_version(self):
return PootleDataConfig.version
@cached_property
def cache_key(self):
return (
'%s.%s.%s'
% (self.cache_key_name,
self.context_name,
self.rev_cache_key))
@property
def child_stats_qs(self):
"""Aggregates grouped sum/max fields"""
return self.annotate_fields(self.stat_data)
@property
def context_name(self):
return self.context.code
@property
def data_model(self):
return StoreData.objects
@property
def dir_path(self):
return split_pootle_path(self.context.pootle_path)[2]
@persistent_property
def checks_data(self):
return dict(
self.filter_accessible(
self.filter_data(self.checks_data_model).values_list(
"name").annotate(Sum("count"))))
@property
def checks_data_model(self):
return StoreChecksData.objects
@persistent_property
def children_stats(self):
"""For a given object returns stats for each of the objects
immediate descendants
"""
return self.get_children_stats(self.child_stats_qs)
@property
def filename(self):
return split_pootle_path(self.context.pootle_path)[3]
@persistent_property
def object_stats(self):
return self.get_object_stats(self.stat_data)
@property
def project_code(self):
return split_pootle_path(self.context.pootle_path)[1]
@property
def stat_data(self):
return self.filter_accessible(self.all_stat_data)
def filter_accessible(self, qs):
return (
qs.exclude(store__translation_project__project__disabled=True)
.exclude(store__obsolete=True))
def filter_data(self, qs):
return qs
def add_last_created_info(self, stat_data, children):
updated = self.get_last_created_for_children(stat_data, children)
for k, v in children.items():
children[k]["last_created_unit"] = updated.get(
children[k]["last_created_unit__pk"])
del children[k]["last_created_unit__pk"]
def add_submission_info(self, stat_data, children):
"""For a given qs.values of child stats data, updates the values
with submission info
"""
subs = self.get_submissions_for_children(stat_data, children)
for child in children.values():
add_sub_info = (
child["last_submission__pk"]
and subs.get(child["last_submission__pk"]))
if add_sub_info:
child["last_submission"] = self.get_info_for_sub(
subs[child["last_submission__pk"]])
def aggregate_children(self, stats):
"""For a stats dictionary containing children qs.values, aggregate the
children to calculate the sum/max for the context
"""
agg = dict(
total=0, fuzzy=0, translated=0, critical=0, suggestions=0)
latest = dict(last_submission=None, last_created_unit=None)
last_submission_pk = None
last_created_unit_time = None
for path, child in stats["children"].items():
if path.startswith("templates-") or path == "templates":
if not self.context.pootle_path.startswith("/templates/"):
del child["last_submission__pk"]
continue
for k in agg.keys():
agg[k] += child[k]
if child.get("last_created_unit"):
last_created = child["last_created_unit"]
if last_created["creation_time"] > last_created_unit_time:
latest["last_created_unit"] = last_created
last_created_unit_time = last_created["creation_time"]
if child["last_submission__pk"] > last_submission_pk:
latest['last_submission'] = child["last_submission"]
last_submission_pk = child["last_submission__pk"]
del child["last_submission__pk"]
stats.update(agg)
stats.update(latest)
return stats
def annotate_fields(self, stat_data):
return (
stat_data.values(*self.group_by)
.annotate(*(self.aggregate_sum_fields
+ self.aggregate_max_fields)))
def get_checks(self, user=None):
return (
self.all_checks_data
if self.show_all_to(user)
else self.checks_data)
def get_children_stats(self, qs):
children = {}
for child in qs.iterator():
self.add_child_stats(children, child)
self.add_submission_info(qs, children)
self.add_last_created_info(qs, children)
return children
def get_info_for_sub(self, sub):
"""Uses a SubmissionProxy to turn the member of a qs.values
into submission_info
"""
return SubmissionProxy(sub).get_submission_info()
def get_root_child_path(self, child):
"""For a given child returns the label for its root node (ie the parent
node which is the immediate descendant of the context).
"""
return child[self.group_by[0]]
@persistent_property
def aggregated_children_stats(self):
stats = dict(children=self.children_stats)
self.aggregate_children(stats)
return stats
@persistent_property
def all_aggregated_children_stats(self):
stats = dict(children=self.all_children_stats)
self.aggregate_children(stats)
return stats
def get_stats(self, include_children=True, aggregate=True, user=None):
"""Get stats for an object. If include_children is set it will
also return stats for each of the immediate descendants.
"""
if include_children:
if aggregate:
stats = (
self.all_aggregated_children_stats
if self.show_all_to(user)
else self.aggregated_children_stats)
else:
stats = (
self.all_children_stats
if self.show_all_to(user)
else self.children_stats)
else:
stats = (
self.all_object_stats
if self.show_all_to(user)
else self.object_stats)
add_untranslated = (
stats.get("total") is not None
and not self.context.pootle_path.startswith("/templates/"))
if add_untranslated:
stats["untranslated"] = stats["total"] - stats["translated"]
stats["incomplete"] = stats["total"] - stats["translated"]
return stats
def get_submissions_for_children(self, stat_data, children):
"""For a given qs.values of children returns a qs.values
of related last_submission data
"""
last_submissions = [
v["last_submission__pk"]
for v in children.values()]
subs = Submission.objects.filter(pk__in=last_submissions).order_by()
subs = subs.values(
*[field
for field
in self.submission_fields])
return {sub["pk"]: sub for sub in subs}
def get_last_created_for_children(self, stat_data, children):
last_created_units = set(
[v["last_created_unit__pk"] for v in children.values()])
return {
unit.pk: unit.get_last_created_unit_info()
for unit
in Unit.objects.select_related(
"store").filter(pk__in=last_created_units)}
def add_child_stats(self, children, child, root=None, use_aggregates=True):
"""For a child member of children qs.values, add the childs stats to aggregate
stats for the child' root node (ie the parent node which is the immediate
descendant of the context).
"""
root = root or self.get_root_child_path(child)
children[root] = children.get(
root,
dict(critical=0,
total=0,
fuzzy=0,
translated=0,
suggestions=0))
for k in self.sum_fields:
child_k = (
k if not use_aggregates
else "%s__sum" % k)
mapped_k = self.stats_mapping.get(k, k)
children[root][mapped_k] += child[child_k]
for k in self.max_fields:
child_k = (
k if not use_aggregates
else "%s__max" % k)
mapped_k = self.stats_mapping.get(k, k)
update_max = (
mapped_k not in children[root]
or (child[child_k]
and (child[child_k] > children[root][mapped_k])))
if update_max:
children[root][mapped_k] = child[child_k]
return root
def get_object_stats(self, stat_data):
stats = {
k[:-5]: v
for k, v
in stat_data.aggregate(*self.aggregate_sum_fields).items()}
stats = {
self.stats_mapping.get(k, k): v
for k, v
in stats.items()}
stats["last_submission"] = None
stats["last_created_unit"] = None
stats["suggestions"] = None
return stats
def show_all_to(self, user):
return user and user.is_superuser
class RelatedTPsDataTool(RelatedStoresDataTool):
group_by = (
"tp__language__code",
"tp__project__code")
@property
def data_model(self):
return TPData.objects
def filter_accessible(self, qs):
return qs.exclude(tp__project__disabled=True)
@property
def checks_data_model(self):
return TPChecksData.objects
def get_root_child_path(self, child):
return "-".join(child[field] for field in self.group_by)
| 19,880
|
Python
|
.py
| 531
| 27.305085
| 86
| 0.580972
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,597
|
__init__.py
|
translate_pootle/pootle/apps/pootle_data/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
default_app_config = 'pootle_data.apps.PootleDataConfig'
| 333
|
Python
|
.py
| 8
| 40.5
| 77
| 0.765432
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,598
|
store_data.py
|
translate_pootle/pootle/apps/pootle_data/store_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from translate.filters.decorators import Category
from django.db import models
from django.db.models import Case, Count, Max, Q, When
from pootle.core.bulk import BulkCRUD
from pootle.core.signals import update_data, update_revisions
from pootle_statistics.models import Submission
from pootle_store.constants import FUZZY, OBSOLETE, TRANSLATED
from pootle_store.models import QualityCheck
from .models import StoreChecksData, StoreData
from .utils import DataTool, DataUpdater
class StoreDataCRUD(BulkCRUD):
model = StoreData
def update_tps_and_revisions(self, stores):
tps = {}
for store in stores:
if store.translation_project_id not in tps:
tps[store.translation_project_id] = store.translation_project
update_revisions.send(
store.__class__,
instance=store,
keys=["stats", "checks"])
for tp in tps.values():
update_data.send(
tp.__class__,
instance=tp)
def post_create(self, instance=None, objects=None, pre=None, result=None):
if objects:
self.update_tps_and_revisions(set(result.store for data in objects))
def post_update(self, instance=None, objects=None, pre=None, result=None):
if objects:
self.update_tps_and_revisions(set(data.store for data in objects))
class StoreChecksDataCRUD(BulkCRUD):
model = StoreChecksData
class StoreDataTool(DataTool):
"""Sets the stats for a store"""
@property
def object_stats(self):
stats = {
v: getattr(self.context.data, k)
for k, v in self.stats_mapping.items()}
stats["children"] = {}
stats["last_submission"] = (
self.context.data.last_submission
and self.context.data.last_submission.get_submission_info()
or None)
stats["last_created_unit"] = (
self.context.data.last_created_unit
and self.context.data.last_created_unit.get_last_created_unit_info()
or None)
return stats
def get_checks(self, **kwargs):
return dict(self.context.check_data.values_list("name", "count"))
class StoreDataUpdater(DataUpdater):
related_name = "store"
aggregate_fields = (
"words",
"max_unit_revision",
"max_unit_mtime")
@property
def store(self):
return self.model
@property
def store_data_qs(self):
return self.store.unit_set
@property
def units(self):
"""Non-obsolete units in this Store"""
return self.store_data_qs.filter(state__gt=OBSOLETE)
@property
def aggregate_words(self):
return dict(
total_words=models.Sum(
Case(
When(Q(state__gt=OBSOLETE)
& Q(unit_source__source_wordcount__gt=0),
then="unit_source__source_wordcount"),
default=0)),
translated_words=models.Sum(
Case(
When(Q(state=TRANSLATED)
& Q(unit_source__source_wordcount__gt=0),
then="unit_source__source_wordcount"),
default=0)),
fuzzy_words=models.Sum(
Case(
When(Q(state=FUZZY)
& Q(unit_source__source_wordcount__gt=0),
then="unit_source__source_wordcount"),
default=0)))
@property
def aggregate_max_unit_revision(self):
return dict(max_unit_revision=Max("revision"))
@property
def aggregate_max_unit_mtime(self):
return dict(max_unit_mtime=Max("mtime"))
def get_last_created_unit(self, **kwargs):
order_by = ("-creation_time", "-revision", "-id")
units = self.store.unit_set.filter(
state__gt=OBSOLETE, creation_time__isnull=False)
return units.order_by(*order_by).values_list("id", flat=True).first()
def get_critical_checks(self, **kwargs):
return sum(
check["count"]
for check
in kwargs["data"]["checks"]
if check["category"] == Category.CRITICAL)
def get_checks(self, **kwargs):
if self.store.obsolete:
return []
return (
QualityCheck.objects.exclude(false_positive=True)
.filter(unit__store_id=self.store.id)
.filter(unit__state__gt=OBSOLETE)
.values("category", "name")
.annotate(count=Count("id")))
def get_last_submission(self, **kwargs):
"""Last submission for this store"""
submissions = Submission.objects.filter(unit__store_id=self.store.id)
try:
return (
submissions.values_list("pk", flat=True)
.latest())
except submissions.model.DoesNotExist:
return None
def get_pending_suggestions(self, **kwargs):
"""Return the count of pending suggestions for the store"""
return (
self.units.filter(suggestion__state__name="pending")
.values_list("suggestion").count())
def get_store_data(self, **kwargs):
if self.store.obsolete:
kwargs["fields"] = (
"checks",
"last_created_unit",
"max_unit_mtime",
"max_unit_revision",
"last_submission")
data = super(StoreDataUpdater, self).get_store_data(**kwargs)
if self.store.obsolete:
data.update(self.aggregate_defaults)
return data
| 5,994
|
Python
|
.py
| 148
| 29.797297
| 80
| 0.591261
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,599
|
project_data.py
|
translate_pootle/pootle/apps/pootle_data/project_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.delegate import revision
from .utils import RelatedStoresDataTool, RelatedTPsDataTool
class ProjectDataTool(RelatedTPsDataTool):
"""Retrieves aggregate stats for a Project"""
cache_key_name = "project"
def filter_data(self, qs):
qs = qs.exclude(tp__language__code="templates")
return qs.filter(tp__project=self.context)
@property
def rev_cache_key(self):
return revision.get(
self.context.__class__)(self.context.directory).get(key="stats")
class ProjectResourceDataTool(RelatedStoresDataTool):
group_by = ("store__translation_project__language__code", )
cache_key_name = "project_resource"
@property
def project_path(self):
return (
"/%s%s"
% (self.project_code, self.tp_path))
@property
def tp_path(self):
return (
"/%s%s"
% (self.dir_path,
self.filename))
def filter_data(self, qs):
return (
qs.filter(store__translation_project__project__code=self.project_code)
.filter(store__tp_path__startswith=self.tp_path))
@property
def context_name(self):
return "/projects%s" % self.project_path
class ProjectSetDataTool(RelatedTPsDataTool):
group_by = ("tp__project__code", )
cache_key_name = "projects"
def get_root_child_path(self, child):
return child[self.group_by[0]]
@property
def context_name(self):
return "ALL"
def filter_data(self, qs):
qs = super(ProjectSetDataTool, self).filter_data(qs)
return qs.exclude(tp__language__code="templates")
| 1,925
|
Python
|
.py
| 51
| 31.117647
| 82
| 0.662177
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|