Name callbacks to ease debugging
[gsh.git] / gsh / callbacks.py
blob67421a9dcc61a61a59d69a17008f6ee8c38e10a0
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2008 Guillaume Chazarain <guichaz@gmail.com>
19 import random
21 DIGITS_LETTERS = map(str, range(10)) + \
22 map(chr, range(ord('a'), ord('z') + 1)) + \
23 map(chr, range(ord('A'), ord('Z') + 1))
25 RANDOM_LENGTH = 20
27 def random_string():
28 def random_char():
29 return DIGITS_LETTERS[random.randint(0, len(DIGITS_LETTERS) - 1)]
30 return ''.join(map(lambda i: random_char(), xrange(RANDOM_LENGTH)))
32 GSH_COMMON_PREFIX = 'gsh-' + random_string() + ','
34 # {'random_string()': (function, continuous)}
35 GSH_CALLBACKS = {}
37 def add(name, function, continous):
38 clean_name = name.replace(':', '_').replace('.', '_')
39 trigger1 = clean_name + ':' + random_string() + '/'
40 trigger2 = random_string() + '.'
41 trigger = trigger1 + trigger2
42 GSH_CALLBACKS[trigger] = (function, continous)
43 return GSH_COMMON_PREFIX + trigger1, trigger2
45 def contains(data):
46 return GSH_COMMON_PREFIX in data
48 def process(line):
49 start = line.find(GSH_COMMON_PREFIX)
50 if start < 0:
51 return False
53 trigger_start = start + len(GSH_COMMON_PREFIX)
54 trigger_end = line.find('.', trigger_start) + 1
55 if trigger_end <= 0:
56 return False
58 trigger = line[trigger_start:trigger_end]
59 callback, continous = GSH_CALLBACKS.get(trigger, (None, True))
60 if not callback:
61 return False
63 if not continous:
64 del GSH_CALLBACKS[trigger]
66 callback(line[trigger_end:])
67 return True