Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_creation(self):
link = self.component.get_repo_link_url()
self.assertEqual(Component.objects.filter(repo=link).count(), 0)
addon = DiscoveryAddon.create(
self.component,
configuration={
'file_format': 'po',
'match': r'(?P[^/]*)/(?P[^/]*)\.po',
'name_template': '{{ component|title }}',
'language_regex': '^(?!xx).*$',
'base_file_template': '',
'remove': True,
},
)
self.assertEqual(Component.objects.filter(repo=link).count(), 3)
addon.post_update(self.component, '')
self.assertEqual(Component.objects.filter(repo=link).count(), 3)
# Get name and slug
name = get_val('name')
slug = get_val('slug')
# Copy attributes from main component
for key in COPY_ATTRIBUTES:
if key not in kwargs and main is not None:
kwargs[key] = getattr(main, key)
# Fill in repository
if 'repo' not in kwargs:
kwargs['repo'] = main.get_repo_link_url()
# Deal with duplicate name or slug
components = Component.objects.filter(project=kwargs['project'])
if components.filter(Q(slug=slug) | Q(name=name)).exists():
base_name = get_val('name', 4)
base_slug = get_val('slug', 4)
for i in range(1, 1000):
name = '{} {}'.format(base_name, i)
slug = '{}-{}'.format(base_slug, i)
if components.filter(Q(slug=slug) | Q(name=name)).exists():
continue
break
# Fill in remaining attributes
kwargs.update({
'name': name,
'slug': slug,
def handle(self, *args, **options): # noqa: C901
"""Automatic import of components."""
# Get project
try:
project = Project.objects.get(slug=options['project'])
except Project.DoesNotExist:
raise CommandError('Project does not exist!')
# Get main component
main_component = None
if options['main_component']:
try:
main_component = Component.objects.get(
project=project,
slug=options['main_component']
)
except Component.DoesNotExist:
raise CommandError('Main component does not exist!')
try:
data = json.load(options['json-file'])
except ValueError:
raise CommandError('Failed to parse JSON file!')
finally:
options['json-file'].close()
allfields = {
field.name
for field in Component._meta.get_fields()
def widgets(request, project):
obj = get_project(request, project)
# Parse possible language selection
form = EngageForm(obj, request.GET)
lang = None
component = None
if form.is_valid():
if form.cleaned_data['lang']:
lang = Language.objects.get(code=form.cleaned_data['lang']).code
if form.cleaned_data['component']:
component = Component.objects.get(
slug=form.cleaned_data['component'],
project=obj
).slug
kwargs = {'project': obj.slug}
if lang is not None:
kwargs['lang'] = lang
engage_url = get_site_url(reverse('engage', kwargs=kwargs))
engage_url_track = '{0}?utm_source=widget'.format(engage_url)
engage_link = mark_safe(
'<a id="engage-link" href="{0}">{0}</a>'.format(escape(engage_url))
)
widget_base_url = get_site_url(
reverse('widgets', kwargs={'project': obj.slug})
)
widget_list = []
class NotificationForm(forms.Form):
scope = forms.ChoiceField(
choices=SCOPE_CHOICES,
widget=forms.HiddenInput,
required=True
)
project = forms.ModelChoiceField(
widget=forms.HiddenInput,
queryset=Project.objects.none(),
required=False,
)
component = forms.ModelChoiceField(
widget=forms.HiddenInput,
queryset=Component.objects.none(),
required=False,
)
def __init__(self, user, show_default, subscriptions, is_active,
*args, **kwargs):
super(NotificationForm, self).__init__(*args, **kwargs)
self.user = user
self.is_active = is_active
self.show_default = show_default
self.fields['project'].queryset = user.allowed_projects
self.fields['component'].queryset = Component.objects.filter(
project__in=user.allowed_projects
)
language_fields = []
component_fields = []
for field, notification_cls in self.notification_fields():
def get_form(self, form_class=None, empty=False):
form = super(CreateComponentSelection, self).get_form(form_class, empty=empty)
if isinstance(form, ComponentBranchForm):
form.fields['component'].queryset = Component.objects.filter(
pk__in=self.branch_data.keys()
)
form.branch_data = self.branch_data
form.auto_id = "id_branch_%s"
elif isinstance(form, ComponentSelectForm):
form.fields['component'].queryset = self.components
form.auto_id = "id_existing_%s"
return form
def __init__(self, user, obj, *args, **kwargs):
"""Generate choices for other component in same project."""
other_components = obj.component.project.component_set.exclude(
id=obj.component.id
)
choices = [(s.id, force_text(s)) for s in other_components]
# Add components from other owned projects
owned_components = Component.objects.filter(
project__in=user.owned_projects,
).exclude(
project=obj.component.project
).distinct()
for component in owned_components:
choices.append(
(component.id, force_text(component))
)
super(AutoForm, self).__init__(*args, **kwargs)
self.fields['component'].choices = \
[('', _('All components in current project'))] + choices
self.fields['engines'].choices = [
(key, mt.name) for key, mt in MACHINE_TRANSLATION_SERVICES.items()
]
def get_components(self, **options):
"""Return list of components matching parameters."""
if options['all']:
# all components
if self.needs_repo:
result = Component.objects.exclude(
repo__startswith='weblate:/'
)
else:
result = Component.objects.all()
elif not options['component']:
# no argumets to filter projects
self.stderr.write(
'Please specify either --all '
'or at least one '
)
raise CommandError('Nothing to process!')
else:
# start with none and add found
result = Component.objects.none()
# process arguments
# users from older system
if user.is_authenticated and (not user.full_name or not user.email):
messages.warning(
request,
mark_safe('<a href="{0}">{1}</a>'.format(
reverse('profile') + '#account',
escape(
_('Please set your full name and e-mail in your profile.')
)
))
)
# Redirect to single project or component
if settings.SINGLE_PROJECT:
if Component.objects.count() == 1:
return redirect(Component.objects.first())
if Project.objects.count() == 1:
return redirect(Project.objects.first())
if not user.is_authenticated:
return dashboard_anonymous(request)
return dashboard_user(request)
def fetch_params(self, request):
super(CreateComponentSelection, self).fetch_params(request)
self.components = Component.objects.with_repo().prefetch().filter(
project__in=self.projects
)
if self.selected_project:
self.components = self.components.filter(project__pk=self.selected_project)
self.origin = request.POST.get('origin')