<commit_before>import copy
import threading
import warnings
from django.utils.encoding import force_unicode
from django.core.exceptions import ImproperlyConfigured
from haystack import connections, connection_router
from haystack.constants import ID, DJANGO_CT, DJANGO_ID, Indexable, DEFAULT_ALIAS
from haystack.fields import *
from haystack.manager import HaystackManager
from haystack.utils import get_identifier, get_facet_field_name


class DeclarativeMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['fields'] = {}

        # Inherit any fields from parent(s).
        try:
            parents = [b for b in bases if issubclass(b, SearchIndex)]
            # Simulate the MRO.
            parents.reverse()

            for p in parents:
                fields = getattr(p, 'fields', None)

                if fields:
                    attrs['fields'].update(fields)
        except NameError:
            pass

        # Build a dictionary of faceted fields for cross-referencing.
        facet_fields = {}

        for field_name, obj in attrs.items():
            # Only need to check the FacetFields.
            if hasattr(obj, 'facet_for'):
                if not obj.facet_for in facet_fields:
                    facet_fields[obj.facet_for] = []

                facet_fields[obj.facet_for].append(field_name)

        for field_name, obj in attrs.items():
            if isinstance(obj, SearchField):
                field = attrs.pop(field_name)
                field.set_instance_name(field_name)
                attrs['fields'][field_name] = field

                # Only check non-faceted fields for the following info.
                if not hasattr(field, 'facet_for'):
                    if field.faceted == True:
                        # If no other field is claiming this field as
                        # ``facet_for``, create a shadow ``FacetField``.
                        if not field_name in facet_fields:
                            shadow_facet_name = get_facet_field_name(field_name)
                            shadow_facet_field = field.facet_class(facet_for=field_name)
                            shadow_facet_field.set_instance_name(shadow_facet_name)
                            attrs['fields'][shadow_facet_name] = shadow_facet_field

        # Assigning default 'objects' query manager if it does not already exist
        if not attrs.has_key('objects'):
            try:
                attrs['objects'] = HaystackManager(attrs['Meta'].index_label)
            except KeyError:
                attrs['objects'] = HaystackManager(DEFAULT_ALIAS)
            
        return super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs)


class SearchIndex(threading.local):
    """
    Base class for building indexes.

    An example might look like this::

        import datetime
        from haystack import indexes
        from myapp.models import Note

        class NoteIndex(indexes.SearchIndex, indexes.Indexable):
            text = indexes.CharField(document=True, use_template=True)
            author = indexes.CharField(model_attr='user')
            pub_date = indexes.DateTimeField(model_attr='pub_date')

            def get_model(self):
                return Note

            def index_queryset(self, using=None):
                return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())

    """
    __metaclass__ = DeclarativeMetaclass
<commit_msg>Fixed the case where index_name isn't available.<commit_after>import copy
import threading
import warnings
from django.utils.encoding import force_unicode
from django.core.exceptions import ImproperlyConfigured
from haystack import connections, connection_router
from haystack.constants import ID, DJANGO_CT, DJANGO_ID, Indexable, DEFAULT_ALIAS
from haystack.fields import *
from haystack.manager import HaystackManager
from haystack.utils import get_identifier, get_facet_field_name


class DeclarativeMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['fields'] = {}

        # Inherit any fields from parent(s).
        try:
            parents = [b for b in bases if issubclass(b, SearchIndex)]
            # Simulate the MRO.
            parents.reverse()

            for p in parents:
                fields = getattr(p, 'fields', None)

                if fields:
                    attrs['fields'].update(fields)
        except NameError:
            pass

        # Build a dictionary of faceted fields for cross-referencing.
        facet_fields = {}

        for field_name, obj in attrs.items():
            # Only need to check the FacetFields.
            if hasattr(obj, 'facet_for'):
                if not obj.facet_for in facet_fields:
                    facet_fields[obj.facet_for] = []

                facet_fields[obj.facet_for].append(field_name)

        for field_name, obj in attrs.items():
            if isinstance(obj, SearchField):
                field = attrs.pop(field_name)
                field.set_instance_name(field_name)
                attrs['fields'][field_name] = field

                # Only check non-faceted fields for the following info.
                if not hasattr(field, 'facet_for'):
                    if field.faceted == True:
                        # If no other field is claiming this field as
                        # ``facet_for``, create a shadow ``FacetField``.
                        if not field_name in facet_fields:
                            shadow_facet_name = get_facet_field_name(field_name)
                            shadow_facet_field = field.facet_class(facet_for=field_name)
                            shadow_facet_field.set_instance_name(shadow_facet_name)
                            attrs['fields'][shadow_facet_name] = shadow_facet_field

        # Assigning default 'objects' query manager if it does not already exist
        if not attrs.has_key('objects'):
            try:
                attrs['objects'] = HaystackManager(attrs['Meta'].index_label)
            except (KeyError, AttributeError):
                attrs['objects'] = HaystackManager(DEFAULT_ALIAS)

        return super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs)


class SearchIndex(threading.local):
    """
    Base class for building indexes.

    An example might look like this::

        import datetime
        from haystack import indexes
        from myapp.models import Note

        class NoteIndex(indexes.SearchIndex, indexes.Indexable):
            text = indexes.CharField(document=True, use_template=True)
            author = indexes.CharField(model_attr='user')
            pub_date = indexes.DateTimeField(model_attr='pub_date')

            def get_model(self):
                return Note

            def index_queryset(self, using=None):
                return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())

    """
    __metaclass__ = DeclarativeMetaclass

{'fraction_non_alphanumeric': 0.07767408470926059, 'fraction_numerical': 0.0, 'mean_word_length': 2.116778523489933, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '69731', 'n_tokens_mistral': 1892, 'n_tokens_neox': 1825, 'n_words': 477}