flexget.plugins.module_try_regexp
Covered: 19 lines
Missed: 36 lines
Skipped 12 lines
Percent: 34 %
 1
import logging
 2
import re
 3
from flexget.plugin import *
 5
log = logging.getLogger('try_regexp')
 8
class PluginTryRegexp:
 9
    """
10
        This plugin allows user to test regexps for a feed.
11
    """
13
    def __init__(self):
14
        self.abort = False
16
    def validator(self):
18
        from flexget import validator
19
        return validator.factory('any')
21
    def matches(self, entry, regexp):
22
        """Return True if any of the entry string fields match given regexp"""
23
        for field, value in entry.iteritems():
24
            if not isinstance(value, basestring):
25
                continue
26
            if re.search(regexp, value, re.IGNORECASE | re.UNICODE):
27
                return (True, field)
28
        return (False, None)
30
    def on_feed_filter(self, feed):
31
        if not feed.manager.options.try_regexp and not 'try_regexp' in feed.config:
32
            return
33
        if self.abort: 
34
            return
36
        print '-' * 79
37
        print 'Hi there, welcome to try regexps in realtime!'
38
        print 'Press ^D or type \'exit\' to continue. Type \'continue\' to continue non-interactive execution.'
39
        print 'Feed \'%s\' has %s entries, enter regexp to see what matches it.' % (feed.name, len(feed.entries))
40
        while (True):
41
            try:
42
                s = raw_input('--> ')
43
                if s == 'exit':
44
                    break
45
                if s == 'abort' or s == 'continue':
46
                    self.abort = True
47
                    break
48
            except EOFError:
49
                break
51
            count = 0
52
            for entry in feed.entries:
53
                try:
54
                    match, field = self.matches(entry, s)
55
                    if match:
56
                        print 'Title: %-40s URL: %-30s From: %s' % (entry['title'], entry['url'], field)
57
                        count += 1
58
                except:
59
                    print 'Invalid regular expression'
60
                    break
61
            print '%s of %s entries matched' % (count, len(feed.entries))
62
        print 'Bye!'
64
register_plugin(PluginTryRegexp, '--try-regexp', builtin=True)
65
register_parser_option('--try-regexp', action='store_true', dest='try_regexp', default=False,
66
                       help='Try regular expressions interactively.')