summaryrefslogtreecommitdiffstats
path: root/askbot/management/commands/apply_hinted_tags.py
blob: 94bf23839c3ddb3a71b51ea5eaae54d60600649c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import datetime
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from optparse import make_option
from askbot.utils.console import ProgressBar
from askbot.models import Thread
from askbot.models import User

class Command(BaseCommand):
    help = """Adds tags to questions. Tags should be given via a file
    with one tag per line. The tags will be matched with the words
    found in the question title. Then, most frequently used matching tags
    will be applied. This command respects the maximum number of tags
    allowed per question.
    """
    option_list = BaseCommand.option_list + (
        make_option('--tags-file', '-t',
            action = 'store',
            type = 'str',
            dest = 'tags_file',
            default = None,
            help = 'file containing tag names, one per line'
        ),
    )
    def handle(self, *args, **kwargs):
        """reads the tags file, parses it,
        then applies tags to questions by matching them
        with the question titles and content
        """
        if kwargs['tags_file'] is None:
            raise CommandError('parameter --tags-file is required')
        try:
            tags_input = open(kwargs['tags_file']).read()
        except IOError:
            raise CommandError('file "%s" not found' % kwargs['tags_file'])

        tags_list = map(lambda v: v.strip(), tags_input.split('\n'))

        multiword_tags = list()
        for tag in tags_list:
            if ' ' in tag:
                multiword_tags.append(tag)

        if len(multiword_tags):
            message = 'multiword tags tags not allowed, have: %s' % ', '.join(multiword_tags)
            raise CommandError(message)

        threads = Thread.objects.all()
        count = threads.count()
        message = 'Applying tags to questions'

        user = User.objects.all().order_by('-id')[0]
        now = datetime.datetime.now()

        for thread in ProgressBar(threads.iterator(), count, message):
            thread.apply_hinted_tags(
                tags_list, user=user, timestamp=now, silent=True
            )