0001import os
0002import glob
0003from paste.script.command import Command, BadCommand
0004from paste.script import pluginlib, copydir
0005
0006class ServletCommand(Command):
0007
0008    summary = "Create servlet"
0009    usage = 'SERVLET_NAME'
0010
0011    min_args = 1
0012    max_args = 1
0013    default_verbosity = 1
0014
0015    parser = Command.standard_parser(simulate=True,
0016                                     interactive=True,
0017                                     quiet=True)
0018    parser.add_option('--no-servlet',
0019                      action='store_true',
0020                      dest='no_servlet',
0021                      help="Don't create a servlet; just template(s)")
0022
0023    def command(self):
0024        servlet = self.args[0]
0025        if servlet.endswith('.py'):
0026            # Erase extensions
0027            servlet = servlet[:-3]
0028        if '.' in servlet:
0029            # Turn into directory name:
0030            servlet = servlet.replace('.', os.path.sep)
0031        if '/' != os.path.sep:
0032            servlet = servlet.replace('/', os.path.sep)
0033        parts = servlet.split(os.path.sep)
0034        name = parts[-1]
0035        base_package, base = self.web_dir()
0036        if not parts[:-1]:
0037            dir = ''
0038        elif len(parts[:-1]) == 1:
0039            dir = parts[0]
0040        else:
0041            dir = os.path.join(*parts[:-1])
0042
0043        vars = {'name': name,
0044                'base_package': base_package}
0045
0046        if not self.options.no_servlet:
0047            self.create_servlet(
0048                base_package, base, dir, name, vars)
0049
0050        template_base = os.path.join(os.path.dirname(base), 'templates')
0051        if not os.path.exists(template_base):
0052            if self.verbose > 1:
0053                print 'No template directory %s' % template_base
0054            return
0055
0056        blanks = glob.glob(os.path.join(base, template_base, 'blank.*'))
0057        if not blanks and self.verbose:
0058            print 'No blank templates found in %s' % self.shorten(template_base)
0059
0060        for blank in blanks:
0061            self.create_blank(
0062                blank, template_base, dir, name, vars)
0063
0064    def create_servlet(self, base_package, base, dir, name, vars):
0065        self.ensure_dir(os.path.join(base, dir))
0066        blank = os.path.join(base, 'blank.py')
0067        if not os.path.exists(blank):
0068            blank = os.path.join(os.path.dirname(__file__),
0069                                 'paster_templates',
0070                                 'blank_servlet.py_tmpl')
0071        f = open(blank, 'r')
0072        content = f.read()
0073        f.close()
0074        if blank.endswith('_tmpl'):
0075            content = copydir.substitute_content(content, vars,
0076                                                 filename=blank)
0077        dest = os.path.join(base, dir, '%s.py' % name)
0078        self.write_file(dest, content, source=blank)
0079
0080    def create_blank(self, blank, template_base, dir, name, vars):
0081        ext = os.path.splitext(blank)[1]
0082        f = open(blank, 'r')
0083        content = f.read()
0084        f.close()
0085        if ext.endswith('_tmpl'):
0086            content = copydir.substitute_content(
0087                content, vars, filename=blank)
0088            ext = ext[:-5]
0089        dest = os.path.join(template_base, dir, name + ext)
0090        self.ensure_dir(os.path.dirname(dest))
0091        self.write_file(dest, content, source=blank)
0092
0093    def web_dir(self):
0094        egg_info = pluginlib.find_egg_info_dir(os.getcwd())
0095        # @@: Should give error about egg_info when top_leve.txt missing
0096        f = open(os.path.join(egg_info, 'top_level.txt'))
0097        packages = [l.strip() for l in f.readlines()
0098                    if l.strip() and not l.strip().startswith('#')]
0099        f.close()
0100        # @@: This doesn't support deeper servlet directories,
0101        # or packages not kept at the top level.
0102        base = os.path.dirname(egg_info)
0103        possible = []
0104        for pkg in packages:
0105            d = os.path.join(base, pkg, 'web')
0106            if os.path.exists(d):
0107                possible.append((pkg, d))
0108        if not possible:
0109            raise BadCommand(
0110                "No web package found (looked in %s)"
0111                % ', '.join(packages))
0112        if len(possible) > 1:
0113            raise BadCommand(
0114                "Multiple web packages found (%s)" % possible)
0115        return possible[0]