initial import code into git
[platform/upstream/mic.git] / micng / utils / cmdln.py
1 # Copyright (c) 2002-2005 ActiveState Corp.
2 # License: MIT (see LICENSE.txt for license details)
3 # Author:  Trent Mick (TrentM@ActiveState.com)
4 # Home:    http://trentm.com/projects/cmdln/
5
6 """An improvement on Python's standard cmd.py module.
7
8 As with cmd.py, this module provides "a simple framework for writing
9 line-oriented command intepreters."  This module provides a 'RawCmdln'
10 class that fixes some design flaws in cmd.Cmd, making it more scalable
11 and nicer to use for good 'cvs'- or 'svn'-style command line interfaces
12 or simple shells.  And it provides a 'Cmdln' class that add
13 optparse-based option processing. Basically you use it like this:
14
15     import cmdln
16
17     class MySVN(cmdln.Cmdln):
18         name = "svn"
19
20         @cmdln.alias('stat', 'st')
21         @cmdln.option('-v', '--verbose', action='store_true'
22                       help='print verbose information')
23         def do_status(self, subcmd, opts, *paths):
24             print "handle 'svn status' command"
25
26         #...
27
28     if __name__ == "__main__":
29         shell = MySVN()
30         retval = shell.main()
31         sys.exit(retval)
32
33 See the README.txt or <http://trentm.com/projects/cmdln/> for more
34 details.
35 """
36
37 __revision__ = "$Id: cmdln.py 1666 2007-05-09 03:13:03Z trentm $"
38 __version_info__ = (1, 0, 0)
39 __version__ = '.'.join(map(str, __version_info__))
40
41 import os
42 import re
43 import cmd
44 import optparse
45 from pprint import pprint
46 from datetime import date
47
48
49
50
51 #---- globals
52
53 LOOP_ALWAYS, LOOP_NEVER, LOOP_IF_EMPTY = range(3)
54
55 # An unspecified optional argument when None is a meaningful value.
56 _NOT_SPECIFIED = ("Not", "Specified")
57
58 # Pattern to match a TypeError message from a call that
59 # failed because of incorrect number of arguments (see
60 # Python/getargs.c).
61 _INCORRECT_NUM_ARGS_RE = re.compile(
62     r"(takes [\w ]+ )(\d+)( arguments? \()(\d+)( given\))")
63
64 # Static bits of man page
65 MAN_HEADER = r""".TH %(ucname)s "1" "%(date)s" "%(name)s %(version)s" "User Commands"
66 .SH NAME
67 %(name)s \- Program to do useful things.
68 .SH SYNOPSIS
69 .B %(name)s
70 [\fIGLOBALOPTS\fR] \fISUBCOMMAND \fR[\fIOPTS\fR] [\fIARGS\fR...]
71 .br
72 .B %(name)s
73 \fIhelp SUBCOMMAND\fR
74 .SH DESCRIPTION
75 """
76 MAN_COMMANDS_HEADER = r"""
77 .SS COMMANDS
78 """
79 MAN_OPTIONS_HEADER = r"""
80 .SS GLOBAL OPTIONS
81 """
82 MAN_FOOTER = r"""
83 .SH AUTHOR
84 This man page is automatically generated.
85 """
86
87 #---- exceptions
88
89 class CmdlnError(Exception):
90     """A cmdln.py usage error."""
91     def __init__(self, msg):
92         self.msg = msg
93     def __str__(self):
94         return self.msg
95
96 class CmdlnUserError(Exception):
97     """An error by a user of a cmdln-based tool/shell."""
98     pass
99
100
101
102 #---- public methods and classes
103
104 def alias(*aliases):
105     """Decorator to add aliases for Cmdln.do_* command handlers.
106
107     Example:
108         class MyShell(cmdln.Cmdln):
109             @cmdln.alias("!", "sh")
110             def do_shell(self, argv):
111                 #...implement 'shell' command
112     """
113     def decorate(f):
114         if not hasattr(f, "aliases"):
115             f.aliases = []
116         f.aliases += aliases
117         return f
118     return decorate
119
120 MAN_REPLACES = [
121     (re.compile(r'(^|[ \t\[\'])--([^/ \t/,-]*)-([^/ \t/,-]*)-([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\-\2\-\3\-\4'),
122     (re.compile(r'(^|[ \t\[\'])-([^/ \t/,-]*)-([^/ \t/,-]*)-([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\2\-\3\-\4'),
123     (re.compile(r'(^|[ \t\[\'])--([^/ \t/,-]*)-([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\-\2\-\3'),
124     (re.compile(r'(^|[ \t\[\'])-([^/ \t/,-]*)-([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\2\-\3'),
125     (re.compile(r'(^|[ \t\[\'])--([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\-\2'),
126     (re.compile(r'(^|[ \t\[\'])-([^/ \t/,-]*)(?=$|[ \t=\]\'/,])'), r'\1\-\2'),
127     (re.compile(r"^'"), r" '"),
128     ]
129
130 def man_escape(text):
131     '''
132     Escapes text to be included in man page.
133
134     For now it only escapes dashes in command line options.
135     '''
136     for repl in MAN_REPLACES:
137         text = repl[0].sub(repl[1], text)
138     return text
139
140 class RawCmdln(cmd.Cmd):
141     """An improved (on cmd.Cmd) framework for building multi-subcommand
142     scripts (think "svn" & "cvs") and simple shells (think "pdb" and
143     "gdb").
144
145     A simple example:
146
147         import cmdln
148
149         class MySVN(cmdln.RawCmdln):
150             name = "svn"
151
152             @cmdln.aliases('stat', 'st')
153             def do_status(self, argv):
154                 print "handle 'svn status' command"
155
156         if __name__ == "__main__":
157             shell = MySVN()
158             retval = shell.main()
159             sys.exit(retval)
160
161     See <http://trentm.com/projects/cmdln> for more information.
162     """
163     name = None      # if unset, defaults basename(sys.argv[0])
164     prompt = None    # if unset, defaults to self.name+"> "
165     version = None   # if set, default top-level options include --version
166
167     # Default messages for some 'help' command error cases.
168     # They are interpolated with one arg: the command.
169     nohelp = "no help on '%s'"
170     unknowncmd = "unknown command: '%s'"
171
172     helpindent = '' # string with which to indent help output
173
174     # Default man page parts, please change them in subclass
175     man_header = MAN_HEADER
176     man_commands_header = MAN_COMMANDS_HEADER
177     man_options_header = MAN_OPTIONS_HEADER
178     man_footer = MAN_FOOTER
179
180     def __init__(self, completekey='tab',
181                  stdin=None, stdout=None, stderr=None):
182         """Cmdln(completekey='tab', stdin=None, stdout=None, stderr=None)
183
184         The optional argument 'completekey' is the readline name of a
185         completion key; it defaults to the Tab key. If completekey is
186         not None and the readline module is available, command completion
187         is done automatically.
188
189         The optional arguments 'stdin', 'stdout' and 'stderr' specify
190         alternate input, output and error output file objects; if not
191         specified, sys.* are used.
192
193         If 'stdout' but not 'stderr' is specified, stdout is used for
194         error output. This is to provide least surprise for users used
195         to only the 'stdin' and 'stdout' options with cmd.Cmd.
196         """
197         import sys
198         if self.name is None:
199             self.name = os.path.basename(sys.argv[0])
200         if self.prompt is None:
201             self.prompt = self.name+"> "
202         self._name_str = self._str(self.name)
203         self._prompt_str = self._str(self.prompt)
204         if stdin is not None:
205             self.stdin = stdin
206         else:
207             self.stdin = sys.stdin
208         if stdout is not None:
209             self.stdout = stdout
210         else:
211             self.stdout = sys.stdout
212         if stderr is not None:
213             self.stderr = stderr
214         elif stdout is not None:
215             self.stderr = stdout
216         else:
217             self.stderr = sys.stderr
218         self.cmdqueue = []
219         self.completekey = completekey
220         self.cmdlooping = False
221
222     def get_optparser(self):
223         """Hook for subclasses to set the option parser for the
224         top-level command/shell.
225
226         This option parser is used retrieved and used by `.main()' to
227         handle top-level options.
228
229         The default implements a single '-h|--help' option. Sub-classes
230         can return None to have no options at the top-level. Typically
231         an instance of CmdlnOptionParser should be returned.
232         """
233         version = (self.version is not None
234                     and "%s %s" % (self._name_str, self.version)
235                     or None)
236         return CmdlnOptionParser(self, version=version)
237
238     def get_version(self):
239         """
240         Returns version of program. To be replaced in subclass.
241         """
242         return __version__
243
244     def postoptparse(self):
245         """Hook method executed just after `.main()' parses top-level
246         options.
247
248         When called `self.values' holds the results of the option parse.
249         """
250         pass
251
252     def main(self, argv=None, loop=LOOP_NEVER):
253         """A possible mainline handler for a script, like so:
254
255             import cmdln
256             class MyCmd(cmdln.Cmdln):
257                 name = "mycmd"
258                 ...
259
260             if __name__ == "__main__":
261                 MyCmd().main()
262
263         By default this will use sys.argv to issue a single command to
264         'MyCmd', then exit. The 'loop' argument can be use to control
265         interactive shell behaviour.
266
267         Arguments:
268             "argv" (optional, default sys.argv) is the command to run.
269                 It must be a sequence, where the first element is the
270                 command name and subsequent elements the args for that
271                 command.
272             "loop" (optional, default LOOP_NEVER) is a constant
273                 indicating if a command loop should be started (i.e. an
274                 interactive shell). Valid values (constants on this module):
275                     LOOP_ALWAYS     start loop and run "argv", if any
276                     LOOP_NEVER      run "argv" (or .emptyline()) and exit
277                     LOOP_IF_EMPTY   run "argv", if given, and exit;
278                                     otherwise, start loop
279         """
280         if argv is None:
281             import sys
282             argv = sys.argv
283         else:
284             argv = argv[:] # don't modify caller's list
285
286         self.optparser = self.get_optparser()
287         if self.optparser: # i.e. optparser=None means don't process for opts
288             try:
289                 self.options, args = self.optparser.parse_args(argv[1:])
290             except CmdlnUserError, ex:
291                 msg = "%s: %s\nTry '%s help' for info.\n"\
292                       % (self.name, ex, self.name)
293                 self.stderr.write(self._str(msg))
294                 self.stderr.flush()
295                 return 1
296             except StopOptionProcessing, ex:
297                 return 0
298         else:
299             self.options, args = None, argv[1:]
300         self.postoptparse()
301
302         if loop == LOOP_ALWAYS:
303             if args:
304                 self.cmdqueue.append(args)
305             return self.cmdloop()
306         elif loop == LOOP_NEVER:
307             if args:
308                 return self.cmd(args)
309             else:
310                 return self.emptyline()
311         elif loop == LOOP_IF_EMPTY:
312             if args:
313                 return self.cmd(args)
314             else:
315                 return self.cmdloop()
316
317     def cmd(self, argv):
318         """Run one command and exit.
319
320             "argv" is the arglist for the command to run. argv[0] is the
321                 command to run. If argv is an empty list then the
322                 'emptyline' handler is run.
323
324         Returns the return value from the command handler.
325         """
326         assert isinstance(argv, (list, tuple)), \
327                 "'argv' is not a sequence: %r" % argv
328         retval = None
329         try:
330             argv = self.precmd(argv)
331             retval = self.onecmd(argv)
332             self.postcmd(argv)
333         except:
334             if not self.cmdexc(argv):
335                 raise
336             retval = 1
337         return retval
338
339     def _str(self, s):
340         """Safely convert the given str/unicode to a string for printing."""
341         try:
342             return str(s)
343         except UnicodeError:
344             #XXX What is the proper encoding to use here? 'utf-8' seems
345             #    to work better than "getdefaultencoding" (usually
346             #    'ascii'), on OS X at least.
347             #import sys
348             #return s.encode(sys.getdefaultencoding(), "replace")
349             return s.encode("utf-8", "replace")
350
351     def cmdloop(self, intro=None):
352         """Repeatedly issue a prompt, accept input, parse into an argv, and
353         dispatch (via .precmd(), .onecmd() and .postcmd()), passing them
354         the argv. In other words, start a shell.
355
356             "intro" (optional) is a introductory message to print when
357                 starting the command loop. This overrides the class
358                 "intro" attribute, if any.
359         """
360         self.cmdlooping = True
361         self.preloop()
362         if intro is None:
363             intro = self.intro
364         if intro:
365             intro_str = self._str(intro)
366             self.stdout.write(intro_str+'\n')
367         self.stop = False
368         retval = None
369         while not self.stop:
370             if self.cmdqueue:
371                 argv = self.cmdqueue.pop(0)
372                 assert isinstance(argv, (list, tuple)), \
373                         "item on 'cmdqueue' is not a sequence: %r" % argv
374             else:
375                 if self.use_rawinput:
376                     try:
377                         line = raw_input(self._prompt_str)
378                     except EOFError:
379                         line = 'EOF'
380                 else:
381                     self.stdout.write(self._prompt_str)
382                     self.stdout.flush()
383                     line = self.stdin.readline()
384                     if not len(line):
385                         line = 'EOF'
386                     else:
387                         line = line[:-1] # chop '\n'
388                 argv = line2argv(line)
389             try:
390                 argv = self.precmd(argv)
391                 retval = self.onecmd(argv)
392                 self.postcmd(argv)
393             except:
394                 if not self.cmdexc(argv):
395                     raise
396                 retval = 1
397             self.lastretval = retval
398         self.postloop()
399         self.cmdlooping = False
400         return retval
401
402     def precmd(self, argv):
403         """Hook method executed just before the command argv is
404         interpreted, but after the input prompt is generated and issued.
405
406             "argv" is the cmd to run.
407
408         Returns an argv to run (i.e. this method can modify the command
409         to run).
410         """
411         return argv
412
413     def postcmd(self, argv):
414         """Hook method executed just after a command dispatch is finished.
415
416             "argv" is the command that was run.
417         """
418         pass
419
420     def cmdexc(self, argv):
421         """Called if an exception is raised in any of precmd(), onecmd(),
422         or postcmd(). If True is returned, the exception is deemed to have
423         been dealt with. Otherwise, the exception is re-raised.
424
425         The default implementation handles CmdlnUserError's, which
426         typically correspond to user error in calling commands (as
427         opposed to programmer error in the design of the script using
428         cmdln.py).
429         """
430         import sys
431         type, exc, traceback = sys.exc_info()
432         if isinstance(exc, CmdlnUserError):
433             msg = "%s %s: %s\nTry '%s help %s' for info.\n"\
434                   % (self.name, argv[0], exc, self.name, argv[0])
435             self.stderr.write(self._str(msg))
436             self.stderr.flush()
437             return True
438
439     def onecmd(self, argv):
440         if not argv:
441             return self.emptyline()
442         self.lastcmd = argv
443         cmdname = self._get_canonical_cmd_name(argv[0])
444         if cmdname:
445             handler = self._get_cmd_handler(cmdname)
446             if handler:
447                 return self._dispatch_cmd(handler, argv)
448         return self.default(argv)
449
450     def _dispatch_cmd(self, handler, argv):
451         return handler(argv)
452
453     def default(self, argv):
454         """Hook called to handle a command for which there is no handler.
455
456             "argv" is the command and arguments to run.
457
458         The default implementation writes and error message to stderr
459         and returns an error exit status.
460
461         Returns a numeric command exit status.
462         """
463         errmsg = self._str(self.unknowncmd % (argv[0],))
464         if self.cmdlooping:
465             self.stderr.write(errmsg+"\n")
466         else:
467             self.stderr.write("%s: %s\nTry '%s help' for info.\n"
468                               % (self._name_str, errmsg, self._name_str))
469         self.stderr.flush()
470         return 1
471
472     def parseline(self, line):
473         # This is used by Cmd.complete (readline completer function) to
474         # massage the current line buffer before completion processing.
475         # We override to drop special '!' handling.
476         line = line.strip()
477         if not line:
478             return None, None, line
479         elif line[0] == '?':
480             line = 'help ' + line[1:]
481         i, n = 0, len(line)
482         while i < n and line[i] in self.identchars: i = i+1
483         cmd, arg = line[:i], line[i:].strip()
484         return cmd, arg, line
485
486     def helpdefault(self, cmd, known):
487         """Hook called to handle help on a command for which there is no
488         help handler.
489
490             "cmd" is the command name on which help was requested.
491             "known" is a boolean indicating if this command is known
492                 (i.e. if there is a handler for it).
493
494         Returns a return code.
495         """
496         if known:
497             msg = self._str(self.nohelp % (cmd,))
498             if self.cmdlooping:
499                 self.stderr.write(msg + '\n')
500             else:
501                 self.stderr.write("%s: %s\n" % (self.name, msg))
502         else:
503             msg = self.unknowncmd % (cmd,)
504             if self.cmdlooping:
505                 self.stderr.write(msg + '\n')
506             else:
507                 self.stderr.write("%s: %s\n"
508                                   "Try '%s help' for info.\n"
509                                   % (self.name, msg, self.name))
510         self.stderr.flush()
511         return 1
512
513
514     def do_help(self, argv):
515         """${cmd_name}: give detailed help on a specific sub-command
516
517         usage:
518             ${name} help [SUBCOMMAND]
519         """
520         if len(argv) > 1: # asking for help on a particular command
521             doc = None
522             cmdname = self._get_canonical_cmd_name(argv[1]) or argv[1]
523             if not cmdname:
524                 return self.helpdefault(argv[1], False)
525             else:
526                 helpfunc = getattr(self, "help_"+cmdname, None)
527                 if helpfunc:
528                     doc = helpfunc()
529                 else:
530                     handler = self._get_cmd_handler(cmdname)
531                     if handler:
532                         doc = handler.__doc__
533                     if doc is None:
534                         return self.helpdefault(argv[1], handler != None)
535         else: # bare "help" command
536             doc = self.__class__.__doc__  # try class docstring
537             if doc is None:
538                 # Try to provide some reasonable useful default help.
539                 if self.cmdlooping: prefix = ""
540                 else:               prefix = self.name+' '
541                 doc = """usage:
542                     %sSUBCOMMAND [ARGS...]
543                     %shelp [SUBCOMMAND]
544
545                 ${option_list}
546                 ${command_list}
547                 ${help_list}
548                 """ % (prefix, prefix)
549             cmdname = None
550
551         if doc: # *do* have help content, massage and print that
552             doc = self._help_reindent(doc)
553             doc = self._help_preprocess(doc, cmdname)
554             doc = doc.rstrip() + '\n' # trim down trailing space
555             self.stdout.write(self._str(doc))
556             self.stdout.flush()
557     do_help.aliases = ["?"]
558
559
560     def do_man(self, argv):
561         """${cmd_name}: generates a man page
562
563         usage:
564             ${name} man
565         """
566         self.stdout.write(self.man_header % {
567                 'date': date.today().strftime('%b %Y'),
568                 'version': self.get_version(),
569                 'name': self.name,
570                 'ucname': self.name.upper()
571                 }
572         )
573
574         self.stdout.write(self.man_commands_header)
575         commands = self._help_get_command_list()
576         for command, doc in commands:
577             cmdname = command.split(' ')[0]
578             text = self._help_preprocess(doc, cmdname)
579             lines = []
580             for line in text.splitlines(False):
581                 if line[:8] == ' ' * 8:
582                     line = line[8:]
583                 lines.append(man_escape(line))
584
585             self.stdout.write('.TP\n\\fB%s\\fR\n%s\n' % (command, '\n'.join(lines)))
586
587         self.stdout.write(self.man_options_header)
588         self.stdout.write(man_escape(self._help_preprocess('${option_list}', None)))
589
590         self.stdout.write(self.man_footer)
591
592         self.stdout.flush()
593
594     def _help_reindent(self, help, indent=None):
595         """Hook to re-indent help strings before writing to stdout.
596
597             "help" is the help content to re-indent
598             "indent" is a string with which to indent each line of the
599                 help content after normalizing. If unspecified or None
600                 then the default is use: the 'self.helpindent' class
601                 attribute. By default this is the empty string, i.e.
602                 no indentation.
603
604         By default, all common leading whitespace is removed and then
605         the lot is indented by 'self.helpindent'. When calculating the
606         common leading whitespace the first line is ignored -- hence
607         help content for Conan can be written as follows and have the
608         expected indentation:
609
610             def do_crush(self, ...):
611                 '''${cmd_name}: crush your enemies, see them driven before you...
612
613                 c.f. Conan the Barbarian'''
614         """
615         if indent is None:
616             indent = self.helpindent
617         lines = help.splitlines(0)
618         _dedentlines(lines, skip_first_line=True)
619         lines = [(indent+line).rstrip() for line in lines]
620         return '\n'.join(lines)
621
622     def _help_preprocess(self, help, cmdname):
623         """Hook to preprocess a help string before writing to stdout.
624
625             "help" is the help string to process.
626             "cmdname" is the canonical sub-command name for which help
627                 is being given, or None if the help is not specific to a
628                 command.
629
630         By default the following template variables are interpolated in
631         help content. (Note: these are similar to Python 2.4's
632         string.Template interpolation but not quite.)
633
634         ${name}
635             The tool's/shell's name, i.e. 'self.name'.
636         ${option_list}
637             A formatted table of options for this shell/tool.
638         ${command_list}
639             A formatted table of available sub-commands.
640         ${help_list}
641             A formatted table of additional help topics (i.e. 'help_*'
642             methods with no matching 'do_*' method).
643         ${cmd_name}
644             The name (and aliases) for this sub-command formatted as:
645             "NAME (ALIAS1, ALIAS2, ...)".
646         ${cmd_usage}
647             A formatted usage block inferred from the command function
648             signature.
649         ${cmd_option_list}
650             A formatted table of options for this sub-command. (This is
651             only available for commands using the optparse integration,
652             i.e.  using @cmdln.option decorators or manually setting the
653             'optparser' attribute on the 'do_*' method.)
654
655         Returns the processed help.
656         """
657         preprocessors = {
658             "${name}":            self._help_preprocess_name,
659             "${option_list}":     self._help_preprocess_option_list,
660             "${command_list}":    self._help_preprocess_command_list,
661             "${help_list}":       self._help_preprocess_help_list,
662             "${cmd_name}":        self._help_preprocess_cmd_name,
663             "${cmd_usage}":       self._help_preprocess_cmd_usage,
664             "${cmd_option_list}": self._help_preprocess_cmd_option_list,
665         }
666
667         for marker, preprocessor in preprocessors.items():
668             if marker in help:
669                 help = preprocessor(help, cmdname)
670         return help
671
672     def _help_preprocess_name(self, help, cmdname=None):
673         return help.replace("${name}", self.name)
674
675     def _help_preprocess_option_list(self, help, cmdname=None):
676         marker = "${option_list}"
677         indent, indent_width = _get_indent(marker, help)
678         suffix = _get_trailing_whitespace(marker, help)
679
680         if self.optparser:
681             # Setup formatting options and format.
682             # - Indentation of 4 is better than optparse default of 2.
683             #   C.f. Damian Conway's discussion of this in Perl Best
684             #   Practices.
685             self.optparser.formatter.indent_increment = 4
686             self.optparser.formatter.current_indent = indent_width
687             block = self.optparser.format_option_help() + '\n'
688         else:
689             block = ""
690
691         help = help.replace(indent+marker+suffix, block, 1)
692         return help
693
694     def _help_get_command_list(self):
695         # Find any aliases for commands.
696         token2canonical = self._get_canonical_map()
697         aliases = {}
698         for token, cmdname in token2canonical.items():
699             if token == cmdname: continue
700             aliases.setdefault(cmdname, []).append(token)
701
702         # Get the list of (non-hidden) commands and their
703         # documentation, if any.
704         cmdnames = {} # use a dict to strip duplicates
705         for attr in self.get_names():
706             if attr.startswith("do_"):
707                 cmdnames[attr[3:]] = True
708         cmdnames = cmdnames.keys()
709         cmdnames.remove("help")
710         cmdnames.remove("man")
711         #cmdnames.sort()
712         linedata = []
713         for cmdname in cmdnames:
714             if aliases.get(cmdname):
715                 a = aliases[cmdname]
716                 a.sort()
717                 cmdstr = "%s (%s)" % (cmdname, ", ".join(a))
718             else:
719                 cmdstr = cmdname
720             doc = None
721             try:
722                 helpfunc = getattr(self, 'help_'+cmdname)
723             except AttributeError:
724                 handler = self._get_cmd_handler(cmdname)
725                 if handler:
726                     doc = handler.__doc__
727             else:
728                 doc = helpfunc()
729
730             # Strip "${cmd_name}: " from the start of a command's doc. Best
731             # practice dictates that command help strings begin with this, but
732             # it isn't at all wanted for the command list.
733             to_strip = "${cmd_name}:"
734             if doc and doc.startswith(to_strip):
735                 #log.debug("stripping %r from start of %s's help string",
736                 #          to_strip, cmdname)
737                 doc = doc[len(to_strip):].lstrip()
738             if not getattr(self._get_cmd_handler(cmdname), "hidden", None):
739                 linedata.append( (cmdstr, doc) )
740
741         return linedata
742
743     def _help_preprocess_command_list(self, help, cmdname=None):
744         marker = "${command_list}"
745         indent, indent_width = _get_indent(marker, help)
746         suffix = _get_trailing_whitespace(marker, help)
747
748         linedata = self._help_get_command_list()
749
750         if linedata:
751             subindent = indent + ' '*4
752             lines = _format_linedata(linedata, subindent, indent_width+4)
753             block = indent + "commands:\n" \
754                     + '\n'.join(lines) + "\n\n"
755             help = help.replace(indent+marker+suffix, block, 1)
756         return help
757
758     def _help_preprocess_help_list(self, help, cmdname=None):
759         marker = "${help_list}"
760         indent, indent_width = _get_indent(marker, help)
761         suffix = _get_trailing_whitespace(marker, help)
762
763         # Determine the additional help topics, if any.
764         helpnames = {}
765         token2cmdname = self._get_canonical_map()
766         for attr in self.get_names():
767             if not attr.startswith("help_"): continue
768             helpname = attr[5:]
769             if helpname not in token2cmdname:
770                 helpnames[helpname] = True
771
772         if helpnames:
773             helpnames = helpnames.keys()
774             helpnames.sort()
775             linedata = [(self.name+" help "+n, "") for n in helpnames]
776
777             subindent = indent + ' '*4
778             lines = _format_linedata(linedata, subindent, indent_width+4)
779             block = indent + "additional help topics:\n" \
780                     + '\n'.join(lines) + "\n\n"
781         else:
782             block = ''
783         help = help.replace(indent+marker+suffix, block, 1)
784         return help
785
786     def _help_preprocess_cmd_name(self, help, cmdname=None):
787         marker = "${cmd_name}"
788         handler = self._get_cmd_handler(cmdname)
789         if not handler:
790             raise CmdlnError("cannot preprocess '%s' into help string: "
791                              "could not find command handler for %r"
792                              % (marker, cmdname))
793         s = cmdname
794         if hasattr(handler, "aliases"):
795             s += " (%s)" % (", ".join(handler.aliases))
796         help = help.replace(marker, s)
797         return help
798
799     #TODO: this only makes sense as part of the Cmdln class.
800     #      Add hooks to add help preprocessing template vars and put
801     #      this one on that class.
802     def _help_preprocess_cmd_usage(self, help, cmdname=None):
803         marker = "${cmd_usage}"
804         handler = self._get_cmd_handler(cmdname)
805         if not handler:
806             raise CmdlnError("cannot preprocess '%s' into help string: "
807                              "could not find command handler for %r"
808                              % (marker, cmdname))
809         indent, indent_width = _get_indent(marker, help)
810         suffix = _get_trailing_whitespace(marker, help)
811
812         # Extract the introspection bits we need.
813         func = handler.im_func
814         if func.func_defaults:
815             func_defaults = list(func.func_defaults)
816         else:
817             func_defaults = []
818         co_argcount = func.func_code.co_argcount
819         co_varnames = func.func_code.co_varnames
820         co_flags = func.func_code.co_flags
821         CO_FLAGS_ARGS = 4
822         CO_FLAGS_KWARGS = 8
823
824         # Adjust argcount for possible *args and **kwargs arguments.
825         argcount = co_argcount
826         if co_flags & CO_FLAGS_ARGS:   argcount += 1
827         if co_flags & CO_FLAGS_KWARGS: argcount += 1
828
829         # Determine the usage string.
830         usage = "%s %s" % (self.name, cmdname)
831         if argcount <= 2:   # handler ::= do_FOO(self, argv)
832             usage += " [ARGS...]"
833         elif argcount >= 3: # handler ::= do_FOO(self, subcmd, opts, ...)
834             argnames = list(co_varnames[3:argcount])
835             tail = ""
836             if co_flags & CO_FLAGS_KWARGS:
837                 name = argnames.pop(-1)
838                 import warnings
839                 # There is no generally accepted mechanism for passing
840                 # keyword arguments from the command line. Could
841                 # *perhaps* consider: arg=value arg2=value2 ...
842                 warnings.warn("argument '**%s' on '%s.%s' command "
843                               "handler will never get values"
844                               % (name, self.__class__.__name__,
845                                  func.func_name))
846             if co_flags & CO_FLAGS_ARGS:
847                 name = argnames.pop(-1)
848                 tail = "[%s...]" % name.upper()
849             while func_defaults:
850                 func_defaults.pop(-1)
851                 name = argnames.pop(-1)
852                 tail = "[%s%s%s]" % (name.upper(), (tail and ' ' or ''), tail)
853             while argnames:
854                 name = argnames.pop(-1)
855                 tail = "%s %s" % (name.upper(), tail)
856             usage += ' ' + tail
857
858         block_lines = [
859             self.helpindent + "usage:",
860             self.helpindent + ' '*4 + usage
861         ]
862         block = '\n'.join(block_lines) + '\n\n'
863
864         help = help.replace(indent+marker+suffix, block, 1)
865         return help
866
867     #TODO: this only makes sense as part of the Cmdln class.
868     #      Add hooks to add help preprocessing template vars and put
869     #      this one on that class.
870     def _help_preprocess_cmd_option_list(self, help, cmdname=None):
871         marker = "${cmd_option_list}"
872         handler = self._get_cmd_handler(cmdname)
873         if not handler:
874             raise CmdlnError("cannot preprocess '%s' into help string: "
875                              "could not find command handler for %r"
876                              % (marker, cmdname))
877         indent, indent_width = _get_indent(marker, help)
878         suffix = _get_trailing_whitespace(marker, help)
879         if hasattr(handler, "optparser"):
880             # Setup formatting options and format.
881             # - Indentation of 4 is better than optparse default of 2.
882             #   C.f. Damian Conway's discussion of this in Perl Best
883             #   Practices.
884             handler.optparser.formatter.indent_increment = 4
885             handler.optparser.formatter.current_indent = indent_width
886             block = handler.optparser.format_option_help() + '\n'
887         else:
888             block = ""
889
890         help = help.replace(indent+marker+suffix, block, 1)
891         return help
892
893     def _get_canonical_cmd_name(self, token):
894         map = self._get_canonical_map()
895         return map.get(token, None)
896
897     def _get_canonical_map(self):
898         """Return a mapping of available command names and aliases to
899         their canonical command name.
900         """
901         cacheattr = "_token2canonical"
902         if not hasattr(self, cacheattr):
903             # Get the list of commands and their aliases, if any.
904             token2canonical = {}
905             cmd2funcname = {} # use a dict to strip duplicates
906             for attr in self.get_names():
907                 if attr.startswith("do_"):    cmdname = attr[3:]
908                 elif attr.startswith("_do_"): cmdname = attr[4:]
909                 else:
910                     continue
911                 cmd2funcname[cmdname] = attr
912                 token2canonical[cmdname] = cmdname
913             for cmdname, funcname in cmd2funcname.items(): # add aliases
914                 func = getattr(self, funcname)
915                 aliases = getattr(func, "aliases", [])
916                 for alias in aliases:
917                     if alias in cmd2funcname:
918                         import warnings
919                         warnings.warn("'%s' alias for '%s' command conflicts "
920                                       "with '%s' handler"
921                                       % (alias, cmdname, cmd2funcname[alias]))
922                         continue
923                     token2canonical[alias] = cmdname
924             setattr(self, cacheattr, token2canonical)
925         return getattr(self, cacheattr)
926
927     def _get_cmd_handler(self, cmdname):
928         handler = None
929         try:
930             handler = getattr(self, 'do_' + cmdname)
931         except AttributeError:
932             try:
933                 # Private command handlers begin with "_do_".
934                 handler = getattr(self, '_do_' + cmdname)
935             except AttributeError:
936                 pass
937         return handler
938
939     def _do_EOF(self, argv):
940         # Default EOF handler
941         # Note: an actual EOF is redirected to this command.
942         #TODO: separate name for this. Currently it is available from
943         #      command-line. Is that okay?
944         self.stdout.write('\n')
945         self.stdout.flush()
946         self.stop = True
947
948     def emptyline(self):
949         # Different from cmd.Cmd: don't repeat the last command for an
950         # emptyline.
951         if self.cmdlooping:
952             pass
953         else:
954             return self.do_help(["help"])
955
956
957 #---- optparse.py extension to fix (IMO) some deficiencies
958 #
959 # See the class _OptionParserEx docstring for details.
960 #
961
962 class StopOptionProcessing(Exception):
963     """Indicate that option *and argument* processing should stop
964     cleanly. This is not an error condition. It is similar in spirit to
965     StopIteration. This is raised by _OptionParserEx's default "help"
966     and "version" option actions and can be raised by custom option
967     callbacks too.
968
969     Hence the typical CmdlnOptionParser (a subclass of _OptionParserEx)
970     usage is:
971
972         parser = CmdlnOptionParser(mycmd)
973         parser.add_option("-f", "--force", dest="force")
974         ...
975         try:
976             opts, args = parser.parse_args()
977         except StopOptionProcessing:
978             # normal termination, "--help" was probably given
979             sys.exit(0)
980     """
981
982 class _OptionParserEx(optparse.OptionParser):
983     """An optparse.OptionParser that uses exceptions instead of sys.exit.
984
985     This class is an extension of optparse.OptionParser that differs
986     as follows:
987     - Correct (IMO) the default OptionParser error handling to never
988       sys.exit(). Instead OptParseError exceptions are passed through.
989     - Add the StopOptionProcessing exception (a la StopIteration) to
990       indicate normal termination of option processing.
991       See StopOptionProcessing's docstring for details.
992
993     I'd also like to see the following in the core optparse.py, perhaps
994     as a RawOptionParser which would serve as a base class for the more
995     generally used OptionParser (that works as current):
996     - Remove the implicit addition of the -h|--help and --version
997       options. They can get in the way (e.g. if want '-?' and '-V' for
998       these as well) and it is not hard to do:
999         optparser.add_option("-h", "--help", action="help")
1000         optparser.add_option("--version", action="version")
1001       These are good practices, just not valid defaults if they can
1002       get in the way.
1003     """
1004     def error(self, msg):
1005         raise optparse.OptParseError(msg)
1006
1007     def exit(self, status=0, msg=None):
1008         if status == 0:
1009             raise StopOptionProcessing(msg)
1010         else:
1011             #TODO: don't lose status info here
1012             raise optparse.OptParseError(msg)
1013
1014
1015
1016 #---- optparse.py-based option processing support
1017
1018 class CmdlnOptionParser(_OptionParserEx):
1019     """An optparse.OptionParser class more appropriate for top-level
1020     Cmdln options. For parsing of sub-command options, see
1021     SubCmdOptionParser.
1022
1023     Changes:
1024     - disable_interspersed_args() by default, because a Cmdln instance
1025       has sub-commands which may themselves have options.
1026     - Redirect print_help() to the Cmdln.do_help() which is better
1027       equiped to handle the "help" action.
1028     - error() will raise a CmdlnUserError: OptionParse.error() is meant
1029       to be called for user errors. Raising a well-known error here can
1030       make error handling clearer.
1031     - Also see the changes in _OptionParserEx.
1032     """
1033     def __init__(self, cmdln, **kwargs):
1034         self.cmdln = cmdln
1035         kwargs["prog"] = self.cmdln.name
1036         _OptionParserEx.__init__(self, **kwargs)
1037         self.disable_interspersed_args()
1038
1039     def print_help(self, file=None):
1040         self.cmdln.onecmd(["help"])
1041
1042     def error(self, msg):
1043         raise CmdlnUserError(msg)
1044
1045
1046 class SubCmdOptionParser(_OptionParserEx):
1047     def set_cmdln_info(self, cmdln, subcmd):
1048         """Called by Cmdln to pass relevant info about itself needed
1049         for print_help().
1050         """
1051         self.cmdln = cmdln
1052         self.subcmd = subcmd
1053
1054     def print_help(self, file=None):
1055         self.cmdln.onecmd(["help", self.subcmd])
1056
1057     def error(self, msg):
1058         raise CmdlnUserError(msg)
1059
1060
1061 def option(*args, **kwargs):
1062     """Decorator to add an option to the optparser argument of a Cmdln
1063     subcommand.
1064
1065     Example:
1066         class MyShell(cmdln.Cmdln):
1067             @cmdln.option("-f", "--force", help="force removal")
1068             def do_remove(self, subcmd, opts, *args):
1069                 #...
1070     """
1071     #XXX Is there a possible optimization for many options to not have a
1072     #    large stack depth here?
1073     def decorate(f):
1074         if not hasattr(f, "optparser"):
1075             f.optparser = SubCmdOptionParser()
1076         f.optparser.add_option(*args, **kwargs)
1077         return f
1078     return decorate
1079
1080 def hide(*args):
1081     """For obsolete calls, hide them in help listings.
1082
1083     Example:
1084         class MyShell(cmdln.Cmdln):
1085             @cmdln.hide()
1086             def do_shell(self, argv):
1087                 #...implement 'shell' command
1088     """
1089     def decorate(f):
1090         f.hidden = 1
1091         return f
1092     return decorate
1093
1094
1095 class Cmdln(RawCmdln):
1096     """An improved (on cmd.Cmd) framework for building multi-subcommand
1097     scripts (think "svn" & "cvs") and simple shells (think "pdb" and
1098     "gdb").
1099
1100     A simple example:
1101
1102         import cmdln
1103
1104         class MySVN(cmdln.Cmdln):
1105             name = "svn"
1106
1107             @cmdln.aliases('stat', 'st')
1108             @cmdln.option('-v', '--verbose', action='store_true'
1109                           help='print verbose information')
1110             def do_status(self, subcmd, opts, *paths):
1111                 print "handle 'svn status' command"
1112
1113             #...
1114
1115         if __name__ == "__main__":
1116             shell = MySVN()
1117             retval = shell.main()
1118             sys.exit(retval)
1119
1120     'Cmdln' extends 'RawCmdln' by providing optparse option processing
1121     integration.  See this class' _dispatch_cmd() docstring and
1122     <http://trentm.com/projects/cmdln> for more information.
1123     """
1124     def _dispatch_cmd(self, handler, argv):
1125         """Introspect sub-command handler signature to determine how to
1126         dispatch the command. The raw handler provided by the base
1127         'RawCmdln' class is still supported:
1128
1129             def do_foo(self, argv):
1130                 # 'argv' is the vector of command line args, argv[0] is
1131                 # the command name itself (i.e. "foo" or an alias)
1132                 pass
1133
1134         In addition, if the handler has more than 2 arguments option
1135         processing is automatically done (using optparse):
1136
1137             @cmdln.option('-v', '--verbose', action='store_true')
1138             def do_bar(self, subcmd, opts, *args):
1139                 # subcmd = <"bar" or an alias>
1140                 # opts = <an optparse.Values instance>
1141                 if opts.verbose:
1142                     print "lots of debugging output..."
1143                 # args = <tuple of arguments>
1144                 for arg in args:
1145                     bar(arg)
1146
1147         TODO: explain that "*args" can be other signatures as well.
1148
1149         The `cmdln.option` decorator corresponds to an `add_option()`
1150         method call on an `optparse.OptionParser` instance.
1151
1152         You can declare a specific number of arguments:
1153
1154             @cmdln.option('-v', '--verbose', action='store_true')
1155             def do_bar2(self, subcmd, opts, bar_one, bar_two):
1156                 #...
1157
1158         and an appropriate error message will be raised/printed if the
1159         command is called with a different number of args.
1160         """
1161         co_argcount = handler.im_func.func_code.co_argcount
1162         if co_argcount == 2:   # handler ::= do_foo(self, argv)
1163             return handler(argv)
1164         elif co_argcount >= 3: # handler ::= do_foo(self, subcmd, opts, ...)
1165             try:
1166                 optparser = handler.optparser
1167             except AttributeError:
1168                 optparser = handler.im_func.optparser = SubCmdOptionParser()
1169             assert isinstance(optparser, SubCmdOptionParser)
1170             optparser.set_cmdln_info(self, argv[0])
1171             try:
1172                 opts, args = optparser.parse_args(argv[1:])
1173             except StopOptionProcessing:
1174                 #TODO: this doesn't really fly for a replacement of
1175                 #      optparse.py behaviour, does it?
1176                 return 0 # Normal command termination
1177
1178             try:
1179                 return handler(argv[0], opts, *args)
1180             except TypeError, ex:
1181                 # Some TypeError's are user errors:
1182                 #   do_foo() takes at least 4 arguments (3 given)
1183                 #   do_foo() takes at most 5 arguments (6 given)
1184                 #   do_foo() takes exactly 5 arguments (6 given)
1185                 # Raise CmdlnUserError for these with a suitably
1186                 # massaged error message.
1187                 import sys
1188                 tb = sys.exc_info()[2] # the traceback object
1189                 if tb.tb_next is not None:
1190                     # If the traceback is more than one level deep, then the
1191                     # TypeError do *not* happen on the "handler(...)" call
1192                     # above. In that we don't want to handle it specially
1193                     # here: it would falsely mask deeper code errors.
1194                     raise
1195                 msg = ex.args[0]
1196                 match = _INCORRECT_NUM_ARGS_RE.search(msg)
1197                 if match:
1198                     msg = list(match.groups())
1199                     msg[1] = int(msg[1]) - 3
1200                     if msg[1] == 1:
1201                         msg[2] = msg[2].replace("arguments", "argument")
1202                     msg[3] = int(msg[3]) - 3
1203                     msg = ''.join(map(str, msg))
1204                     raise CmdlnUserError(msg)
1205                 else:
1206                     raise
1207         else:
1208             raise CmdlnError("incorrect argcount for %s(): takes %d, must "
1209                              "take 2 for 'argv' signature or 3+ for 'opts' "
1210                              "signature" % (handler.__name__, co_argcount))
1211
1212
1213
1214 #---- internal support functions
1215
1216 def _format_linedata(linedata, indent, indent_width):
1217     """Format specific linedata into a pleasant layout.
1218
1219         "linedata" is a list of 2-tuples of the form:
1220             (<item-display-string>, <item-docstring>)
1221         "indent" is a string to use for one level of indentation
1222         "indent_width" is a number of columns by which the
1223             formatted data will be indented when printed.
1224
1225     The <item-display-string> column is held to 15 columns.
1226     """
1227     lines = []
1228     WIDTH = 78 - indent_width
1229     SPACING = 3
1230     MAX_NAME_WIDTH = 15
1231
1232     NAME_WIDTH = min(max([len(s) for s,d in linedata]), MAX_NAME_WIDTH)
1233     DOC_WIDTH = WIDTH - NAME_WIDTH - SPACING
1234     for namestr, doc in linedata:
1235         line = indent + namestr
1236         if len(namestr) <= NAME_WIDTH:
1237             line += ' ' * (NAME_WIDTH + SPACING - len(namestr))
1238         else:
1239             lines.append(line)
1240             line = indent + ' ' * (NAME_WIDTH + SPACING)
1241         line += _summarize_doc(doc, DOC_WIDTH)
1242         lines.append(line.rstrip())
1243     return lines
1244
1245 def _summarize_doc(doc, length=60):
1246     r"""Parse out a short one line summary from the given doclines.
1247
1248         "doc" is the doc string to summarize.
1249         "length" is the max length for the summary
1250
1251     >>> _summarize_doc("this function does this")
1252     'this function does this'
1253     >>> _summarize_doc("this function does this", 10)
1254     'this fu...'
1255     >>> _summarize_doc("this function does this\nand that")
1256     'this function does this and that'
1257     >>> _summarize_doc("this function does this\n\nand that")
1258     'this function does this'
1259     """
1260     import re
1261     if doc is None:
1262         return ""
1263     assert length > 3, "length <= 3 is absurdly short for a doc summary"
1264     doclines = doc.strip().splitlines(0)
1265     if not doclines:
1266         return ""
1267
1268     summlines = []
1269     for i, line in enumerate(doclines):
1270         stripped = line.strip()
1271         if not stripped:
1272             break
1273         summlines.append(stripped)
1274         if len(''.join(summlines)) >= length:
1275             break
1276
1277     summary = ' '.join(summlines)
1278     if len(summary) > length:
1279         summary = summary[:length-3] + "..."
1280     return summary
1281
1282
1283 def line2argv(line):
1284     r"""Parse the given line into an argument vector.
1285
1286         "line" is the line of input to parse.
1287
1288     This may get niggly when dealing with quoting and escaping. The
1289     current state of this parsing may not be completely thorough/correct
1290     in this respect.
1291
1292     >>> from cmdln import line2argv
1293     >>> line2argv("foo")
1294     ['foo']
1295     >>> line2argv("foo bar")
1296     ['foo', 'bar']
1297     >>> line2argv("foo bar ")
1298     ['foo', 'bar']
1299     >>> line2argv(" foo bar")
1300     ['foo', 'bar']
1301
1302     Quote handling:
1303
1304     >>> line2argv("'foo bar'")
1305     ['foo bar']
1306     >>> line2argv('"foo bar"')
1307     ['foo bar']
1308     >>> line2argv(r'"foo\"bar"')
1309     ['foo"bar']
1310     >>> line2argv("'foo bar' spam")
1311     ['foo bar', 'spam']
1312     >>> line2argv("'foo 'bar spam")
1313     ['foo bar', 'spam']
1314     >>> line2argv("'foo")
1315     Traceback (most recent call last):
1316         ...
1317     ValueError: command line is not terminated: unfinished single-quoted segment
1318     >>> line2argv('"foo')
1319     Traceback (most recent call last):
1320         ...
1321     ValueError: command line is not terminated: unfinished double-quoted segment
1322     >>> line2argv('some\tsimple\ttests')
1323     ['some', 'simple', 'tests']
1324     >>> line2argv('a "more complex" test')
1325     ['a', 'more complex', 'test']
1326     >>> line2argv('a more="complex test of " quotes')
1327     ['a', 'more=complex test of ', 'quotes']
1328     >>> line2argv('a more" complex test of " quotes')
1329     ['a', 'more complex test of ', 'quotes']
1330     >>> line2argv('an "embedded \\"quote\\""')
1331     ['an', 'embedded "quote"']
1332     """
1333     import string
1334     line = line.strip()
1335     argv = []
1336     state = "default"
1337     arg = None  # the current argument being parsed
1338     i = -1
1339     while 1:
1340         i += 1
1341         if i >= len(line): break
1342         ch = line[i]
1343
1344         if ch == "\\": # escaped char always added to arg, regardless of state
1345             if arg is None: arg = ""
1346             i += 1
1347             arg += line[i]
1348             continue
1349
1350         if state == "single-quoted":
1351             if ch == "'":
1352                 state = "default"
1353             else:
1354                 arg += ch
1355         elif state == "double-quoted":
1356             if ch == '"':
1357                 state = "default"
1358             else:
1359                 arg += ch
1360         elif state == "default":
1361             if ch == '"':
1362                 if arg is None: arg = ""
1363                 state = "double-quoted"
1364             elif ch == "'":
1365                 if arg is None: arg = ""
1366                 state = "single-quoted"
1367             elif ch in string.whitespace:
1368                 if arg is not None:
1369                     argv.append(arg)
1370                 arg = None
1371             else:
1372                 if arg is None: arg = ""
1373                 arg += ch
1374     if arg is not None:
1375         argv.append(arg)
1376     if state != "default":
1377         raise ValueError("command line is not terminated: unfinished %s "
1378                          "segment" % state)
1379     return argv
1380
1381
1382 def argv2line(argv):
1383     r"""Put together the given argument vector into a command line.
1384
1385         "argv" is the argument vector to process.
1386
1387     >>> from cmdln import argv2line
1388     >>> argv2line(['foo'])
1389     'foo'
1390     >>> argv2line(['foo', 'bar'])
1391     'foo bar'
1392     >>> argv2line(['foo', 'bar baz'])
1393     'foo "bar baz"'
1394     >>> argv2line(['foo"bar'])
1395     'foo"bar'
1396     >>> print argv2line(['foo" bar'])
1397     'foo" bar'
1398     >>> print argv2line(["foo' bar"])
1399     "foo' bar"
1400     >>> argv2line(["foo'bar"])
1401     "foo'bar"
1402     """
1403     escapedArgs = []
1404     for arg in argv:
1405         if ' ' in arg and '"' not in arg:
1406             arg = '"'+arg+'"'
1407         elif ' ' in arg and "'" not in arg:
1408             arg = "'"+arg+"'"
1409         elif ' ' in arg:
1410             arg = arg.replace('"', r'\"')
1411             arg = '"'+arg+'"'
1412         escapedArgs.append(arg)
1413     return ' '.join(escapedArgs)
1414
1415
1416 # Recipe: dedent (0.1) in /Users/trentm/tm/recipes/cookbook
1417 def _dedentlines(lines, tabsize=8, skip_first_line=False):
1418     """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
1419
1420         "lines" is a list of lines to dedent.
1421         "tabsize" is the tab width to use for indent width calculations.
1422         "skip_first_line" is a boolean indicating if the first line should
1423             be skipped for calculating the indent width and for dedenting.
1424             This is sometimes useful for docstrings and similar.
1425
1426     Same as dedent() except operates on a sequence of lines. Note: the
1427     lines list is modified **in-place**.
1428     """
1429     DEBUG = False
1430     if DEBUG:
1431         print "dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
1432               % (tabsize, skip_first_line)
1433     indents = []
1434     margin = None
1435     for i, line in enumerate(lines):
1436         if i == 0 and skip_first_line: continue
1437         indent = 0
1438         for ch in line:
1439             if ch == ' ':
1440                 indent += 1
1441             elif ch == '\t':
1442                 indent += tabsize - (indent % tabsize)
1443             elif ch in '\r\n':
1444                 continue # skip all-whitespace lines
1445             else:
1446                 break
1447         else:
1448             continue # skip all-whitespace lines
1449         if DEBUG: print "dedent: indent=%d: %r" % (indent, line)
1450         if margin is None:
1451             margin = indent
1452         else:
1453             margin = min(margin, indent)
1454     if DEBUG: print "dedent: margin=%r" % margin
1455
1456     if margin is not None and margin > 0:
1457         for i, line in enumerate(lines):
1458             if i == 0 and skip_first_line: continue
1459             removed = 0
1460             for j, ch in enumerate(line):
1461                 if ch == ' ':
1462                     removed += 1
1463                 elif ch == '\t':
1464                     removed += tabsize - (removed % tabsize)
1465                 elif ch in '\r\n':
1466                     if DEBUG: print "dedent: %r: EOL -> strip up to EOL" % line
1467                     lines[i] = lines[i][j:]
1468                     break
1469                 else:
1470                     raise ValueError("unexpected non-whitespace char %r in "
1471                                      "line %r while removing %d-space margin"
1472                                      % (ch, line, margin))
1473                 if DEBUG:
1474                     print "dedent: %r: %r -> removed %d/%d"\
1475                           % (line, ch, removed, margin)
1476                 if removed == margin:
1477                     lines[i] = lines[i][j+1:]
1478                     break
1479                 elif removed > margin:
1480                     lines[i] = ' '*(removed-margin) + lines[i][j+1:]
1481                     break
1482     return lines
1483
1484 def _dedent(text, tabsize=8, skip_first_line=False):
1485     """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
1486
1487         "text" is the text to dedent.
1488         "tabsize" is the tab width to use for indent width calculations.
1489         "skip_first_line" is a boolean indicating if the first line should
1490             be skipped for calculating the indent width and for dedenting.
1491             This is sometimes useful for docstrings and similar.
1492
1493     textwrap.dedent(s), but don't expand tabs to spaces
1494     """
1495     lines = text.splitlines(1)
1496     _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
1497     return ''.join(lines)
1498
1499
1500 def _get_indent(marker, s, tab_width=8):
1501     """_get_indent(marker, s, tab_width=8) ->
1502         (<indentation-of-'marker'>, <indentation-width>)"""
1503     # Figure out how much the marker is indented.
1504     INDENT_CHARS = tuple(' \t')
1505     start = s.index(marker)
1506     i = start
1507     while i > 0:
1508         if s[i-1] not in INDENT_CHARS:
1509             break
1510         i -= 1
1511     indent = s[i:start]
1512     indent_width = 0
1513     for ch in indent:
1514         if ch == ' ':
1515             indent_width += 1
1516         elif ch == '\t':
1517             indent_width += tab_width - (indent_width % tab_width)
1518     return indent, indent_width
1519
1520 def _get_trailing_whitespace(marker, s):
1521     """Return the whitespace content trailing the given 'marker' in string 's',
1522     up to and including a newline.
1523     """
1524     suffix = ''
1525     start = s.index(marker) + len(marker)
1526     i = start
1527     while i < len(s):
1528         if s[i] in ' \t':
1529             suffix += s[i]
1530         elif s[i] in '\r\n':
1531             suffix += s[i]
1532             if s[i] == '\r' and i+1 < len(s) and s[i+1] == '\n':
1533                 suffix += s[i+1]
1534             break
1535         else:
1536             break
1537         i += 1
1538     return suffix
1539