idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
28,100
def _build_callback ( self , config ) : wrapped = config [ 'callback' ] plugins = self . plugins + config [ 'apply' ] skip = config [ 'skip' ] try : for plugin in reversed ( plugins ) : if True in skip : break if plugin in skip or type ( plugin ) in skip : continue if getattr ( plugin , 'name' , True ) in skip : contin...
Apply plugins to a route and return a new callable .
28,101
def hook ( self , name ) : def wrapper ( func ) : self . hooks . add ( name , func ) return func return wrapper
Return a decorator that attaches a callback to a hook .
28,102
def bind ( self , environ ) : self . environ = environ self . path = '/' + environ . get ( 'PATH_INFO' , '/' ) . lstrip ( '/' ) self . method = environ . get ( 'REQUEST_METHOD' , 'GET' ) . upper ( )
Bind a new WSGI environment .
28,103
def _body ( self ) : maxread = max ( 0 , self . content_length ) stream = self . environ [ 'wsgi.input' ] body = BytesIO ( ) if maxread < MEMFILE_MAX else TemporaryFile ( mode = 'w+b' ) while maxread > 0 : part = stream . read ( min ( maxread , MEMFILE_MAX ) ) if not part : break body . write ( part ) maxread -= len ( ...
The HTTP request body as a seekable file - like object .
28,104
def bind ( self ) : self . _COOKIES = None self . status = 200 self . headers = HeaderDict ( ) self . content_type = 'text/html; charset=UTF-8'
Resets the Response object to its factory defaults .
28,105
def delete_cookie ( self , key , ** kwargs ) : kwargs [ 'max_age' ] = - 1 kwargs [ 'expires' ] = 0 self . set_cookie ( key , '' , ** kwargs )
Delete a cookie . Be sure to use the same domain and path parameters as used to create the cookie .
28,106
def add ( self , name , func ) : if name not in self . hooks : raise ValueError ( "Unknown hook name %s" % name ) was_empty = self . _empty ( ) self . hooks [ name ] . append ( func ) if self . app and was_empty and not self . _empty ( ) : self . app . reset ( )
Attach a callback to a hook .
28,107
def global_config ( cls , key , * args ) : if args : cls . settings [ key ] = args [ 0 ] else : return cls . settings [ key ]
This reads or sets the global settings stored in class . settings .
28,108
def service ( self ) : if self . _service is not None : return self . _service if self . _input_definition is None : return None splunkd_uri = self . _input_definition . metadata [ "server_uri" ] session_key = self . _input_definition . metadata [ "session_key" ] splunkd = urlsplit ( splunkd_uri , allow_fragments = Fal...
Returns a Splunk service object for this script invocation .
28,109
def validate_input ( self , validation_definition ) : minimum = float ( validation_definition . parameters [ "min" ] ) maximum = float ( validation_definition . parameters [ "max" ] ) if minimum >= maximum : raise ValueError ( "min must be less than max; found min=%f, max=%f" % minimum , maximum )
In this example we are using external validation to verify that min is less than max . If validate_input does not raise an Exception the input is assumed to be valid . Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid .
28,110
def write_to ( self , stream ) : if self . data is None : raise ValueError ( "Events must have at least the data field set to be written to XML." ) event = ET . Element ( "event" ) if self . stanza is not None : event . set ( "stanza" , self . stanza ) event . set ( "unbroken" , str ( int ( self . unbroken ) ) ) if sel...
Write an XML representation of self an Event object to the given stream .
28,111
def capabilities ( self ) : response = self . get ( PATH_CAPABILITIES ) return _load_atom ( response , MATCH_ENTRY_CONTENT ) . capabilities
Returns the list of system capabilities .
28,112
def modular_input_kinds ( self ) : if self . splunk_version >= ( 5 , ) : return ReadOnlyCollection ( self , PATH_MODULAR_INPUTS , item = ModularInputKind ) else : raise IllegalOperationException ( "Modular inputs are not supported before Splunk version 5." )
Returns the collection of the modular input kinds on this Splunk instance .
28,113
def restart_required ( self ) : response = self . get ( "messages" ) . body . read ( ) messages = data . load ( response ) [ 'feed' ] if 'entry' not in messages : result = False else : if isinstance ( messages [ 'entry' ] , dict ) : titles = [ messages [ 'entry' ] [ 'title' ] ] else : titles = [ x [ 'title' ] for x in ...
Indicates whether splunkd is in a state that requires a restart .
28,114
def splunk_version ( self ) : if self . _splunk_version is None : self . _splunk_version = tuple ( [ int ( p ) for p in self . info [ 'version' ] . split ( '.' ) ] ) return self . _splunk_version
Returns the version of the splunkd instance this object is attached to .
28,115
def get ( self , path_segment = "" , owner = None , app = None , sharing = None , ** query ) : if path_segment . startswith ( '/' ) : path = path_segment else : path = self . service . _abspath ( self . path + path_segment , owner = owner , app = app , sharing = sharing ) return self . service . get ( path , owner = ow...
Performs a GET operation on the path segment relative to this endpoint .
28,116
def _run_action ( self , path_segment , ** kwargs ) : response = self . get ( path_segment , ** kwargs ) data = self . _load_atom_entry ( response ) rec = _parse_atom_entry ( data ) return rec . content
Run a method and return the content Record from the returned XML .
28,117
def _proper_namespace ( self , owner = None , app = None , sharing = None ) : if owner is None and app is None and sharing is None : if self . _state is not None and 'access' in self . _state : return ( self . _state . access . owner , self . _state . access . app , self . _state . access . sharing ) else : return ( se...
Produce a namespace sans wildcards for use in entity requests .
28,118
def refresh ( self , state = None ) : if state is not None : self . _state = state else : self . _state = self . read ( self . get ( ) ) return self
Refreshes the state of this entity .
28,119
def disable ( self ) : self . post ( "disable" ) if self . service . restart_required : self . service . restart ( 120 ) return self
Disables the entity at this endpoint .
28,120
def _entity_path ( self , state ) : raw_path = urllib . parse . unquote ( state . links . alternate ) if 'servicesNS/' in raw_path : return _trailing ( raw_path , 'servicesNS/' , '/' , '/' ) elif 'services/' in raw_path : return _trailing ( raw_path , 'services/' ) else : return raw_path
Calculate the path to an entity to be returned .
28,121
def itemmeta ( self ) : response = self . get ( "_new" ) content = _load_atom ( response , MATCH_ENTRY_CONTENT ) return _parse_atom_metadata ( content )
Returns metadata for members of the collection .
28,122
def iter ( self , offset = 0 , count = None , pagesize = None , ** kwargs ) : assert pagesize is None or pagesize > 0 if count is None : count = self . null_count fetched = 0 while count == self . null_count or fetched < count : response = self . get ( count = pagesize or count , offset = offset , ** kwargs ) items = s...
Iterates over the collection .
28,123
def list ( self , count = None , ** kwargs ) : return list ( self . iter ( count = count , ** kwargs ) )
Retrieves a list of entities in this collection .
28,124
def delete ( self , name , ** params ) : name = UrlEncoded ( name , encode_slash = True ) if 'namespace' in params : namespace = params . pop ( 'namespace' ) params [ 'owner' ] = namespace . owner params [ 'app' ] = namespace . app params [ 'sharing' ] = namespace . sharing try : self . service . delete ( _path ( self ...
Deletes a specified entity from the collection .
28,125
def get ( self , name = "" , owner = None , app = None , sharing = None , ** query ) : name = UrlEncoded ( name , encode_slash = True ) return super ( Collection , self ) . get ( name , owner , app , sharing , ** query )
Performs a GET request to the server on the collection .
28,126
def submit ( self , stanza ) : body = _encode ( ** stanza ) self . service . post ( self . path , body = body ) return self
Adds keys to the current configuration stanza as a dictionary of key - value pairs .
28,127
def delete ( self , name ) : if self . service . splunk_version >= ( 5 , ) : Collection . delete ( self , name ) else : raise IllegalOperationException ( "Deleting indexes via the REST API is " "not supported before Splunk version 5." )
Deletes a given index .
28,128
def attached_socket ( self , * args , ** kwargs ) : try : sock = self . attach ( * args , ** kwargs ) yield sock finally : sock . shutdown ( socket . SHUT_RDWR ) sock . close ( )
Opens a raw socket in a with block to write data to Splunk .
28,129
def clean ( self , timeout = 60 ) : self . refresh ( ) tds = self [ 'maxTotalDataSizeMB' ] ftp = self [ 'frozenTimePeriodInSecs' ] was_disabled_initially = self . disabled try : if ( not was_disabled_initially and self . service . splunk_version < ( 5 , ) ) : self . disable ( ) self . update ( maxTotalDataSizeMB = 1 , ...
Deletes the contents of the index .
28,130
def submit ( self , event , host = None , source = None , sourcetype = None ) : args = { 'index' : self . name } if host is not None : args [ 'host' ] = host if source is not None : args [ 'source' ] = source if sourcetype is not None : args [ 'sourcetype' ] = sourcetype self . service . post ( PATH_RECEIVERS_SIMPLE , ...
Submits a single event to the index using HTTP POST .
28,131
def upload ( self , filename , ** kwargs ) : kwargs [ 'index' ] = self . name path = 'data/inputs/oneshot' self . service . post ( path , name = filename , ** kwargs ) return self
Uploads a file for immediate indexing .
28,132
def update ( self , ** kwargs ) : if self . kind not in [ 'tcp' , 'splunktcp' , 'tcp/raw' , 'tcp/cooked' , 'udp' ] : return super ( Input , self ) . update ( ** kwargs ) else : to_update = kwargs . copy ( ) if 'restrictToHost' in kwargs : raise IllegalOperationException ( "Cannot set restrictToHost on an existing input...
Updates the server with any changes you ve made to the current input along with any additional arguments you specify .
28,133
def create ( self , name , kind , ** kwargs ) : kindpath = self . kindpath ( kind ) self . post ( kindpath , name = name , ** kwargs ) name = UrlEncoded ( name , encode_slash = True ) path = _path ( self . path + kindpath , '%s:%s' % ( kwargs [ 'restrictToHost' ] , name ) if 'restrictToHost' in kwargs else name ) retur...
Creates an input of a specific kind in this collection with any arguments you specify .
28,134
def delete ( self , name , kind = None ) : if kind is None : self . service . delete ( self [ name ] . path ) else : self . service . delete ( self [ name , kind ] . path ) return self
Removes an input from the collection .
28,135
def cancel ( self ) : try : self . post ( "control" , action = "cancel" ) except HTTPError as he : if he . status == 404 : pass else : raise return self
Stops the current search and deletes the results cache .
28,136
def events ( self , ** kwargs ) : kwargs [ 'segmentation' ] = kwargs . get ( 'segmentation' , 'none' ) return self . get ( "events" , ** kwargs ) . body
Returns a streaming handle to this job s events .
28,137
def is_done ( self ) : if not self . is_ready ( ) : return False done = ( self . _state . content [ 'isDone' ] == '1' ) return done
Indicates whether this job finished running .
28,138
def is_ready ( self ) : response = self . get ( ) if response . status == 204 : return False self . _state = self . read ( response ) ready = self . _state . content [ 'dispatchState' ] not in [ 'QUEUED' , 'PARSING' ] return ready
Indicates whether this job is ready for querying .
28,139
def preview ( self , ** query_params ) : query_params [ 'segmentation' ] = query_params . get ( 'segmentation' , 'none' ) return self . get ( "results_preview" , ** query_params ) . body
Returns a streaming handle to this job s preview search results .
28,140
def create ( self , query , ** kwargs ) : if kwargs . get ( "exec_mode" , None ) == "oneshot" : raise TypeError ( "Cannot specify exec_mode=oneshot; use the oneshot method instead." ) response = self . post ( search = query , ** kwargs ) sid = _load_sid ( response ) return Job ( self . service , sid )
Creates a search using a search query and any additional parameters you provide .
28,141
def oneshot ( self , query , ** params ) : if "exec_mode" in params : raise TypeError ( "Cannot specify an exec_mode to oneshot." ) params [ 'segmentation' ] = params . get ( 'segmentation' , 'none' ) return self . post ( search = query , exec_mode = "oneshot" , ** params ) . body
Run a oneshot search and returns a streaming handle to the results .
28,142
def dispatch ( self , ** kwargs ) : response = self . post ( "dispatch" , ** kwargs ) sid = _load_sid ( response ) return Job ( self . service , sid )
Runs the saved search and returns the resulting search job .
28,143
def history ( self ) : response = self . get ( "history" ) entries = _load_atom_entries ( response ) if entries is None : return [ ] jobs = [ ] for entry in entries : job = Job ( self . service , entry . title ) jobs . append ( job ) return jobs
Returns a list of search jobs corresponding to this saved search .
28,144
def update ( self , search = None , ** kwargs ) : if search is None : search = self . content . search Entity . update ( self , search = search , ** kwargs ) return self
Updates the server with any changes you ve made to the current saved search along with any additional arguments you specify .
28,145
def scheduled_times ( self , earliest_time = 'now' , latest_time = '+1h' ) : response = self . get ( "scheduled_times" , earliest_time = earliest_time , latest_time = latest_time ) data = self . _load_atom_entry ( response ) rec = _parse_atom_entry ( data ) times = [ datetime . fromtimestamp ( int ( t ) ) for t in rec ...
Returns the times when this search is scheduled to run .
28,146
def create ( self , name , search , ** kwargs ) : return Collection . create ( self , name , search = search , ** kwargs )
Creates a saved search .
28,147
def role_entities ( self ) : return [ self . service . roles [ name ] for name in self . content . roles ]
Returns a list of roles assigned to this user .
28,148
def grant ( self , * capabilities_to_grant ) : possible_capabilities = self . service . capabilities for capability in capabilities_to_grant : if capability not in possible_capabilities : raise NoSuchCapability ( capability ) new_capabilities = self [ 'capabilities' ] + list ( capabilities_to_grant ) self . post ( capa...
Grants additional capabilities to this role .
28,149
def revoke ( self , * capabilities_to_revoke ) : possible_capabilities = self . service . capabilities for capability in capabilities_to_revoke : if capability not in possible_capabilities : raise NoSuchCapability ( capability ) old_capabilities = self [ 'capabilities' ] new_capabilities = [ ] for c in old_capabilities...
Revokes zero or more capabilities from this role .
28,150
def create ( self , name , ** params ) : if not isinstance ( name , six . string_types ) : raise ValueError ( "Invalid role name: %s" % str ( name ) ) name = name . lower ( ) self . post ( name = name , ** params ) response = self . get ( name ) entry = _load_atom ( response , XNAME_ENTRY ) . entry state = _parse_atom_...
Creates a new role .
28,151
def create ( self , name , indexes = { } , fields = { } , ** kwargs ) : for k , v in six . iteritems ( indexes ) : if isinstance ( v , dict ) : v = json . dumps ( v ) kwargs [ 'index.' + k ] = v for k , v in six . iteritems ( fields ) : kwargs [ 'field.' + k ] = v return self . post ( name = name , ** kwargs )
Creates a KV Store Collection .
28,152
def update_index ( self , name , value ) : kwargs = { } kwargs [ 'index.' + name ] = value if isinstance ( value , basestring ) else json . dumps ( value ) return self . post ( ** kwargs )
Changes the definition of a KV Store index .
28,153
def update_field ( self , name , value ) : kwargs = { } kwargs [ 'field.' + name ] = value return self . post ( ** kwargs )
Changes the definition of a KV Store field .
28,154
def query ( self , ** query ) : return json . loads ( self . _get ( '' , ** query ) . body . read ( ) . decode ( 'utf-8' ) )
Gets the results of query with optional parameters sort limit skip and fields .
28,155
def query_by_id ( self , id ) : return json . loads ( self . _get ( UrlEncoded ( str ( id ) ) ) . body . read ( ) . decode ( 'utf-8' ) )
Returns object with _id = id .
28,156
def insert ( self , data ) : return json . loads ( self . _post ( '' , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) )
Inserts item into this collection . An _id field will be generated if not assigned in the data .
28,157
def update ( self , id , data ) : return json . loads ( self . _post ( UrlEncoded ( str ( id ) ) , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) )
Replaces document with _id = id with data .
28,158
def batch_find ( self , * dbqueries ) : if len ( dbqueries ) < 1 : raise Exception ( 'Must have at least one query.' ) data = json . dumps ( dbqueries ) return json . loads ( self . _post ( 'batch_find' , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) )
Returns array of results from queries dbqueries .
28,159
def batch_save ( self , * documents ) : if len ( documents ) < 1 : raise Exception ( 'Must have at least one document.' ) data = json . dumps ( documents ) return json . loads ( self . _post ( 'batch_save' , headers = KVStoreCollectionData . JSON_HEADER , body = data ) . body . read ( ) . decode ( 'utf-8' ) )
Inserts or updates every document specified in documents .
28,160
def get_python_files ( files ) : python_files = [ ] for file_name in files : if file_name . endswith ( ".py" ) : python_files . append ( file_name ) return python_files
Utility function to get . py files from a list
28,161
def _parse_cookies ( cookie_str , dictionary ) : parsed_cookie = six . moves . http_cookies . SimpleCookie ( cookie_str ) for cookie in parsed_cookie . values ( ) : dictionary [ cookie . key ] = cookie . coded_value
Tries to parse any key - value pairs of cookies in a string then updates the the dictionary with any key - value pairs found .
28,162
def namespace ( sharing = None , owner = None , app = None , ** kwargs ) : if sharing in [ "system" ] : return record ( { 'sharing' : sharing , 'owner' : "nobody" , 'app' : "system" } ) if sharing in [ "global" , "app" ] : return record ( { 'sharing' : sharing , 'owner' : "nobody" , 'app' : app } ) if sharing in [ "use...
This function constructs a Splunk namespace .
28,163
def request ( self , path_segment , method = "GET" , headers = None , body = "" , owner = None , app = None , sharing = None ) : if headers is None : headers = [ ] path = self . authority + self . _abspath ( path_segment , owner = owner , app = app , sharing = sharing ) all_headers = headers + self . additional_headers...
Issues an arbitrary HTTP request to the REST path segment .
28,164
def delete ( self , url , headers = None , ** kwargs ) : if headers is None : headers = [ ] if kwargs : url = url + UrlEncoded ( '?' + _encode ( ** kwargs ) , skip_encode = True ) message = { 'method' : "DELETE" , 'headers' : headers , } return self . request ( url , message )
Sends a DELETE request to a URL .
28,165
def get ( self , url , headers = None , ** kwargs ) : if headers is None : headers = [ ] if kwargs : url = url + UrlEncoded ( '?' + _encode ( ** kwargs ) , skip_encode = True ) return self . request ( url , { 'method' : "GET" , 'headers' : headers } )
Sends a GET request to a URL .
28,166
def peek ( self , size ) : c = self . read ( size ) self . _buffer = self . _buffer + c return c
Nondestructively retrieves a given number of characters .
28,167
def close ( self ) : if self . _connection : self . _connection . close ( ) self . _response . close ( )
Closes this response .
28,168
def readinto ( self , byte_array ) : max_size = len ( byte_array ) data = self . read ( max_size ) bytes_read = len ( data ) byte_array [ : bytes_read ] = data return bytes_read
Read data into a byte array upto the size of the byte array .
28,169
def parse ( stream ) : definition = ValidationDefinition ( ) root = ET . parse ( stream ) . getroot ( ) for node in root : if node . tag == "item" : definition . metadata [ "name" ] = node . get ( "name" ) definition . parameters = parse_xml_data ( node , "" ) else : definition . metadata [ node . tag ] = node . text r...
Creates a ValidationDefinition from a provided stream containing XML .
28,170
def output_results ( results , mvdelim = '\n' , output = sys . stdout ) : fields = set ( ) for result in results : for key in result . keys ( ) : if ( isinstance ( result [ key ] , list ) ) : result [ '__mv_' + key ] = encode_mv ( result [ key ] ) result [ key ] = mvdelim . join ( result [ key ] ) fields . update ( lis...
Given a list of dictionaries each representing a single result and an optional list of fields output those results to stdout for consumption by the Splunk pipeline
28,171
def validate_input ( self , validation_definition ) : owner = validation_definition . parameters [ "owner" ] repo_name = validation_definition . parameters [ "repo_name" ] repo_url = "https://api.github.com/repos/%s/%s" % ( owner , repo_name ) response = urllib2 . urlopen ( repo_url ) . read ( ) jsondata = json . loads...
In this example we are using external validation to verify that the Github repository exists . If validate_input does not raise an Exception the input is assumed to be valid . Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid .
28,172
def read ( self , ifile ) : name , value = None , None for line in ifile : if line == '\n' : break item = line . split ( ':' , 1 ) if len ( item ) == 2 : if name is not None : self [ name ] = value [ : - 1 ] name , value = item [ 0 ] , urllib . parse . unquote ( item [ 1 ] ) elif name is not None : value += urllib . pa...
Reads an input header from an input file .
28,173
def parse ( stream ) : definition = InputDefinition ( ) root = ET . parse ( stream ) . getroot ( ) for node in root : if node . tag == "configuration" : definition . inputs = parse_xml_data ( node , "stanza" ) else : definition . metadata [ node . tag ] = node . text return definition
Parse a stream containing XML into an InputDefinition .
28,174
def configure_logging ( logger_name , filename = None ) : if filename is None : if logger_name is None : probing_paths = [ path . join ( 'local' , 'logging.conf' ) , path . join ( 'default' , 'logging.conf' ) ] else : probing_paths = [ path . join ( 'local' , logger_name + '.logging.conf' ) , path . join ( 'default' , ...
Configure logging and return the named logger and the location of the logging configuration file loaded .
28,175
def git_exec ( self , command , ** kwargs ) : from . cli import verbose_echo command . insert ( 0 , self . git ) if kwargs . pop ( 'no_verbose' , False ) : verbose = False else : verbose = self . verbose verbose_echo ( ' ' . join ( command ) , verbose , self . fake ) if not self . fake : result = self . repo . git . ex...
Execute git commands
28,176
def unstash_index ( self , sync = False , branch = None ) : stash_list = self . git_exec ( [ 'stash' , 'list' ] , no_verbose = True ) if branch is None : branch = self . get_current_branch_name ( ) for stash in stash_list . splitlines ( ) : verb = 'syncing' if sync else 'switching' if ( ( ( 'Legit' in stash ) and ( 'On...
Returns an unstash index if one is available .
28,177
def unstash_it ( self , sync = False ) : if self . stash_index is not None : return self . git_exec ( [ 'stash' , 'pop' , 'stash@{{{0}}}' . format ( self . stash_index ) ] )
Unstashes changes from current branch for branch sync . Requires prior code setting self . stash_index .
28,178
def checkout_branch ( self , branch ) : _ , stdout , stderr = self . git_exec ( [ 'checkout' , branch ] , with_extended_output = True ) return '\n' . join ( [ stderr , stdout ] )
Checks out given branch .
28,179
def unpublish_branch ( self , branch ) : try : return self . git_exec ( [ 'push' , self . remote . name , ':{0}' . format ( branch ) ] ) except GitCommandError : _ , _ , log = self . git_exec ( [ 'fetch' , self . remote . name , '--prune' ] , with_extended_output = True ) abort ( 'Unpublish failed. Fetching.' , log = l...
Unpublishes given branch .
28,180
def undo ( self , hard = False ) : if not self . fake : return self . repo . git . reset ( 'HEAD^' , working_tree = hard ) else : click . echo ( crayons . red ( 'Faked! >>> git reset {}{}' . format ( '--hard ' if hard else '' , 'HEAD^' ) ) ) return 0
Makes last commit not exist
28,181
def get_branches ( self , local = True , remote_branches = True ) : if not self . repo . remotes : remote_branches = False branches = [ ] if remote_branches : try : for b in self . remote . refs : name = '/' . join ( b . name . split ( '/' ) [ 1 : ] ) if name not in legit_settings . forbidden_branches : branches . appe...
Returns a list of local and remote branches .
28,182
def display_available_branches ( self ) : if not self . repo . remotes : remote_branches = False else : remote_branches = True branches = self . get_branches ( local = True , remote_branches = remote_branches ) if not branches : click . echo ( crayons . red ( 'No branches available' ) ) return branch_col = len ( max ( ...
Displays available branches .
28,183
def status_log ( func , message , * args , ** kwargs ) : click . echo ( message ) log = func ( * args , ** kwargs ) if log : out = [ ] for line in log . split ( '\n' ) : if not line . startswith ( '#' ) : out . append ( line ) click . echo ( black ( '\n' . join ( out ) ) )
Emits header message executes a callable and echoes the return strings .
28,184
def verbose_echo ( str , verbose = False , fake = False ) : verbose = fake or verbose if verbose : color = crayons . green prefix = '' if fake : color = crayons . red prefix = 'Faked!' click . echo ( color ( '{} >>> {}' . format ( prefix , str ) ) )
Selectively output str with special formatting if fake is True
28,185
def output_aliases ( aliases ) : for alias in aliases : cmd = '!legit ' + alias click . echo ( columns ( [ colored . yellow ( 'git ' + alias ) , 20 ] , [ cmd , None ] ) )
Display git aliases
28,186
def cli ( ctx , verbose , fake , install , uninstall , config ) : ctx . obj = SCMRepo ( ) ctx . obj . fake = fake ctx . obj . verbose = fake or verbose if install : do_install ( ctx , verbose , fake ) ctx . exit ( ) elif uninstall : do_uninstall ( ctx , verbose , fake ) ctx . exit ( ) elif config : do_edit_settings ( f...
legit command line interface
28,187
def switch ( scm , to_branch , verbose , fake ) : scm . fake = fake scm . verbose = fake or verbose scm . repo_check ( ) if to_branch is None : scm . display_available_branches ( ) raise click . BadArgumentUsage ( 'Please specify a branch to switch to' ) scm . stash_log ( ) status_log ( scm . checkout_branch , 'Switchi...
Switches from one branch to another safely stashing and restoring local changes .
28,188
def sync ( ctx , scm , to_branch , verbose , fake ) : scm . fake = fake scm . verbose = fake or verbose scm . repo_check ( require_remote = True ) if to_branch : branch = scm . fuzzy_match_branch ( to_branch ) if branch : is_external = True original_branch = scm . get_current_branch_name ( ) else : raise click . BadArg...
Stashes unstaged changes Fetches remote data Performs smart pull + merge Pushes local commits up and Unstashes changes .
28,189
def publish ( scm , to_branch , verbose , fake ) : scm . fake = fake scm . verbose = fake or verbose scm . repo_check ( require_remote = True ) branch = scm . fuzzy_match_branch ( to_branch ) if not branch : branch = scm . get_current_branch_name ( ) scm . display_available_branches ( ) if to_branch is None : click . e...
Pushes an unpublished branch to a remote repository .
28,190
def unpublish ( scm , published_branch , verbose , fake ) : scm . fake = fake scm . verbose = fake or verbose scm . repo_check ( require_remote = True ) branch = scm . fuzzy_match_branch ( published_branch ) if not branch : scm . display_available_branches ( ) raise click . BadArgumentUsage ( 'Please specify a branch t...
Removes a published branch from the remote repository .
28,191
def undo ( scm , verbose , fake , hard ) : scm . fake = fake scm . verbose = fake or verbose scm . repo_check ( ) status_log ( scm . undo , 'Last commit removed from history.' , hard )
Removes the last commit from history .
28,192
def do_install ( ctx , verbose , fake ) : click . echo ( 'The following git aliases will be installed:\n' ) aliases = cli . list_commands ( ctx ) output_aliases ( aliases ) if click . confirm ( '\n{}Install aliases above?' . format ( 'FAKE ' if fake else '' ) , default = fake ) : for alias in aliases : cmd = '!legit ' ...
Installs legit git aliases .
28,193
def do_uninstall ( ctx , verbose , fake ) : aliases = cli . list_commands ( ctx ) aliases . extend ( [ 'graft' , 'harvest' , 'sprout' , 'resync' , 'settings' , 'install' , 'uninstall' ] ) for alias in aliases : system_command = 'git config --global --unset-all alias.{0}' . format ( alias ) verbose_echo ( system_command...
Uninstalls legit git aliases including deprecated legit sub - commands .
28,194
def do_edit_settings ( fake ) : path = resources . user . open ( 'config.ini' ) . name click . echo ( 'Legit Settings:\n' ) for ( option , _ , description ) in legit_settings . config_defaults : click . echo ( columns ( [ crayons . yellow ( option ) , 25 ] , [ description , None ] ) ) click . echo ( "" ) if fake : clic...
Opens legit settings in editor .
28,195
def get_command ( self , ctx , cmd_name ) : rv = click . Group . get_command ( self , ctx , cmd_name ) if rv is not None : return rv cmd_name = self . command_aliases . get ( cmd_name , "" ) return click . Group . get_command ( self , ctx , cmd_name )
Override to handle command aliases
28,196
def _get_parser ( ) : import argparse parser = argparse . ArgumentParser ( description = ( "Convert between mesh formats." ) ) parser . add_argument ( "infile" , type = str , help = "mesh file to be read from" ) parser . add_argument ( "--input-format" , "-i" , type = str , choices = input_filetypes , help = "input fil...
Parse input options .
28,197
def _read_header ( f ) : line = f . readline ( ) . decode ( "utf-8" ) str_list = list ( filter ( None , line . split ( ) ) ) fmt_version = str_list [ 0 ] assert str_list [ 1 ] in [ "0" , "1" ] is_ascii = str_list [ 1 ] == "0" data_size = int ( str_list [ 2 ] ) if not is_ascii : one = f . read ( struct . calcsize ( "i" ...
Read the mesh format block
28,198
def write ( filename , mesh , fmt_version , write_binary = True ) : try : writer = _writers [ fmt_version ] except KeyError : try : writer = _writers [ fmt_version . split ( "." ) [ 0 ] ] except KeyError : raise ValueError ( "Need mesh format in {} (got {})" . format ( sorted ( _writers . keys ( ) ) , fmt_version ) ) w...
Writes a Gmsh msh file .
28,199
def write ( filename , mesh , file_format = None , ** kwargs ) : if not file_format : file_format = _filetype_from_filename ( filename ) for key , value in mesh . cells . items ( ) : if key [ : 7 ] == "polygon" : assert value . shape [ 1 ] == int ( key [ 7 : ] ) else : assert value . shape [ 1 ] == num_nodes_per_cell [...
Writes mesh together with data to a file .