<commit_before># -*- coding: utf-8 -*-

# Copyright 2014,  Digital Reasoning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import logging
from urlparse import urlsplit, urlunsplit

from rest_framework import serializers

from stackdio.core.fields import PasswordField
from stackdio.core.mixins import CreateOnlyFieldsMixin
from stackdio.core.serializers import StackdioHyperlinkedModelSerializer
from stackdio.core.utils import recursively_sort_dict
from . import models, tasks, validators


logger = logging.getLogger(__name__)


class FormulaSerializer(CreateOnlyFieldsMixin, StackdioHyperlinkedModelSerializer):
    # Non-model fields
    git_password = PasswordField(write_only=True, required=False,
                                 allow_blank=True, label='Git Password')

    # Link fields
    properties = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-properties')
    components = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-component-list')
    valid_versions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-valid-version-list')
    action = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-action')
    user_permissions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-object-user-permissions-list')
    group_permissions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-object-group-permissions-list')

    class Meta:
        model = models.Formula
        fields = (
            'id',
            'url',
            'title',
            'description',
            'uri',
            'private_git_repo',
            'git_username',
            'git_password',
            'access_token',
            'root_path',
            'created',
            'modified',
            'status',
            'status_detail',
            'properties',
            'components',
            'valid_versions',
            'action',
            'user_permissions',
            'group_permissions',
        )

        read_only_fields = (
            'title',
            'description',
            'private_git_repo',
            'root_path',
            'status',
            'status_detail',
        )

        create_only_fields = (
            'uri',
            'git_password',
        )

        extra_kwargs = {
            'access_token': {'default': serializers.CreateOnlyDefault(False)},
        }

    def validate(self, attrs):
        git_username = attrs.get('git_username')

        errors = {}

        if git_username:
            # We only need validation if a non-empty username is provided

            # We only care about this if we're importing
            access_token = attrs.get('access_token')
            git_password = attrs.get('git_password')

            if not access_token and not git_password:
                err_msg = 'Your git password is required if you\'re not using an access token.'
                errors.setdefault('access_token', []).append(err_msg)
                errors.setdefault('git_password', []).append(err_msg)

            if access_token and git_password:
                err_msg = 'If you are using an access_token, you may not provide a password.'
                errors.setdefault('access_token', []).append(err_msg)
                errors.setdefault('git_password', []).append(err_msg)

        if self.instance:
            uri = attrs.get('uri') if 'uri' in attrs else self.instance.uri
        else:
            uri = attrs['uri']

        # Remove the git username from the uri if necessary
        parse_res = urlsplit(uri)
        if '@' in parse_res.netloc:
            new_netloc = parse_res.netloc.split('@')[-1]
            attrs['uri'] = urlunsplit((
                parse_res.scheme,
                new_netloc,
                parse_res.path,
                parse_res.query,
                parse_res.fragment
            ))<commit_msg>Fixed logic error in formula serializer<commit_after># -*- coding: utf-8 -*-

# Copyright 2014,  Digital Reasoning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import logging
from urlparse import urlsplit, urlunsplit

from rest_framework import serializers

from stackdio.core.fields import PasswordField
from stackdio.core.mixins import CreateOnlyFieldsMixin
from stackdio.core.serializers import StackdioHyperlinkedModelSerializer
from stackdio.core.utils import recursively_sort_dict
from . import models, tasks, validators


logger = logging.getLogger(__name__)


class FormulaSerializer(CreateOnlyFieldsMixin, StackdioHyperlinkedModelSerializer):
    # Non-model fields
    git_password = PasswordField(write_only=True, required=False,
                                 allow_blank=True, label='Git Password')

    # Link fields
    properties = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-properties')
    components = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-component-list')
    valid_versions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-valid-version-list')
    action = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-action')
    user_permissions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-object-user-permissions-list')
    group_permissions = serializers.HyperlinkedIdentityField(
        view_name='api:formulas:formula-object-group-permissions-list')

    class Meta:
        model = models.Formula
        fields = (
            'id',
            'url',
            'title',
            'description',
            'uri',
            'private_git_repo',
            'git_username',
            'git_password',
            'access_token',
            'root_path',
            'created',
            'modified',
            'status',
            'status_detail',
            'properties',
            'components',
            'valid_versions',
            'action',
            'user_permissions',
            'group_permissions',
        )

        read_only_fields = (
            'title',
            'description',
            'private_git_repo',
            'root_path',
            'status',
            'status_detail',
        )

        create_only_fields = (
            'uri',
            'git_password',
        )

        extra_kwargs = {
            'access_token': {'default': serializers.CreateOnlyDefault(False)},
        }

    def validate(self, attrs):
        git_username = attrs.get('git_username')

        errors = {}

        if git_username and not self.instance:
            # We only need validation if a non-empty username is provided
            # We only care about this if we're importing
            access_token = attrs.get('access_token')
            git_password = attrs.get('git_password')

            if not access_token and not git_password:
                err_msg = 'Your git password is required if you\'re not using an access token.'
                errors.setdefault('access_token', []).append(err_msg)
                errors.setdefault('git_password', []).append(err_msg)

            if access_token and git_password:
                err_msg = 'If you are using an access_token, you may not provide a password.'
                errors.setdefault('access_token', []).append(err_msg)
                errors.setdefault('git_password', []).append(err_msg)

        if self.instance:
            uri = attrs.get('uri') if 'uri' in attrs else self.instance.uri
        else:
            uri = attrs['uri']

        # Remove the git username from the uri if necessary
        parse_res = urlsplit(uri)
        if '@' in parse_res.netloc:
            new_netloc = parse_res.netloc.split('@')[-1]
            attrs['uri'] = urlunsplit((
                parse_res.scheme,
                new_netloc,
                parse_res.path,
                parse_res.query,
                parse_res.fragment
            ))
{'fraction_non_alphanumeric': 0.09036610994359032, 'fraction_numerical': 0.002212144674261697, 'mean_word_length': 2.272529858849077, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2121347', 'n_tokens_mistral': 2423, 'n_tokens_neox': 2349, 'n_words': 606}