def test_generate_application(self): Application('Test', 'Test App', '1.0', ('app.json', None), 8080, True) self.assertTrue(filepath.exists('test/test.py')) self.assertTrue(filepath.exists('test/config/app.json')) self.assertTrue(filepath.exists('test/twisted/plugins/test_plugin.py')) self.assertTrue(filepath.exists('test/application')) self.assertTrue(filepath.exists('test/application/controller')) self.assertTrue(filepath.exists('test/application/model')) self.assertTrue(filepath.exists('test/application/view')) self.assertTrue(filepath.exists('test/application/view/templates')) self.assertTrue(filepath.exists('test/application/view/stylesheets')) self.assertTrue( filepath.exists('test/application/view/templates/layout.html'))
def test_generate_application(self): Application('Test', 'Test App', '1.0', ('app.json', None), 8080, True) self.assertTrue(filepath.exists('test/test.py')) self.assertTrue(filepath.exists('test/config/app.json')) self.assertTrue(filepath.exists('test/twisted/plugins/test_plugin.py')) self.assertTrue(filepath.exists('test/application')) self.assertTrue(filepath.exists('test/application/controller')) self.assertTrue(filepath.exists('test/application/model')) self.assertTrue(filepath.exists('test/application/view')) self.assertTrue(filepath.exists('test/application/view/templates')) self.assertTrue(filepath.exists('test/application/view/stylesheets')) self.assertTrue( filepath.exists('test/application/view/templates/layout.html') )
def deploy(self, config_file=None): """Deploys the system following the configuration in the config file """ if config_file is None: raise FabricMissingConfigFile( 'deploy was called without \'config_file\' parameter' ) if not filepath.exists(config_file): raise FabricConfigFileDontExists( 'The {file} file doesn\'t exists'.format(file=config_file) ) if not _valid_file(config_file): raise FabricNotValidConfigFile( 'The {file} file is not a valid Fabric config file'.format( file=config_file ) ) try: self.load(config_file) except SystemExit: raise # propagate except KeyboardInterrupt: if state.output.status: sys.stderr.write('\nStopped\.n') sys.exit(1) except Exception: sys.excepthook(*sys.exc_info()) # we might leave stale threads if we don't explicitly exit() sys.exit(1) finally: fabric_main.disconnect_all()
def log_file(self, file): path = filepath.FilePath(file) if not filepath.exists(path.dirname()): raise ApplicationError( '%s' % ('Given directory %s don\t exists' % path.dirname())) self._log_file = file
def deploy(self, config_file=None): """Deploys the system following the configuration in the config file """ if config_file is None: raise FabricMissingConfigFile("deploy was called without 'config_file' parameter") if not filepath.exists(config_file): raise FabricConfigFileDontExists("The {file} file doesn't exists".format(file=config_file)) if not _valid_file(config_file): raise FabricNotValidConfigFile("The {file} file is not a valid Fabric config file".format(file=config_file)) try: self.load(config_file) except SystemExit: raise # propagate except KeyboardInterrupt: if state.output.status: sys.stderr.write("\nStopped\.n") sys.exit(1) except Exception: sys.excepthook(*sys.exc_info()) # we might leave stale threads if we don't explicitly exit() sys.exit(1) finally: fabric_main.disconnect_all()
def _write_view(self): """Write the view to a file in the file system """ view_path = 'templates/' if self.options.subOptions.opts['controller'] is not None: controller = self.options.subOptions.opts['controller'].lower() if filepath.exists( 'application/controller/{}.py'.format(controller)): view_path = '{}/'.format(controller.capitalize()) view_file = filepath.FilePath( 'application/view/{}{}.html'.format( view_path, self.options.subOptions.opts['filename']) ) if self.options.subOptions.opts['noquestions'] is False: if view_file.exists(): if commons.Interaction.userquery( '{} file already exists in the file system. ' 'Are you really sure do you want to overwrite it?'.format( view_file.path ) ) == 'No': return print('Writing the view...'.ljust(73), end='') try: view_file.open('w').write(self._process_template()) except IOError: # controller directory doesn't exists on view yet filepath.FilePath( 'application/view/{}'.format(view_path)).createDirectory() view_file.open('w').write(self._process_template())
def _write_view(self): """Write the view to a file in the file system """ view_path = 'templates/' if self.options.subOptions.opts['controller'] is not None: controller = self.options.subOptions.opts['controller'].lower() if filepath.exists( 'application/controller/{}.py'.format(controller)): view_path = '{}/'.format(controller.capitalize()) view_file = filepath.FilePath('application/view/{}{}.html'.format( view_path, self.options.subOptions.opts['filename'])) if self.options.subOptions.opts['noquestions'] is False: if view_file.exists(): if commons.Interaction.userquery( '{} file already exists in the file system. ' 'Are you really sure do you want to overwrite it?'. format(view_file.path)) == 'No': return print('Writing the view...'.ljust(73), end='') try: view_file.open('w').write(self._process_template()) except IOError: # controller directory doesn't exists on view yet filepath.FilePath( 'application/view/{}'.format(view_path)).createDirectory() view_file.open('w').write(self._process_template())
def log_file(self, file): path = filepath.FilePath(file) if not filepath.exists(path.dirname()): raise ApplicationError('%s' % ( 'Given directory %s don\t exists' % path.dirname()) ) self._log_file = file
def handle_start_command(options): """I handle the start command """ if GNU_LINUX or BSD: app = config.Application('config/application.json') if app.port <= 1024: if os.getuid() != 0: print( '[{e}]: This application is configured to use a reserved ' 'port (a port under 1025) only root can open a port from ' 'this range root access is needed to start this ' 'application using the {port} port.\n\nTry something ' 'like: sudo mamba-admin start\n\nYou can also change the ' 'configuration for this application editing ' '\'config/application.json\''.format( e=darkred('ERROR'), port=app.port ) ) sys.exit(-1) args = ['twistd'] try: app_name = glob.glob( 'twisted/plugins/*.py')[0].split(os.sep)[-1].split('_')[0] except IndexError: print( 'error: twisted directory can\'t be found. You should be in ' 'the application directory in order to start it' ) sys.exit(-1) if filepath.exists('twistd.pid'): print( 'error: twistd.pid found, seems like the application is ' 'running already. If the application is not running, please ' 'delete twistd.pid and try again' ) sys.exit(-1) if BSD: args.append('--reactor=kqueue') args.append(app_name) if options.subOptions.opts['port']: args.append('--port={}'.format(options.subOptions.opts['port'])) print('starting application {}...'.format(app_name).ljust(73), end='') if subprocess.call(args) == 0: print('[{}]'.format(darkgreen('Ok'))) sys.exit(0) else: print('[{}]'.format(darkred('Fail'))) sys.exit(-1)
def create_package_directory(self, name, options, config): """Create the package directory layout """ # check if README.rst and LICENSE files are present if not filepath.exists('README.rst') or not filepath.exists('LICENSE'): raise usage.UsageError( 'You must create a README.rst and LICENSE files if you want ' 'to pack/install this application.') # check if docs directory exists if not filepath.exists('docs'): raise usage.UsageError( 'You have to add a *docs* directory to your package') # check if MANIFEST.in exits and copy it if does if filepath.exists('MANIFEST.in'): self.do(['cp', 'MANIFEST.in', 'package/']) # clean the application self.do(['find', '.', '-type', 'f', '-name', '"*.py[co]"', "-delete"]) # create layout self.do(['mkdir', 'package']) self.do(['cp', '-Rf', 'docs', 'package/']) self.do(['cp', 'README.rst', 'LICENSE', 'package/']) self.do(['cp', '-Rf', 'application', 'package/' + name]) self.do(['cp', '-Rf', 'static', 'package/' + name + '/static']) if len(options['extra_directories']) != 0: for directory in options['extra_directories']: self.do(['cp', '-Rf', directory, 'package/']) self.do(['touch', 'package/.mamba-package']) os.chdir('package') self.write_setup_script(name, options, config) self.fix_application_path(name) self.write_manifest(name, options, config) os.chdir('..')
def handle_start_command(options=None, dropin_cache_wa=False): """I handle the start command """ try: mamba_services = import_services() mamba_services.config.Application('config/application.json') except ImportError: print( 'error: make sure you are inside a mamba application root ' 'directory and then run this command again' ) sys.exit(-1) if POSIX: app = mamba_services.config.Application() if app.port is None: print( 'Your application configuration file does not define a valid ' 'port. Is your configuration file valid JSON format?' ) sys.exit(-1) elif app.port <= 1024: if os.getuid() != 0: print( '[{e}]: This application is configured to use a reserved ' 'port (a port under 1025) only root can open a port from ' 'this range root access is needed to start this ' 'application using the {port} port.\n\nTry something ' 'like: sudo mamba-admin start\n\nYou can also change the ' 'configuration for this application editing ' '\'config/application.json\''.format( e=darkred('ERROR'), port=app.port ) ) sys.exit(-1) args = ['twistd'] try: app_name = glob.glob( 'twisted/plugins/*.py')[0].split(os.sep)[-1].rsplit('_', 1)[0] except IndexError: print( 'error: twisted directory can\'t be found. You should be in ' 'the application directory in order to start it' ) sys.exit(-1) if filepath.exists('twistd.pid'): print( 'error: twistd.pid found, seems like the application is ' 'running already. If the application is not running, please ' 'delete twistd.pid and try again' ) sys.exit(-1) # determine if we are running in heroku in_heroku = '.heroku' in os.environ.get('PYTHONHOME', '') args.append('--nodaemon') if not in_heroku: if not mamba_services.config.Application().auto_select_reactor: args.append(determine_platform_reactor(mamba_services)) if not mamba_services.config.Application().development: args.remove('--nodaemon') args.append('--syslog') args.append(app_name) if options is not None and options.subOptions.opts['port']: args.append('--port={}'.format(options.subOptions.opts['port'])) if in_heroku or mamba_services.config.Application().development: os.execlp('twistd', *args) else: if not dropin_cache_wa: print( 'starting application {}...'.format(app_name).ljust(73), end='' ) proc = subprocess.Popen( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = proc.communicate() if not err: if 'exception' in out: result = darkred('Fail') exit_code = -1 elif 'already installed' in out: return handle_start_command(options, True) else: result = darkgreen('Ok') exit_code = 0 else: result = darkred('Fail') exit_code = -1 print('[{}]'.format(result)) print(err if exit_code == -1 else out) sys.exit(exit_code)
def _is_pip_installable(): """Check if we can pip install the package - setup.py is required""" return filepath.exists('setup.py')