| 1 | #!/usr/bin/env python |
|---|
| 2 | """ |
|---|
| 3 | using pastescript template from a string |
|---|
| 4 | """ |
|---|
| 5 | |
|---|
| 6 | import os |
|---|
| 7 | import re |
|---|
| 8 | import shutil |
|---|
| 9 | import tempfile |
|---|
| 10 | |
|---|
| 11 | from paste.script.copydir import LaxTemplate |
|---|
| 12 | from paste.script.templates import Template |
|---|
| 13 | from traclegos.pastescript.command import create_distro_command |
|---|
| 14 | |
|---|
| 15 | class PasteScriptStringTemplate(Template): |
|---|
| 16 | |
|---|
| 17 | def __init__(self, string, name=None, summary='', interactive=False, |
|---|
| 18 | vars=None): |
|---|
| 19 | |
|---|
| 20 | self.string = string |
|---|
| 21 | self.cmd = create_distro_command(interactive) |
|---|
| 22 | |
|---|
| 23 | # make a temporary directory + file for the string |
|---|
| 24 | directory = tempfile.mkdtemp() |
|---|
| 25 | if not name: |
|---|
| 26 | name = tempfile.mktemp(dir=directory) |
|---|
| 27 | fd = file(os.path.join(directory, name), 'w') |
|---|
| 28 | print >> fd, string |
|---|
| 29 | fd.close() |
|---|
| 30 | self.name = name |
|---|
| 31 | |
|---|
| 32 | # variables for PasteScript's template |
|---|
| 33 | Template.__init__(self, name) |
|---|
| 34 | self._template_dir = directory |
|---|
| 35 | self.summary = summary |
|---|
| 36 | self.vars = vars or [] |
|---|
| 37 | |
|---|
| 38 | def __del__(self): |
|---|
| 39 | shutil.rmtree(self._template_dir) |
|---|
| 40 | |
|---|
| 41 | def interpolate(self, vars=None, interactive=False, fp=None): |
|---|
| 42 | """return the interpolated string""" |
|---|
| 43 | |
|---|
| 44 | vars = vars or {} |
|---|
| 45 | directory = tempfile.mkdtemp() |
|---|
| 46 | self.run(self.cmd, directory, vars) |
|---|
| 47 | string = file(os.path.join(directory, self.name)).read() |
|---|
| 48 | shutil.rmtree(directory) |
|---|
| 49 | return string |
|---|
| 50 | |
|---|
| 51 | def substitute(self, **vars): |
|---|
| 52 | return LaxTemplate(self.string).safe_substitute(vars) |
|---|
| 53 | |
|---|
| 54 | def missing(self, vars=()): |
|---|
| 55 | return set([ i[2] for i in re.findall(LaxTemplate.pattern, self.string) |
|---|
| 56 | if i[2] and i[2] not in vars ]) |
|---|
| 57 | |
|---|
| 58 | if __name__ == '__main__': |
|---|
| 59 | import sys |
|---|
| 60 | template = StringTemplate(' '.join(sys.argv[1:])) |
|---|
| 61 | result = template.interpolate() |
|---|
| 62 | print result |
|---|
| 63 | |
|---|