def get_createenv_data(self): returnvals = [] # Basic instructions self.print_line() printout(_("""Starting Interactive environment creation at <%(envname)s> This is the interactive guide on environment creation. Just follow the instructions.""", envname=self.envname)) self.print_line() # Env path printout(_(""" Now enter the absolute path where your environment should be created.""")) path = self.envname returnvals.append(raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout(_(""" Enter the name of the project you are about to create""")) path = "My Project" returnvals.append(raw_input(_("project_name [%(default)s]> ", default=path)).strip() or path) self.print_line() return returnvals
def get_createenv_data(self): returnvals = [] # Basic instructions self.print_line() printout( _("""Starting Interactive environment creation at <%(envname)s> This is the interactive guide on environment creation. Just follow the instructions.""", envname=self.envname)) self.print_line() # Env path printout( _(""" Now enter the absolute path where your environment should be created.""" )) path = self.envname returnvals.append( raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout( _(""" Enter the name of the project you are about to create""")) path = "My Project" returnvals.append( raw_input(_("project_name [%(default)s]> ", default=path)).strip() or path) self.print_line() return returnvals
def get_recover_data(self): returnvals = [] # Basic instructions self.print_line() printout( _("""Starting Interactive environment recovering at <%(envname)s> Follow the instructions to recover environment!""", envname=self.envname)) self.print_line() # Env path printout( _(""" Now enter the absolute path where your environment should be created.""" )) path = self.envname returnvals.append( raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout(_(""" Enter path where the backup file is locates""")) prompt = _("Backup File [</path/to/file>]> ") returnvals.append(raw_input(prompt).strip()) return returnvals
def print_usage_help(self): printout( _("Usage: <appname> </path/to/projenv> " "[command [subcommand] [option ...]]\n")) printout( _("Invoking <appname> without command starts " "interactive mode."))
def print_usage_help(self): printout( _("Usage: con-admin </path/to/project> " "[command [subcommand] [option ...]]\n")) printout( _("Invoking con-admin without command starts " "interactive mode."))
def get_backup_data(self): returnvals = [] # Basic instructions self.print_line() printout( _("""Starting Interactive environment backup at <%(envname)s> Follow the instructions to backup the environment!""", envname=self.envname)) self.print_line() # Env path printout( _(""" Now enter the absolute path to the environment that you will backup.""" )) path = self.envname returnvals.append( raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout(_(""" Destination file for tghe backup""")) dest = self.__env.backup_get_default_file_name() returnvals.append( raw_input(_("</dest/file> [%(default)s]> ", default=dest)).strip() or dest) return returnvals
def do_delete(self, line): def delete_error(msg): printerr(_("Delete for '%(env)s' failed:", env=self.envname), "\n", msg) # get arguments env_dir = None args = self.unicod_safe_split(line) # Interactive or not interactive_delete = False if len(args) == 1 and not args[0]: returnvals = self.get_delete_data() env_dir = returnvals[0] interactive_delete = True elif len(args) != 1: delete_error('Wrong number of arguments: %d' % len(args)) return 2 else: env_dir = args[0] # Set the right env dir self.envname = env_dir if self.__env and self.__env.basepath == self.envname: delete_error( "Can not delete currently open environment! Close and open the admin!" ) return 2 # Open env if not self.ceck_env(): delete_error("Environment not created or corrupted!") return 2 if interactive_delete: no_option = "no" value = raw_input( _("Delete Environment? [%(default)s]> ", default=no_option)).strip() or no_option # Ask again if we want to delete the env! value = value.lower() in get_true_values() if not value: printout(_("Delete Canceled!")) return # Delete it! printout(_("Starting Delete Process")) self.__env.delete() # Close environment! self.__env.shutdown() # It's deleted, so purge it! printout( _(" Purge env directory %(purge_dir)s", purge_dir=self.envname)) purge_dir(self.envname) printout(_("Environment successfully deleted"))
def do_plugin(self, line): args = self.unicod_safe_split(line) if args[0] == 'list': printout(_("TODO: register plugins")) elif args[0] == 'setapp' and len(args) == 2: printout(_("TODO: set app to life in env")) else: self.do_help('plugin')
def do_plugin(self, line): args = self.unicod_safe_split(line) if args[0] == 'list': printout(_("TODO: register plugins")) elif args[0] == 'setapp' and len(args)==2: printout(_("TODO: set app to life in env")) else: self.do_help ('plugin')
def delete(self): """ Delete an environment is like uninstalling it """ printout(_(" Uninstalling Components")) for deleter in self.delete_components: deleter.env_delete() printout(_(" Environment successfully uninstalled"))
def delete(self): """ Delete an environment is like uninstalling it """ printout(_(" Uninstalling Components")) for deleter in self.delete_components: deleter.env_delete() printout(_(" Environment successfully uninstalled"))
def do_delete(self, line): def delete_error(msg): printerr(_("Delete for '%(env)s' failed:", env=self.envname), "\n", msg) # get arguments env_dir = None args = self.unicod_safe_split(line) # Interactive or not interactive_delete = False if len(args) == 1 and not args[0]: returnvals = self.get_delete_data() env_dir = returnvals[0] interactive_delete = True elif len(args) != 1: delete_error('Wrong number of arguments: %d' % len(args)) return 2 else: env_dir = args[0] # Set the right env dir self.envname = env_dir if self.__env and self.__env.basepath == self.envname: delete_error("Can not delete currently open environment! Close and open the admin!") return 2 # Open env if not self.ceck_env(): delete_error("Environment not created or corrupted!") return 2 if interactive_delete: no_option = "no" value = raw_input(_("Delete Environment? [%(default)s]> ", default=no_option)).strip() or no_option # Ask again if we want to delete the env! value = value.lower() in get_true_values() if not value: printout(_("Delete Canceled!")) return # Delete it! printout(_("Starting Delete Process")) self.__env.delete() # Close environment! self.__env.shutdown() # It's deleted, so purge it! printout(_(" Purge env directory %(purge_dir)s", purge_dir=self.envname)) purge_dir(self.envname) printout(_("Environment successfully deleted"))
def zip_create_from_folder( source_dir, dest_file='', exclude_dirs=[], include_root=True ): """ Method that just. Inpired by: http://stackoverflow.com/questions/458436/adding-folders-to-a-zip-file-using-python @param source_dir: The folder that will be zipped @param dest_file: Destination zip file. If not set `source_dir` base name will be used @param exclude_dirs: List of directories that should be excluded @param include_root: If True `source_dir` will be included in the resulting zip """ # Build right dest_file name and verify if source exists if dest_file is '': dest_file = os.path.join(os.path.basename(source_dir),'.zip') if not os.path.isdir(source_dir): raise OSError("source_folder argument must point to a valid directory.") base_dir, root_dir = os.path.split(source_dir) #Little nested function to prepare the proper archive path def trim_path(path): archive_dir = path.replace(base_dir, "", 1) if base_dir: archive_dir = archive_dir.replace(os.path.sep, "", 1) if not include_root: archive_dir = archive_dir.replace(root_dir + os.path.sep, "", 1) return os.path.normcase(archive_dir) # nested function to exclude a file from beeing added to the zip file def should_be_excluded( dir ): for excluded_dir in exclude_dirs: if root.rfind(excluded_dir) > 0: return True return False # Create file out_file = zip_open(dest_file) printout(_( "Creating Zip %(NewZip)s", NewZip=dest_file)) for root, dirs, files in os.walk(source_dir): for file_name in files: # Check excluded dirs! if not should_be_excluded( root ): # Write the file file_path = os.path.join(root, file_name) printout(_( " - Adding %(file_path)s", file_path=trim_path(file_path))) out_file.write(file_path, trim_path(file_path)) # Empty folder needs to be added too if not files and not dirs: zipInfo = zipfile.ZipInfo(trim_path(root) + "/") out_file.writestr(zipInfo, "") out_file.close() printout(_( "Zip file created successfully!"))
def get_version_from_file(self): """ Return the version saved in the 'VERSION' file of the env """ if not os.path.exists(self.get_version_file_path()): raise EnvWrongVersionError(_("Env needs a file called `VERSION` "\ "to save it's version in the env root.")) try: file_handle = open(self.get_version_file_path(), 'r') saved_version = file_handle.read().split()[0] return saved_version except: raise EnvWrongVersionError(_("Version file corrupted!"))
def get_version_from_file(self): """ Return the version saved in the 'VERSION' file of the env """ if not os.path.exists(self.get_version_file_path()): raise EnvWrongVersionError(_("Env needs a file called `VERSION` "\ "to save it's version in the env root.")) try: file_handle = open(self.get_version_file_path(), 'r') saved_version = file_handle.read().split()[0] return saved_version except: raise EnvWrongVersionError(_("Version file corrupted!"))
def get_delete_data(self): returnvals = [] # Basic instructions self.print_line() printout(_("""Starting Interactive environment deletion at <%(envname)s>""", envname=self.envname)) self.print_line() # Env path printout(_(""" Now enter the absolute path to the environment that will be deleted.""")) path = self.envname returnvals.append(raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() return returnvals
def recover_env(self, backupfile, dest_env=None, ): """ recreate an env from a backup file """ if zip_is_valid( backupfile ): if not dest_env: dest_env = self.envname self.print_line() printout(_("Starting recovery")) printout(_("\trecovery file: \t%(backupfile)s",backupfile=backupfile)) printout(_("\tenv path: \t%(dest_env)s",dest_env=dest_env)) #TODO: call self.__env.restored() on the recovered env! else: raise RecoverBackupFileError(_("Invalid zip file for recovery!"))
def get_host(self, name, default='localhost:80'): """ Get a host tuple in form of (host,port) """ value = self.get(name, default) if not value: return ('localhost',80) items = [item.strip() for item in value.split(':')] if len(items) == 2: try: items[1] = int(items[1]) except ValueError: raise BaseConfigError(_('[%(section)s] %(entry)s: expected integer port number, got %(value)s', section=self.name, entry=name, value=repr(value))) return tuple(items) raise BaseConfigError(_('[%(section)s] %(entry)s: expected url in form of host:port, got %(value)s', section=self.name, entry=name, value=repr(value)))
def print_line(self): """ Print a line :P """ printout( _("""--------------------------------------------------------------------------""" ))
def check_dir(cls, dirname): """ Check if the dir has a file with the same name as it's children """ if not os.path.exists(dirname): raise EnvFolderCheckError(_("%(dir)s does not exist!", dir=dirname))
def print_interactive_header(self): printout( _("""[Generic CMD App] Copyright (c) 2014 Moritz Wundke Type: '?' or 'help' for help on commands. """))
def print_interactive_header(self): printout( _("""[Welcome to Concurrent Environment Admin] %(version)s Copyright (c) 2014 Moritz Wundke Type: '?' or 'help' for help on commands. """, version=CONCURRENT_VERSION))
def _get_connection_string(self): """ Private method to build the current connection string """ return _("postgresql://%(user)s:%(password)s@%(host)s:%(port)s/%(dbname)s", user=self.db_user, password=self.db_pass, host=self.db_host, port=self.db_port, dbname=self.db_name)
def get_delete_data(self): returnvals = [] # Basic instructions self.print_line() printout( _("""Starting Interactive environment deletion at <%(envname)s>""", envname=self.envname)) self.print_line() # Env path printout( _(""" Now enter the absolute path to the environment that will be deleted.""" )) path = self.envname returnvals.append( raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() return returnvals
def open_env(self): """ Opens the currently selected environment """ try: if not self.__env: self.__env = Environment(self.envname) except Exception as e: printerr(_("Ups... I could not open the environment!"), e ) traceback.print_exc() sys.exit(1)
def check_version(self): """ Checks current installed framework version """ from concurrent import __version__ as VERSION saved_version = self.get_version_from_file() if saved_version != VERSION: raise EnvWrongVersionError(_("Version check failed! Saved " \ "Version `%(saved_version)s` != Concurrent Version " \ "`%(concurrent_version)s`" \ ,saved_version=saved_version,concurrent_version=VERSION))
def open_env(self): """ Opens the currently selected environment """ try: if not self.__env: self.__env = Environment(self.envname) except Exception as e: printerr(_("Ups... I could not open the environment!"), e) traceback.print_exc() sys.exit(1)
def recover_env( self, backupfile, dest_env=None, ): """ recreate an env from a backup file """ if zip_is_valid(backupfile): if not dest_env: dest_env = self.envname self.print_line() printout(_("Starting recovery")) printout( _("\trecovery file: \t%(backupfile)s", backupfile=backupfile)) printout(_("\tenv path: \t%(dest_env)s", dest_env=dest_env)) #TODO: call self.__env.restored() on the recovered env! else: raise RecoverBackupFileError(_("Invalid zip file for recovery!"))
def _get_connection_string(self): """ Private method to build the current connection string """ return _( "postgresql://%(user)s:%(password)s@%(host)s:%(port)s/%(dbname)s", user=self.db_user, password=self.db_pass, host=self.db_host, port=self.db_port, dbname=self.db_name)
def check_version(self): """ Checks current installed framework version """ from concurrent import __version__ as VERSION saved_version = self.get_version_from_file() if saved_version != VERSION: raise EnvWrongVersionError(_("Version check failed! Saved " \ "Version `%(saved_version)s` != Concurrent Version " \ "`%(concurrent_version)s`" \ ,saved_version=saved_version,concurrent_version=VERSION))
def do_help(self, line=None): self.print_help_header() arg = self.unicod_safe_split(line) if arg[0]: try: doc = getattr(self, "_help_" + arg[0]) self.print_help(doc) except AttributeError: printerr(_("No documentation found for '%(cmd)s'", cmd=arg[0])) else: self.print_usage_help() self.print_help(self.all_docs())
def zip_print_info( zip_file_name ): zf = zipfile.ZipFile( zip_file_name ) for info in zf.infolist(): printout(_(info.filename)) printout(_("tComment:t",info.comment)) printout(_("tModified:t", datetime.datetime(*info.date_time))) printout(_("tSystem:tt", info.create_system, '(0 = Windows, 3 = Unix)')) printout(_("tZIP version:t", info.create_version)) printout(_("tCompressed:t", info.compress_size, 'bytes')) printout(_("tUncompressed:t", info.file_size, 'bytes'))
def ceck_env(self, print_error=False): """ Will return true if the environment can be opened and false otherwise """ try: self.__env = Environment(self.envname) except Exception as e: if print_error: printerr(_("Ups... I could not open the environment!"), e ) traceback.print_exc() return False return True
def ceck_env(self, print_error=False): """ Will return true if the environment can be opened and false otherwise """ try: self.__env = Environment(self.envname) except Exception as e: if print_error: printerr(_("Ups... I could not open the environment!"), e) traceback.print_exc() return False return True
def do_help(self, line=None): self.print_help_header() arg = self.unicod_safe_split(line) if arg[0]: try: doc = getattr(self, "_help_" + arg[0]) self.print_help(doc) except AttributeError: printerr(_("No documentation found for '%(cmd)s'", cmd=arg[0])) else: self.print_usage_help() self.print_help(self.all_docs())
def get_float(self, name, default=''): """ Return the value of the specified item as float. @raise BaseConfigError: if value is not an float """ value = self.get(name, default) if not value: return 0 try: return float(value) except ValueError: raise BaseConfigError(_('[%(section)s] %(entry)s: expected float, got %(value)s', section=self.name, entry=name, value=repr(value)))
def get_recover_data(self): returnvals = [] # Basic instructions self.print_line() printout(_("""Starting Interactive environment recovering at <%(envname)s> Follow the instructions to recover environment!""", envname=self.envname)) self.print_line() # Env path printout(_(""" Now enter the absolute path where your environment should be created.""")) path = self.envname returnvals.append(raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout(_(""" Enter path where the backup file is locates""")) prompt = _("Backup File [</path/to/file>]> ") returnvals.append(raw_input(prompt).strip()) return returnvals
def get_host(self, name, default='localhost:80'): """ Get a host tuple in form of (host,port) """ value = self.get(name, default) if not value: return ('localhost', 80) items = [item.strip() for item in value.split(':')] if len(items) == 2: try: items[1] = int(items[1]) except ValueError: raise BaseConfigError( _('[%(section)s] %(entry)s: expected integer port number, got %(value)s', section=self.name, entry=name, value=repr(value))) return tuple(items) raise BaseConfigError( _('[%(section)s] %(entry)s: expected url in form of host:port, got %(value)s', section=self.name, entry=name, value=repr(value)))
def get_backup_data(self): returnvals = [] # Basic instructions self.print_line() printout(_("""Starting Interactive environment backup at <%(envname)s> Follow the instructions to backup the environment!""", envname=self.envname)) self.print_line() # Env path printout(_(""" Now enter the absolute path to the environment that you will backup.""")) path = self.envname returnvals.append(raw_input(_("</path/to/project> [%(default)s]> ", default=path)).strip() or path) self.print_line() # Environment app printout(_(""" Destination file for tghe backup""")) dest = self.__env.backup_get_default_file_name() returnvals.append(raw_input(_("</dest/file> [%(default)s]> ", default=dest)).strip() or dest) return returnvals
def get_float(self, name, default=''): """ Return the value of the specified item as float. @raise BaseConfigError: if value is not an float """ value = self.get(name, default) if not value: return 0 try: return float(value) except ValueError: raise BaseConfigError( _('[%(section)s] %(entry)s: expected float, got %(value)s', section=self.name, entry=name, value=repr(value)))
def onecmd(self, line): """`line` may be a `str` or an `unicode` object""" try: if isinstance(line, str): if self.interactive: encoding = sys.stdin.encoding else: encoding = locale.getpreferredencoding() # sys.argv line = to_unicode(line, encoding) if self.interactive: line = line.replace('\\', '\\\\') rv = cmd.Cmd.onecmd(self, line) or 0 except SystemExit: raise except BaseError as e: printerr(_("Command failed:"), e) rv = 2 if not self.interactive: return rv
def onecmd(self, line): """`line` may be a `str` or an `unicode` object""" try: if isinstance(line, str): if self.interactive: encoding = sys.stdin.encoding else: encoding = locale.getpreferredencoding() # sys.argv line = to_unicode(line, encoding) if self.interactive: line = line.replace('\\', '\\\\') rv = cmd.Cmd.onecmd(self, line) or 0 except SystemExit: raise except BaseError as e: printerr(_("Command failed:"), e) rv = 2 if not self.interactive: return rv
def main(self, args=None): """ Main entry point for this application """ if args is None: args = sys.argv[1:] if len(args) > 0: if args[0] in ('-h', '--help', 'help'): return self.onecmd('help') elif args[0] in ('-v', '--version'): self.print_version() else: env_path = os.path.abspath(args[0]) try: try: unicode(env_path, 'ascii') except NameError: str(env_path, 'ascii') except UnicodeDecodeError: printerr( _( "non-ascii environment path '%(path)s' not " "supported.", path=env_path)) sys.exit(2) self.set_env(env_path) if len(args) > 1: s_args = ' '.join(["'%s'" % c for c in args[2:]]) command = args[1] + ' ' + s_args return self.onecmd(command) else: while True: try: self.run() except KeyboardInterrupt: self.do_quit('') else: while True: try: self.run() except KeyboardInterrupt: self.do_quit('')
def main(self, args=None): """ Main entry point for this application """ if args is None: args = sys.argv[1:] if len(args) > 0: if args[0] in ('-h', '--help', 'help'): return self.onecmd('help') elif args[0] in ('-v','--version'): self.print_version() else: env_path = os.path.abspath(args[0]) try: try: unicode(env_path, 'ascii') except NameError: str(env_path, 'ascii') except UnicodeDecodeError: printerr(_("non-ascii environment path '%(path)s' not " "supported.", path=env_path)) sys.exit(2) self.set_env(env_path) if len(args) > 1: s_args = ' '.join(["'%s'" % c for c in args[2:]]) command = args[1] + ' ' +s_args return self.onecmd(command) else: while True: try: self.run() except KeyboardInterrupt: self.do_quit('') else: while True: try: self.run() except KeyboardInterrupt: self.do_quit('')
def create(self, args=None): """ Will try to create a new environment. Our basepath has already been set in the constructor. If args contains ('baseon', 'file'), default values will not be loaded; they are expected to be provided by that file or other options. @param args: List of tuples used to setup the env. The tuples are styled like: (section, name, value) """ from concurrent import __version__ as VERSION # Default empty array, do not do this as a default argument! # see: http://pylint-messages.wikidot.com/messages:w0102 if args is None: args = [] # Create base Concurrent files create_file(self.get_version_file_path(), _('%(version)s\n', version=VERSION)) create_file(self.get_readme_file_path(), 'A simple Concurrent environment\n') # Create base config file! create_file( os.path.join(self.get_configs_dir(), self.get_ini_filename())) # Setup the default configuration skip_defaults = args and ('baseon', 'file') in [(section, option) \ for (section, option, value) in args] self.setup_config(use_defaults=not skip_defaults) for section, name, value in args: self.config.set(section, name, value) self.config.save() self.config.conditional_parse()
def create(self, args=None): """ Will try to create a new environment. Our basepath has already been set in the constructor. If args contains ('baseon', 'file'), default values will not be loaded; they are expected to be provided by that file or other options. @param args: List of tuples used to setup the env. The tuples are styled like: (section, name, value) """ from concurrent import __version__ as VERSION # Default empty array, do not do this as a default argument! # see: http://pylint-messages.wikidot.com/messages:w0102 if args is None: args = [] # Create base Concurrent files create_file(self.get_version_file_path(), _('%(version)s\n', version=VERSION)) create_file(self.get_readme_file_path(), 'A simple Concurrent environment\n') # Create base config file! create_file(os.path.join(self.get_configs_dir(), self.get_ini_filename())) # Setup the default configuration skip_defaults = args and ('baseon', 'file') in [(section, option) \ for (section, option, value) in args] self.setup_config(use_defaults=not skip_defaults) for section, name, value in args: self.config.set(section, name, value) self.config.save() self.config.conditional_parse()
def print_help_header(self): printout(_("Concurrent - Environment Admin"))
def recover_error(msg): printerr(_("Recover for '%(env)s' failed:", env=self.envname), "\n", msg)
def print_line(self): """ Print a line :P """ printout(_("""--------------------------------------------------------------------------"""))
def print_interactive_header(self): printout(_("""[Welcome to Concurrent Environment Admin] %(version)s Copyright (c) 2014 Moritz Wundke Type: '?' or 'help' for help on commands. """, version=CONCURRENT_VERSION))
def print_help_header(self): printout(_("Concurrent - Console application"))
def print_usage_help(self): printout(_("Usage: <appname> </path/to/projenv> " "[command [subcommand] [option ...]]\n") ) printout(_("Invoking <appname> without command starts " "interactive mode."))
def backup_error(msg): printerr(_("Backup for '%(env)s' failed:", env=self.envname), "\n", msg)
def backup_error(msg): printerr(_("Backup for '%(env)s' failed:", env=self.envname), "\n", msg)
def delete_error(msg): printerr(_("Delete for '%(env)s' failed:", env=self.envname), "\n", msg)
def do_quit(self, line): printout(_("\nSee you soon!")) sys.exit()
def recover_error(msg): printerr(_("Recover for '%(env)s' failed:", env=self.envname), "\n", msg)
def print_interactive_header(self): printout(_("""[Generic CMD App] Copyright (c) 2014 Moritz Wundke Type: '?' or 'help' for help on commands. """))