1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
13 # Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """The ``command_stack`` module provides tools for managing and
20 executing stacks of :class:`~hooke.engine.CommandMessage`\s.
28 from .engine import CommandMessage
31 class CommandStack (list):
32 """Store a stack of commands.
36 >>> c = CommandStack([CommandMessage('CommandA', {'param':'A'})])
37 >>> c.append(CommandMessage('CommandB', {'param':'B'}))
38 >>> c.append(CommandMessage('CommandA', {'param':'C'}))
39 >>> c.append(CommandMessage('CommandB', {'param':'D'}))
41 Implement a dummy :meth:`execute_command` for testing.
43 >>> def execute_cmd(hooke, command_message, stack=None):
44 ... cm = command_message
45 ... print 'EXECUTE', cm.command, cm.arguments
46 >>> c.execute_command = execute_cmd
48 >>> c.execute(hooke=None) # doctest: +ELLIPSIS
49 EXECUTE CommandA {'param': 'A'}
50 EXECUTE CommandB {'param': 'B'}
51 EXECUTE CommandA {'param': 'C'}
52 EXECUTE CommandB {'param': 'D'}
54 :meth:`filter` allows you to select which commands get executed.
55 If, for example, you are applying a set of commands to the current
56 :class:`~hooke.curve.Curve`, you may only want to execute
57 instances of :class:`~hooke.plugin.curve.CurveCommand`. Here we
58 only execute commands named `CommandB`.
60 >>> def filter(hooke, command_message):
61 ... return command_message.command == 'CommandB'
63 Apply the stack to the current curve.
65 >>> c.execute(hooke=None, filter=filter) # doctest: +ELLIPSIS
66 EXECUTE CommandB {'param': 'B'}
67 EXECUTE CommandB {'param': 'D'}
69 Execute a new command and add it to the stack.
71 >>> cm = CommandMessage('CommandC', {'param':'E'})
72 >>> c.execute_command(hooke=None, command_message=cm)
73 EXECUTE CommandC {'param': 'E'}
75 >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE
76 ['<CommandMessage CommandA {param: A}>',
77 '<CommandMessage CommandB {param: B}>',
78 '<CommandMessage CommandA {param: C}>',
79 '<CommandMessage CommandB {param: D}>',
80 '<CommandMessage CommandC {param: E}>']
82 The data-type is also pickleable, which ensures we can move it
83 between processes with :class:`multiprocessing.Queue`\s and easily
84 save it to disk. We must remove the unpickleable dummy executor
85 before testing though.
87 >>> c.execute_command # doctest: +ELLIPSIS
88 <function execute_cmd at 0x...>
89 >>> del(c.__dict__['execute_command'])
90 >>> c.execute_command # doctest: +ELLIPSIS
91 <bound method CommandStack.execute_command of ...>
93 Lets also attach a child command message to demonstrate recursive
94 serialization (we can't append `c` itself because of
95 `Python issue 1062277`_).
97 .. _Python issue 1062277: http://bugs.python.org/issue1062277
100 >>> c.append(CommandMessage('CommandD', {'param': copy.deepcopy(c)}))
102 Run the pickle (and YAML) tests.
105 >>> s = pickle.dumps(c)
106 >>> z = pickle.loads(s)
107 >>> print '\\n'.join([repr(cm) for cm in c]
108 ... ) # doctest: +NORMALIZE_WHITESPACE,
109 <CommandMessage CommandA {param: A}>
110 <CommandMessage CommandB {param: B}>
111 <CommandMessage CommandA {param: C}>
112 <CommandMessage CommandB {param: D}>
113 <CommandMessage CommandC {param: E}>
114 <CommandMessage CommandD {param:
115 [<CommandMessage CommandA {param: A}>,
116 <CommandMessage CommandB {param: B}>,
117 <CommandMessage CommandA {param: C}>,
118 <CommandMessage CommandB {param: D}>,
119 <CommandMessage CommandC {param: E}>]}>
121 >>> print yaml.dump(c)
122 !!python/object/new:hooke.command_stack.CommandStack
124 - !!python/object:hooke.engine.CommandMessage
125 arguments: {param: A}
127 - !!python/object:hooke.engine.CommandMessage
128 arguments: {param: B}
130 - !!python/object:hooke.engine.CommandMessage
131 arguments: {param: C}
133 - !!python/object:hooke.engine.CommandMessage
134 arguments: {param: D}
136 - !!python/object:hooke.engine.CommandMessage
137 arguments: {param: E}
139 - !!python/object:hooke.engine.CommandMessage
141 param: !!python/object/new:hooke.command_stack.CommandStack
143 - !!python/object:hooke.engine.CommandMessage
144 arguments: {param: A}
146 - !!python/object:hooke.engine.CommandMessage
147 arguments: {param: B}
149 - !!python/object:hooke.engine.CommandMessage
150 arguments: {param: C}
152 - !!python/object:hooke.engine.CommandMessage
153 arguments: {param: D}
155 - !!python/object:hooke.engine.CommandMessage
156 arguments: {param: E}
161 There is also a convenience function for clearing the stack.
164 >>> print [repr(cm) for cm in c]
167 def execute(self, hooke, filter=None, stack=False):
168 """Execute a stack of commands.
172 execute_command, filter
176 for command_message in self:
177 if filter(hooke, command_message) == True:
178 self.execute_command(
179 hooke=hooke, command_message=command_message, stack=stack)
181 def filter(self, hooke, command_message):
182 """Return `True` to execute `command_message`, `False` otherwise.
184 The default implementation always returns `True`.
188 def execute_command(self, hooke, command_message, stack=False):
189 arguments = dict(command_message.arguments)
190 arguments['stack'] = stack
191 hooke.run_command(command=command_message.command,
199 class FileCommandStack (CommandStack):
200 """A file-backed :class:`CommandStack`.
204 def __init__(self, *args, **kwargs):
205 super(FileCommandStack, self).__init__(*args, **kwargs)
206 self.name = self.path = None
208 def __setstate__(self, state):
209 self.name = self.path = None
210 for key,value in state.items:
211 setattr(self, key, value)
212 self.set_path(state.get('path', None))
214 def set_path(self, path):
215 """Set the path (and possibly the name) of the command stack.
219 >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
221 :attr:`name` is set only if it starts out equal to `None`.
224 >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
226 'path/to/my/command/stack'
229 >>> c.set_path(os.path.join('another', 'path'))
237 if self.name == None:
238 self.name = os.path.basename(path)
240 def save(self, path=None, makedirs=True):
241 """Saves the command stack to `path`.
244 dirname = os.path.dirname(self.path) or '.'
245 if makedirs == True and not os.path.isdir(dirname):
247 with open(self.path, 'w') as f:
248 f.write(self.flatten())
250 def load(self, path=None):
251 """Load a command stack from `path`.
254 with open(self.path, 'r') as f:
256 self.from_string(text)
259 """Create a string representation of the command stack.
261 A playlist is a YAML document with the following syntax::
263 - arguments: {param: A}
265 - arguments: {param: B, ...}
271 >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
272 >>> c.append(CommandMessage('CommandB', {'param':'B'}))
273 >>> c.append(CommandMessage('CommandA', {'param':'C'}))
274 >>> c.append(CommandMessage('CommandB', {'param':'D'}))
275 >>> print c.flatten()
276 - arguments: {param: A}
278 - arguments: {param: B}
280 - arguments: {param: C}
282 - arguments: {param: D}
286 return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
289 def from_string(self, string):
290 """Load a playlist from a string.
292 .. warning:: This is *not safe* with untrusted input.
297 >>> string = '''- arguments: {param: A}
298 ... command: CommandA
299 ... - arguments: {param: B}
300 ... command: CommandB
301 ... - arguments: {param: C}
302 ... command: CommandA
303 ... - arguments: {param: D}
304 ... command: CommandB
306 >>> c = FileCommandStack()
307 >>> c.from_string(string)
308 >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE
309 ['<CommandMessage CommandA {param: A}>',
310 '<CommandMessage CommandB {param: B}>',
311 '<CommandMessage CommandA {param: C}>',
312 '<CommandMessage CommandB {param: D}>']
314 for x in yaml.load(string):
315 self.append(CommandMessage(command=x['command'],
316 arguments=x['arguments']))