idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
243,200
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 .
79
9
243,201
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 .
84
9
243,202
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 .
62
15
243,203
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 .
58
8
243,204
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 .
84
15
243,205
def get ( self , object_path , interfaces_and_properties = None ) : # check this before creating the DBus object for more # controlled behaviour: 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 .
123
8
243,206
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 .
166
8
243,207
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 .
75
9
243,208
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 .
72
8
243,209
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 .
74
8
243,210
def device_added ( self , device ) : if not self . _mounter . is_handleable ( device ) : return if self . _has_actions ( 'device_added' ) : # wait for partitions etc to be reported to udiskie, otherwise we # can't discover the actions GLib . timeout_add ( 500 , self . _device_added , device ) else : self . _device_added ( device )
Show discovery notification for specified device object .
92
8
243,211
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 .
107
8
243,212
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 .
190
9
243,213
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 : # Catch and log the exception. Starting udiskie with notifications # enabled while not having a notification service installed is a # mistake too easy to be made, but it shoud not render the rest of # udiskie's logic useless by raising an exception before the # automount handler gets invoked. self . _log . error ( _ ( "Failed to show notification: {0}" , exc_message ( exc ) ) ) self . _log . debug ( format_exc ( ) )
Show a notification .
218
4
243,214
def _add_action ( self , notification , action , label , callback , * args ) : on_action_click = run_bg ( lambda * _ : callback ( * args ) ) try : # this is the correct signature for Notify-0.7, the last argument # being 'user_data': notification . add_action ( action , label , on_action_click , None ) except TypeError : # this is the signature for some older version, I don't know what # the last argument is for. notification . add_action ( action , label , on_action_click , None , None ) # gi.Notify does not store hard references to the notification # objects. When a signal is received and the notification does not # exist anymore, no handler will be called. Therefore, we need to # prevent these notifications from being destroyed by storing # references: notification . connect ( 'closed' , self . _notifications . remove ) self . _notifications . append ( notification )
Show an action button button in mount notifications .
210
9
243,215
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 .
51
10
243,216
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 .
38
10
243,217
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 .
39
9
243,218
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 .
85
12
243,219
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 .
101
11
243,220
def from_file ( cls , path = None ) : # None => use default 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 ( { } ) # False/'' => no config 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 .
214
11
243,221
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 .
68
14
243,222
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 .
58
13
243,223
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 .
48
14
243,224
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 , ) ) # append menu item for closing the application 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 .
310
6
243,225
def detect ( self ) : root = self . _actions . detect ( ) prune_empty_node ( root , set ( ) ) return root
Detect all currently known devices . Returns the root device .
31
11
243,226
def _create_menu ( self , items ) : menu = Gtk . Menu ( ) self . _create_menu_items ( menu , items ) return menu
Create a menu from the given node .
34
8
243,227
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 ) # I don't really care for the "show icons only for nouns, not # for verbs" policy: 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 .
172
6
243,228
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 .
73
11
243,229
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 .
116
9
243,230
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 .
67
9
243,231
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 .
38
7
243,232
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 .
88
5
243,233
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 .
62
5
243,234
def create_context_menu ( self , extended ) : menu = Gtk . Menu ( ) self . _menu ( menu , extended ) return menu
Create the context menu .
31
5
243,235
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 .
75
7
243,236
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 .
63
10
243,237
async def get_password_tty ( device , options ) : # TODO: make this a TRUE async 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 .
65
10
243,238
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 .
108
6
243,239
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 : # Why not raise an exception? -I think it is more convenient (for # end users) to have a reasonable default, without enforcing it. 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 .
157
7
243,240
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 .
98
4
243,241
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 .
183
27
243,242
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 .
56
5
243,243
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 .
71
10
243,244
def _subtask_error ( self , idx , error ) : self . set_exception ( error ) self . errbacks . clear ( )
Receive an error from a single subtask .
32
10
243,245
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 .
125
21
243,246
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 .
339
46
243,247
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 .
71
17
243,248
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 .
53
18
243,249
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 .
74
25
243,250
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 .
53
18
243,251
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 .
47
17
243,252
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 .
51
19
243,253
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 .
166
14
243,254
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 .
306
14
243,255
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 .
109
25
243,256
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 .
151
15
243,257
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 .
73
11
243,258
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 .
154
7
243,259
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
73
5
243,260
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 .
111
16
243,261
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 .
119
18
243,262
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 .
56
14
243,263
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
106
3
243,264
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
155
11
243,265
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 .
91
16
243,266
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 .
174
9
243,267
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 .
82
14
243,268
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 .
111
17
243,269
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 .
262
20
243,270
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 .
384
11
243,271
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 .
160
26
243,272
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
92
6
243,273
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 .
53
18
243,274
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
90
13
243,275
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 : # No need to make changes to the repo, we're just retrying. 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 .
499
31
243,276
def publish ( * * kwargs ) : current_version = get_current_version ( ) click . echo ( 'Current version: {0}' . format ( current_version ) ) retry = kwargs . get ( "retry" ) debug ( 'publish: retry=' , retry ) if retry : # The "new" version will actually be the current version, and the # "current" version will be the previous version. new_version = current_version current_version = get_previous_version ( current_version ) else : level_bump = evaluate_version_bump ( current_version , kwargs [ 'force_level' ] ) new_version = get_new_version ( current_version , level_bump ) owner , name = get_repository_owner_and_name ( ) ci_checks . check ( 'master' ) checkout ( 'master' ) if version ( * * kwargs ) : push_new_version ( gh_token = os . environ . get ( 'GH_TOKEN' ) , owner = owner , name = name ) if config . getboolean ( 'semantic_release' , 'upload_to_pypi' ) : upload_to_pypi ( username = os . environ . get ( 'PYPI_USERNAME' ) , password = os . environ . get ( 'PYPI_PASSWORD' ) , # We are retrying, so we don't want errors for files that are already on PyPI. skip_existing = retry , ) if check_token ( ) : click . echo ( 'Updating changelog' ) try : log = generate_changelog ( current_version , new_version ) post_changelog ( owner , name , new_version , markdown_changelog ( new_version , log , header = False ) ) except GitError : click . echo ( click . style ( 'Posting changelog failed.' , 'red' ) , err = True ) else : click . echo ( click . style ( 'Missing token: cannot post changelog' , 'red' ) , err = True ) click . echo ( click . style ( 'New release published' , 'green' ) ) else : click . echo ( 'Version failed, no release will be published.' , err = True )
Runs the version task before pushing to git and uploading to pypi .
515
16
243,277
def flatpages_link_list ( request ) : from django . contrib . flatpages . models import FlatPage link_list = [ ( page . title , page . url ) for page in FlatPage . objects . all ( ) ] return render_to_link_list ( link_list )
Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages .
64
20
243,278
def _interactive_loop ( self , sin : IO [ str ] , sout : IO [ str ] ) -> None : self . _sin = sin self . _sout = sout tasknum = len ( all_tasks ( loop = self . _loop ) ) s = '' if tasknum == 1 else 's' self . _sout . write ( self . intro . format ( tasknum = tasknum , s = s ) ) try : while not self . _closing . is_set ( ) : self . _sout . write ( self . prompt ) self . _sout . flush ( ) try : user_input = sin . readline ( ) . strip ( ) except Exception as e : msg = 'Could not read from user input due to:\n{}\n' log . exception ( msg ) self . _sout . write ( msg . format ( repr ( e ) ) ) self . _sout . flush ( ) else : try : self . _command_dispatch ( user_input ) except Exception as e : msg = 'Unexpected Exception during command execution:\n{}\n' # noqa log . exception ( msg ) self . _sout . write ( msg . format ( repr ( e ) ) ) self . _sout . flush ( ) finally : self . _sin = None # type: ignore self . _sout = None
Main interactive loop of the monitor
295
6
243,279
def do_help ( self , * cmd_names : str ) -> None : def _h ( cmd : str , template : str ) -> None : try : func = getattr ( self , cmd ) except AttributeError : self . _sout . write ( 'No such command: {}\n' . format ( cmd ) ) else : doc = func . __doc__ if func . __doc__ else '' doc_firstline = doc . split ( '\n' , maxsplit = 1 ) [ 0 ] arg_list = ' ' . join ( p for p in inspect . signature ( func ) . parameters ) self . _sout . write ( template . format ( cmd_name = cmd [ len ( self . _cmd_prefix ) : ] , arg_list = arg_list , cmd_arg_sep = ' ' if arg_list else '' , doc = doc , doc_firstline = doc_firstline ) + '\n' ) if not cmd_names : cmds = sorted ( c . method_name for c in self . _filter_cmds ( with_alts = False ) ) self . _sout . write ( 'Available Commands are:\n\n' ) for cmd in cmds : _h ( cmd , self . help_short_template ) else : for cmd in cmd_names : _h ( self . _cmd_prefix + cmd , self . help_template )
Show help for command name
305
5
243,280
def do_ps ( self ) -> None : headers = ( 'Task ID' , 'State' , 'Task' ) table_data = [ headers ] for task in sorted ( all_tasks ( loop = self . _loop ) , key = id ) : taskid = str ( id ( task ) ) if task : t = '\n' . join ( wrap ( str ( task ) , 80 ) ) table_data . append ( ( taskid , task . _state , t ) ) table = AsciiTable ( table_data ) self . _sout . write ( table . table ) self . _sout . write ( '\n' ) self . _sout . flush ( )
Show task table
151
3
243,281
def do_where ( self , taskid : int ) -> None : task = task_by_id ( taskid , self . _loop ) if task : self . _sout . write ( _format_stack ( task ) ) self . _sout . write ( '\n' ) else : self . _sout . write ( 'No task %d\n' % taskid )
Show stack frames for a task
85
6
243,282
def do_signal ( self , signame : str ) -> None : if hasattr ( signal , signame ) : os . kill ( os . getpid ( ) , getattr ( signal , signame ) ) else : self . _sout . write ( 'Unknown signal %s\n' % signame )
Send a Unix signal
68
4
243,283
def do_stacktrace ( self ) -> None : frame = sys . _current_frames ( ) [ self . _event_loop_thread_id ] traceback . print_stack ( frame , file = self . _sout )
Print a stack trace from the event loop thread
50
9
243,284
def do_cancel ( self , taskid : int ) -> None : task = task_by_id ( taskid , self . _loop ) if task : fut = asyncio . run_coroutine_threadsafe ( cancel_task ( task ) , loop = self . _loop ) fut . result ( timeout = 3 ) self . _sout . write ( 'Cancel task %d\n' % taskid ) else : self . _sout . write ( 'No task %d\n' % taskid )
Cancel an indicated task
113
5
243,285
def do_console ( self ) -> None : if not self . _console_enabled : self . _sout . write ( 'Python console disabled for this sessiong\n' ) self . _sout . flush ( ) return h , p = self . _host , self . _console_port log . info ( 'Starting console at %s:%d' , h , p ) fut = init_console_server ( self . _host , self . _console_port , self . _locals , self . _loop ) server = fut . result ( timeout = 3 ) try : console_proxy ( self . _sin , self . _sout , self . _host , self . _console_port ) finally : coro = close_server ( server ) close_fut = asyncio . run_coroutine_threadsafe ( coro , loop = self . _loop ) close_fut . result ( timeout = 15 )
Switch to async Python REPL
201
5
243,286
def alt_names ( names : str ) -> Callable [ ... , Any ] : names_split = names . split ( ) def decorator ( func : Callable [ ... , Any ] ) -> Callable [ ... , Any ] : func . alt_names = names_split # type: ignore return func return decorator
Add alternative names to you custom commands .
68
8
243,287
def set_interactive_policy ( * , locals = None , banner = None , serve = None , prompt_control = None ) : policy = InteractiveEventLoopPolicy ( locals = locals , banner = banner , serve = serve , prompt_control = prompt_control ) asyncio . set_event_loop_policy ( policy )
Use an interactive event loop by default .
69
8
243,288
def run_console ( * , locals = None , banner = None , serve = None , prompt_control = None ) : loop = InteractiveEventLoop ( locals = locals , banner = banner , serve = serve , prompt_control = prompt_control ) asyncio . set_event_loop ( loop ) try : loop . run_forever ( ) except KeyboardInterrupt : pass
Run the interactive event loop .
79
6
243,289
def make_arg ( key , annotation = None ) : arg = ast . arg ( key , annotation ) arg . lineno , arg . col_offset = 0 , 0 return arg
Make an ast function argument .
38
6
243,290
def make_coroutine_from_tree ( tree , filename = "<aexec>" , symbol = "single" , local = { } ) : dct = { } tree . body [ 0 ] . args . args = list ( map ( make_arg , local ) ) exec ( compile ( tree , filename , symbol ) , dct ) return asyncio . coroutine ( dct [ CORO_NAME ] ) ( * * local )
Make a coroutine from a tree structure .
93
9
243,291
def feature_needs ( * feas ) : fmap = { 'stateful_files' : 22 , 'stateful_dirs' : 23 , 'stateful_io' : ( 'stateful_files' , 'stateful_dirs' ) , 'stateful_files_keep_cache' : 23 , 'stateful_files_direct_io' : 23 , 'keep_cache' : ( 'stateful_files_keep_cache' , ) , 'direct_io' : ( 'stateful_files_direct_io' , ) , 'has_opendir' : ( 'stateful_dirs' , ) , 'has_releasedir' : ( 'stateful_dirs' , ) , 'has_fsyncdir' : ( 'stateful_dirs' , ) , 'has_create' : 25 , 'has_access' : 25 , 'has_fgetattr' : 25 , 'has_ftruncate' : 25 , 'has_fsinit' : ( 'has_init' ) , 'has_fsdestroy' : ( 'has_destroy' ) , 'has_lock' : 26 , 'has_utimens' : 26 , 'has_bmap' : 26 , 'has_init' : 23 , 'has_destroy' : 23 , '*' : '!re:^\*$' } if not feas : return fmap def resolve ( args , maxva ) : for fp in args : if isinstance ( fp , int ) : maxva [ 0 ] = max ( maxva [ 0 ] , fp ) continue if isinstance ( fp , list ) or isinstance ( fp , tuple ) : for f in fp : yield f continue ma = isinstance ( fp , str ) and re . compile ( "(!\s*|)re:(.*)" ) . match ( fp ) if isinstance ( fp , type ( re . compile ( '' ) ) ) or ma : neg = False if ma : mag = ma . groups ( ) fp = re . compile ( mag [ 1 ] ) neg = bool ( mag [ 0 ] ) for f in list ( fmap . keys ( ) ) + [ 'has_' + a for a in Fuse . _attrs ] : if neg != bool ( re . search ( fp , f ) ) : yield f continue ma = re . compile ( "has_(.*)" ) . match ( fp ) if ma and ma . groups ( ) [ 0 ] in Fuse . _attrs and not fp in fmap : yield 21 continue yield fmap [ fp ] maxva = [ 0 ] while feas : feas = set ( resolve ( feas , maxva ) ) return maxva [ 0 ]
Get info about the FUSE API version needed for the support of some features .
598
16
243,292
def assemble ( self ) : self . canonify ( ) args = [ sys . argv and sys . argv [ 0 ] or "python" ] if self . mountpoint : args . append ( self . mountpoint ) for m , v in self . modifiers . items ( ) : if v : args . append ( self . fuse_modifiers [ m ] ) opta = [ ] for o , v in self . optdict . items ( ) : opta . append ( o + '=' + v ) opta . extend ( self . optlist ) if opta : args . append ( "-o" + "," . join ( opta ) ) return args
Mangle self into an argument array
141
7
243,293
def parse ( self , * args , * * kw ) : ev = 'errex' in kw and kw . pop ( 'errex' ) if ev and not isinstance ( ev , int ) : raise TypeError ( "error exit value should be an integer" ) try : self . cmdline = self . parser . parse_args ( * args , * * kw ) except OptParseError : if ev : sys . exit ( ev ) raise return self . fuse_args
Parse command line fill fuse_args attribute .
105
10
243,294
def main ( self , args = None ) : if get_compat_0_1 ( ) : args = self . main_0_1_preamble ( ) d = { 'multithreaded' : self . multithreaded and 1 or 0 } d [ 'fuse_args' ] = args or self . fuse_args . assemble ( ) for t in 'file_class' , 'dir_class' : if hasattr ( self , t ) : getattr ( self . methproxy , 'set_' + t ) ( getattr ( self , t ) ) for a in self . _attrs : b = a if get_compat_0_1 ( ) and a in self . compatmap : b = self . compatmap [ a ] if hasattr ( self , b ) : c = '' if get_compat_0_1 ( ) and hasattr ( self , a + '_compat_0_1' ) : c = '_compat_0_1' d [ a ] = ErrnoWrapper ( self . lowwrap ( a + c ) ) try : main ( * * d ) except FuseError : if args or self . fuse_args . mount_expected ( ) : raise
Enter filesystem service loop .
269
5
243,295
def fuseoptref ( cls ) : import os , re pr , pw = os . pipe ( ) pid = os . fork ( ) if pid == 0 : os . dup2 ( pw , 2 ) os . close ( pr ) fh = cls ( ) fh . fuse_args = FuseArgs ( ) fh . fuse_args . setmod ( 'showhelp' ) fh . main ( ) sys . exit ( ) os . close ( pw ) fa = FuseArgs ( ) ore = re . compile ( "-o\s+([\w\[\]]+(?:=\w+)?)" ) fpr = os . fdopen ( pr ) for l in fpr : m = ore . search ( l ) if m : o = m . groups ( ) [ 0 ] oa = [ o ] # try to catch two-in-one options (like "[no]foo") opa = o . split ( "[" ) if len ( opa ) == 2 : o1 , ox = opa oxpa = ox . split ( "]" ) if len ( oxpa ) == 2 : oo , o2 = oxpa oa = [ o1 + o2 , o1 + oo + o2 ] for o in oa : fa . add ( o ) fpr . close ( ) return fa
Find out which options are recognized by the library . Result is a FuseArgs instance with the list of supported options suitable for passing on to the filter method of another FuseArgs instance .
290
38
243,296
def filter ( self , other ) : self . canonify ( ) other . canonify ( ) rej = self . __class__ ( ) rej . optlist = self . optlist . difference ( other . optlist ) self . optlist . difference_update ( rej . optlist ) for x in self . optdict . copy ( ) : if x not in other . optdict : self . optdict . pop ( x ) rej . optdict [ x ] = None return rej
Throw away those options which are not in the other one . Returns a new instance with the rejected options .
106
21
243,297
def add ( self , opt , val = None ) : ov = opt . split ( '=' , 1 ) o = ov [ 0 ] v = len ( ov ) > 1 and ov [ 1 ] or None if ( v ) : if val != None : raise AttributeError ( "ambiguous option value" ) val = v if val == False : return if val in ( None , True ) : self . optlist . add ( o ) else : self . optdict [ o ] = val
Add a suboption .
104
5
243,298
def register_sub ( self , o ) : if o . subopt in self . subopt_map : raise OptionConflictError ( "conflicting suboption handlers for `%s'" % o . subopt , o ) self . subopt_map [ o . subopt ] = o
Register argument a suboption for self .
63
8
243,299
def __parse_content ( tuc_content , content_to_be_parsed ) : initial_parsed_content = { } i = 0 for content_dict in tuc_content : if content_to_be_parsed in content_dict . keys ( ) : contents_raw = content_dict [ content_to_be_parsed ] if content_to_be_parsed == "phrase" : # for 'phrase', 'contents_raw' is a dictionary initial_parsed_content [ i ] = contents_raw [ 'text' ] i += 1 elif content_to_be_parsed == "meanings" : # for 'meanings', 'contents_raw' is a list for meaning_content in contents_raw : initial_parsed_content [ i ] = meaning_content [ 'text' ] i += 1 final_parsed_content = { } # removing duplicates(if any) from the dictionary for key , value in initial_parsed_content . items ( ) : if value not in final_parsed_content . values ( ) : final_parsed_content [ key ] = value # calling __clean_dict formatted_list = Vocabulary . __clean_dict ( final_parsed_content ) return formatted_list
parses the passed tuc_content for - meanings - synonym received by querying the glosbe API
292
24