idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
52,400
def build_report ( self , msg = '' ) : shutit_global . shutit_global_object . yield_to_draw ( ) s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global . shutit_global_object . build_id + '\n' s += self . get_commands ( ) s += '# COMMAND HISTORY END ' + shutit_global . shutit_global_object . build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global . shutit_global_object . build_id + '\n' s += '# ' + msg + '\n' if self . build [ 'report' ] != '' : s += self . build [ 'report' ] + '\n' else : s += '# Nothing to report\n' if 'container_id' in self . target : s += '# CONTAINER_ID: ' + self . target [ 'container_id' ] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global . shutit_global_object . build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys . executable for arg in sys . argv : s += ' ' + arg s += '\n' s += '###############################################################################\n' return s
Resposible for constructing a report to be output as part of the build . Returns report as a string .
52,401
def match_string ( self , string_to_match , regexp ) : shutit_global . shutit_global_object . yield_to_draw ( ) if not isinstance ( string_to_match , str ) : return None lines = string_to_match . split ( '\r\n' ) new_lines = [ ] for line in lines : new_lines = new_lines + line . split ( '\r' ) for line in lines : new_lines = new_lines + line . split ( '\n' ) lines = new_lines if not shutit_util . check_regexp ( regexp ) : self . fail ( 'Illegal regexp found in match_string call: ' + regexp ) for line in lines : match = re . match ( regexp , line ) if match is not None : if match . groups ( ) : return match . group ( 1 ) return True return None
Get regular expression from the first of the lines passed in in string that matched . Handles first group of regexp as a return value .
52,402
def is_to_be_built_or_is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg if cfg [ shutit_module_obj . module_id ] [ 'shutit.core.module.build' ] : return True return self . is_installed ( shutit_module_obj )
Returns true if this module is configured to be built or if it is already installed .
52,403
def is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_installed : return True if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed : return False if shutit_module_obj . is_installed ( self ) : self . get_current_shutit_pexpect_session_environment ( ) . modules_installed . append ( shutit_module_obj . module_id ) return True else : if shutit_module_obj . module_id not in self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed : self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed . append ( shutit_module_obj . module_id ) return False return False
Returns true if this module is installed . Uses cache where possible .
52,404
def allowed_image ( self , module_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( "In allowed_image: " + module_id , level = logging . DEBUG ) cfg = self . cfg if self . build [ 'ignoreimage' ] : self . log ( "ignoreimage == true, returning true" + module_id , level = logging . DEBUG ) return True self . log ( str ( cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] ) , level = logging . DEBUG ) if cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] : for regexp in cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] : if not shutit_util . check_regexp ( regexp ) : self . fail ( 'Illegal regexp found in allowed_images: ' + regexp ) if re . match ( '^' + regexp + '$' , self . target [ 'docker_image' ] ) : return True return False
Given a module id determine whether the image is allowed to be built .
52,405
def print_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self . module_ids ( ) : module_string += ' ' + str ( self . shutit_map [ module_id ] . run_order ) + ' ' + str ( cfg [ module_id ] [ 'shutit.core.module.build' ] ) + ' ' + str ( cfg [ module_id ] [ 'shutit.core.module.remove' ] ) + ' ' + module_id + '\n' return module_string
Returns a string table representing the modules in the ShutIt module map .
52,406
def load_shutit_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) if self . loglevel <= logging . DEBUG : self . log ( 'ShutIt module paths now: ' , level = logging . DEBUG ) self . log ( self . host [ 'shutit_module_path' ] , level = logging . DEBUG ) for shutit_module_path in self . host [ 'shutit_module_path' ] : self . load_all_from_path ( shutit_module_path )
Responsible for loading the shutit modules based on the configured module paths .
52,407
def get_command ( self , command ) : shutit_global . shutit_global_object . yield_to_draw ( ) if command in ( 'md5sum' , 'sed' , 'head' ) : if self . get_current_shutit_pexpect_session_environment ( ) . distro == 'osx' : return 'g' + command return command
Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed .
52,408
def get_send_command ( self , send ) : shutit_global . shutit_global_object . yield_to_draw ( ) if send is None : return send cmd_arr = send . split ( ) if cmd_arr and cmd_arr [ 0 ] in ( 'md5sum' , 'sed' , 'head' ) : newcmd = self . get_command ( cmd_arr [ 0 ] ) send = send . replace ( cmd_arr [ 0 ] , newcmd ) return send
Internal helper function to get command that s really sent
52,409
def load_configs ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) configs = [ ( 'defaults' , StringIO ( default_cnf ) ) , os . path . expanduser ( '~/.shutit/config' ) , os . path . join ( self . host [ 'shutit_path' ] , 'config' ) , 'configs/build.cnf' ] for config_file_name in self . build [ 'extra_configs' ] : run_config_file = os . path . expanduser ( config_file_name ) if not os . path . isfile ( run_config_file ) : shutit_global . shutit_global_object . shutit_print ( 'Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?' ) shutit_global . shutit_global_object . handle_exit ( exit_code = 0 ) configs . append ( run_config_file ) if self . action [ 'list_configs' ] or self . loglevel <= logging . DEBUG : msg = '' for c in configs : if isinstance ( c , tuple ) : c = c [ 0 ] msg = msg + ' \n' + c self . log ( ' ' + c , level = logging . DEBUG ) if self . build [ 'config_overrides' ] : override_cp = ConfigParser . RawConfigParser ( ) for o_sec , o_key , o_val in self . build [ 'config_overrides' ] : if not override_cp . has_section ( o_sec ) : override_cp . add_section ( o_sec ) override_cp . set ( o_sec , o_key , o_val ) override_fd = StringIO ( ) override_cp . write ( override_fd ) override_fd . seek ( 0 ) configs . append ( ( 'overrides' , override_fd ) ) self . config_parser = self . get_configs ( configs ) self . get_base_config ( )
Responsible for loading config files into ShutIt . Recurses down from configured shutit module paths .
52,410
def config_collection ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In config_collection' , level = logging . DEBUG ) cfg = self . cfg for module_id in self . module_ids ( ) : self . get_config ( module_id , 'shutit.core.module.build' , None , boolean = True , forcenone = True ) self . get_config ( module_id , 'shutit.core.module.remove' , False , boolean = True ) self . get_config ( module_id , 'shutit.core.module.tag' , False , boolean = True ) self . get_config ( module_id , 'shutit.core.module.allowed_images' , [ ".*" ] ) module = self . shutit_map [ module_id ] cfg_file = os . path . dirname ( get_module_file ( self , module ) ) + '/configs/build.cnf' if os . path . isfile ( cfg_file ) : config_parser = ConfigParser . ConfigParser ( ) config_parser . read ( cfg_file ) for section in config_parser . sections ( ) : if section == module_id : for option in config_parser . options ( section ) : if option == 'shutit.core.module.allowed_images' : override = False for mod , opt , val in self . build [ 'config_overrides' ] : val = val if mod == module_id and opt == option : override = True if override : continue value = config_parser . get ( section , option ) if option == 'shutit.core.module.allowed_images' : value = json . loads ( value ) self . get_config ( module_id , option , value , forceask = True ) if cfg [ module_id ] [ 'shutit.core.module.build' ] is None : self . get_config ( module_id , 'shutit.core.module.build_ifneeded' , True , boolean = True ) cfg [ module_id ] [ 'shutit.core.module.build' ] = False else : self . get_config ( module_id , 'shutit.core.module.build_ifneeded' , False , boolean = True )
Collect core config from config files for all seen modules .
52,411
def print_config ( self , cfg , hide_password = True , history = False , module_id = None ) : shutit_global . shutit_global_object . yield_to_draw ( ) cp = self . config_parser s = '' keys1 = list ( cfg . keys ( ) ) if keys1 : keys1 . sort ( ) for k in keys1 : if module_id is not None and k != module_id : continue if isinstance ( k , str ) and isinstance ( cfg [ k ] , dict ) : s += '\n[' + k + ']\n' keys2 = list ( cfg [ k ] . keys ( ) ) if keys2 : keys2 . sort ( ) for k1 in keys2 : line = '' line += k1 + ':' if hide_password and ( k1 == 'password' or k1 == 'passphrase' ) : p = hashlib . sha512 ( cfg [ k ] [ k1 ] ) . hexdigest ( ) i = 27 while i > 0 : i -= 1 p = hashlib . sha512 ( s ) . hexdigest ( ) line += p else : if type ( cfg [ k ] [ k1 ] == bool ) : line += str ( cfg [ k ] [ k1 ] ) elif type ( cfg [ k ] [ k1 ] == str ) : line += cfg [ k ] [ k1 ] if history : try : line += ( 30 - len ( line ) ) * ' ' + ' # ' + cp . whereset ( k , k1 ) except Exception : line += ( 30 - len ( line ) ) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s
Returns a string representing the config of this ShutIt run .
52,412
def process_args ( self , args ) : shutit_global . shutit_global_object . yield_to_draw ( ) assert isinstance ( args , ShutItInit ) , shutit_util . print_debug ( ) if args . action == 'version' : shutit_global . shutit_global_object . shutit_print ( 'ShutIt version: ' + shutit . shutit_version ) shutit_global . shutit_global_object . handle_exit ( exit_code = 0 ) self . action [ 'list_configs' ] = args . action == 'list_configs' self . action [ 'list_modules' ] = args . action == 'list_modules' self . action [ 'list_deps' ] = args . action == 'list_deps' self . action [ 'skeleton' ] = args . action == 'skeleton' self . action [ 'build' ] = args . action == 'build' self . action [ 'run' ] = args . action == 'run' if not self . logging_setup_done : self . logfile = args . logfile self . loglevel = args . loglevel if self . loglevel is None or self . loglevel == '' : self . loglevel = 'INFO' self . setup_logging ( ) shutit_global . shutit_global_object . setup_panes ( action = args . action ) if self . action [ 'skeleton' ] : self . handle_skeleton ( args ) shutit_global . shutit_global_object . handle_exit ( ) elif self . action [ 'run' ] : self . handle_run ( args ) sys . exit ( 0 ) elif self . action [ 'build' ] or self . action [ 'list_configs' ] or self . action [ 'list_modules' ] : self . handle_build ( args ) else : self . fail ( 'Should not get here: action was: ' + str ( self . action ) ) self . nocolor = args . nocolor
Process the args we have . args is always a ShutItInit object .
52,413
def check_deps ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: dependencies' , level = logging . DEBUG ) self . pause_point ( '\nNow checking for dependencies between modules' , print_input = False , level = 3 ) to_build = [ self . shutit_map [ module_id ] for module_id in self . shutit_map if module_id in cfg and cfg [ module_id ] [ 'shutit.core.module.build' ] ] for module in to_build : self . resolve_dependencies ( to_build , module ) def err_checker ( errs , triples ) : new_triples = [ ] for err , triple in zip ( errs , triples ) : if not err : new_triples . append ( triple ) continue found_errs . append ( err ) return new_triples found_errs = [ ] triples = [ ] for depender in to_build : for dependee_id in depender . depends_on : triples . append ( ( depender , self . shutit_map . get ( dependee_id ) , dependee_id ) ) triples = err_checker ( [ self . check_dependee_exists ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ self . check_dependee_build ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ check_dependee_order ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) if found_errs : return [ ( err , ) for err in found_errs ] self . log ( 'Modules configured to be built (in order) are: ' , level = logging . DEBUG ) for module_id in self . module_ids ( ) : module = self . shutit_map [ module_id ] if cfg [ module_id ] [ 'shutit.core.module.build' ] : self . log ( module_id + ' ' + str ( module . run_order ) , level = logging . DEBUG ) self . log ( '\n' , level = logging . DEBUG ) return [ ]
Dependency checking phase is performed in this method .
52,414
def check_conflicts ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: conflicts' , level = logging . DEBUG ) errs = [ ] self . pause_point ( '\nNow checking for conflicts between modules' , print_input = False , level = 3 ) for module_id in self . module_ids ( ) : if not cfg [ module_id ] [ 'shutit.core.module.build' ] : continue conflicter = self . shutit_map [ module_id ] for conflictee in conflicter . conflicts_with : conflictee_obj = self . shutit_map . get ( conflictee ) if conflictee_obj is None : continue if ( ( cfg [ conflicter . module_id ] [ 'shutit.core.module.build' ] or self . is_to_be_built_or_is_installed ( conflicter ) ) and ( cfg [ conflictee_obj . module_id ] [ 'shutit.core.module.build' ] or self . is_to_be_built_or_is_installed ( conflictee_obj ) ) ) : errs . append ( ( 'conflicter module id: ' + conflicter . module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj . module_id , ) ) return errs
Checks for any conflicts between modules configured to be built .
52,415
def do_remove ( self , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: remove' , level = loglevel ) self . pause_point ( '\nNow removing any modules that need removing' , print_input = False , level = 3 ) for module_id in self . module_ids ( ) : module = self . shutit_map [ module_id ] self . log ( 'considering whether to remove: ' + module_id , level = logging . DEBUG ) if cfg [ module_id ] [ 'shutit.core.module.remove' ] : self . log ( 'removing: ' + module_id , level = logging . DEBUG ) self . login ( prompt_prefix = module_id , command = shutit_global . shutit_global_object . bash_startup_command , echo = False ) if not module . remove ( self ) : self . log ( self . print_modules ( ) , level = logging . DEBUG ) self . fail ( module_id + ' failed on remove' , shutit_pexpect_child = self . get_shutit_pexpect_session_from_id ( 'target_child' ) . pexpect_child ) else : if self . build [ 'delivery' ] in ( 'docker' , 'dockerfile' ) : self . send ( ' command mkdir -p ' + shutit_global . shutit_global_object . shutit_state_dir_build_db_dir + '/module_record/' + module . module_id + ' && command rm -f ' + shutit_global . shutit_global_object . shutit_state_dir_build_db_dir + '/module_record/' + module . module_id + '/built && command touch ' + shutit_global . shutit_global_object . shutit_state_dir_build_db_dir + '/module_record/' + module . module_id + '/removed' , loglevel = loglevel , echo = False ) if module . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_installed : self . get_current_shutit_pexpect_session_environment ( ) . modules_installed . remove ( module . module_id ) self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed . append ( module . module_id ) self . logout ( echo = False )
Remove modules by calling remove method on those configured for removal .
52,416
def do_build ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: build, repository work' , level = logging . DEBUG ) module_id_list = self . module_ids ( ) if self . build [ 'deps_only' ] : module_id_list_build_only = filter ( lambda x : cfg [ x ] [ 'shutit.core.module.build' ] , module_id_list ) for module_id in module_id_list : module = self . shutit_map [ module_id ] self . log ( 'Considering whether to build: ' + module . module_id , level = logging . INFO ) if cfg [ module . module_id ] [ 'shutit.core.module.build' ] : if self . build [ 'delivery' ] not in module . ok_delivery_methods : self . fail ( 'Module: ' + module . module_id + ' can only be built with one of these --delivery methods: ' + str ( module . ok_delivery_methods ) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation' ) if self . is_installed ( module ) : self . build [ 'report' ] = ( self . build [ 'report' ] + '\nBuilt already: ' + module . module_id + ' with run order: ' + str ( module . run_order ) ) else : if self . build [ 'deps_only' ] and module_id == module_id_list_build_only [ - 1 ] : self . build [ 'report' ] = ( self . build [ 'report' ] + '\nSkipping: ' + module . module_id + ' with run order: ' + str ( module . run_order ) + '\n\tas this is the final module and we are building dependencies only' ) else : revert_dir = os . getcwd ( ) self . get_current_shutit_pexpect_session_environment ( ) . module_root_dir = os . path . dirname ( self . shutit_file_map [ module_id ] ) self . chdir ( self . get_current_shutit_pexpect_session_environment ( ) . module_root_dir ) self . login ( prompt_prefix = module_id , command = shutit_global . shutit_global_object . bash_startup_command , echo = False ) self . build_module ( module ) self . logout ( echo = False ) self . chdir ( revert_dir ) if self . is_installed ( module ) : self . log ( 'Starting module' , level = logging . DEBUG ) if not module . start ( self ) : self . fail ( module . module_id + ' failed on start' , shutit_pexpect_child = self . get_shutit_pexpect_session_from_id ( 'target_child' ) . pexpect_child )
Runs build phase building any modules that we ve determined need building .
52,417
def stop_all ( self , run_order = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) for module_id in self . module_ids ( rev = True ) : shutit_module_obj = self . shutit_map [ module_id ] if run_order == - 1 or shutit_module_obj . run_order <= run_order : if self . is_installed ( shutit_module_obj ) : if not shutit_module_obj . stop ( self ) : self . fail ( 'failed to stop: ' + module_id , shutit_pexpect_child = self . get_shutit_pexpect_session_from_id ( 'target_child' ) . shutit_pexpect_child )
Runs stop method on all modules less than the passed - in run_order . Used when target is exporting itself mid - build so we clean up state before committing run files etc .
52,418
def start_all ( self , run_order = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) for module_id in self . module_ids ( ) : shutit_module_obj = self . shutit_map [ module_id ] if run_order == - 1 or shutit_module_obj . run_order <= run_order : if self . is_installed ( shutit_module_obj ) : if not shutit_module_obj . start ( self ) : self . fail ( 'failed to start: ' + module_id , shutit_pexpect_child = self . get_shutit_pexpect_session_from_id ( 'target_child' ) . shutit_pexpect_child )
Runs start method on all modules less than the passed - in run_order . Used when target is exporting itself mid - build so we can export a clean target and still depended - on modules running if necessary .
52,419
def init_shutit_map ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) modules = self . shutit_modules if len ( [ mod for mod in modules if mod . run_order > 0 ] ) < 1 : self . log ( modules , level = logging . DEBUG ) path = ':' . join ( self . host [ 'shutit_module_path' ] ) self . log ( '\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n' , level = logging . INFO ) if path == '' : self . fail ( 'No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n' ) elif path == '.' : self . fail ( 'No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?' ) else : self . fail ( 'No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.' ) self . log ( 'PHASE: base setup' , level = logging . DEBUG ) run_orders = { } has_core_module = False for module in modules : assert isinstance ( module , ShutItModule ) , shutit_util . print_debug ( ) if module . module_id in self . shutit_map : self . fail ( 'Duplicated module id: ' + module . module_id + '\n\nYou may want to check your --shutit_module_path setting' ) if module . run_order in run_orders : self . fail ( 'Duplicate run order: ' + str ( module . run_order ) + ' for ' + module . module_id + ' and ' + run_orders [ module . run_order ] . module_id + '\n\nYou may want to check your --shutit_module_path setting' ) if module . run_order == 0 : has_core_module = True self . shutit_map [ module . module_id ] = run_orders [ module . run_order ] = module self . shutit_file_map [ module . module_id ] = get_module_file ( self , module ) if not has_core_module : self . fail ( 'No module with run_order=0 specified! This is required.' )
Initializes the module map of shutit based on the modules we have gathered .
52,420
def conn_target ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) conn_module = None for mod in self . conn_modules : if mod . module_id == self . build [ 'conn_module' ] : conn_module = mod break if conn_module is None : self . fail ( 'Couldn\'t find conn_module ' + self . build [ 'conn_module' ] ) conn_module . get_config ( self ) conn_module . build ( self )
Connect to the target .
52,421
def finalize_target ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . pause_point ( '\nFinalizing the target module (' + self . shutit_main_dir + '/shutit_setup.py)' , print_input = False , level = 3 ) for mod in self . conn_modules : if mod . module_id == self . build [ 'conn_module' ] : conn_module = mod break conn_module . finalize ( self )
Finalize the target using the core finalize method .
52,422
def resolve_dependencies ( self , to_build , depender ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In resolve_dependencies' , level = logging . DEBUG ) cfg = self . cfg for dependee_id in depender . depends_on : dependee = self . shutit_map . get ( dependee_id ) if ( dependee and dependee not in to_build and cfg [ dependee_id ] [ 'shutit.core.module.build_ifneeded' ] ) : to_build . append ( dependee ) cfg [ dependee_id ] [ 'shutit.core.module.build' ] = True return True
Add any required dependencies .
52,423
def check_dependee_exists ( self , depender , dependee , dependee_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) if dependee is None : return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str ( self . host [ 'shutit_module_path' ] ) + ' but needed for ' + depender . module_id + '\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg "--shutit_module_path /path/to/other/module/:."\n\nAlso check that the module is configured to be built with the correct module id in that module\'s configs/build.cnf file.\n\nSee also help.' return ''
Checks whether a depended - on module is available .
52,424
def check_dependee_build ( self , depender , dependee , dependee_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg if not ( cfg [ dependee . module_id ] [ 'shutit.core.module.build' ] or self . is_to_be_built_or_is_installed ( dependee ) ) : return 'depender module id:\n\n[' + depender . module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"' return ''
Checks whether a depended on module is configured to be built .
52,425
def destroy ( self ) : if self . session_type == 'bash' : self . logout ( ) elif self . session_type == 'vagrant' : self . logout ( )
Finish up a session .
52,426
def shutit_method_scope ( func ) : def wrapper ( self , shutit ) : ret = func ( self , shutit ) return ret return wrapper
Notifies the ShutIt object whenever we call a shutit module method . This allows setting values for the scope of a function .
52,427
def managing_thread_main_simple ( ) : import shutit_global last_msg = '' while True : printed_anything = False if shutit_global . shutit_global_object . log_trace_when_idle and time . time ( ) - shutit_global . shutit_global_object . last_log_time > 10 : this_msg = '' this_header = '' for thread_id , stack in sys . _current_frames ( ) . items ( ) : if thread_id == threading . current_thread ( ) . ident : continue printed_thread_started = False for filename , lineno , name , line in traceback . extract_stack ( stack ) : if not printed_anything : printed_anything = True this_header += '\n=' * 80 + '\n' this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str ( thread_id ) + ' at ' + time . strftime ( '%c' ) + '\n' this_header += '=' * 80 + '\n' if not printed_thread_started : printed_thread_started = True this_msg += '%s:%d:%s' % ( filename , lineno , name ) + '\n' if line : this_msg += ' %s' % ( line , ) + '\n' if printed_anything : this_msg += '=' * 80 + '\n' this_msg += 'STACK TRACES DONE\n' this_msg += '=' * 80 + '\n' if this_msg != last_msg : print ( this_header + this_msg ) last_msg = this_msg time . sleep ( 5 )
Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed .
52,428
def map_package ( shutit_pexpect_session , package , install_type ) : if package in PACKAGE_MAP . keys ( ) : for itype in PACKAGE_MAP [ package ] . keys ( ) : if itype == install_type : ret = PACKAGE_MAP [ package ] [ install_type ] if isinstance ( ret , str ) : return ret if callable ( ret ) : ret ( shutit_pexpect_session ) return '' return package
If package mapping exists then return it else return package .
52,429
def is_file_secure ( file_name ) : if not os . path . isfile ( file_name ) : return True file_mode = os . stat ( file_name ) . st_mode if file_mode & ( stat . S_IRGRP | stat . S_IWGRP | stat . S_IXGRP | stat . S_IROTH | stat . S_IWOTH | stat . S_IXOTH ) : return False return True
Returns false if file is considered insecure true if secure . If file doesn t exist it s considered secure!
52,430
def random_id ( size = 8 , chars = string . ascii_letters + string . digits ) : return '' . join ( random . choice ( chars ) for _ in range ( size ) )
Generates a random string of given size from the given chars .
52,431
def random_word ( size = 6 ) : words = shutit_assets . get_words ( ) . splitlines ( ) word = '' while len ( word ) != size or "'" in word : word = words [ int ( random . random ( ) * ( len ( words ) - 1 ) ) ] return word . lower ( )
Returns a random word in lower case .
52,432
def ctrl_c_signal_handler ( _ , frame ) : global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10 : shutit_global . shutit_global_object . handle_exit ( exit_code = 1 ) shutit_frame = get_shutit_frame ( frame ) if in_ctrlc : msg = 'CTRL-C hit twice, quitting' if shutit_frame : shutit_global . shutit_global_object . shutit_print ( '\n' ) shutit = shutit_frame . f_locals [ 'shutit' ] shutit . log ( msg , level = logging . CRITICAL ) else : shutit_global . shutit_global_object . shutit_print ( msg ) shutit_global . shutit_global_object . handle_exit ( exit_code = 1 ) if shutit_frame : shutit = shutit_frame . f_locals [ 'shutit' ] if shutit . build [ 'ctrlc_passthrough' ] : shutit . self . get_current_shutit_pexpect_session ( ) . pexpect_child . sendline ( r'' ) return shutit_global . shutit_global_object . shutit_print ( colorise ( 31 , "\r" + r"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\ to quit." ) ) shutit . build [ 'ctrlc_stop' ] = True t = threading . Thread ( target = ctrlc_background ) t . daemon = True t . start ( ) ctrl_c_calls = 0 return shutit_global . shutit_global_object . shutit_print ( colorise ( 31 , '\n' + '*' * 80 ) ) shutit_global . shutit_global_object . shutit_print ( colorise ( 31 , "CTRL-c caught, CTRL-c twice to quit." ) ) shutit_global . shutit_global_object . shutit_print ( colorise ( 31 , '*' * 80 ) ) t = threading . Thread ( target = ctrlc_background ) t . daemon = True t . start ( ) ctrl_c_calls = 0
CTRL - c signal handler - enters a pause point if it can .
52,433
def get_input ( msg , default = '' , valid = None , boolean = False , ispass = False , color = None ) : log_trace_when_idle_original_value = shutit_global . shutit_global_object . log_trace_when_idle shutit_global . shutit_global_object . log_trace_when_idle = False if boolean and valid is None : valid = ( 'yes' , 'y' , 'Y' , '1' , 'true' , 'no' , 'n' , 'N' , '0' , 'false' ) if color : answer = util_raw_input ( prompt = colorise ( color , msg ) , ispass = ispass ) else : answer = util_raw_input ( msg , ispass = ispass ) if boolean and answer in ( '' , None ) and default != '' : shutit_global . shutit_global_object . log_trace_when_idle = log_trace_when_idle_original_value return default if valid is not None : while answer not in valid : shutit_global . shutit_global_object . shutit_print ( 'Answer must be one of: ' + str ( valid ) , transient = True ) if color : answer = util_raw_input ( prompt = colorise ( color , msg ) , ispass = ispass ) else : answer = util_raw_input ( msg , ispass = ispass ) if boolean : if answer . lower ( ) in ( 'yes' , 'y' , '1' , 'true' , 't' ) : shutit_global . shutit_global_object . log_trace_when_idle = log_trace_when_idle_original_value return True elif answer . lower ( ) in ( 'no' , 'n' , '0' , 'false' , 'f' ) : shutit_global . shutit_global_object . log_trace_when_idle = log_trace_when_idle_original_value return False shutit_global . shutit_global_object . log_trace_when_idle = log_trace_when_idle_original_value return answer or default
Gets input from the user and returns the answer .
52,434
def build ( self , shutit ) : target_child = self . start_container ( shutit , 'target_child' ) self . setup_host_child ( shutit ) self . setup_target_child ( shutit , target_child ) shutit . send ( 'chmod -R 777 ' + shutit_global . shutit_global_object . shutit_state_dir + ' && mkdir -p ' + shutit_global . shutit_global_object . shutit_state_dir_build_db_dir + '/' + shutit_global . shutit_global_object . build_id , shutit_pexpect_child = target_child , echo = False ) return True
Sets up the target ready for building .
52,435
def build ( self , shutit ) : shutit_pexpect_session = ShutItPexpectSession ( shutit , 'target_child' , '/bin/bash' ) target_child = shutit_pexpect_session . pexpect_child shutit_pexpect_session . expect ( shutit_global . shutit_global_object . base_prompt . strip ( ) , timeout = 10 ) self . setup_host_child ( shutit ) self . setup_target_child ( shutit , target_child ) return True
Sets up the machine ready for building .
52,436
def build ( self , shutit ) : if shutit . build [ 'delivery' ] in ( 'docker' , 'dockerfile' ) : if shutit . get_current_shutit_pexpect_session_environment ( ) . install_type == 'apt' : shutit . add_to_bashrc ( 'export DEBIAN_FRONTEND=noninteractive' ) if not shutit . command_available ( 'lsb_release' ) : shutit . install ( 'lsb-release' ) shutit . lsb_release ( ) elif shutit . get_current_shutit_pexpect_session_environment ( ) . install_type == 'yum' : shutit . send ( 'yum update -y' , timeout = 9999 , exit_values = [ '0' , '1' ] ) shutit . pause_point ( 'Anything you want to do to the target host ' + 'before the build starts?' , level = 2 ) return True
Initializes target ready for build and updating package management if in container .
52,437
def __set_config ( self , cfg_section ) : defaults = [ 'shutit.core.alerting.emailer.mailto' , None , 'shutit.core.alerting.emailer.mailfrom' , 'angry@shutit.tk' , 'shutit.core.alerting.emailer.smtp_server' , 'localhost' , 'shutit.core.alerting.emailer.smtp_port' , 25 , 'shutit.core.alerting.emailer.use_tls' , True , 'shutit.core.alerting.emailer.send_mail' , True , 'shutit.core.alerting.emailer.subject' , 'Shutit Report' , 'shutit.core.alerting.emailer.signature' , '--Angry Shutit' , 'shutit.core.alerting.emailer.compress' , True , 'shutit.core.alerting.emailer.username' , '' , 'shutit.core.alerting.emailer.password' , '' , 'shutit.core.alerting.emailer.safe_mode' , True , 'shutit.core.alerting.emailer.maintainer' , '' , 'shutit.core.alerting.emailer.mailto_maintainer' , True ] for cfg_name , cfg_default in zip ( defaults [ 0 : : 2 ] , defaults [ 1 : : 2 ] ) : try : self . config [ cfg_name ] = self . shutit . cfg [ cfg_section ] [ cfg_name ] except KeyError : if cfg_default is None : raise Exception ( cfg_section + ' ' + cfg_name + ' must be set' ) else : self . config [ cfg_name ] = cfg_default if self . config [ 'shutit.core.alerting.emailer.mailto_maintainer' ] and ( self . config [ 'shutit.core.alerting.emailer.maintainer' ] == "" or self . config [ 'shutit.core.alerting.emailer.maintainer' ] == self . config [ 'shutit.core.alerting.emailer.mailto' ] ) : self . config [ 'shutit.core.alerting.emailer.mailto_maintainer' ] = False self . config [ 'shutit.core.alerting.emailer.maintainer' ] = ""
Set a local config array up according to defaults and main shutit configuration
52,438
def __get_smtp ( self ) : use_tls = self . config [ 'shutit.core.alerting.emailer.use_tls' ] if use_tls : smtp = SMTP ( self . config [ 'shutit.core.alerting.emailer.smtp_server' ] , self . config [ 'shutit.core.alerting.emailer.smtp_port' ] ) smtp . starttls ( ) else : smtp = SMTP_SSL ( self . config [ 'shutit.core.alerting.emailer.smtp_server' ] , self . config [ 'shutit.core.alerting.emailer.smtp_port' ] ) return smtp
Return the appropraite smtplib depending on wherther we re using TLS
52,439
def __compose ( self ) : msg = MIMEMultipart ( ) msg [ 'Subject' ] = self . config [ 'shutit.core.alerting.emailer.subject' ] msg [ 'To' ] = self . config [ 'shutit.core.alerting.emailer.mailto' ] msg [ 'From' ] = self . config [ 'shutit.core.alerting.emailer.mailfrom' ] if self . config [ 'shutit.core.alerting.emailer.mailto_maintainer' ] : msg [ 'Cc' ] = self . config [ 'shutit.core.alerting.emailer.maintainer' ] if self . config [ 'shutit.core.alerting.emailer.signature' ] != '' : signature = '\n\n' + self . config [ 'shutit.core.alerting.emailer.signature' ] else : signature = self . config [ 'shutit.core.alerting.emailer.signature' ] body = MIMEText ( '\n' . join ( self . lines ) + signature ) msg . attach ( body ) for attach in self . attaches : msg . attach ( attach ) return msg
Compose the message pulling together body attachments etc
52,440
def send ( self , attachment_failure = False ) : if not self . config [ 'shutit.core.alerting.emailer.send_mail' ] : self . shutit . log ( 'emailer.send: Not configured to send mail!' , level = logging . INFO ) return True msg = self . __compose ( ) mailto = [ self . config [ 'shutit.core.alerting.emailer.mailto' ] ] smtp = self . __get_smtp ( ) if self . config [ 'shutit.core.alerting.emailer.username' ] != '' : smtp . login ( self . config [ 'shutit.core.alerting.emailer.username' ] , self . config [ 'shutit.core.alerting.emailer.password' ] ) if self . config [ 'shutit.core.alerting.emailer.mailto_maintainer' ] : mailto . append ( self . config [ 'shutit.core.alerting.emailer.maintainer' ] ) try : self . shutit . log ( 'Attempting to send email' , level = logging . INFO ) smtp . sendmail ( self . config [ 'shutit.core.alerting.emailer.mailfrom' ] , mailto , msg . as_string ( ) ) except SMTPSenderRefused as refused : code = refused . args [ 0 ] if code == 552 and not attachment_failure : self . shutit . log ( "Mailserver rejected message due to " + "oversize attachments, attempting to resend without" , level = logging . INFO ) self . attaches = [ ] self . lines . append ( "Oversized attachments not sent" ) self . send ( attachment_failure = True ) else : self . shutit . log ( "Unhandled SMTP error:" + str ( refused ) , level = logging . INFO ) if not self . config [ 'shutit.core.alerting.emailer.safe_mode' ] : raise refused except Exception as error : self . shutit . log ( 'Unhandled exception: ' + str ( error ) , level = logging . INFO ) if not self . config [ 'shutit.core.alerting.emailer.safe_mode' ] : raise error finally : smtp . quit ( )
Send the email according to the configured setup
52,441
def setup_signals ( ) : signal . signal ( signal . SIGINT , shutit_util . ctrl_c_signal_handler ) signal . signal ( signal . SIGQUIT , shutit_util . ctrl_quit_signal_handler )
Set up the signal handlers .
52,442
def get_shutit_pexpect_sessions ( ) : sessions = [ ] for shutit_object in shutit_global_object . shutit_objects : for key in shutit_object . shutit_pexpect_sessions : sessions . append ( shutit_object . shutit_pexpect_sessions [ key ] ) return sessions
Returns all the shutit_pexpect sessions in existence .
52,443
def main ( ) : shutit = shutit_global . shutit_global_object . shutit_objects [ 0 ] if sys . version_info [ 0 ] == 2 : if sys . version_info [ 1 ] < 7 : shutit . fail ( 'Python version must be 2.7+' ) try : shutit . setup_shutit_obj ( ) except KeyboardInterrupt : shutit_util . print_debug ( sys . exc_info ( ) ) shutit_global . shutit_global_object . shutit_print ( 'Keyboard interrupt caught, exiting with status 1' ) sys . exit ( 1 )
Main ShutIt function .
52,444
def has_blocking_background_send ( self ) : for background_object in self . background_objects : if background_object . block_other_commands and background_object . run_state in ( 'S' , 'N' ) : self . shutit_obj . log ( 'All objects are: ' + str ( self ) , level = logging . DEBUG ) self . shutit_obj . log ( 'The current blocking send object is: ' + str ( background_object ) , level = logging . DEBUG ) return True elif background_object . block_other_commands and background_object . run_state in ( 'F' , 'C' , 'T' ) : assert False , shutit_util . print_debug ( msg = 'Blocking command should have been removed, in run_state: ' + background_object . run_state ) else : assert background_object . block_other_commands is False , shutit_util . print_debug ( ) return False
Check whether any blocking background commands are waiting to run . If any are return True . If none are return False .
52,445
def check_background_commands_complete ( self ) : unstarted_command_exists = False self . shutit_obj . log ( 'In check_background_commands_complete: all background objects: ' + str ( self . background_objects ) , level = logging . DEBUG ) self . shutit_obj . log ( 'Login id: ' + str ( self . login_id ) , level = logging . DEBUG ) for background_object in self . background_objects : self . shutit_obj . log ( 'Background object send: ' + str ( background_object . sendspec . send ) , level = logging . DEBUG ) background_objects_to_remove = [ ] def remove_background_objects ( a_background_objects_to_remove ) : for background_object in a_background_objects_to_remove : self . background_objects . remove ( background_object ) for background_object in self . background_objects : self . shutit_obj . log ( 'Checking background object: ' + str ( background_object ) , level = logging . DEBUG ) state = background_object . check_background_command_state ( ) self . shutit_obj . log ( 'State is: ' + state , level = logging . DEBUG ) if state in ( 'C' , 'F' , 'T' ) : background_objects_to_remove . append ( background_object ) self . background_objects_completed . append ( background_object ) elif state == 'S' : self . shutit_obj . log ( 'check_background_command_state returning False (S) for ' + str ( background_object ) , level = logging . DEBUG ) remove_background_objects ( background_objects_to_remove ) return False , 'S' , background_object elif state == 'N' : self . shutit_obj . log ( 'UNSTARTED COMMAND! ' + str ( background_object . sendspec . send ) , level = logging . DEBUG ) unstarted_command_exists = True else : remove_background_objects ( background_objects_to_remove ) assert False , shutit_util . print_debug ( msg = 'Un-handled: ' + state ) if state == 'F' : self . shutit_obj . log ( 'check_background_command_state returning False (F) for ' + str ( background_object ) , level = logging . DEBUG ) remove_background_objects ( background_objects_to_remove ) return False , 'F' , background_object remove_background_objects ( background_objects_to_remove ) self . shutit_obj . log ( 'Checking background objects done.' , level = logging . DEBUG ) if unstarted_command_exists : for background_object in self . background_objects : state = background_object . check_background_command_state ( ) if state == 'N' : background_object . run_background_command ( ) self . shutit_obj . log ( 'check_background_command_state returning False (N) for ' + str ( background_object ) , level = logging . DEBUG ) return False , 'N' , background_object self . shutit_obj . log ( 'check_background_command_state returning True (OK)' , level = logging . DEBUG ) return True , 'OK' , None
Check whether any background commands are running or to be run . If none are return True . If any are return False .
52,446
def open_remote ( cls , username , password , multifactor_password = None , client_id = None ) : blob = cls . fetch_blob ( username , password , multifactor_password , client_id ) return cls . open ( blob , username , password )
Fetches a blob from the server and creates a vault
52,447
def open ( cls , blob , username , password ) : return cls ( blob , blob . encryption_key ( username , password ) )
Creates a vault from a blob object
52,448
def fetch_blob ( cls , username , password , multifactor_password = None , client_id = None ) : session = fetcher . login ( username , password , multifactor_password , client_id ) blob = fetcher . fetch ( session ) fetcher . logout ( session ) return blob
Just fetches the blob could be used to store it locally
52,449
def extract_chunks ( blob ) : chunks = [ ] stream = BytesIO ( blob . bytes ) current_pos = stream . tell ( ) stream . seek ( 0 , 2 ) length = stream . tell ( ) stream . seek ( current_pos , 0 ) while stream . tell ( ) < length : chunks . append ( read_chunk ( stream ) ) return chunks
Splits the blob into chucks grouped by kind .
52,450
def parse_ACCT ( chunk , encryption_key ) : io = BytesIO ( chunk . payload ) id = read_item ( io ) name = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) group = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) url = decode_hex ( read_item ( io ) ) notes = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) skip_item ( io , 2 ) username = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) password = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) skip_item ( io , 2 ) secure_note = read_item ( io ) if secure_note == b'1' : parsed = parse_secure_note_server ( notes ) if parsed . get ( 'type' ) in ALLOWED_SECURE_NOTE_TYPES : url = parsed . get ( 'url' , url ) username = parsed . get ( 'username' , username ) password = parsed . get ( 'password' , password ) return Account ( id , name , username , password , url , group , notes )
Parses an account chunk decrypts and creates an Account object . May return nil when the chunk does not represent an account . All secure notes are ACCTs but not all of them strore account information .
52,451
def parse_PRIK ( chunk , encryption_key ) : decrypted = decode_aes256 ( 'cbc' , encryption_key [ : 16 ] , decode_hex ( chunk . payload ) , encryption_key ) hex_key = re . match ( br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$' , decrypted ) . group ( 'hex_key' ) rsa_key = RSA . importKey ( decode_hex ( hex_key ) ) rsa_key . dmp1 = rsa_key . d % ( rsa_key . p - 1 ) rsa_key . dmq1 = rsa_key . d % ( rsa_key . q - 1 ) rsa_key . iqmp = number . inverse ( rsa_key . q , rsa_key . p ) return rsa_key
Parse PRIK chunk which contains private RSA key
52,452
def decode_aes256_cbc_base64 ( data , encryption_key ) : if not data : return b'' else : return decode_aes256 ( 'cbc' , decode_base64 ( data [ 1 : 25 ] ) , decode_base64 ( data [ 26 : ] ) , encryption_key )
Decrypts base64 encoded AES - 256 CBC bytes .
52,453
def api_delete ( service , file_id , owner_token ) : service += 'api/delete/%s' % file_id r = requests . post ( service , json = { 'owner_token' : owner_token , 'delete_token' : owner_token } ) r . raise_for_status ( ) if r . text == 'OK' : return True return False
Delete a file already uploaded to Send
52,454
def api_params ( service , file_id , owner_token , download_limit ) : service += 'api/params/%s' % file_id r = requests . post ( service , json = { 'owner_token' : owner_token , 'dlimit' : download_limit } ) r . raise_for_status ( ) if r . text == 'OK' : return True return False
Change the download limit for a file hosted on a Send Server
52,455
def api_download ( service , fileId , authorisation ) : data = tempfile . SpooledTemporaryFile ( max_size = SPOOL_SIZE , mode = 'w+b' ) headers = { 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode ( authorisation ) } url = service + 'api/download/' + fileId r = requests . get ( url , headers = headers , stream = True ) r . raise_for_status ( ) content_length = int ( r . headers [ 'Content-length' ] ) pbar = progbar ( content_length ) for chunk in r . iter_content ( chunk_size = CHUNK_SIZE ) : data . write ( chunk ) pbar . update ( len ( chunk ) ) pbar . close ( ) data . seek ( 0 ) return data
Given a Send url download and return the encrypted data and metadata
52,456
def decrypt_filedata ( data , keys ) : data . seek ( - 16 , 2 ) tag = data . read ( ) data . seek ( - 16 , 2 ) data . truncate ( ) data . seek ( 0 ) plain = tempfile . NamedTemporaryFile ( mode = 'w+b' , delete = False ) pbar = progbar ( fileSize ( data ) ) obj = Cryptodome . Cipher . AES . new ( keys . encryptKey , Cryptodome . Cipher . AES . MODE_GCM , keys . encryptIV ) prev_chunk = b'' for chunk in iter ( lambda : data . read ( CHUNK_SIZE ) , b'' ) : plain . write ( obj . decrypt ( prev_chunk ) ) pbar . update ( len ( chunk ) ) prev_chunk = chunk plain . write ( obj . decrypt_and_verify ( prev_chunk , tag ) ) data . close ( ) pbar . close ( ) plain . seek ( 0 ) return plain
Decrypts a file from Send
52,457
def sign_nonce ( key , nonce ) : return Cryptodome . Hash . HMAC . new ( key , nonce , digestmod = Cryptodome . Hash . SHA256 ) . digest ( )
sign the server nonce from the WWW - Authenticate header with an authKey
52,458
def api_password ( service , fileId , ownerToken , newAuthKey ) : service += 'api/password/%s' % fileId auth = sendclient . common . unpadded_urlsafe_b64encode ( newAuthKey ) r = requests . post ( service , json = { 'owner_token' : ownerToken , 'auth' : auth } ) r . raise_for_status ( ) if r . text == 'OK' : return True return False
changes the authKey required to download a file hosted on a send server
52,459
def set_password ( url , ownerToken , password ) : service , fileId , key = sendclient . common . splitkeyurl ( url ) rawKey = sendclient . common . unpadded_urlsafe_b64decode ( key ) keys = sendclient . common . secretKeys ( rawKey , password , url ) return api_password ( service , fileId , ownerToken , keys . newAuthKey )
set or change the password required to download a file hosted on a send server .
52,460
def splitkeyurl ( url ) : key = url [ - 22 : ] urlid = url [ - 34 : - 24 ] service = url [ : - 43 ] return service , urlid , key
Splits a Send url into key urlid and prefix for the Send server Should handle any hostname but will brake on key & id length changes
52,461
def api_upload ( service , encData , encMeta , keys ) : service += 'api/upload' files = requests_toolbelt . MultipartEncoder ( fields = { 'file' : ( 'blob' , encData , 'application/octet-stream' ) } ) pbar = progbar ( files . len ) monitor = requests_toolbelt . MultipartEncoderMonitor ( files , lambda files : pbar . update ( monitor . bytes_read - pbar . n ) ) headers = { 'X-File-Metadata' : unpadded_urlsafe_b64encode ( encMeta ) , 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode ( keys . authKey ) , 'Content-type' : monitor . content_type } r = requests . post ( service , data = monitor , headers = headers , stream = True ) r . raise_for_status ( ) pbar . close ( ) body_json = r . json ( ) secretUrl = body_json [ 'url' ] + '#' + unpadded_urlsafe_b64encode ( keys . secretKey ) fileId = body_json [ 'id' ] fileNonce = unpadded_urlsafe_b64decode ( r . headers [ 'WWW-Authenticate' ] . replace ( 'send-v1 ' , '' ) ) try : owner_token = body_json [ 'owner' ] except : owner_token = body_json [ 'delete' ] return secretUrl , fileId , fileNonce , owner_token
Uploads data to Send . Caution! Data is uploaded as given this function will not encrypt it for you
52,462
def send_file ( service , file , fileName = None , password = None , ignoreVersion = False ) : if checkServerVersion ( service , ignoreVersion = ignoreVersion ) == False : print ( '\033[1;41m!!! Potentially incompatible server version !!!\033[0m' ) fileName = fileName if fileName != None else os . path . basename ( file . name ) print ( 'Encrypting data from "' + fileName + '"' ) keys = secretKeys ( ) encData = encrypt_file ( file , keys ) encMeta = encrypt_metadata ( keys , fileName ) print ( 'Uploading "' + fileName + '"' ) secretUrl , fileId , fileNonce , owner_token = api_upload ( service , encData , encMeta , keys ) if password != None : print ( 'Setting password' ) sendclient . password . set_password ( secretUrl , owner_token , password ) return secretUrl , fileId , owner_token
Encrypt & Upload a file to send and return the download URL
52,463
def fetch ( self , endpoint , data = None ) : payload = { "lastServerChangeId" : "-1" , "csrf" : self . __csrf , "apiClient" : "WEB" } if data is not None : payload . update ( data ) return self . post ( endpoint , payload )
for getting data after logged in
52,464
def __identify_user ( self , username , csrf ) : data = { "username" : username , "csrf" : csrf , "apiClient" : "WEB" , "bindDevice" : "false" , "skipLinkAccount" : "false" , "redirectTo" : "" , "skipFirstUse" : "" , "referrerId" : "" , } r = self . post ( "/login/identifyUser" , data ) if r . status_code == requests . codes . ok : result = r . json ( ) new_csrf = getSpHeaderValue ( result , CSRF_KEY ) auth_level = getSpHeaderValue ( result , AUTH_LEVEL_KEY ) return ( new_csrf , auth_level ) return ( None , None )
Returns reusable CSRF code and the auth level as a 2 - tuple
52,465
def get_args ( cls , dist , header = None ) : if header is None : header = cls . get_header ( ) spec = str ( dist . as_requirement ( ) ) for type_ in 'console' , 'gui' : group = type_ + '_scripts' for name , ep in dist . get_entry_map ( group ) . items ( ) : if re . search ( r'[\\/]' , name ) : raise ValueError ( "Path separators not allowed in script names" ) script_text = TEMPLATE . format ( ep . module_name , ep . attrs [ 0 ] , '.' . join ( ep . attrs ) , spec , group , name , ) args = cls . _get_script_args ( type_ , name , header , script_text ) for res in args : yield res
Overrides easy_install . ScriptWriter . get_args
52,466
def clean_pip_env ( ) -> Generator [ None , None , None ] : require_venv = os . environ . pop ( PIP_REQUIRE_VIRTUALENV , None ) try : yield finally : if require_venv is not None : os . environ [ PIP_REQUIRE_VIRTUALENV ] = require_venv
A context manager for temporarily removing PIP_REQUIRE_VIRTUALENV from the environment .
52,467
def install ( args : List [ str ] ) -> None : with clean_pip_env ( ) : subprocess_env = os . environ . copy ( ) sitedir_index = _first_sitedir_index ( ) _extend_python_path ( subprocess_env , sys . path [ sitedir_index : ] ) process = subprocess . Popen ( [ sys . executable , "-m" , "pip" , "--disable-pip-version-check" , "install" ] + args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , env = subprocess_env , ) for output in process . stdout : if output : click . echo ( output . decode ( ) . rstrip ( ) ) if process . wait ( ) > 0 : sys . exit ( PIP_INSTALL_ERROR )
pip install as a function .
52,468
def current_zipfile ( ) : if zipfile . is_zipfile ( sys . argv [ 0 ] ) : fd = open ( sys . argv [ 0 ] , "rb" ) return zipfile . ZipFile ( fd )
A function to vend the current zipfile if any
52,469
def extract_site_packages ( archive , target_path , compile_pyc , compile_workers = 0 , force = False ) : parent = target_path . parent target_path_tmp = Path ( parent , target_path . stem + ".tmp" ) lock = Path ( parent , target_path . stem + ".lock" ) if not parent . exists ( ) : parent . mkdir ( parents = True , exist_ok = True ) with FileLock ( lock ) : if not target_path . exists ( ) or force : for filename in archive . namelist ( ) : if filename . startswith ( "site-packages" ) : archive . extract ( filename , target_path_tmp ) if compile_pyc : compileall . compile_dir ( target_path_tmp , quiet = 2 , workers = compile_workers ) if target_path . exists ( ) : shutil . rmtree ( str ( target_path ) ) shutil . move ( str ( target_path_tmp ) , str ( target_path ) )
Extract everything in site - packages to a specified path .
52,470
def bootstrap ( ) : archive = current_zipfile ( ) env = Environment . from_json ( archive . read ( "environment.json" ) . decode ( ) ) site_packages = cache_path ( archive , env . root , env . build_id ) / "site-packages" if not site_packages . exists ( ) or env . force_extract : extract_site_packages ( archive , site_packages . parent , env . compile_pyc , env . compile_workers , env . force_extract ) length = len ( sys . path ) index = _first_sitedir_index ( ) or length site . addsitedir ( site_packages ) if env . extend_pythonpath : _extend_python_path ( os . environ , sys . path [ index : ] ) sys . path = sys . path [ : index ] + sys . path [ length : ] + sys . path [ index : length ] if not env . interpreter : if env . entry_point is not None : mod = import_string ( env . entry_point ) try : sys . exit ( mod ( ) ) except TypeError : sys . exit ( getattr ( mod , env . entry_point . replace ( ":" , "." ) . split ( "." ) [ 1 ] ) ( ) ) elif env . script is not None : sys . exit ( runpy . run_path ( site_packages / "bin" / env . script , run_name = "__main__" ) ) execute_interpreter ( )
Actually bootstrap our shiv environment .
52,471
def write_file_prefix ( f : IO [ Any ] , interpreter : str ) -> None : if len ( interpreter ) > BINPRM_BUF_SIZE : sys . exit ( BINPRM_ERROR ) f . write ( b"#!" + interpreter . encode ( sys . getfilesystemencoding ( ) ) + b"\n" )
Write a shebang line .
52,472
def create_archive ( source : Path , target : Path , interpreter : str , main : str , compressed : bool = True ) -> None : mod , sep , fn = main . partition ( ":" ) mod_ok = all ( part . isidentifier ( ) for part in mod . split ( "." ) ) fn_ok = all ( part . isidentifier ( ) for part in fn . split ( "." ) ) if not ( sep == ":" and mod_ok and fn_ok ) : raise zipapp . ZipAppError ( "Invalid entry point: " + main ) main_py = MAIN_TEMPLATE . format ( module = mod , fn = fn ) with maybe_open ( target , "wb" ) as fd : write_file_prefix ( fd , interpreter ) compression = zipfile . ZIP_DEFLATED if compressed else zipfile . ZIP_STORED with zipfile . ZipFile ( fd , "w" , compression = compression ) as z : for child in source . rglob ( "*" ) : if child . suffix == '.pyc' : continue arcname = child . relative_to ( source ) z . write ( str ( child ) , str ( arcname ) ) z . writestr ( "__main__.py" , main_py . encode ( "utf-8" ) ) target . chmod ( target . stat ( ) . st_mode | stat . S_IXUSR | stat . S_IXGRP | stat . S_IXOTH )
Create an application archive from SOURCE .
52,473
def acquire_win ( lock_file ) : try : fd = os . open ( lock_file , OPEN_MODE ) except OSError : pass else : try : msvcrt . locking ( fd , msvcrt . LK_NBLCK , 1 ) except ( IOError , OSError ) : os . close ( fd ) else : return fd
Acquire a lock file on windows .
52,474
def acquire_nix ( lock_file ) : fd = os . open ( lock_file , OPEN_MODE ) try : fcntl . flock ( fd , fcntl . LOCK_EX | fcntl . LOCK_NB ) except ( IOError , OSError ) : os . close ( fd ) else : return fd
Acquire a lock file on linux or osx .
52,475
def find_entry_point ( site_packages : Path , console_script : str ) -> str : config_parser = ConfigParser ( ) config_parser . read ( site_packages . rglob ( "entry_points.txt" ) ) return config_parser [ "console_scripts" ] [ console_script ]
Find a console_script in a site - packages directory .
52,476
def copy_bootstrap ( bootstrap_target : Path ) -> None : for bootstrap_file in importlib_resources . contents ( bootstrap ) : if importlib_resources . is_resource ( bootstrap , bootstrap_file ) : with importlib_resources . path ( bootstrap , bootstrap_file ) as f : shutil . copyfile ( f . absolute ( ) , bootstrap_target / f . name )
Copy bootstrap code from shiv into the pyz .
52,477
def _interpreter_path ( append_version : bool = False ) -> str : base_dir = Path ( getattr ( sys , "real_prefix" , sys . base_prefix ) ) . resolve ( ) sys_exec = Path ( sys . executable ) name = sys_exec . stem suffix = sys_exec . suffix if append_version : name += str ( sys . version_info . major ) name += suffix try : return str ( next ( iter ( base_dir . rglob ( name ) ) ) ) except StopIteration : if not append_version : return _interpreter_path ( append_version = True ) return sys . executable
A function to return the path to the current Python interpreter .
52,478
def main ( output_file : str , entry_point : Optional [ str ] , console_script : Optional [ str ] , python : Optional [ str ] , site_packages : Optional [ str ] , compressed : bool , compile_pyc : bool , extend_pythonpath : bool , pip_args : List [ str ] , ) -> None : if not pip_args and not site_packages : sys . exit ( NO_PIP_ARGS_OR_SITE_PACKAGES ) if output_file is None : sys . exit ( NO_OUTFILE ) for disallowed in DISALLOWED_ARGS : for supplied_arg in pip_args : if supplied_arg in disallowed : sys . exit ( DISALLOWED_PIP_ARGS . format ( arg = supplied_arg , reason = DISALLOWED_ARGS [ disallowed ] ) ) with TemporaryDirectory ( ) as working_path : tmp_site_packages = Path ( working_path , "site-packages" ) if site_packages : shutil . copytree ( site_packages , tmp_site_packages ) if pip_args : pip . install ( [ "--target" , str ( tmp_site_packages ) ] + list ( pip_args ) ) if entry_point is None and console_script is not None : try : entry_point = find_entry_point ( tmp_site_packages , console_script ) except KeyError : if not Path ( tmp_site_packages , "bin" , console_script ) . exists ( ) : sys . exit ( NO_ENTRY_POINT . format ( entry_point = console_script ) ) env = Environment ( build_id = str ( uuid . uuid4 ( ) ) , entry_point = entry_point , script = console_script , compile_pyc = compile_pyc , extend_pythonpath = extend_pythonpath , ) Path ( working_path , "environment.json" ) . write_text ( env . to_json ( ) ) bootstrap_target = Path ( working_path , "_bootstrap" ) bootstrap_target . mkdir ( parents = True , exist_ok = True ) copy_bootstrap ( bootstrap_target ) builder . create_archive ( Path ( working_path ) , target = Path ( output_file ) . expanduser ( ) , interpreter = python or _interpreter_path ( ) , main = "_bootstrap:bootstrap" , compressed = compressed , )
Shiv is a command line utility for building fully self - contained Python zipapps as outlined in PEP 441 but with all their dependencies included!
52,479
def get_session ( * , env_vars = None , loop = None ) : loop = loop or asyncio . get_event_loop ( ) return AioSession ( session_vars = env_vars , loop = loop )
Return a new session object .
52,480
async def read ( self , amt = None ) : chunk = await self . __wrapped__ . read ( amt if amt is not None else - 1 ) self . _self_amount_read += len ( chunk ) if amt is None or ( not chunk and amt > 0 ) : self . _verify_content_length ( ) return chunk
Read at most amt bytes from the stream .
52,481
async def iter_lines ( self , chunk_size = 1024 ) : pending = b'' async for chunk in self . iter_chunks ( chunk_size ) : lines = ( pending + chunk ) . splitlines ( True ) for line in lines [ : - 1 ] : await yield_ ( line . splitlines ( ) [ 0 ] ) pending = lines [ - 1 ] if pending : await yield_ ( pending . splitlines ( ) [ 0 ] )
Return an iterator to yield lines from the raw stream .
52,482
async def iter_chunks ( self , chunk_size = _DEFAULT_CHUNK_SIZE ) : while True : current_chunk = await self . read ( chunk_size ) if current_chunk == b"" : break await yield_ ( current_chunk )
Return an iterator to yield chunks of chunk_size bytes from the raw stream .
52,483
def get_items ( start_num , num_items ) : result = [ ] for i in range ( start_num , start_num + num_items ) : result . append ( { 'pk' : { 'S' : 'item{0}' . format ( i ) } } ) return result
Generate a sequence of dynamo items
52,484
def create_batch_write_structure ( table_name , start_num , num_items ) : return { table_name : [ { 'PutRequest' : { 'Item' : item } } for item in get_items ( start_num , num_items ) ] }
Create item structure for passing to batch_write_item
52,485
def get_paginator ( self , operation_name ) : if not self . can_paginate ( operation_name ) : raise OperationNotPageableError ( operation_name = operation_name ) else : Paginator . PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self . _PY_TO_OP_NAME [ operation_name ] def paginate ( self , ** kwargs ) : return Paginator . paginate ( self , ** kwargs ) paginator_config = self . _cache [ 'page_config' ] [ actual_operation_name ] paginator_class_name = str ( '%s.Paginator.%s' % ( get_service_module_name ( self . meta . service_model ) , actual_operation_name ) ) documented_paginator_cls = type ( paginator_class_name , ( Paginator , ) , { 'paginate' : paginate } ) operation_model = self . _service_model . operation_model ( actual_operation_name ) paginator = documented_paginator_cls ( getattr ( self , operation_name ) , paginator_config , operation_model ) return paginator
Create a paginator for an operation .
52,486
def get_waiter ( self , waiter_name ) : config = self . _get_waiter_config ( ) if not config : raise ValueError ( "Waiter does not exist: %s" % waiter_name ) model = waiter . WaiterModel ( config ) mapping = { } for name in model . waiter_names : mapping [ xform_name ( name ) ] = name if waiter_name not in mapping : raise ValueError ( "Waiter does not exist: %s" % waiter_name ) return waiter . create_waiter_with_client ( mapping [ waiter_name ] , model , self , loop = self . _loop )
Returns an object that can wait for some condition .
52,487
def url_fix ( s , charset = None ) : if charset : warnings . warn ( "{}.url_fix() charset argument is deprecated" . format ( __name__ ) , DeprecationWarning ) scheme , netloc , path , querystring , fragment = urlsplit ( s ) path = quote ( path , b'/%' ) querystring = quote_plus ( querystring , b':&=' ) return urlunsplit ( ( scheme , netloc , path , querystring , fragment ) )
escapes special characters
52,488
def httprettified ( test = None , allow_net_connect = True ) : def decorate_unittest_TestCase_setUp ( klass ) : use_addCleanup = hasattr ( klass , 'addCleanup' ) original_setUp = ( klass . setUp if hasattr ( klass , 'setUp' ) else None ) def new_setUp ( self ) : httpretty . reset ( ) httpretty . enable ( allow_net_connect ) if use_addCleanup : self . addCleanup ( httpretty . disable ) if original_setUp : original_setUp ( self ) klass . setUp = new_setUp if not use_addCleanup : original_tearDown = ( klass . setUp if hasattr ( klass , 'tearDown' ) else None ) def new_tearDown ( self ) : httpretty . disable ( ) httpretty . reset ( ) if original_tearDown : original_tearDown ( self ) klass . tearDown = new_tearDown return klass def decorate_test_methods ( klass ) : for attr in dir ( klass ) : if not attr . startswith ( 'test_' ) : continue attr_value = getattr ( klass , attr ) if not hasattr ( attr_value , "__call__" ) : continue setattr ( klass , attr , decorate_callable ( attr_value ) ) return klass def is_unittest_TestCase ( klass ) : try : import unittest return issubclass ( klass , unittest . TestCase ) except ImportError : return False "A decorator for tests that use HTTPretty" def decorate_class ( klass ) : if is_unittest_TestCase ( klass ) : return decorate_unittest_TestCase_setUp ( klass ) return decorate_test_methods ( klass ) def decorate_callable ( test ) : @ functools . wraps ( test ) def wrapper ( * args , ** kw ) : with httprettized ( allow_net_connect ) : return test ( * args , ** kw ) return wrapper if isinstance ( test , ClassTypes ) : return decorate_class ( test ) elif callable ( test ) : return decorate_callable ( test ) return decorate_callable
decorator for test functions
52,489
def parse_request_body ( self , body ) : PARSING_FUNCTIONS = { 'application/json' : json . loads , 'text/json' : json . loads , 'application/x-www-form-urlencoded' : self . parse_querystring , } content_type = self . headers . get ( 'content-type' , '' ) do_parse = PARSING_FUNCTIONS . get ( content_type , FALLBACK_FUNCTION ) try : body = decode_utf8 ( body ) return do_parse ( body ) except ( Exception , BaseException ) : return body
Attempt to parse the post based on the content - type passed . Return the regular body if not
52,490
def fill_filekind ( self , fk ) : now = datetime . utcnow ( ) headers = { 'status' : self . status , 'date' : now . strftime ( '%a, %d %b %Y %H:%M:%S GMT' ) , 'server' : 'Python/HTTPretty' , 'connection' : 'close' , } if self . forcing_headers : headers = self . forcing_headers if self . adding_headers : headers . update ( self . normalize_headers ( self . adding_headers ) ) headers = self . normalize_headers ( headers ) status = headers . get ( 'status' , self . status ) if self . body_is_callable : status , headers , self . body = self . callable_body ( self . request , self . info . full_url ( ) , headers ) headers = self . normalize_headers ( headers ) if 'content-length' not in headers : headers . update ( { 'content-length' : len ( self . body ) } ) string_list = [ 'HTTP/1.1 %d %s' % ( status , STATUSES [ status ] ) , ] if 'date' in headers : string_list . append ( 'date: %s' % headers . pop ( 'date' ) ) if not self . forcing_headers : content_type = headers . pop ( 'content-type' , 'text/plain; charset=utf-8' ) content_length = headers . pop ( 'content-length' , self . body_length ) string_list . append ( 'content-type: %s' % content_type ) if not self . streaming : string_list . append ( 'content-length: %s' % content_length ) server = headers . pop ( 'server' , None ) if server : string_list . append ( 'server: %s' % server ) for k , v in headers . items ( ) : string_list . append ( '{}: {}' . format ( k , v ) , ) for item in string_list : fk . write ( utf8 ( item ) + b'\n' ) fk . write ( b'\r\n' ) if self . streaming : self . body , body = itertools . tee ( self . body ) for chunk in body : fk . write ( utf8 ( chunk ) ) else : fk . write ( utf8 ( self . body ) ) fk . seek ( 0 )
writes HTTP Response data to a file descriptor
52,491
def draw_text ( stdscr , text , color = 0 , fallback = None , title = None ) : if fallback is None : fallback = text y , x = stdscr . getmaxyx ( ) if title : title = pad_to_size ( title , x , 1 ) if "\n" in title . rstrip ( "\n" ) : title += "\n" * 5 text = title + "\n" + pad_to_size ( text , x , len ( text . split ( "\n" ) ) ) lines = pad_to_size ( text , x , y ) . rstrip ( "\n" ) . split ( "\n" ) try : for i , line in enumerate ( lines ) : stdscr . insstr ( i , 0 , line , curses . color_pair ( color ) ) except : lines = pad_to_size ( fallback , x , y ) . rstrip ( "\n" ) . split ( "\n" ) try : for i , line in enumerate ( lines [ : ] ) : stdscr . insstr ( i , 0 , line , curses . color_pair ( color ) ) except : pass stdscr . refresh ( )
Draws text in the given color . Duh .
52,492
def format_seconds ( seconds , hide_seconds = False ) : if seconds <= 60 : return str ( seconds ) output = "" for period , period_seconds in ( ( 'y' , 31557600 ) , ( 'd' , 86400 ) , ( 'h' , 3600 ) , ( 'm' , 60 ) , ( 's' , 1 ) , ) : if seconds >= period_seconds and not ( hide_seconds and period == 's' ) : output += str ( int ( seconds / period_seconds ) ) output += period output += " " seconds = seconds % period_seconds return output . strip ( )
Returns a human - readable string representation of the given amount of seconds .
52,493
def graceful_ctrlc ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except KeyboardInterrupt : exit ( 1 ) return wrapper
Makes the decorated function exit with code 1 on CTRL + C .
52,494
def pad_to_size ( text , x , y ) : input_lines = text . rstrip ( ) . split ( "\n" ) longest_input_line = max ( map ( len , input_lines ) ) number_of_input_lines = len ( input_lines ) x = max ( x , longest_input_line ) y = max ( y , number_of_input_lines ) output = "" padding_top = int ( ( y - number_of_input_lines ) / 2 ) padding_bottom = y - number_of_input_lines - padding_top padding_left = int ( ( x - longest_input_line ) / 2 ) output += padding_top * ( " " * x + "\n" ) for line in input_lines : output += padding_left * " " + line + " " * ( x - padding_left - len ( line ) ) + "\n" output += padding_bottom * ( " " * x + "\n" ) return output
Adds whitespace to text to center it within a frame of the given dimensions .
52,495
def parse_timestr ( timestr ) : timedelta_secs = parse_timedelta ( timestr ) sync_start = datetime . now ( ) if timedelta_secs : target = datetime . now ( ) + timedelta ( seconds = timedelta_secs ) elif timestr . isdigit ( ) : target = datetime . now ( ) + timedelta ( seconds = int ( timestr ) ) else : try : target = parse ( timestr ) except : raise ValueError ( "Unable to parse '{}'" . format ( timestr ) ) sync_start = sync_start . replace ( microsecond = 0 ) try : target = target . astimezone ( tz = tz . tzlocal ( ) ) . replace ( tzinfo = None ) except ValueError : pass return ( sync_start , target )
Parse a string describing a point in time .
52,496
def parse_timedelta ( deltastr ) : matches = TIMEDELTA_REGEX . match ( deltastr ) if not matches : return None components = { } for name , value in matches . groupdict ( ) . items ( ) : if value : components [ name ] = int ( value ) for period , hours in ( ( 'days' , 24 ) , ( 'years' , 8766 ) ) : if period in components : components [ 'hours' ] = components . get ( 'hours' , 0 ) + components [ period ] * hours del components [ period ] return int ( timedelta ( ** components ) . total_seconds ( ) )
Parse a string describing a period of time .
52,497
def _verify_signature ( self , message , signature ) : if self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY : actual_checksum = signature [ 4 : 12 ] actual_seq_num = struct . unpack ( "<I" , signature [ 12 : 16 ] ) [ 0 ] else : actual_checksum = signature [ 8 : 12 ] actual_seq_num = struct . unpack ( "<I" , signature [ 12 : 16 ] ) [ 0 ] expected_signature = calc_signature ( message , self . negotiate_flags , self . incoming_signing_key , self . incoming_seq_num , self . incoming_handle ) expected_checksum = expected_signature . checksum expected_seq_num = struct . unpack ( "<I" , expected_signature . seq_num ) [ 0 ] if actual_checksum != expected_checksum : raise Exception ( "The signature checksum does not match, message has been altered" ) if actual_seq_num != expected_seq_num : raise Exception ( "The signature sequence number does not match up, message not received in the correct sequence" ) self . incoming_seq_num += 1
Will verify that the signature received from the server matches up with the expected signature computed locally . Will throw an exception if they do not match
52,498
def regex_opt_inner ( strings , open_paren ) : close_paren = open_paren and ')' or '' if not strings : return '' first = strings [ 0 ] if len ( strings ) == 1 : return open_paren + escape ( first ) + close_paren if not first : return open_paren + regex_opt_inner ( strings [ 1 : ] , '(?:' ) + '?' + close_paren if len ( first ) == 1 : oneletter = [ ] rest = [ ] for s in strings : if len ( s ) == 1 : oneletter . append ( s ) else : rest . append ( s ) if len ( oneletter ) > 1 : if rest : return open_paren + regex_opt_inner ( rest , '' ) + '|' + make_charset ( oneletter ) + close_paren return open_paren + make_charset ( oneletter ) + close_paren prefix = commonprefix ( strings ) if prefix : plen = len ( prefix ) return open_paren + escape ( prefix ) + regex_opt_inner ( [ s [ plen : ] for s in strings ] , '(?:' ) + close_paren strings_rev = [ s [ : : - 1 ] for s in strings ] suffix = commonprefix ( strings_rev ) if suffix : slen = len ( suffix ) return open_paren + regex_opt_inner ( sorted ( s [ : - slen ] for s in strings ) , '(?:' ) + escape ( suffix [ : : - 1 ] ) + close_paren return open_paren + '|' . join ( regex_opt_inner ( list ( group [ 1 ] ) , '' ) for group in groupby ( strings , lambda s : s [ 0 ] == first [ 0 ] ) ) + close_paren
Return a regex that matches any string in the sorted list of strings .
52,499
def regex_opt ( strings , prefix = '' , suffix = '' ) : strings = sorted ( strings ) return prefix + regex_opt_inner ( strings , '(' ) + suffix
Return a compiled regex that matches any string in the given list .