00001 """
00002 MoinMoin - GetCode Macro
00003
00004 <<GetCode(uri,start_line,end_line)>>
00005
00006 """
00007
00008 from urllib import urlopen
00009 import StringIO
00010
00011 from MoinMoin.parser import text_moin_wiki as wiki
00012
00013 Dependencies = ["namespace"]
00014
00015
00016 def execute(macro, args):
00017 args = args.split(',')
00018 if len(args) != 2 and len(args) != 4:
00019 return "invalid arguments: GetCode(uri,spec[,start_line,end_line])"
00020
00021 uri = args[0]
00022 if 'ros.org/wiki' in uri or 'ros.org/doc' in uri:
00023 return "GetCode cannot be used with www.ros.org URLs"
00024
00025 specline = args[1]
00026 if specline[:2] != '#!':
00027 specline = '#!' + specline
00028
00029
00030 if not uri:
00031 return "invalid arguments: no code uri specified"
00032 cache = getattr(macro.request.cfg, 'get_tag_cache', {})
00033 if uri not in cache:
00034 cache[uri] = urlopen(uri).readlines()
00035 lines = cache[uri]
00036 macro.request.cfg.get_tag_cache = dict(cache)
00037
00038 if len(args) == 4:
00039 start_line = int(args[2])
00040 end_line = int(args[3])
00041
00042 if start_line > end_line:
00043 return "invalid arguments: start_line cannot be greater than end_line."
00044
00045 lines = lines[start_line - 1:end_line]
00046 else:
00047 start_line = 1
00048
00049
00050 if len(''.join(lines[0].splitlines())) == 0:
00051 lines[0] += '\n'
00052 code_block = ''.join(lines)
00053
00054 out = StringIO.StringIO()
00055 macro.request.redirect(out)
00056 if len(args) == 4:
00057 wikiizer = wiki.Parser("{{{\n" + specline
00058 + " start=%d" % start_line + "\n"
00059 + str(code_block) + "\n}}}\n",
00060 macro.request)
00061 else:
00062 wikiizer = wiki.Parser("''" + uri + "''\n"
00063 + "{{{\n" + specline
00064 + " start=%d" % start_line + "\n"
00065 + str(code_block) + "\n}}}\n",
00066 macro.request)
00067
00068 wikiizer.format(macro.formatter)
00069 result = out.getvalue()
00070 macro.request.redirect()
00071 del out
00072
00073 return result