idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
55,300
def decode_ay ( ay ) : if ay is None : return '' elif isinstance ( ay , str ) : return ay elif isinstance ( ay , bytes ) : return ay . decode ( 'utf-8' ) else : return bytearray ( ay ) . rstrip ( bytearray ( ( 0 , ) ) ) . decode ( 'utf-8' )
Convert binary blob from DBus queries to strings .
55,301
def format_exc ( * exc_info ) : typ , exc , tb = exc_info or sys . exc_info ( ) error = traceback . format_exception ( typ , exc , tb ) return "" . join ( error )
Show exception with traceback .
55,302
def trigger ( self , event , * args ) : for handler in self . _event_handlers [ event ] : handler ( * args )
Trigger event by name .
55,303
def _check ( self , args ) : if sum ( bool ( args [ arg ] ) for arg in self . _mapping ) > 1 : raise DocoptExit ( _ ( 'These options are mutually exclusive: {0}' , ', ' . join ( self . _mapping ) ) )
Exit in case of multiple exclusive arguments .
55,304
def program_options ( self , args ) : options = { } for name , rule in self . option_rules . items ( ) : val = rule ( args ) if val is not None : options [ name ] = val return options
Get program options from docopt parsed options .
55,305
def run ( self ) : self . exit_code = 1 self . mainloop = GLib . MainLoop ( ) try : future = ensure_future ( self . _start_async_tasks ( ) ) future . callbacks . append ( self . set_exit_code ) self . mainloop . run ( ) return self . exit_code except KeyboardInterrupt : return 1
Run the main loop . Returns exit code .
55,306
async def _start_async_tasks ( self ) : try : self . udisks = await udiskie . udisks2 . Daemon . create ( ) results = await self . _init ( ) return 0 if all ( results ) else 1 except Exception : traceback . print_exc ( ) return 1 finally : self . mainloop . quit ( )
Start asynchronous operations .
55,307
def device_changed ( self , old_state , new_state ) : if ( self . _mounter . is_addable ( new_state ) and not self . _mounter . is_addable ( old_state ) and not self . _mounter . is_removable ( old_state ) ) : self . auto_add ( new_state )
Mount newly mountable devices .
55,308
async def connect_service ( bus_name , object_path , interface ) : proxy = await proxy_new_for_bus ( Gio . BusType . SYSTEM , Gio . DBusProxyFlags . DO_NOT_LOAD_PROPERTIES | Gio . DBusProxyFlags . DO_NOT_CONNECT_SIGNALS , info = None , name = bus_name , object_path = object_path , interface_name = interface , ) return InterfaceProxy ( proxy )
Connect to the service object on DBus return InterfaceProxy .
55,309
def object ( self ) : proxy = self . _proxy return ObjectProxy ( proxy . get_connection ( ) , proxy . get_name ( ) , proxy . get_object_path ( ) )
Get an ObjectProxy instanec for the underlying object .
55,310
def connect ( self , interface , event , object_path , handler ) : if object_path : def callback ( connection , sender_name , object_path , interface_name , signal_name , parameters ) : return handler ( * unpack_variant ( parameters ) ) else : def callback ( connection , sender_name , object_path , interface_name , signal_name , parameters ) : return handler ( object_path , * unpack_variant ( parameters ) ) return self . connection . signal_subscribe ( self . bus_name , interface , event , object_path , None , Gio . DBusSignalFlags . NONE , callback , )
Connect to a DBus signal . If object_path is None subscribe for all objects and invoke the callback with the object_path as its first argument .
55,311
def require_Gtk ( min_version = 2 ) : if not _in_X : raise RuntimeError ( 'Not in X session.' ) if _has_Gtk < min_version : raise RuntimeError ( 'Module gi.repository.Gtk not available!' ) if _has_Gtk == 2 : logging . getLogger ( __name__ ) . warn ( _ ( "Missing runtime dependency GTK 3. Falling back to GTK 2 " "for password prompt" ) ) from gi . repository import Gtk if not Gtk . init_check ( None ) [ 0 ] : raise RuntimeError ( _ ( "X server not connected!" ) ) return Gtk
Make sure Gtk is properly initialized .
55,312
def _ ( text , * args , ** kwargs ) : msg = _t . gettext ( text ) if args or kwargs : return msg . format ( * args , ** kwargs ) else : return msg
Translate and then and format the text with str . format .
55,313
def filter_opt ( opt ) : return { k : GLib . Variant ( * v ) for k , v in opt . items ( ) if v [ 1 ] is not None }
Remove None values from a dictionary .
55,314
def eject ( self , auth_no_user_interaction = None ) : return self . _assocdrive . _M . Drive . Eject ( '(a{sv})' , filter_opt ( { 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
Eject media from the device .
55,315
def device_id ( self ) : if self . is_block : for filename in self . _P . Block . Symlinks : parts = decode_ay ( filename ) . split ( '/' ) if parts [ - 2 ] == 'by-id' : return parts [ - 1 ] elif self . is_drive : return self . _assocdrive . _P . Drive . Id return ''
Return a unique and persistent identifier for the device .
55,316
def is_external ( self ) : if self . _P . Block . HintSystem == False : return True if self . is_luks_cleartext and self . luks_cleartext_slave . is_external : return True if self . is_partition and self . partition_slave . is_external : return True return False
Check if the device is external .
55,317
def drive ( self ) : if self . is_drive : return self cleartext = self . luks_cleartext_slave if cleartext : return cleartext . drive if self . is_block : return self . _daemon [ self . _P . Block . Drive ] return None
Get wrapper to the drive containing this device .
55,318
def root ( self ) : drive = self . drive for device in self . _daemon : if device . is_drive : continue if device . is_toplevel and device . drive == drive : return device return None
Get the top level block device in the ancestry of this device .
55,319
def symlinks ( self ) : if not self . _P . Block . Symlinks : return [ ] return [ decode_ay ( path ) for path in self . _P . Block . Symlinks ]
Known symlinks of the block device .
55,320
def mount ( self , fstype = None , options = None , auth_no_user_interaction = None ) : return self . _M . Filesystem . Mount ( '(a{sv})' , filter_opt ( { 'fstype' : ( 's' , fstype ) , 'options' : ( 's' , ',' . join ( options or [ ] ) ) , 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
Mount filesystem .
55,321
def unmount ( self , force = None , auth_no_user_interaction = None ) : return self . _M . Filesystem . Unmount ( '(a{sv})' , filter_opt ( { 'force' : ( 'b' , force ) , 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
Unmount filesystem .
55,322
def luks_cleartext_holder ( self ) : if not self . is_luks : return None for device in self . _daemon : if device . luks_cleartext_slave == self : return device return None
Get wrapper to the unlocked luks cleartext device .
55,323
def unlock ( self , password , auth_no_user_interaction = None ) : return self . _M . Encrypted . Unlock ( '(sa{sv})' , password , filter_opt ( { 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
Unlock Luks device .
55,324
def set_autoclear ( self , value , auth_no_user_interaction = None ) : return self . _M . Loop . SetAutoclear ( '(ba{sv})' , value , filter_opt ( { 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) )
Set autoclear flag for loop partition .
55,325
def is_file ( self , path ) : return ( samefile ( path , self . device_file ) or samefile ( path , self . loop_file ) or any ( samefile ( path , mp ) for mp in self . mount_paths ) or sameuuid ( path , self . id_uuid ) or sameuuid ( path , self . partition_uuid ) )
Comparison by mount and device file path .
55,326
def in_use ( self ) : if self . is_mounted or self . is_unlocked : return True if self . is_partition_table : for device in self . _daemon : if device . partition_slave == self and device . in_use : return True return False
Check whether this device is in use i . e . mounted or unlocked .
55,327
def ui_label ( self ) : return ': ' . join ( filter ( None , [ self . ui_device_presentation , self . ui_id_label or self . ui_id_uuid or self . drive_label ] ) )
UI string identifying the partition if possible .
55,328
def find ( self , path ) : if isinstance ( path , Device ) : return path for device in self : if device . is_file ( path ) : self . _log . debug ( _ ( 'found device owning "{0}": "{1}"' , path , device ) ) return device raise FileNotFoundError ( _ ( 'no device found owning "{0}"' , path ) )
Get a device proxy by device name or any mount path of the device .
55,329
def get ( self , object_path , interfaces_and_properties = None ) : if not interfaces_and_properties : interfaces_and_properties = self . _objects . get ( object_path ) if not interfaces_and_properties : return None property_hub = PropertyHub ( interfaces_and_properties ) method_hub = MethodHub ( self . _proxy . object . bus . get_object ( object_path ) ) return Device ( self , object_path , property_hub , method_hub )
Create a Device instance from object path .
55,330
def device_mounted ( self , device ) : if not self . _mounter . is_handleable ( device ) : return browse_action = ( 'browse' , _ ( 'Browse directory' ) , self . _mounter . browse , device ) terminal_action = ( 'terminal' , _ ( 'Open terminal' ) , self . _mounter . terminal , device ) self . _show_notification ( 'device_mounted' , _ ( 'Device mounted' ) , _ ( '{0.ui_label} mounted on {0.mount_paths[0]}' , device ) , device . icon_name , self . _mounter . _browser and browse_action , self . _mounter . _terminal and terminal_action )
Show mount notification for specified device object .
55,331
def device_unmounted ( self , device ) : if not self . _mounter . is_handleable ( device ) : return self . _show_notification ( 'device_unmounted' , _ ( 'Device unmounted' ) , _ ( '{0.ui_label} unmounted' , device ) , device . icon_name )
Show unmount notification for specified device object .
55,332
def device_locked ( self , device ) : if not self . _mounter . is_handleable ( device ) : return self . _show_notification ( 'device_locked' , _ ( 'Device locked' ) , _ ( '{0.device_presentation} locked' , device ) , device . icon_name )
Show lock notification for specified device object .
55,333
def device_unlocked ( self , device ) : if not self . _mounter . is_handleable ( device ) : return self . _show_notification ( 'device_unlocked' , _ ( 'Device unlocked' ) , _ ( '{0.device_presentation} unlocked' , device ) , device . icon_name )
Show unlock notification for specified device object .
55,334
def device_added ( self , device ) : if not self . _mounter . is_handleable ( device ) : return if self . _has_actions ( 'device_added' ) : GLib . timeout_add ( 500 , self . _device_added , device ) else : self . _device_added ( device )
Show discovery notification for specified device object .
55,335
def device_removed ( self , device ) : if not self . _mounter . is_handleable ( device ) : return device_file = device . device_presentation if ( device . is_drive or device . is_toplevel ) and device_file : self . _show_notification ( 'device_removed' , _ ( 'Device removed' ) , _ ( 'device disappeared on {0.device_presentation}' , device ) , device . icon_name )
Show removal notification for specified device object .
55,336
def job_failed ( self , device , action , message ) : if not self . _mounter . is_handleable ( device ) : return device_file = device . device_presentation or device . object_path if message : text = _ ( 'failed to {0} {1}:\n{2}' , action , device_file , message ) else : text = _ ( 'failed to {0} device {1}.' , action , device_file ) try : retry = getattr ( self . _mounter , action ) except AttributeError : retry_action = None else : retry_action = ( 'retry' , _ ( 'Retry' ) , retry , device ) self . _show_notification ( 'job_failed' , _ ( 'Job failed' ) , text , device . icon_name , retry_action )
Show Job failed notification with Retry button .
55,337
def _show_notification ( self , event , summary , message , icon , * actions ) : notification = self . _notify ( summary , message , icon ) timeout = self . _get_timeout ( event ) if timeout != - 1 : notification . set_timeout ( int ( timeout * 1000 ) ) for action in actions : if action and self . _action_enabled ( event , action [ 0 ] ) : self . _add_action ( notification , * action ) try : notification . show ( ) except GLib . GError as exc : self . _log . error ( _ ( "Failed to show notification: {0}" , exc_message ( exc ) ) ) self . _log . debug ( format_exc ( ) )
Show a notification .
55,338
def _add_action ( self , notification , action , label , callback , * args ) : on_action_click = run_bg ( lambda * _ : callback ( * args ) ) try : notification . add_action ( action , label , on_action_click , None ) except TypeError : notification . add_action ( action , label , on_action_click , None , None ) notification . connect ( 'closed' , self . _notifications . remove ) self . _notifications . append ( notification )
Show an action button button in mount notifications .
55,339
def _action_enabled ( self , event , action ) : event_actions = self . _aconfig . get ( event ) if event_actions is None : return True if event_actions is False : return False return action in event_actions
Check if an action for a notification is enabled .
55,340
def _has_actions ( self , event ) : event_actions = self . _aconfig . get ( event ) return event_actions is None or bool ( event_actions )
Check if a notification type has any enabled actions .
55,341
def match ( self , device ) : return all ( match_value ( getattr ( device , k ) , v ) for k , v in self . _match . items ( ) )
Check if the device object matches this filter .
55,342
def value ( self , kind , device ) : self . _log . debug ( _ ( '{0}(match={1!r}, {2}={3!r}) used for {4}' , self . __class__ . __name__ , self . _match , kind , self . _values [ kind ] , device . object_path ) ) return self . _values [ kind ]
Get the value for the device object associated with this filter .
55,343
def default_pathes ( cls ) : try : from xdg . BaseDirectory import xdg_config_home as config_home except ImportError : config_home = os . path . expanduser ( '~/.config' ) return [ os . path . join ( config_home , 'udiskie' , 'config.yml' ) , os . path . join ( config_home , 'udiskie' , 'config.json' ) ]
Return the default config file pathes as a list .
55,344
def from_file ( cls , path = None ) : if path is None : for path in cls . default_pathes ( ) : try : return cls . from_file ( path ) except IOError as e : logging . getLogger ( __name__ ) . debug ( _ ( "Failed to read config file: {0}" , exc_message ( e ) ) ) except ImportError as e : logging . getLogger ( __name__ ) . warn ( _ ( "Failed to read {0!r}: {1}" , path , exc_message ( e ) ) ) return cls ( { } ) if not path : return cls ( { } ) if os . path . splitext ( path ) [ 1 ] . lower ( ) == '.json' : from json import load else : from yaml import safe_load as load with open ( path ) as f : return cls ( load ( f ) )
Read YAML config file . Returns Config object .
55,345
def get_icon_name ( self , icon_id : str ) -> str : icon_theme = Gtk . IconTheme . get_default ( ) for name in self . _icon_names [ icon_id ] : if icon_theme . has_icon ( name ) : return name return 'not-available'
Lookup the system icon name from udisie - internal id .
55,346
def get_icon ( self , icon_id : str , size : "Gtk.IconSize" ) -> "Gtk.Image" : return Gtk . Image . new_from_gicon ( self . get_gicon ( icon_id ) , size )
Load Gtk . Image from udiskie - internal id .
55,347
def get_gicon ( self , icon_id : str ) -> "Gio.Icon" : return Gio . ThemedIcon . new_from_names ( self . _icon_names [ icon_id ] )
Lookup Gio . Icon from udiskie - internal id .
55,348
def _insert_options ( self , menu ) : menu . append ( Gtk . SeparatorMenuItem ( ) ) menu . append ( self . _menuitem ( _ ( 'Mount disc image' ) , self . _icons . get_icon ( 'losetup' , Gtk . IconSize . MENU ) , run_bg ( lambda _ : self . _losetup ( ) ) ) ) menu . append ( Gtk . SeparatorMenuItem ( ) ) menu . append ( self . _menuitem ( _ ( "Enable automounting" ) , icon = None , onclick = lambda _ : self . _daemon . automounter . toggle_on ( ) , checked = self . _daemon . automounter . is_on ( ) , ) ) menu . append ( self . _menuitem ( _ ( "Enable notifications" ) , icon = None , onclick = lambda _ : self . _daemon . notify . toggle ( ) , checked = self . _daemon . notify . active , ) ) if self . _quit_action : menu . append ( Gtk . SeparatorMenuItem ( ) ) menu . append ( self . _menuitem ( _ ( 'Quit' ) , self . _icons . get_icon ( 'quit' , Gtk . IconSize . MENU ) , lambda _ : self . _quit_action ( ) ) )
Add configuration options to menu .
55,349
def detect ( self ) : root = self . _actions . detect ( ) prune_empty_node ( root , set ( ) ) return root
Detect all currently known devices . Returns the root device .
55,350
def _create_menu ( self , items ) : menu = Gtk . Menu ( ) self . _create_menu_items ( menu , items ) return menu
Create a menu from the given node .
55,351
def _menuitem ( self , label , icon , onclick , checked = None ) : if checked is not None : item = Gtk . CheckMenuItem ( ) item . set_active ( checked ) elif icon is None : item = Gtk . MenuItem ( ) else : item = Gtk . ImageMenuItem ( ) item . set_image ( icon ) item . set_always_show_image ( True ) if label is not None : item . set_label ( label ) if isinstance ( onclick , Gtk . Menu ) : item . set_submenu ( onclick ) elif onclick is not None : item . connect ( 'activate' , onclick ) return item
Create a generic menu item .
55,352
def _prepare_menu ( self , node , flat = None ) : if flat is None : flat = self . flat ItemGroup = MenuSection if flat else SubMenu return [ ItemGroup ( branch . label , self . _collapse_device ( branch , flat ) ) for branch in node . branches if branch . methods or branch . branches ]
Prepare the menu hierarchy from the given device tree .
55,353
def _collapse_device ( self , node , flat ) : items = [ item for branch in node . branches for item in self . _collapse_device ( branch , flat ) if item ] show_all = not flat or self . _quickmenu_actions == 'all' methods = node . methods if show_all else [ method for method in node . methods if method . method in self . _quickmenu_actions ] if flat : items . extend ( methods ) else : items . append ( MenuSection ( None , methods ) ) return items
Collapse device hierarchy into a flat folder .
55,354
def _create_statusicon ( self ) : statusicon = Gtk . StatusIcon ( ) statusicon . set_from_gicon ( self . _icons . get_gicon ( 'media' ) ) statusicon . set_tooltip_text ( _ ( "udiskie" ) ) return statusicon
Return a new Gtk . StatusIcon .
55,355
def show ( self , show = True ) : if show and not self . visible : self . _show ( ) if not show and self . visible : self . _hide ( )
Show or hide the tray icon .
55,356
def _show ( self ) : if not self . _icon : self . _icon = self . _create_statusicon ( ) widget = self . _icon widget . set_visible ( True ) self . _conn_left = widget . connect ( "activate" , self . _activate ) self . _conn_right = widget . connect ( "popup-menu" , self . _popup_menu )
Show the tray icon .
55,357
def _hide ( self ) : self . _icon . set_visible ( False ) self . _icon . disconnect ( self . _conn_left ) self . _icon . disconnect ( self . _conn_right ) self . _conn_left = None self . _conn_right = None
Hide the tray icon .
55,358
def create_context_menu ( self , extended ) : menu = Gtk . Menu ( ) self . _menu ( menu , extended ) return menu
Create the context menu .
55,359
async def password_dialog ( key , title , message , options ) : with PasswordDialog . create ( key , title , message , options ) as dialog : response = await dialog if response == Gtk . ResponseType . OK : return PasswordResult ( dialog . get_text ( ) , dialog . use_cache . get_active ( ) ) return None
Show a Gtk password dialog .
55,360
def get_password_gui ( device , options ) : text = _ ( 'Enter password for {0.device_presentation}: ' , device ) try : return password_dialog ( device . id_uuid , 'udiskie' , text , options ) except RuntimeError : return None
Get the password to unlock a device from GUI .
55,361
async def get_password_tty ( device , options ) : text = _ ( 'Enter password for {0.device_presentation}: ' , device ) try : return getpass . getpass ( text ) except EOFError : print ( "" ) return None
Get the password to unlock a device from terminal .
55,362
def password ( password_command ) : gui = lambda : has_Gtk ( ) and get_password_gui tty = lambda : sys . stdin . isatty ( ) and get_password_tty if password_command == 'builtin:gui' : return gui ( ) or tty ( ) elif password_command == 'builtin:tty' : return tty ( ) or gui ( ) elif password_command : return DeviceCommand ( password_command ) . password else : return None
Create a password prompt function .
55,363
def browser ( browser_name = 'xdg-open' ) : if not browser_name : return None argv = shlex . split ( browser_name ) executable = find_executable ( argv [ 0 ] ) if executable is None : logging . getLogger ( __name__ ) . warn ( _ ( "Can't find file browser: {0!r}. " "You may want to change the value for the '-f' option." , browser_name ) ) return None def browse ( path ) : return subprocess . Popen ( argv + [ path ] ) return browse
Create a browse - directory function .
55,364
def notify_command ( command_format , mounter ) : udisks = mounter . udisks for event in [ 'device_mounted' , 'device_unmounted' , 'device_locked' , 'device_unlocked' , 'device_added' , 'device_removed' , 'job_failed' ] : udisks . connect ( event , run_bg ( DeviceCommand ( command_format , event = event ) ) )
Command notification tool .
55,365
async def exec_subprocess ( argv ) : future = Future ( ) process = Gio . Subprocess . new ( argv , Gio . SubprocessFlags . STDOUT_PIPE | Gio . SubprocessFlags . STDIN_INHERIT ) stdin_buf = None cancellable = None process . communicate_utf8_async ( stdin_buf , cancellable , gio_callback , future ) result = await future success , stdout , stderr = process . communicate_utf8_finish ( result ) if not success : raise RuntimeError ( "Subprocess did not exit normally!" ) exit_code = process . get_exit_status ( ) if exit_code != 0 : raise CalledProcessError ( "Subprocess returned a non-zero exit-status!" , exit_code , stdout ) return stdout
An Future task that represents a subprocess . If successful the task s result is set to the collected STDOUT of the subprocess .
55,366
def set_exception ( self , exception ) : was_handled = self . _finish ( self . errbacks , exception ) if not was_handled : traceback . print_exception ( type ( exception ) , exception , exception . __traceback__ )
Signal unsuccessful completion .
55,367
def _subtask_result ( self , idx , value ) : self . _results [ idx ] = value if len ( self . _results ) == self . _num_tasks : self . set_result ( [ self . _results [ i ] for i in range ( self . _num_tasks ) ] )
Receive a result from a single subtask .
55,368
def _subtask_error ( self , idx , error ) : self . set_exception ( error ) self . errbacks . clear ( )
Receive an error from a single subtask .
55,369
def _resume ( self , func , * args ) : try : value = func ( * args ) except StopIteration : self . _generator . close ( ) self . set_result ( None ) except Exception as e : self . _generator . close ( ) self . set_exception ( e ) else : assert isinstance ( value , Future ) value . callbacks . append ( partial ( self . _resume , self . _generator . send ) ) value . errbacks . append ( partial ( self . _resume , self . _generator . throw ) )
Resume the coroutine by throwing a value or returning a value from the await and handle further awaits .
55,370
def parse_commit_message ( message : str ) -> Tuple [ int , str , Optional [ str ] , Tuple [ str , str , str ] ] : parsed = re_parser . match ( message ) if not parsed : raise UnknownCommitMessageStyleError ( 'Unable to parse the given commit message: {0}' . format ( message ) ) subject = parsed . group ( 'subject' ) if config . get ( 'semantic_release' , 'minor_tag' ) in message : level = 'feature' level_bump = 2 if subject : subject = subject . replace ( config . get ( 'semantic_release' , 'minor_tag' . format ( level ) ) , '' ) elif config . get ( 'semantic_release' , 'fix_tag' ) in message : level = 'fix' level_bump = 1 if subject : subject = subject . replace ( config . get ( 'semantic_release' , 'fix_tag' . format ( level ) ) , '' ) else : raise UnknownCommitMessageStyleError ( 'Unable to parse the given commit message: {0}' . format ( message ) ) if parsed . group ( 'text' ) and 'BREAKING CHANGE' in parsed . group ( 'text' ) : level = 'breaking' level_bump = 3 body , footer = parse_text_block ( parsed . group ( 'text' ) ) return level_bump , level , None , ( subject . strip ( ) , body . strip ( ) , footer . strip ( ) )
Parses a commit message according to the 1 . 0 version of python - semantic - release . It expects a tag of some sort in the commit message and will use the rest of the first line as changelog content .
55,371
def checker ( func : Callable ) -> Callable : def func_wrapper ( * args , ** kwargs ) : try : func ( * args , ** kwargs ) return True except AssertionError : raise CiVerificationError ( 'The verification check for the environment did not pass.' ) return func_wrapper
A decorator that will convert AssertionErrors into CiVerificationError .
55,372
def travis ( branch : str ) : assert os . environ . get ( 'TRAVIS_BRANCH' ) == branch assert os . environ . get ( 'TRAVIS_PULL_REQUEST' ) == 'false'
Performs necessary checks to ensure that the travis build is one that should create releases .
55,373
def semaphore ( branch : str ) : assert os . environ . get ( 'BRANCH_NAME' ) == branch assert os . environ . get ( 'PULL_REQUEST_NUMBER' ) is None assert os . environ . get ( 'SEMAPHORE_THREAD_RESULT' ) != 'failed'
Performs necessary checks to ensure that the semaphore build is successful on the correct branch and not a pull - request .
55,374
def frigg ( branch : str ) : assert os . environ . get ( 'FRIGG_BUILD_BRANCH' ) == branch assert not os . environ . get ( 'FRIGG_PULL_REQUEST' )
Performs necessary checks to ensure that the frigg build is one that should create releases .
55,375
def circle ( branch : str ) : assert os . environ . get ( 'CIRCLE_BRANCH' ) == branch assert not os . environ . get ( 'CI_PULL_REQUEST' )
Performs necessary checks to ensure that the circle build is one that should create releases .
55,376
def bitbucket ( branch : str ) : assert os . environ . get ( 'BITBUCKET_BRANCH' ) == branch assert not os . environ . get ( 'BITBUCKET_PR_ID' )
Performs necessary checks to ensure that the bitbucket build is one that should create releases .
55,377
def check ( branch : str = 'master' ) : if os . environ . get ( 'TRAVIS' ) == 'true' : travis ( branch ) elif os . environ . get ( 'SEMAPHORE' ) == 'true' : semaphore ( branch ) elif os . environ . get ( 'FRIGG' ) == 'true' : frigg ( branch ) elif os . environ . get ( 'CIRCLECI' ) == 'true' : circle ( branch ) elif os . environ . get ( 'GITLAB_CI' ) == 'true' : gitlab ( branch ) elif 'BITBUCKET_BUILD_NUMBER' in os . environ : bitbucket ( branch )
Detects the current CI environment if any and performs necessary environment checks .
55,378
def parse_commit_message ( message : str ) -> Tuple [ int , str , str , Tuple [ str , str , str ] ] : parsed = re_parser . match ( message ) if not parsed : raise UnknownCommitMessageStyleError ( 'Unable to parse the given commit message: {}' . format ( message ) ) level_bump = 0 if parsed . group ( 'text' ) and 'BREAKING CHANGE' in parsed . group ( 'text' ) : level_bump = 3 if parsed . group ( 'type' ) == 'feat' : level_bump = max ( [ level_bump , 2 ] ) if parsed . group ( 'type' ) == 'fix' : level_bump = max ( [ level_bump , 1 ] ) body , footer = parse_text_block ( parsed . group ( 'text' ) ) if debug . enabled : debug ( 'parse_commit_message -> ({}, {}, {}, {})' . format ( level_bump , TYPES [ parsed . group ( 'type' ) ] , parsed . group ( 'scope' ) , ( parsed . group ( 'subject' ) , body , footer ) ) ) return ( level_bump , TYPES [ parsed . group ( 'type' ) ] , parsed . group ( 'scope' ) , ( parsed . group ( 'subject' ) , body , footer ) )
Parses a commit message according to the angular commit guidelines specification .
55,379
def parse_text_block ( text : str ) -> Tuple [ str , str ] : body , footer = '' , '' if text : body = text . split ( '\n\n' ) [ 0 ] if len ( text . split ( '\n\n' ) ) == 2 : footer = text . split ( '\n\n' ) [ 1 ] return body . replace ( '\n' , ' ' ) , footer . replace ( '\n' , ' ' )
This will take a text block and return a tuple with body and footer where footer is defined as the last paragraph .
55,380
def upload_to_pypi ( dists : str = 'sdist bdist_wheel' , username : str = None , password : str = None , skip_existing : bool = False ) : if username is None or password is None or username == "" or password == "" : raise ImproperConfigurationError ( 'Missing credentials for uploading' ) run ( 'rm -rf build dist' ) run ( 'python setup.py {}' . format ( dists ) ) run ( 'twine upload -u {} -p {} {} {}' . format ( username , password , '--skip-existing' if skip_existing else '' , 'dist/*' ) ) run ( 'rm -rf build dist' )
Creates the wheel and uploads to pypi with twine .
55,381
def get_commit_log ( from_rev = None ) : check_repo ( ) rev = None if from_rev : rev = '...{from_rev}' . format ( from_rev = from_rev ) for commit in repo . iter_commits ( rev ) : yield ( commit . hexsha , commit . message )
Yields all commit messages from last to first .
55,382
def get_last_version ( skip_tags = None ) -> Optional [ str ] : debug ( 'get_last_version skip_tags=' , skip_tags ) check_repo ( ) skip_tags = skip_tags or [ ] def version_finder ( tag ) : if isinstance ( tag . commit , TagObject ) : return tag . tag . tagged_date return tag . commit . committed_date for i in sorted ( repo . tags , reverse = True , key = version_finder ) : if re . match ( r'v\d+\.\d+\.\d+' , i . name ) : if i . name in skip_tags : continue return i . name [ 1 : ] return None
Return last version from repo tags .
55,383
def get_version_from_tag ( tag_name : str ) -> Optional [ str ] : debug ( 'get_version_from_tag({})' . format ( tag_name ) ) check_repo ( ) for i in repo . tags : if i . name == tag_name : return i . commit . hexsha return None
Get git hash from tag
55,384
def get_repository_owner_and_name ( ) -> Tuple [ str , str ] : check_repo ( ) url = repo . remote ( 'origin' ) . url parts = re . search ( r'([^/:]+)/([^/]+).git$' , url ) if not parts : raise HvcsRepoParseError debug ( 'get_repository_owner_and_name' , parts ) return parts . group ( 1 ) , parts . group ( 2 )
Checks the origin remote to get the owner and name of the remote repository .
55,385
def commit_new_version ( version : str ) : check_repo ( ) commit_message = config . get ( 'semantic_release' , 'commit_message' ) message = '{0}\n\n{1}' . format ( version , commit_message ) repo . git . add ( config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) [ 0 ] ) return repo . git . commit ( m = message , author = "semantic-release <semantic-release>" )
Commits the file containing the version number variable with the version number as the commit message .
55,386
def tag_new_version ( version : str ) : check_repo ( ) return repo . git . tag ( '-a' , 'v{0}' . format ( version ) , m = 'v{0}' . format ( version ) )
Creates a new tag with the version number prefixed with v .
55,387
def current_commit_parser ( ) -> Callable : try : parts = config . get ( 'semantic_release' , 'commit_parser' ) . split ( '.' ) module = '.' . join ( parts [ : - 1 ] ) return getattr ( importlib . import_module ( module ) , parts [ - 1 ] ) except ( ImportError , AttributeError ) as error : raise ImproperConfigurationError ( 'Unable to import parser "{}"' . format ( error ) )
Current commit parser
55,388
def get_current_version_by_config_file ( ) -> str : debug ( 'get_current_version_by_config_file' ) filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) variable = variable . strip ( ) debug ( filename , variable ) with open ( filename , 'r' ) as fd : parts = re . search ( r'^{0}\s*=\s*[\'"]([^\'"]*)[\'"]' . format ( variable ) , fd . read ( ) , re . MULTILINE ) if not parts : raise ImproperConfigurationError debug ( parts ) return parts . group ( 1 )
Get current version from the version variable defined in the configuration
55,389
def get_new_version ( current_version : str , level_bump : str ) -> str : debug ( 'get_new_version("{}", "{}")' . format ( current_version , level_bump ) ) if not level_bump : return current_version return getattr ( semver , 'bump_{0}' . format ( level_bump ) ) ( current_version )
Calculates the next version based on the given bump level with semver .
55,390
def get_previous_version ( version : str ) -> Optional [ str ] : debug ( 'get_previous_version' ) found_version = False for commit_hash , commit_message in get_commit_log ( ) : debug ( 'checking commit {}' . format ( commit_hash ) ) if version in commit_message : found_version = True debug ( 'found_version in "{}"' . format ( commit_message ) ) continue if found_version : matches = re . match ( r'v?(\d+.\d+.\d+)' , commit_message ) if matches : debug ( 'version matches' , commit_message ) return matches . group ( 1 ) . strip ( ) return get_last_version ( [ version , 'v{}' . format ( version ) ] )
Returns the version prior to the given version .
55,391
def replace_version_string ( content , variable , new_version ) : return re . sub ( r'({0} ?= ?["\'])\d+\.\d+(?:\.\d+)?(["\'])' . format ( variable ) , r'\g<1>{0}\g<2>' . format ( new_version ) , content )
Given the content of a file finds the version string and updates it .
55,392
def set_new_version ( new_version : str ) -> bool : filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' ) variable = variable . strip ( ) with open ( filename , mode = 'r' ) as fr : content = fr . read ( ) content = replace_version_string ( content , variable , new_version ) with open ( filename , mode = 'w' ) as fw : fw . write ( content ) return True
Replaces the version number in the correct place and writes the changed file to disk .
55,393
def evaluate_version_bump ( current_version : str , force : str = None ) -> Optional [ str ] : debug ( 'evaluate_version_bump("{}", "{}")' . format ( current_version , force ) ) if force : return force bump = None changes = [ ] commit_count = 0 for _hash , commit_message in get_commit_log ( 'v{0}' . format ( current_version ) ) : if ( current_version in commit_message and config . get ( 'semantic_release' , 'version_source' ) == 'commit' ) : debug ( 'found {} in "{}. breaking loop' . format ( current_version , commit_message ) ) break try : message = current_commit_parser ( ) ( commit_message ) changes . append ( message [ 0 ] ) except UnknownCommitMessageStyleError as err : debug ( 'ignored' , err ) pass commit_count += 1 if changes : level = max ( changes ) if level in LEVELS : bump = LEVELS [ level ] if config . getboolean ( 'semantic_release' , 'patch_without_tag' ) and commit_count : bump = 'patch' return bump
Reads git log since last release to find out if should be a major minor or patch release .
55,394
def generate_changelog ( from_version : str , to_version : str = None ) -> dict : debug ( 'generate_changelog("{}", "{}")' . format ( from_version , to_version ) ) changes : dict = { 'feature' : [ ] , 'fix' : [ ] , 'documentation' : [ ] , 'refactor' : [ ] , 'breaking' : [ ] } found_the_release = to_version is None rev = None if from_version : rev = 'v{0}' . format ( from_version ) for _hash , commit_message in get_commit_log ( rev ) : if not found_the_release : if to_version and to_version not in commit_message : continue else : found_the_release = True if from_version is not None and from_version in commit_message : break try : message = current_commit_parser ( ) ( commit_message ) if message [ 1 ] not in changes : continue changes [ message [ 1 ] ] . append ( ( _hash , message [ 3 ] [ 0 ] ) ) if message [ 3 ] [ 1 ] and 'BREAKING CHANGE' in message [ 3 ] [ 1 ] : parts = re_breaking . match ( message [ 3 ] [ 1 ] ) if parts : changes [ 'breaking' ] . append ( parts . group ( 1 ) ) if message [ 3 ] [ 2 ] and 'BREAKING CHANGE' in message [ 3 ] [ 2 ] : parts = re_breaking . match ( message [ 3 ] [ 2 ] ) if parts : changes [ 'breaking' ] . append ( parts . group ( 1 ) ) except UnknownCommitMessageStyleError as err : debug ( 'Ignoring' , err ) pass return changes
Generates a changelog for the given version .
55,395
def markdown_changelog ( version : str , changelog : dict , header : bool = False ) -> str : debug ( 'markdown_changelog(version="{}", header={}, changelog=...)' . format ( version , header ) ) output = '' if header : output += '## v{0}\n' . format ( version ) for section in CHANGELOG_SECTIONS : if not changelog [ section ] : continue output += '\n### {0}\n' . format ( section . capitalize ( ) ) for item in changelog [ section ] : output += '* {0} ({1})\n' . format ( item [ 1 ] , item [ 0 ] ) return output
Generates a markdown version of the changelog . Takes a parsed changelog dict from generate_changelog .
55,396
def get_hvcs ( ) -> Base : hvcs = config . get ( 'semantic_release' , 'hvcs' ) debug ( 'get_hvcs: hvcs=' , hvcs ) try : return globals ( ) [ hvcs . capitalize ( ) ] except KeyError : raise ImproperConfigurationError ( '"{0}" is not a valid option for hvcs.' )
Get HVCS helper class
55,397
def check_build_status ( owner : str , repository : str , ref : str ) -> bool : debug ( 'check_build_status' ) return get_hvcs ( ) . check_build_status ( owner , repository , ref )
Checks the build status of a commit on the api from your hosted version control provider .
55,398
def post_changelog ( owner : str , repository : str , version : str , changelog : str ) -> Tuple [ bool , dict ] : debug ( 'post_changelog(owner={}, repository={}, version={})' . format ( owner , repository , version ) ) return get_hvcs ( ) . post_release_changelog ( owner , repository , version , changelog )
Posts the changelog to the current hvcs release API
55,399
def version ( ** kwargs ) : retry = kwargs . get ( "retry" ) if retry : click . echo ( 'Retrying publication of the same version...' ) else : click . echo ( 'Creating new version..' ) try : current_version = get_current_version ( ) except GitError as e : click . echo ( click . style ( str ( e ) , 'red' ) , err = True ) return False click . echo ( 'Current version: {0}' . format ( current_version ) ) level_bump = evaluate_version_bump ( current_version , kwargs [ 'force_level' ] ) new_version = get_new_version ( current_version , level_bump ) if new_version == current_version and not retry : click . echo ( click . style ( 'No release will be made.' , fg = 'yellow' ) ) return False if kwargs [ 'noop' ] is True : click . echo ( '{0} Should have bumped from {1} to {2}.' . format ( click . style ( 'No operation mode.' , fg = 'yellow' ) , current_version , new_version ) ) return False if config . getboolean ( 'semantic_release' , 'check_build_status' ) : click . echo ( 'Checking build status..' ) owner , name = get_repository_owner_and_name ( ) if not check_build_status ( owner , name , get_current_head_hash ( ) ) : click . echo ( click . style ( 'The build has failed' , 'red' ) ) return False click . echo ( click . style ( 'The build was a success, continuing the release' , 'green' ) ) if retry : return True if config . get ( 'semantic_release' , 'version_source' ) == 'commit' : set_new_version ( new_version ) commit_new_version ( new_version ) tag_new_version ( new_version ) click . echo ( 'Bumping with a {0} version to {1}.' . format ( level_bump , new_version ) ) return True
Detects the new version according to git log and semver . Writes the new version number and commits it unless the noop - option is True .