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