Example #1
0
 def find_dir(self, dirname, package=False):
     egg_info = pluginlib.find_egg_info_dir(os.getcwd())
     # @@: Should give error about egg_info when top_level.txt missing
     f = open(os.path.join(egg_info, 'top_level.txt'))
     packages = [
         l.strip() for l in f.readlines()
         if l.strip() and not l.strip().startswith('#')
     ]
     f.close()
     if not len(packages):
         raise BadCommand("No top level dir found for %s" % dirname)
     # @@: This doesn't support deeper servlet directories,
     # or packages not kept at the top level.
     base = os.path.dirname(egg_info)
     possible = []
     for pkg in packages:
         d = os.path.join(base, pkg, dirname)
         if os.path.exists(d):
             possible.append((pkg, d))
     if not possible:
         self.ensure_dir(os.path.join(base, packages[0], dirname),
                         package=package)
         return self.find_dir(dirname)
     if len(possible) > 1:
         raise BadCommand("Multiple %s dirs found (%s)" %
                          (dirname, possible))
     return possible[0]
Example #2
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == name.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.' % base_package)
            # Validate the name
            name = name.replace('-', '_')
            validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = (
                    'from %s.controllers import BaseController' % base_package)
            else:
                importstatement = ('from %s.lib.base import BaseController' %
                                   base_package)
            if defines_render(base_package):
                importstatement += ', render'

            # Setup the controller
            fullname = os.path.join(directory, name)
            controller_name = util.class_name_from_module_name(
                name.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            module_dir = directory.replace('/', os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            file_op.template_vars.update({
                'name': controller_name,
                'fname': os.path.join(directory, name),
                'tmpl_name': name,
                'package': base_package,
                'importstatement': importstatement
            })
            file_op.copy_file(template='controller.py_tmpl',
                              dest=os.path.join('controllers', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_controller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
Example #3
0
 def check_config_file(self):
     if self.installer.expect_config_directory is None:
         return
     fn = self.config_file
     if self.installer.expect_config_directory:
         if os.path.splitext(fn)[1]:
             raise BadCommand(
                 "The CONFIG_FILE argument %r looks like a filename, "
                 "and a directory name is expected" % fn)
     else:
         if fn.endswith('/') or not os.path.splitext(fn):
             raise BadCommand(
                 "The CONFIG_FILE argument %r looks like a directory "
                 "name and a filename is expected" % fn)
Example #4
0
    def command(self):
        if self.requires_config_file:
            if not self.args:
                raise BadCommand('You must give a config file')
            app_spec = self.args[0]
            if (len(self.args) > 1
                    and self.args[1] in self.possible_subcommands):
                self.cmd = self.args[1]
                self.restvars = self.args[2:]
            else:
                self.cmd = None
                self.restvars = self.args[1:]
        else:
            app_spec = ""
            if (self.args and self.args[0] in self.possible_subcommands):
                self.cmd = self.args[0]
                self.restvars = self.args[1:]
            else:
                self.cmd = None
                self.restvars = self.args[:]

        self.logging_file_config(app_spec)

        config_name = 'config:%s' % app_spec
        here_dir = os.getcwd()

        parser = ConfigParser.ConfigParser()
        parser.read([app_spec])
        if not parser.has_section(self.CONFIG_SECTION):
            raise BadCommand('Error: %s missing %s configuration section' % \
                                 (app_spec, self.CONFIG_SECTION))
        self.config = dict(
            parser.items(self.CONFIG_SECTION, vars={'here': here_dir}))

        engine = engine_from_config(self.config, 'sqlalchemy.')
        init_model(engine)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)
Example #5
0
 def parse_args(self, *av, **kw):
     super(Command, self).parse_args(*av, **kw)
     if not self.args:
         raise BadCommand("please specify a configuration file")
     config = self.args[0]
     self.args = self.args[1:]
     self.parse_config(config)
Example #6
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment and get the mapper
        tresponse = test_app.get('/_test_vars')
        mapper = tresponse.config.get('routes.map')
        if mapper:
            print mapper
Example #7
0
 def get_distribution(self, req):
     """
     This gets a distribution object, and installs the distribution
     if required.
     """
     try:
         dist = pkg_resources.get_distribution(req)
         if self.verbose:
             print('Distribution already installed:')
             print(' ', dist, 'from', dist.location)
         return dist
     except pkg_resources.DistributionNotFound:
         if self.options.no_install:
             print("Because --no-install was given, we won't try to install the package %s" % req)
             raise
         options = ['-v', '-m']
         for op in self.options.easy_install_op or []:
             if not op.startswith('-'):
                 op = '--'+op
             options.append(op)
         for op in self.options.easy_install_find_links or []:
             options.append('--find-links=%s' % op)
         if self.simulate:
             raise BadCommand(
                 "Must install %s, but in simulation mode" % req)
         print("Must install %s" % req)
         from setuptools.command import easy_install
         from setuptools import setup
         setup(script_args=['-q', 'easy_install']
               + options + [req])
         return pkg_resources.get_distribution(req)
Example #8
0
 def command(self):
     config_spec = self.args[0]
     section = self.options.section_name
     if section is None:
         if '#' in config_spec:
             config_spec, section = config_spec.split('#', 1)
         else:
             section = 'main'
     if not ':' in section:
         plain_section = section
         section = 'app:'+section
     else:
         plain_section = section.split(':', 1)[0]
     if not config_spec.startswith('config:'):
         config_spec = 'config:' + config_spec
     if plain_section != 'main':
         config_spec += '#' + plain_section
     config_file = config_spec[len('config:'):].split('#', 1)[0]
     config_file = os.path.join(os.getcwd(), config_file)
     self.logging_file_config(config_file)
     conf = appconfig(config_spec, relative_to=os.getcwd())
     ep_name = conf.context.entry_point_name
     ep_group = conf.context.protocol
     dist = conf.context.distribution
     if dist is None:
         raise BadCommand(
             "The section %r is not the application (probably a filter).  You should add #section_name, where section_name is the section that configures your application" % plain_section)
     installer = self.get_installer(dist, ep_group, ep_name)
     installer.setup_config(
         self, config_file, section, self.sysconfig_install_vars(installer))
     self.call_sysconfig_functions(
         'post_setup_hook', installer, config_file)
Example #9
0
 def run(self, args):
     # This is overridden so we can parse sys-config before we pass
     # it to optparse
     self.sysconfigs = self.default_sysconfigs
     new_args = []
     while args:
         if args[0].startswith('--no-default-sysconfig'):
             self.sysconfigs = []
             args.pop(0)
             continue
         if args[0].startswith('--sysconfig='):
             self.sysconfigs.insert(
                 0, (True, args.pop(0)[len('--sysconfig='):]))
             continue
         if args[0] == '--sysconfig':
             args.pop(0)
             if not args:
                 raise BadCommand(
                     "You gave --sysconfig as the last argument without "
                     "a value")
             self.sysconfigs.insert(0, (True, args.pop(0)))
             continue
         new_args.append(args.pop(0))
     self.load_sysconfigs()
     return super(AbstractInstallCommand, self).run(new_args)
Example #10
0
def check_controller_existence(base_package, directory, name):
    """Check if given controller already exists in project."""
    filename = os.path.join(base_package, 'controllers', directory,
                            name + '.py')
    if os.path.exists(filename):
        raise BadCommand('Controller %s already exists.' %
                         os.path.join(directory, name))
Example #11
0
    def command(self):
        config_spec = self.args[0]
        if not config_spec.startswith('config:'):
            config_spec = 'config:' + config_spec
        config_file = config_spec[len('config:'):].split('#', 1)[0]
        config_file = os.path.join(os.getcwd(), config_file)
        try:
            import isapi_wsgi
        except ImportError:
            raise BadCommand('missing requirement: isapi-wsgi not installed')

        file = '''import sys

if hasattr(sys, "isapidllhandle"):
    import win32traceutil

import isapi_wsgi
import os

def __ExtensionFactory__():
    from paste.deploy import loadapp
    from paste.script.util.logging_config import fileConfig
    fileConfig('%(inifile)s')
    application = loadapp('config:%(inifile)s')

    def app(environ, start_response):
        user = environ.get('REMOTE_USER', None)
        if user is not None:
            os.environ['REMOTE_USER'] = user
        return application(environ, start_response)

    return isapi_wsgi.ISAPIThreadPoolHandler(app)

if __name__=='__main__':
    from isapi.install import *
    params = ISAPIParameters()
    sm = [ScriptMapParams(Extension="*", Flags=0)]
    vd = VirtualDirParameters(Name="%(virtualdir)s",
                              Description = "Kallithea",
                              ScriptMaps = sm,
                              ScriptMapUpdate = "replace")
    params.VirtualDirs = [vd]
    HandleCommandLine(params)
'''

        outdata = file % {
            'inifile': config_file.replace('\\', '\\\\'),
            'virtualdir': self.options.virtualdir
        }

        dispatchfile = os.path.join(os.getcwd(), 'dispatch.py')
        self.ensure_file(dispatchfile, outdata, False)
        print 'generating', dispatchfile

        print(
            'run \'python "%s" install\' with administrative privileges '
            'to generate the _dispatch.dll file and install it into the '
            'default web site') % (dispatchfile, )
Example #12
0
    def command(self):
        """Main command that starts the migration."""
        super(RunMigrationCommand, self).command()

        if self.options.list_scripts:
            self.list_scripts()
            return

        if not self.restvars:
            raise BadCommand("You must specify a migration script to run")

        script = self.restvars[0]

        if not hasattr(scripts, script):
            raise BadCommand("The migration script %s does not exist" % script)

        migrator = getattr(scripts, script)
        migrator()
Example #13
0
def validate_name(name):
    """Validate that the name for the controller isn't present on the
    path already"""
    if not name:
        # This happens when the name is an existing directory
        raise BadCommand('Please give the name of a controller.')
    # 'setup' is a valid controller name, but when paster controller is ran
    # from the root directory of a project, importing setup will import the
    # project's setup.py causing a sys.exit(). Blame relative imports
    if name != 'setup' and can_import(name):
        raise BadCommand(
            "\n\nA module named '%s' is already present in your "
            "PYTHON_PATH.\nChoosing a conflicting name will likely cause "
            "import problems in\nyour controller at some point. It's "
            "suggested that you choose an\nalternate name, and if you'd "
            "like that name to be accessible as\n'%s', add a route "
            "to your projects config/routing.py file similar\nto:\n"
            "    map.connect('%s', controller='my_%s')" \
            % (name, name, name, name))
    return True
Example #14
0
 def change_user_group(self, user, group):
     if not user and not group:
         return
     import pwd, grp
     uid = gid = None
     if group:
         try:
             gid = int(group)
             group = grp.getgrgid(gid).gr_name
         except ValueError:
             import grp
             try:
                 entry = grp.getgrnam(group)
             except KeyError:
                 raise BadCommand(
                     "Bad group: %r; no such group exists" % group)
             gid = entry.gr_gid
     try:
         uid = int(user)
         user = pwd.getpwuid(uid).pw_name
     except ValueError:
         try:
             entry = pwd.getpwnam(user)
         except KeyError:
             raise BadCommand(
                 "Bad username: %r; no such user exists" % user)
         if not gid:
             gid = entry.pw_gid
         uid = entry.pw_uid
     if self.verbose > 0:
         print('Changing user to %s:%s (%s:%s)' % (
             user, group or '(unknown)', uid, gid))
     if hasattr(os, 'initgroups'):
         os.initgroups(user, gid)
     else:
         os.setgroups([e.gr_gid for e in grp.getgrall()
                       if user in e.gr_mem] + [gid])
     if gid:
         os.setgid(gid)
     if uid:
         os.setuid(uid)
Example #15
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (os.path.sep, config_file)
                                )
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)
        
        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(dict(app_conf=conf.local_conf,
                         global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)
Example #16
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (os.path.sep, config_file)
                                )
        else:
            config_file = self.args[0]

        init_mediadrop(config_file, here_dir=os.getcwd(), disable_logging=self.options.quiet)
Example #17
0
    def run(self, args):
        """
        Overrides Command.run

        Checks for a config file argument and loads it.
        """
        if len(args) < self.min_args:
            raise BadCommand(
                self.min_args_error % {'min_args': self.min_args,
                                       'actual_args': len(args)})
        # Decrement because we're going to lob off the first argument.
        # @@ This is hacky
        self.min_args -= 1
        self.bootstrap_config(args[0])
        self.update_parser(args[1:])
        return super(CeleryCommand, self).run(args[1:])
Example #18
0
    def init(self):
        "init"
        if len(self.args) == 0:
            config_file = '/etc/baruwa/production.ini'
        else:
            config_file = self.args[0]

        if not os.path.isfile(config_file):
            raise BadCommand('%sError: CONFIG_FILE not found at: %s, '
                             'Please specify a CONFIG_FILE' %
                             (self.parser.get_usage(), config_file))

        here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        here = os.path.dirname(here)
        config_name = 'config:' + config_file
        self.logging_file_config(config_file)
        conf = appconfig(config_name, relative_to=here)
        conf.update(dict(app_conf=conf.local_conf,
                    global_conf=conf.global_conf))

        wsgiapp = loadapp(config_name, relative_to=here)
        self.conf = conf
Example #19
0
 def load_sysconfigs(self):
     configs = self.sysconfigs[:]
     configs.reverse()
     self.sysconfig_modules = []
     for index, (explicit, name) in enumerate(configs):
         # @@: At some point I'd like to give the specialized
         # modules some access to the values in earlier modules,
         # e.g., to specialize those values or functions.  That's
         # why these modules are loaded backwards.
         if name.endswith('.py'):
             if not os.path.exists(name):
                 if explicit:
                     raise BadCommand(
                         "sysconfig file %s does not exist"
                         % name)
                 else:
                     continue
             globs = {}
             exec(compile(open(name).read(), name, 'exec'), globs)
             mod = new.module('__sysconfig_%i__' % index)
             for name, value in list(globs.items()):
                 setattr(mod, name, value)
             mod.__file__ = name
         else:
             try:
                 mod = import_string.simple_import(name)
             except ImportError as e:
                 if explicit:
                     raise
                 else:
                     continue
         mod.paste_command = self
         self.sysconfig_modules.insert(0, mod)
     # @@: I'd really prefer to clone the parser here somehow,
     # not to modify it in place
     parser = self.parser
     self.call_sysconfig_functions('add_custom_options', parser)
Example #20
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                singularname, singulardirectory = \
                    file_op.parse_path_name_args(self.args[0])
                pluralname, pluraldirectory = \
                    file_op.parse_path_name_args(self.args[1])

            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == pluralname.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.' % base_package)
            # Validate the name
            for name in [pluralname]:
                name = name.replace('-', '_')
                validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = ('from %s.controllers import BaseController'
                                   % base_package)
            else:
                importstatement = ('from %s.lib.base import BaseController' %
                                   base_package)
            if defines_render(base_package):
                importstatement += ', render'

            module_dir = pluraldirectory.replace('/', os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            # Setup the controller
            fullname = os.path.join(pluraldirectory, pluralname)
            controller_name = util.class_name_from_module_name(
                pluralname.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            nameprefix = ''
            path = ''
            if pluraldirectory:
                nameprefix = pluraldirectory.replace(os.path.sep, '_') + '_'
                path = pluraldirectory + '/'

            controller_c = ''
            if nameprefix:
                controller_c = ", controller='%s', \n\t" % \
                    '/'.join([pluraldirectory, pluralname])
                controller_c += "path_prefix='/%s', name_prefix='%s'" % \
                    (pluraldirectory, nameprefix)
            command = "map.resource('%s', '%s'%s)\n" % \
                (singularname, pluralname, controller_c)

            file_op.template_vars.update(
                {'classname': controller_name,
                 'pluralname': pluralname,
                 'singularname': singularname,
                 'name': controller_name,
                 'nameprefix': nameprefix,
                 'package': base_package,
                 'path': path,
                 'resource_command': command.replace('\n\t', '\n%s#%s' % \
                                                         (' ' * 4, ' ' * 9)),
                 'fname': os.path.join(pluraldirectory, pluralname),
                 'importstatement': importstatement})

            resource_command = ("\nTo create the appropriate RESTful mapping, "
                                "add a map statement to your\n")
            resource_command += ("config/routing.py file near the top like "
                                 "this:\n\n")
            resource_command += command
            file_op.copy_file(template='restcontroller.py_tmpl',
                              dest=os.path.join('controllers', pluraldirectory),
                              filename=pluralname,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_restcontroller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
            print resource_command
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
Example #21
0
 def get_or_raise(key):
     if key not in self.config:
         raise BadCommand(
             'Error: %s %s configuration section is missing a '
             'value for %s' % (app_spec, self.CONFIG_SECTION, key))
     return self.config[key]
Example #22
0
 def command(self):
     self.requirement = self.args[0]
     if '#' in self.requirement:
         if self.options.ep_name is not None:
             raise BadCommand(
                 "You may not give both --name and a requirement with "
                 "#name")
         self.requirement, self.options.ep_name = self.requirement.split('#', 1)
     if not self.options.ep_name:
         self.options.ep_name = 'main'
     self.distro = self.get_distribution(self.requirement)
     self.installer = self.get_installer(
         self.distro, self.options.ep_group, self.options.ep_name)
     if self.options.show_info:
         if len(self.args) > 1:
             raise BadCommand(
                 "With --info you can only give one argument")
         return self.show_info()
     if len(self.args) < 2:
         # See if sysconfig can give us a default filename
         options = [_f for _f in self.call_sysconfig_functions(
             'default_config_filename', self.installer) if _f]
         if not options:
             raise BadCommand(
                 "You must give a configuration filename")
         self.config_file = options[0]
     else:
         self.config_file = self.args[1]
     self.check_config_file()
     self.project_name = self.distro.project_name
     self.vars = self.sysconfig_install_vars(self.installer)
     self.vars.update(self.parse_vars(self.args[2:]))
     self.vars['project_name'] = self.project_name
     self.vars['requirement'] = self.requirement
     self.vars['ep_name'] = self.options.ep_name
     self.vars['ep_group'] = self.options.ep_group
     self.vars.setdefault('app_name', self.project_name.lower())
     self.vars.setdefault('app_instance_uuid', uuid.uuid4())
     self.vars.setdefault('app_instance_secret', secret.secret_string())
     if self.verbose > 1:
         print_vars = list(self.vars.items())
         print_vars.sort()
         print('Variables for installation:')
         for name, value in print_vars:
             print('  %s: %r' % (name, value))
     self.installer.write_config(self, self.config_file, self.vars)
     edit_success = True
     if self.options.edit:
         edit_success = self.run_editor()
     setup_configs = self.installer.editable_config_files(self.config_file)
     # @@: We'll just assume the first file in the list is the one
     # that works with setup-app...
     setup_config = setup_configs[0]
     if self.options.run_setup:
         if not edit_success:
             print('Config-file editing was not successful.')
             if self.ask('Run setup-app anyway?', default=False):
                 self.run_setup(setup_config)
         else:
             self.run_setup(setup_config)
     else:
         filenames = self.installer.editable_config_files(self.config_file)
         assert not isinstance(filenames, str), (
             "editable_config_files returned a string, not a list")
         if not filenames and filenames is not None:
             print('No config files need editing')
         else:
             print('Now you should edit the config files')
             if filenames:
                 for fn in filenames:
                     print('  %s' % fn)
Example #23
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(
            dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the .egg-info top_level.txt.
        egg_info = find_egg_info_dir(here_dir)
        f = open(os.path.join(egg_info, 'top_level.txt'))
        packages = [
            l.strip() for l in f.readlines()
            if l.strip() and not l.strip().startswith('#')
        ]
        f.close()

        # Start the rest of our imports now that the app is loaded
        found_base = False
        for pkg_name in packages:
            # Import all objects from the base module
            base_module = pkg_name + '.lib.base'
            found_base = can_import(base_module)
            if not found_base:
                # Minimal template
                base_module = pkg_name + '.controllers'
                found_base = can_import(base_module)

            if found_base:
                break

        if not found_base:
            raise ImportError("Could not import base module. Are you sure "
                              "this is a Pylons app?")

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        for name in base_public:
            locs[name] = getattr(base, name)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'paste.fixture wrapped around wsgiapp')

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            newbanner = "Pylons Interactive Shell\nPython %s\n\n" % sys.version
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Example #24
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, config, request, response, '
              'session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        locs.pop('__builtins__', None)

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
            "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
            'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                # ipython >= 0.11
                from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed(argv=self.args)
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Example #25
0
    def command(self):
        if self.options.stop_daemon:
            return self.stop_daemon()

        if not hasattr(self.options, 'set_user'):
            # Windows case:
            self.options.set_user = self.options.set_group = None
        # @@: Is this the right stage to set the user at?
        self.change_user_group(
            self.options.set_user, self.options.set_group)

        if self.requires_config_file:
            if not self.args:
                raise BadCommand('You must give a config file')
            app_spec = self.args[0]
            if (len(self.args) > 1
                and self.args[1] in self.possible_subcommands):
                cmd = self.args[1]
                restvars = self.args[2:]
            else:
                cmd = None
                restvars = self.args[1:]
        else:
            app_spec = ""
            if (self.args
                and self.args[0] in self.possible_subcommands):
                cmd = self.args[0]
                restvars = self.args[1:]
            else:
                cmd = None
                restvars = self.args[:]

        if (getattr(self.options, 'daemon', False)
            and getattr(self.options, 'reload', False)):
            raise BadCommand('The --daemon and --reload options may not be used together')

        jython_monitor = False
        if self.options.reload:
            if jython and not self.options.disable_jython_reloader:
                # JythonMonitor raises the special SystemRestart
                # exception that'll cause the Jython interpreter to
                # reload in the existing Java process (avoiding
                # subprocess startup time)
                try:
                    from paste.reloader import JythonMonitor
                except ImportError:
                    pass
                else:
                    jython_monitor = JythonMonitor(poll_interval=int(
                            self.options.reload_interval))
                    if self.requires_config_file:
                        jython_monitor.watch_file(self.args[0])

            if not jython_monitor:
                if os.environ.get(self._reloader_environ_key):
                    from paste import reloader
                    if self.verbose > 1:
                        print('Running reloading file monitor')
                    reloader.install(int(self.options.reload_interval))
                    if self.requires_config_file:
                        reloader.watch_file(self.args[0])
                else:
                    return self.restart_with_reloader()

        if cmd not in (None, 'start', 'stop', 'restart', 'status'):
            raise BadCommand(
                'Error: must give start|stop|restart (not %s)' % cmd)

        if cmd == 'status' or self.options.show_status:
            return self.show_status()

        if cmd == 'restart' or cmd == 'stop':
            result = self.stop_daemon()
            if result:
                if cmd == 'restart':
                    print("Could not stop daemon; aborting")
                else:
                    print("Could not stop daemon")
                return result
            if cmd == 'stop':
                return result
            self.options.daemon = True

        if cmd == 'start':
            self.options.daemon = True

        app_name = self.options.app_name
        vars = self.parse_vars(restvars)
        if not self._scheme_re.search(app_spec):
            app_spec = 'config:' + app_spec
        server_name = self.options.server_name
        if self.options.server:
            server_spec = 'egg:PasteScript'
            assert server_name is None
            server_name = self.options.server
        else:
            server_spec = app_spec
        base = os.getcwd()

        if getattr(self.options, 'daemon', False):
            if not self.options.pid_file:
                self.options.pid_file = 'paster.pid'
            if not self.options.log_file:
                self.options.log_file = 'paster.log'

        # Ensure the log file is writeable
        if self.options.log_file:
            try:
                writeable_log_file = open(self.options.log_file, 'a')
            except IOError as ioe:
                msg = 'Error: Unable to write to log file: %s' % ioe
                raise BadCommand(msg)
            writeable_log_file.close()

        # Ensure the pid file is writeable
        if self.options.pid_file:
            try:
                writeable_pid_file = open(self.options.pid_file, 'a')
            except IOError as ioe:
                msg = 'Error: Unable to write to pid file: %s' % ioe
                raise BadCommand(msg)
            writeable_pid_file.close()

        if getattr(self.options, 'daemon', False):
            try:
                self.daemonize()
            except DaemonizeException as ex:
                if self.verbose > 0:
                    print(str(ex))
                return

        if (self.options.monitor_restart
            and not os.environ.get(self._monitor_environ_key)):
            return self.restart_with_monitor()

        if self.options.pid_file:
            self.record_pid(self.options.pid_file)

        if self.options.log_file:
            stdout_log = LazyWriter(self.options.log_file, 'a')
            sys.stdout = stdout_log
            sys.stderr = stdout_log
            logging.basicConfig(stream=stdout_log)

        log_fn = app_spec
        if log_fn.startswith('config:'):
            log_fn = app_spec[len('config:'):]
        elif log_fn.startswith('egg:'):
            log_fn = None
        if log_fn:
            log_fn = os.path.join(base, log_fn)
            self.logging_file_config(log_fn)

        try:
            server = self.loadserver(server_spec, name=server_name,
                                     relative_to=base, global_conf=vars)
            app = self.loadapp(app_spec, name=app_name,
                               relative_to=base, global_conf=vars)
        except SyntaxError as e:
            if self.options.reload and os.environ.get(self._reloader_environ_key):
                traceback.print_exc()
                reloader.watch_file(e.filename)
                while True:
                    time.sleep(60*60)
            else:
                raise

        if self.verbose > 0:
            if hasattr(os, 'getpid'):
                msg = 'Starting server in PID %i.' % os.getpid()
            else:
                msg = 'Starting server.'
            print(msg)

        def serve():
            try:
                server(app)
            except (SystemExit, KeyboardInterrupt) as e:
                if self.verbose > 1:
                    raise
                if str(e):
                    msg = ' '+str(e)
                else:
                    msg = ''
                print('Exiting%s (-v to see traceback)' % msg)

        if jython_monitor:
            # JythonMonitor has to be ran from the main thread
            threading.Thread(target=serve).start()
            print('Starting Jython file monitor')
            jython_monitor.periodic_reload()
        else:
            serve()
Example #26
0
                 'importstatement': importstatement})
            file_op.copy_file(template='controller.py_tmpl',
                              dest=os.path.join('controllers', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_controller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
        except:
            msg = str(sys.exc_info()[1])
            raise BadCommand('An unknown error occurred. %s' % msg)


class RestControllerCommand(Command):
    """Create a REST Controller and accompanying functional test

    The RestController command will create a REST-based Controller file
    for use with the :meth:`~routes.mapper.Mapper.resource`
    REST-based dispatching. This template includes the methods that
    :meth:`~routes.mapper.Mapper.resource` dispatches to in
    addition to doc strings for clarification on when the methods will
    be called.

    The first argument should be the singular form of the REST
    resource. The second argument is the plural form of the word. If
    its a nested controller, put the directory information in front as