idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
37,400 | def has_add_permission ( self , request ) : perm_string = '%s.add_%s' % ( self . model . _meta . app_label , self . model . _meta . object_name . lower ( ) ) return request . user . has_perm ( perm_string ) | Returns True if the requesting user is allowed to add an object False otherwise . |
37,401 | def has_update_permission ( self , request , obj ) : perm_string = '%s.change_%s' % ( self . model . _meta . app_label , self . model . _meta . object_name . lower ( ) ) return request . user . has_perm ( perm_string ) | Returns True if the requesting user is allowed to update the given object False otherwise . |
37,402 | def serialize ( self , obj , fields ) : data = { } remaining_fields = [ ] for field in fields : if callable ( field ) : data [ field . __name__ ] = field ( obj ) elif hasattr ( self , field ) and callable ( getattr ( self , field ) ) : data [ field ] = getattr ( self , field ) ( obj ) elif hasattr ( obj , field ) : attr = getattr ( obj , field ) if isinstance ( attr , Model ) : data [ field ] = attr . pk elif isinstance ( attr , Manager ) : data [ field ] = [ item [ 'pk' ] for item in attr . values ( 'pk' ) ] elif callable ( attr ) : data [ field ] = attr ( ) else : remaining_fields . append ( field ) else : raise AttributeError ( 'Invalid field: %s' % field ) serializer = Serializer ( ) serializer . serialize ( [ obj ] , fields = list ( remaining_fields ) ) data . update ( serializer . getvalue ( ) [ 0 ] [ 'fields' ] ) remaining_fields = set ( remaining_fields ) - set ( data . keys ( ) ) for field in remaining_fields : data [ field ] = getattr ( obj , field ) return data | Serializes a single model instance to a Python dict based on the specified list of fields . |
37,403 | def json_dumps ( self , data , ** options ) : params = { 'sort_keys' : True , 'indent' : 2 } params . update ( options ) if json . __version__ . split ( '.' ) >= [ '2' , '1' , '3' ] : params . update ( { 'use_decimal' : False } ) return json . dumps ( data , cls = DjangoJSONEncoder , ** params ) | Wrapper around json . dumps that uses a special JSON encoder . |
37,404 | def dir ( cls , label , children ) : return FSEntry ( label = label , children = children , type = u"Directory" , use = None ) | Return FSEntry directory object . |
37,405 | def from_fptr ( cls , label , type_ , fptr ) : return FSEntry ( label = label , type = type_ , path = fptr . path , use = fptr . use , file_uuid = fptr . file_uuid , derived_from = fptr . derived_from , checksum = fptr . checksum , checksumtype = fptr . checksumtype , ) | Return FSEntry object . |
37,406 | def file_id ( self ) : if self . type . lower ( ) == "directory" : return None if self . file_uuid is None : raise exceptions . MetsError ( "No FILEID: File %s does not have file_uuid set" % self . path ) if self . is_aip : return os . path . splitext ( os . path . basename ( self . path ) ) [ 0 ] return utils . FILE_ID_PREFIX + self . file_uuid | Returns the fptr |
37,407 | def add_child ( self , child ) : if self . type . lower ( ) != "directory" : raise ValueError ( "Only directory objects can have children" ) if child is self : raise ValueError ( "Cannot be a child of itself!" ) if child not in self . _children : self . _children . append ( child ) child . parent = self return child | Add a child FSEntry to this FSEntry . |
37,408 | def remove_child ( self , child ) : try : self . _children . remove ( child ) except ValueError : pass else : child . parent = None | Remove a child from this FSEntry |
37,409 | def serialize_filesec ( self ) : if ( self . type . lower ( ) not in ( "item" , "archival information package" ) or self . use is None ) : return None el = etree . Element ( utils . lxmlns ( "mets" ) + "file" , ID = self . file_id ( ) ) if self . group_id ( ) : el . attrib [ "GROUPID" ] = self . group_id ( ) if self . admids : el . set ( "ADMID" , " " . join ( self . admids ) ) if self . checksum and self . checksumtype : el . attrib [ "CHECKSUM" ] = self . checksum el . attrib [ "CHECKSUMTYPE" ] = self . checksumtype if self . path : flocat = etree . SubElement ( el , utils . lxmlns ( "mets" ) + "FLocat" ) try : flocat . set ( utils . lxmlns ( "xlink" ) + "href" , utils . urlencode ( self . path ) ) except ValueError : raise exceptions . SerializeError ( 'Value "{}" (for attribute xlink:href) is not a valid' " URL." . format ( self . path ) ) flocat . set ( "LOCTYPE" , "OTHER" ) flocat . set ( "OTHERLOCTYPE" , "SYSTEM" ) for transform_file in self . transform_files : transform_file_el = etree . SubElement ( el , utils . lxmlns ( "mets" ) + "transformFile" ) for key , val in transform_file . items ( ) : attribute = "transform{}" . format ( key ) . upper ( ) transform_file_el . attrib [ attribute ] = str ( val ) return el | Return the file Element for this file appropriate for use in a fileSec . |
37,410 | def is_empty_dir ( self ) : if self . mets_div_type == "Directory" : children = self . _children if children : if all ( child . is_empty_dir for child in children ) : return True else : return False else : return True else : return False | Returns True if this fs item is a directory with no children or a directory with only other empty directories as children . |
37,411 | def serialize_structmap ( self , recurse = True , normative = False ) : if not self . label : return None if self . is_empty_dir and not normative : return None el = etree . Element ( utils . lxmlns ( "mets" ) + "div" , TYPE = self . mets_div_type ) el . attrib [ "LABEL" ] = self . label if ( not normative ) and self . file_id ( ) : etree . SubElement ( el , utils . lxmlns ( "mets" ) + "fptr" , FILEID = self . file_id ( ) ) if self . dmdids : if ( not normative ) or ( normative and self . is_empty_dir ) : el . set ( "DMDID" , " " . join ( self . dmdids ) ) if recurse and self . _children : for child in self . _children : child_el = child . serialize_structmap ( recurse = recurse , normative = normative ) if child_el is not None : el . append ( child_el ) return el | Return the div Element for this file appropriate for use in a structMap . |
37,412 | def check_secret ( self , secret ) : try : return hmac . compare_digest ( secret , self . secret ) except AttributeError : return secret == self . secret | Checks if the secret string used in the authentication attempt matches the known secret string . Some mechanisms will override this method to control how this comparison is made . |
37,413 | def secure ( cls ) : builtin_mechs = cls . _get_builtin_mechanisms ( ) secure_mechs = [ mech for _ , mech in builtin_mechs . items ( ) if not mech . insecure and mech . priority is not None ] return SASLAuth ( secure_mechs ) | Uses only authentication mechanisms that are secure for use in non - encrypted sessions . |
37,414 | def read ( cls , source ) : if hasattr ( source , "read" ) : return cls . fromfile ( source ) if os . path . exists ( source ) : return cls . fromfile ( source ) if isinstance ( source , six . string_types ) : source = source . encode ( "utf8" ) return cls . fromstring ( source ) | Read source into a METSDocument instance . This is an instance constructor . The source may be a path to a METS file a file - like object or a string of XML . |
37,415 | def _collect_all_files ( self , files = None ) : if files is None : files = self . _root_elements collected = set ( ) for entry in files : collected . add ( entry ) collected . update ( self . _collect_all_files ( entry . children ) ) return collected | Collect all FSEntrys into a set including all descendants . |
37,416 | def get_file ( self , ** kwargs ) : for entry in self . all_files ( ) : if all ( value == getattr ( entry , key ) for key , value in kwargs . items ( ) ) : return entry return None | Return the FSEntry that matches parameters . |
37,417 | def append_file ( self , fs_entry ) : if fs_entry in self . _root_elements : return self . _root_elements . append ( fs_entry ) self . _all_files = None | Adds an FSEntry object to this METS document s tree . Any of the represented object s children will also be added to the document . |
37,418 | def remove_entry ( self , fs_entry ) : try : self . _root_elements . remove ( fs_entry ) except ValueError : pass if fs_entry . parent : fs_entry . parent . remove_child ( fs_entry ) self . _all_files = None | Removes an FSEntry object from this METS document . |
37,419 | def _document_root ( self , fully_qualified = True ) : nsmap = { "xsi" : utils . NAMESPACES [ "xsi" ] , "xlink" : utils . NAMESPACES [ "xlink" ] } if fully_qualified : nsmap [ "mets" ] = utils . NAMESPACES [ "mets" ] else : nsmap [ None ] = utils . NAMESPACES [ "mets" ] attrib = { "{}schemaLocation" . format ( utils . lxmlns ( "xsi" ) ) : utils . SCHEMA_LOCATIONS } if self . objid : attrib [ "OBJID" ] = self . objid return etree . Element ( utils . lxmlns ( "mets" ) + "mets" , nsmap = nsmap , attrib = attrib ) | Return the mets Element for the document root . |
37,420 | def _mets_header ( self , now ) : header_tag = etree . QName ( utils . NAMESPACES [ u"mets" ] , u"metsHdr" ) header_attrs = { } if self . createdate is None : header_attrs [ u"CREATEDATE" ] = now else : header_attrs [ u"CREATEDATE" ] = self . createdate header_attrs [ u"LASTMODDATE" ] = now header_element = etree . Element ( header_tag , ** header_attrs ) for agent in self . agents : header_element . append ( agent . serialize ( ) ) for alternate_id in self . alternate_ids : header_element . append ( alternate_id . serialize ( ) ) return header_element | Return the metsHdr Element . |
37,421 | def _collect_mdsec_elements ( files ) : dmdsecs = [ ] amdsecs = [ ] for f in files : for d in f . dmdsecs : dmdsecs . append ( d ) for a in f . amdsecs : amdsecs . append ( a ) dmdsecs . sort ( key = lambda x : x . id_string ) amdsecs . sort ( key = lambda x : x . id_string ) return dmdsecs + amdsecs | Return all dmdSec and amdSec classes associated with the files . |
37,422 | def _structmap ( self ) : structmap = etree . Element ( utils . lxmlns ( "mets" ) + "structMap" , TYPE = "physical" , ID = "structMap_1" , LABEL = "Archivematica default" , ) for item in self . _root_elements : child = item . serialize_structmap ( recurse = True ) if child is not None : structmap . append ( child ) return structmap | Returns structMap element for all files . |
37,423 | def _filesec ( self , files = None ) : if files is None : files = self . all_files ( ) filesec = etree . Element ( utils . lxmlns ( "mets" ) + "fileSec" ) filegrps = { } for file_ in files : if file_ . type . lower ( ) not in ( "item" , AIP_ENTRY_TYPE ) : continue filegrp = filegrps . get ( file_ . use ) if filegrp is None : filegrp = etree . SubElement ( filesec , utils . lxmlns ( "mets" ) + "fileGrp" , USE = file_ . use ) filegrps [ file_ . use ] = filegrp file_el = file_ . serialize_filesec ( ) if file_el is not None : filegrp . append ( file_el ) return filesec | Returns fileSec Element containing all files grouped by use . |
37,424 | def serialize ( self , fully_qualified = True ) : now = datetime . utcnow ( ) . replace ( microsecond = 0 ) . isoformat ( "T" ) files = self . all_files ( ) mdsecs = self . _collect_mdsec_elements ( files ) root = self . _document_root ( fully_qualified = fully_qualified ) root . append ( self . _mets_header ( now = now ) ) for section in mdsecs : root . append ( section . serialize ( now = now ) ) root . append ( self . _filesec ( files ) ) root . append ( self . _structmap ( ) ) root . append ( self . _normative_structmap ( ) ) return root | Returns this document serialized to an xml Element . |
37,425 | def tostring ( self , fully_qualified = True , pretty_print = True , encoding = "UTF-8" ) : root = self . serialize ( fully_qualified = fully_qualified ) kwargs = { "pretty_print" : pretty_print , "encoding" : encoding } if encoding != "unicode" : kwargs [ "xml_declaration" ] = True return etree . tostring ( root , ** kwargs ) | Serialize and return a string of this METS document . |
37,426 | def write ( self , filepath , fully_qualified = True , pretty_print = False , encoding = "UTF-8" ) : root = self . serialize ( fully_qualified = fully_qualified ) tree = root . getroottree ( ) kwargs = { "pretty_print" : pretty_print , "encoding" : encoding } if encoding != "unicode" : kwargs [ "xml_declaration" ] = True tree . write ( filepath , ** kwargs ) | Serialize and write this METS document to filepath . |
37,427 | def _get_el_to_normative ( parent_elem , normative_parent_elem ) : el_to_normative = OrderedDict ( ) if normative_parent_elem is None : for el in parent_elem : el_to_normative [ el ] = None else : for norm_el in normative_parent_elem : matches = [ el for el in parent_elem if el . get ( "TYPE" ) == norm_el . get ( "TYPE" ) and el . get ( "LABEL" ) == norm_el . get ( "LABEL" ) ] if matches : el_to_normative [ matches [ 0 ] ] = norm_el else : el_to_normative [ norm_el ] = None return el_to_normative | Return ordered dict el_to_normative which maps children of parent_elem to their normative counterparts in the children of normative_parent_elem or to None if there is no normative parent . If there is a normative div element with no non - normative counterpart that element is treated as a key with value None . This allows us to create FSEntry instances for empty directory div elements which are only documented in a normative logical structmap . |
37,428 | def fromfile ( cls , path ) : parser = etree . XMLParser ( remove_blank_text = True ) return cls . fromtree ( etree . parse ( path , parser = parser ) ) | Creates a METS by parsing a file . |
37,429 | def fromstring ( cls , string ) : parser = etree . XMLParser ( remove_blank_text = True ) root = etree . fromstring ( string , parser ) tree = root . getroottree ( ) return cls . fromtree ( tree ) | Create a METS by parsing a string . |
37,430 | def fromtree ( cls , tree ) : mets = cls ( ) mets . tree = tree mets . _parse_tree ( tree ) return mets | Create a METS from an ElementTree or Element . |
37,431 | def schematron_validate ( mets_doc , schematron = AM_SCT_PATH ) : if isinstance ( schematron , six . string_types ) : schematron = get_schematron ( schematron ) is_valid = schematron . validate ( mets_doc ) report = schematron . validation_report return is_valid , report | Validate a METS file using a schematron schema . Return a boolean indicating validity and a report as an lxml . ElementTree instance . |
37,432 | def sct_report_string ( report ) : ret = [ ] namespaces = { "svrl" : "http://purl.oclc.org/dsdl/svrl" } for index , failed_assert_el in enumerate ( report . findall ( "svrl:failed-assert" , namespaces = namespaces ) ) : ret . append ( "{}. {}" . format ( index + 1 , failed_assert_el . find ( "svrl:text" , namespaces = namespaces ) . text , ) ) ret . append ( " test: {}" . format ( failed_assert_el . attrib [ "test" ] ) ) ret . append ( " location: {}" . format ( failed_assert_el . attrib [ "location" ] ) ) ret . append ( "\n" ) return "\n" . join ( ret ) | Return a human - readable string representation of the error report returned by lxml s schematron validator . |
37,433 | def xsd_error_log_string ( xsd_error_log ) : ret = [ ] for error in xsd_error_log : ret . append ( "ERROR ON LINE {}: {}" . format ( error . line , error . message . encode ( "utf-8" ) ) ) return "\n" . join ( ret ) | Return a human - readable string representation of the error log returned by lxml s XMLSchema validator . |
37,434 | def get_view_url ( self ) : url = reverse ( "django_popup_view_field:get_popup_view" , args = ( self . view_class_name , ) ) return "{url}?{cd}" . format ( url = url , cd = self . callback_data ) | Return url for ajax to view for render dialog content |
37,435 | def send ( self , data , sample_rate = 1 ) : if self . prefix : data = dict ( ( "." . join ( ( self . prefix , stat ) ) , value ) for stat , value in data . items ( ) ) if sample_rate < 1 : if random . random ( ) > sample_rate : return sampled_data = dict ( ( stat , "%s|@%s" % ( value , sample_rate ) ) for stat , value in data . items ( ) ) else : sampled_data = data try : [ self . udp_sock . sendto ( bytes ( bytearray ( "%s:%s" % ( stat , value ) , "utf-8" ) ) , self . addr ) for stat , value in sampled_data . items ( ) ] except : self . log . exception ( "unexpected error" ) | Squirt the metrics over UDP |
37,436 | def restart ( self , * args , ** kw ) : self . stop ( ) self . start ( * args , ** kw ) | Restart the daemon . |
37,437 | def get_auth_providers ( self , netloc ) : url = "https://%s/info/system?null" % ( netloc ) response = requests . get ( url , verify = self . verify ) if not response . ok or not hasattr ( response , "json" ) : error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' % ( response . status_code , response . reason , response . url , response . text ) raise iControlUnexpectedHTTPError ( error_message , response = response ) respJson = response . json ( ) result = respJson [ 'providers' ] return result | BIG - IQ specific query for auth providers |
37,438 | def get_new_token ( self , netloc ) : login_body = { 'username' : self . username , 'password' : self . password , } if self . auth_provider : if self . auth_provider == 'local' : login_body [ 'loginProviderName' ] = 'local' elif self . auth_provider == 'tmos' : login_body [ 'loginProviderName' ] = 'tmos' elif self . auth_provider not in [ 'none' , 'default' ] : providers = self . get_auth_providers ( netloc ) for provider in providers : if self . auth_provider in provider [ 'link' ] : login_body [ 'loginProviderName' ] = provider [ 'name' ] break elif self . auth_provider == provider [ 'name' ] : login_body [ 'loginProviderName' ] = provider [ 'name' ] break else : if self . login_provider_name == 'tmos' : login_body [ 'loginProviderName' ] = self . login_provider_name login_url = "https://%s/mgmt/shared/authn/login" % ( netloc ) response = requests . post ( login_url , json = login_body , verify = self . verify , auth = HTTPBasicAuth ( self . username , self . password ) ) self . attempts += 1 if not response . ok or not hasattr ( response , "json" ) : error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' % ( response . status_code , response . reason , response . url , response . text ) raise iControlUnexpectedHTTPError ( error_message , response = response ) respJson = response . json ( ) token = self . _get_token_from_response ( respJson ) created_bigip = self . _get_last_update_micros ( token ) try : expiration_bigip = self . _get_expiration_micros ( token , created_bigip ) except ( KeyError , ValueError ) : error_message = '%s Unparseable Response: %s for uri: %s\nText: %r' % ( response . status_code , response . reason , response . url , response . text ) raise iControlUnexpectedHTTPError ( error_message , response = response ) try : self . expiration = self . _get_token_expiration_time ( created_bigip , expiration_bigip ) except iControlUnexpectedHTTPError : error_message = '%s Token already expired: %s for uri: %s\nText: %r' % ( response . status_code , time . ctime ( expiration_bigip ) , response . url , response . text ) raise iControlUnexpectedHTTPError ( error_message , response = response ) | Get a new token from BIG - IP and store it internally . |
37,439 | def decorate_HTTP_verb_method ( method ) : @ functools . wraps ( method ) def wrapper ( self , RIC_base_uri , ** kwargs ) : partition = kwargs . pop ( 'partition' , '' ) sub_path = kwargs . pop ( 'subPath' , '' ) suffix = kwargs . pop ( 'suffix' , '' ) identifier , kwargs = _unique_resource_identifier_from_kwargs ( ** kwargs ) uri_as_parts = kwargs . pop ( 'uri_as_parts' , False ) transform_name = kwargs . pop ( 'transform_name' , False ) transform_subpath = kwargs . pop ( 'transform_subpath' , False ) if uri_as_parts : REST_uri = generate_bigip_uri ( RIC_base_uri , partition , identifier , sub_path , suffix , transform_name = transform_name , transform_subpath = transform_subpath , ** kwargs ) else : REST_uri = RIC_base_uri pre_message = "%s WITH uri: %s AND suffix: %s AND kwargs: %s" % ( method . __name__ , REST_uri , suffix , kwargs ) logger = logging . getLogger ( __name__ ) logger . debug ( pre_message ) response = method ( self , REST_uri , ** kwargs ) post_message = "RESPONSE::STATUS: %s Content-Type: %s Content-Encoding:" " %s\nText: %r" % ( response . status_code , response . headers . get ( 'Content-Type' , None ) , response . headers . get ( 'Content-Encoding' , None ) , response . text ) logger . debug ( post_message ) if response . status_code not in range ( 200 , 207 ) : error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' % ( response . status_code , response . reason , response . url , response . text ) raise iControlUnexpectedHTTPError ( error_message , response = response ) return response return wrapper | Prepare and Post - Process HTTP VERB method for BigIP - RESTServer request . |
37,440 | def _unique_resource_identifier_from_kwargs ( ** kwargs ) : name = kwargs . pop ( 'name' , '' ) uuid = kwargs . pop ( 'uuid' , '' ) id = kwargs . pop ( 'id' , '' ) if uuid : return uuid , kwargs elif id : return id , kwargs else : return name , kwargs | Chooses an identifier given different choices |
37,441 | def delete ( self , uri , ** kwargs ) : args1 = get_request_args ( kwargs ) args2 = get_send_args ( kwargs ) req = requests . Request ( 'DELETE' , uri , ** args1 ) prepared = self . session . prepare_request ( req ) if self . debug : self . _debug_output . append ( debug_prepared_request ( prepared ) ) return self . session . send ( prepared , ** args2 ) | Sends a HTTP DELETE command to the BIGIP REST Server . |
37,442 | def append_user_agent ( self , user_agent ) : old_ua = self . session . headers . get ( 'User-Agent' , '' ) ua = old_ua + ' ' + user_agent self . session . headers [ 'User-Agent' ] = ua . strip ( ) | Append text to the User - Agent header for the request . |
37,443 | def validate_public_key ( value ) : is_valid = False exc = None for load in ( load_pem_public_key , load_ssh_public_key ) : if not is_valid : try : load ( value . encode ( 'utf-8' ) , default_backend ( ) ) is_valid = True except Exception as e : exc = e if not is_valid : raise ValidationError ( 'Public key is invalid: %s' % exc ) | Check that the given value is a valid RSA Public key in either PEM or OpenSSH format . If it is invalid raises django . core . exceptions . ValidationError . |
37,444 | def _register_formats ( cls ) : for fmt in cls . OUTPUT_FORMATS : clean_fmt = fmt . replace ( '+' , '_' ) setattr ( cls , clean_fmt , property ( ( lambda x , fmt = fmt : cls . _output ( x , fmt ) ) , ( lambda x , y , fmt = fmt : cls . _input ( x , y , fmt ) ) ) ) | Adds format properties . |
37,445 | def sign ( username , private_key , generate_nonce = None , iat = None , algorithm = DEFAULT_ALGORITHM ) : iat = iat if iat else time . time ( ) if not generate_nonce : generate_nonce = lambda username , iat : random . random ( ) token_data = { 'username' : username , 'time' : iat , 'nonce' : generate_nonce ( username , iat ) , } token = jwt . encode ( token_data , private_key , algorithm = algorithm ) return token | Create a signed JWT using the given username and RSA private key . |
37,446 | def get_claimed_username ( token ) : unverified_data = jwt . decode ( token , options = { 'verify_signature' : False } ) if 'username' not in unverified_data : return None return unverified_data [ 'username' ] | Given a JWT get the username that it is claiming to be without verifying that the signature is valid . |
37,447 | def verify ( token , public_key , validate_nonce = None , algorithms = [ DEFAULT_ALGORITHM ] ) : try : token_data = jwt . decode ( token , public_key , algorithms = algorithms ) except jwt . InvalidTokenError : logger . debug ( 'JWT failed verification' ) return False claimed_username = token_data . get ( 'username' ) claimed_time = token_data . get ( 'time' , 0 ) claimed_nonce = token_data . get ( 'nonce' ) current_time = time . time ( ) min_time , max_time = ( current_time - TIMESTAMP_TOLERANCE , current_time + TIMESTAMP_TOLERANCE ) if claimed_time < min_time or claimed_time > max_time : logger . debug ( 'Claimed time is outside of allowable tolerances' ) return False if validate_nonce : if not validate_nonce ( claimed_username , claimed_time , claimed_nonce ) : logger . debug ( 'Claimed nonce failed to validate' ) return False else : logger . warning ( 'validate_nonce function was not supplied!' ) return token_data | Verify the validity of the given JWT using the given public key . |
37,448 | def log_used_nonce ( self , username , iat , nonce ) : key = self . create_nonce_key ( username , iat ) used = cache . get ( key , [ ] ) used . append ( nonce ) cache . set ( key , set ( used ) , token . TIMESTAMP_TOLERANCE * 2 ) | Log a nonce as being used and therefore henceforth invalid . |
37,449 | def validate_nonce ( self , username , iat , nonce ) : key = self . create_nonce_key ( username , iat ) used = cache . get ( key , [ ] ) return nonce not in used | Confirm that the given nonce hasn t already been used . |
37,450 | def process_request ( self , request ) : if 'HTTP_AUTHORIZATION' not in request . META : return try : method , claim = request . META [ 'HTTP_AUTHORIZATION' ] . split ( ' ' , 1 ) except ValueError : return if method . upper ( ) != AUTH_METHOD : return username = token . get_claimed_username ( claim ) if not username : return User = get_user_model ( ) try : user = User . objects . get ( username = username ) except User . DoesNotExist : return claim_data = None for public in user . public_keys . all ( ) : claim_data = token . verify ( claim , public . key , validate_nonce = self . validate_nonce ) if claim_data : break if not claim_data : return logger . debug ( 'Successfully authenticated %s using JWT' , user . username ) request . _dont_enforce_csrf_checks = True request . user = user | Process a Django request and authenticate users . |
37,451 | def load_private_key ( key_file , key_password = None ) : key_file = os . path . expanduser ( key_file ) key_file = os . path . abspath ( key_file ) if not key_password : with open ( key_file , 'r' ) as key : return key . read ( ) with open ( key_file , 'rb' ) as key : key_bytes = key . read ( ) return decrypt_key ( key_bytes , key_password ) . decode ( ENCODING ) | Load a private key from disk . |
37,452 | def decrypt_key ( key , password ) : private = serialization . load_pem_private_key ( key , password = password , backend = default_backend ( ) ) return private . private_bytes ( Encoding . PEM , PrivateFormat . PKCS8 , NoEncryption ( ) ) | Decrypt an encrypted private key . |
37,453 | def create_auth_header ( username , key = None , key_file = "~/.ssh/id_rsa" , key_password = None ) : if not key : key = load_private_key ( key_file , key_password ) claim = token . sign ( username , key ) return "%s %s" % ( AUTH_METHOD , claim . decode ( ENCODING ) ) | Create an HTTP Authorization header using a private key file . |
37,454 | def _config_logs ( lvl = None , name = None ) : FORMAT = '%(message)s' for h in list ( logging . root . handlers ) : logging . root . removeHandler ( h ) global _log_level if lvl : _log_level = lvl logging . basicConfig ( level = _log_level , format = FORMAT , stream = sys . stdout ) _log = logging . getLogger ( __name__ ) _log . setLevel ( _log_level ) for log in [ 'urllib3' , 'asyncio' ] : logging . getLogger ( log ) . setLevel ( _log_level ) | Set up or change logging configuration . |
37,455 | def mk_set_headers ( self , data , columns ) : columns = tuple ( columns ) lens = [ ] for key in columns : value_len = max ( len ( str ( each . get ( key , '' ) ) ) for each in data ) lens . append ( max ( value_len , len ( self . _get_name ( key ) ) ) ) fmt = self . mk_fmt ( * lens ) return fmt | figure out sizes and create header fmt |
37,456 | def _get_name ( self , key ) : if key in self . display_names : return self . display_names [ key ] return key . capitalize ( ) | get display name for a key or mangle for display |
37,457 | def display_set ( self , typ , data , columns ) : self . display_section ( "%s (%d)" % ( self . _get_name ( typ ) , len ( data ) ) ) headers = tuple ( map ( self . _get_name , columns ) ) fmt = self . mk_set_headers ( data , columns ) self . display_headers ( fmt , headers ) for each in data : row = tuple ( self . _get_val ( each , k ) for k , v in each . items ( ) ) self . _print ( fmt % row ) self . _print ( "\n" ) | display a list of dicts |
37,458 | def _print ( self , * args ) : string = u" " . join ( args ) + '\n' self . fobj . write ( string ) | internal print to self . fobj |
37,459 | def display ( self , typ , data ) : if hasattr ( self , 'print_' + typ ) : getattr ( self , 'print_' + typ ) ( data ) elif not data : self . _print ( "%s: %s" % ( typ , data ) ) elif isinstance ( data , collections . Mapping ) : self . _print ( "\n" , typ ) for k , v in data . items ( ) : self . print ( k , v ) elif isinstance ( data , ( list , tuple ) ) : if isinstance ( data [ 0 ] , collections . Mapping ) : self . display_set ( typ , data , self . _get_columns ( data [ 0 ] ) ) else : for each in data : self . print ( typ , each ) else : self . _print ( "%s: %s" % ( typ , data ) ) self . fobj . flush ( ) | display section of typ with data |
37,460 | def _handler ( func ) : "Decorate a command handler" def _wrapped ( * a , ** k ) : r = func ( * a , ** k ) if r is None : r = 0 return r return staticmethod ( _wrapped ) | Decorate a command handler |
37,461 | def add_subcommands ( parser , commands ) : "Add commands to a parser" subps = parser . add_subparsers ( ) for cmd , cls in commands : subp = subps . add_parser ( cmd , help = cls . __doc__ ) add_args = getattr ( cls , 'add_arguments' , None ) if add_args : add_args ( subp ) handler = getattr ( cls , 'handle' , None ) if handler : subp . set_defaults ( handler = handler ) | Add commands to a parser |
37,462 | def update ( self , res , pk , depth = 1 , since = None ) : fetch = lambda : self . _fetcher . fetch_latest ( res , pk , 1 , since = since ) self . _update ( res , fetch , depth ) | Try to sync an object to the local database in case of failure where a referenced object is not found attempt to fetch said object from the REST api |
37,463 | def get_task ( self , key ) : res , pk = key jobs , lock = self . _jobs with lock : return jobs [ res ] . get ( pk ) | Get a scheduled task or none |
37,464 | def set_job ( self , key , func , args ) : res , pk = key jobs , lock = self . _jobs task = _tasks . UpdateTask ( func ( * args ) , key ) with lock : job = jobs [ res ] . get ( pk ) had = bool ( job ) if not job : job = task jobs [ res ] [ pk ] = job else : task . cancel ( ) self . _log . debug ( 'Scheduling: %s-%s (%s)' , res . tag , pk , 'new task' if not had else 'dup' ) return job | Get a scheduled task or set if none exists . |
37,465 | def pending_tasks ( self , res ) : "Synchronized access to tasks" jobs , lock = self . _jobs with lock : return jobs [ res ] . copy ( ) | Synchronized access to tasks |
37,466 | def fetch_and_index ( self , fetch_func ) : "Fetch data with func, return dict indexed by ID" data , e = fetch_func ( ) if e : raise e yield { row [ 'id' ] : row for row in data } | Fetch data with func return dict indexed by ID |
37,467 | def initialize_object ( B , res , row ) : B = get_backend ( ) field_groups = FieldGroups ( B . get_concrete ( res ) ) try : obj = B . get_object ( B . get_concrete ( res ) , row [ 'id' ] ) except B . object_missing_error ( B . get_concrete ( res ) ) : tbl = B . get_concrete ( res ) obj = tbl ( ) for fname , field in field_groups [ 'scalars' ] . items ( ) : value = row . get ( fname , getattr ( obj , fname , None ) ) value = B . convert_field ( obj . __class__ , fname , value ) setattr ( obj , fname , value ) fetched , dangling = defaultdict ( dict ) , defaultdict ( set ) def _handle_subrow ( R , subrow ) : if isinstance ( subrow , dict ) : pk = subrow [ 'id' ] fetched [ R ] [ pk ] = subrow else : pk = subrow dangling [ R ] . add ( pk ) return pk for fname , field in field_groups [ 'one_refs' ] . items ( ) : fieldres = _field_resource ( B , B . get_concrete ( res ) , fname ) key = field . column subrow = row . get ( key ) if subrow is None : key = fname subrow = row [ key ] pk = _handle_subrow ( fieldres , subrow ) setattr ( obj , key , pk ) for fname , field in field_groups [ 'many_refs' ] . items ( ) : fieldres = _field_resource ( B , B . get_concrete ( res ) , fname ) pks = [ _handle_subrow ( fieldres , subrow ) for subrow in row . get ( fname , [ ] ) ] return obj , fetched , dangling | Do a shallow initialization of an object |
37,468 | def read_config ( conf_dir = DEFAULT_CONFIG_DIR ) : "Find and read config file for a directory, return None if not found." conf_path = os . path . expanduser ( conf_dir ) if not os . path . exists ( conf_path ) : if conf_dir != DEFAULT_CONFIG_DIR : raise IOError ( "Config directory not found at %s" % ( conf_path , ) ) return munge . load_datafile ( 'config' , conf_path , default = None ) | Find and read config file for a directory return None if not found . |
37,469 | def detect_old ( data ) : "Check for a config file with old schema" if not data : return False ok , errors , warnings = _schema . validate ( _OLD_SCHEMA , data ) return ok and not ( errors or warnings ) | Check for a config file with old schema |
37,470 | def convert_old ( data ) : "Convert config data with old schema to new schema" ret = default_config ( ) ret [ 'sync' ] . update ( data . get ( 'peeringdb' , { } ) ) ret [ 'orm' ] [ 'database' ] . update ( data . get ( 'database' , { } ) ) return ret | Convert config data with old schema to new schema |
37,471 | def write_config ( data , conf_dir = DEFAULT_CONFIG_DIR , codec = "yaml" , backup_existing = False ) : if not codec : codec = 'yaml' codec = munge . get_codec ( codec ) ( ) conf_dir = os . path . expanduser ( conf_dir ) if not os . path . exists ( conf_dir ) : os . mkdir ( conf_dir ) outpath = os . path . join ( conf_dir , 'config.' + codec . extensions [ 0 ] ) if backup_existing and os . path . exists ( outpath ) : os . rename ( outpath , outpath + '.bak' ) codec . dump ( data , open ( outpath , 'w' ) ) | Write config values to a file . |
37,472 | def prompt_config ( sch , defaults = None , path = None ) : out = { } for name , attr in sch . attributes ( ) : fullpath = name if path : fullpath = '{}.{}' . format ( path , name ) if defaults is None : defaults = { } default = defaults . get ( name ) if isinstance ( attr , _schema . Schema ) : value = prompt_config ( attr , defaults = default , path = fullpath ) else : if default is None : default = attr . default if default is None : default = '' value = prompt ( fullpath , default ) out [ name ] = value return sch . validate ( out ) | Utility function to recursively prompt for config values |
37,473 | def fetch ( self , R , pk , depth = 1 ) : "Request object from API" d , e = self . _fetcher . fetch ( R , pk , depth ) if e : raise e return d | Request object from API |
37,474 | def fetch_all ( self , R , depth = 1 , ** kwargs ) : "Request multiple objects from API" d , e = self . _fetcher . fetch_all ( R , depth , kwargs ) if e : raise e return d | Request multiple objects from API |
37,475 | def all ( self , res ) : "Get resources using a filter condition" B = get_backend ( ) return B . get_objects ( B . get_concrete ( res ) ) | Get resources using a filter condition |
37,476 | def run_task ( func ) : def _wrapped ( * a , ** k ) : gen = func ( * a , ** k ) return _consume_task ( gen ) return _wrapped | Decorator to collect and return generator results returning a list if there are multiple results |
37,477 | def get ( self , typ , id , ** kwargs ) : return self . _load ( self . _request ( typ , id = id , params = kwargs ) ) | Load type by id |
37,478 | def wrap_generator ( func ) : async def _wrapped ( * a , ** k ) : r , ret = None , [ ] gen = func ( * a , ** k ) while True : try : item = gen . send ( r ) except StopIteration : break if inspect . isawaitable ( item ) : r = await item else : r = item ret . append ( r ) if len ( ret ) == 1 : return ret . pop ( ) return ret return _wrapped | Decorator to convert a generator function to an async function which collects and returns generator results returning a list if there are multiple results |
37,479 | def run_task ( func ) : def _wrapped ( * a , ** k ) : loop = asyncio . get_event_loop ( ) return loop . run_until_complete ( func ( * a , ** k ) ) return _wrapped | Decorator to wrap an async function in an event loop . Use for main sync interface methods . |
37,480 | def prompt ( msg , default = None ) : "Prompt for input" if default is not None : msg = '{} ({})' . format ( msg , repr ( default ) ) msg = '{}: ' . format ( msg ) try : s = input ( msg ) except KeyboardInterrupt : exit ( 1 ) except EOFError : s = '' if not s : s = default return s | Prompt for input |
37,481 | def limit_mem ( limit = ( 4 * 1024 ** 3 ) ) : "Set soft memory limit" rsrc = resource . RLIMIT_DATA soft , hard = resource . getrlimit ( rsrc ) resource . setrlimit ( rsrc , ( limit , hard ) ) softnew , _ = resource . getrlimit ( rsrc ) assert softnew == limit _log = logging . getLogger ( __name__ ) _log . debug ( 'Set soft memory limit: %s => %s' , soft , softnew ) | Set soft memory limit |
37,482 | def render_module ( inits , calls , inputs , outputs , dst_dir , pytorch_dict , pytorch_module_name ) : inits = [ i for i in inits if len ( i ) > 0 ] output = pytorch_model_template . format ( ** { 'module_name' : pytorch_module_name , 'module_name_lower' : pytorch_module_name . lower ( ) , 'inits' : '\n' . join ( inits ) , 'inputs' : inputs , 'calls' : '\n' . join ( calls ) , 'outputs' : outputs , } ) if dst_dir is not None : import os import errno try : os . makedirs ( dst_dir ) except OSError as e : if e . errno != errno . EEXIST : raise with open ( os . path . join ( dst_dir , pytorch_module_name . lower ( ) + '.py' ) , 'w+' ) as f : f . write ( output ) f . close ( ) torch . save ( pytorch_dict , os . path . join ( dst_dir , pytorch_module_name . lower ( ) + '.pt' ) ) return output | Render model . |
37,483 | def getAllFtpConnections ( self ) : outputMsg = "Current ftp connections:\n" counter = 1 for k in self . ftpList : outputMsg += str ( counter ) + ". " + k + " " outputMsg += str ( self . ftpList [ k ] ) + "\n" counter += 1 if self . printOutput : logger . info ( outputMsg ) return self . ftpList | Returns a dictionary containing active ftp connections . |
37,484 | def setup_logging ( verbose = 0 , colors = False , name = None ) : root_logger = logging . getLogger ( name ) root_logger . setLevel ( logging . DEBUG if verbose > 0 else logging . INFO ) formatter = ColorFormatter ( verbose > 0 , colors ) if colors : colorclass . Windows . enable ( ) handler_stdout = logging . StreamHandler ( sys . stdout ) handler_stdout . setFormatter ( formatter ) handler_stdout . setLevel ( logging . DEBUG ) handler_stdout . addFilter ( type ( '' , ( logging . Filter , ) , { 'filter' : staticmethod ( lambda r : r . levelno <= logging . INFO ) } ) ) root_logger . addHandler ( handler_stdout ) handler_stderr = logging . StreamHandler ( sys . stderr ) handler_stderr . setFormatter ( formatter ) handler_stderr . setLevel ( logging . WARNING ) root_logger . addHandler ( handler_stderr ) | Configure console logging . Info and below go to stdout others go to stderr . |
37,485 | def format ( self , record ) : formatted = super ( ColorFormatter , self ) . format ( record ) if self . verbose or not record . name . startswith ( self . SPECIAL_SCOPE ) : return formatted formatted = '=> ' + formatted if not self . colors : return formatted if record . levelno >= logging . ERROR : formatted = str ( colorclass . Color . red ( formatted ) ) elif record . levelno >= logging . WARNING : formatted = str ( colorclass . Color . yellow ( formatted ) ) else : formatted = str ( colorclass . Color . cyan ( formatted ) ) return formatted | Apply little arrow and colors to the record . |
37,486 | def get_root ( directory ) : command = [ 'git' , 'rev-parse' , '--show-toplevel' ] try : output = run_command ( directory , command , env_var = False ) except CalledProcessError as exc : raise GitError ( 'Failed to find local git repository root in {}.' . format ( repr ( directory ) ) , exc . output ) if IS_WINDOWS : output = output . replace ( '/' , '\\' ) return output . strip ( ) | Get root directory of the local git repo from any subdirectory within it . |
37,487 | def filter_and_date ( local_root , conf_rel_paths , commits ) : dates_paths = dict ( ) for commit in commits : if commit in dates_paths : continue command = [ 'git' , 'ls-tree' , '--name-only' , '-r' , commit ] + conf_rel_paths try : output = run_command ( local_root , command ) except CalledProcessError as exc : raise GitError ( 'Git ls-tree failed on {0}' . format ( commit ) , exc . output ) if output : dates_paths [ commit ] = [ None , output . splitlines ( ) [ 0 ] . strip ( ) ] command_prefix = [ 'git' , 'show' , '--no-patch' , '--pretty=format:%ct' ] for commits_group in chunk ( dates_paths , 50 ) : command = command_prefix + commits_group output = run_command ( local_root , command ) timestamps = [ int ( i ) for i in RE_UNIX_TIME . findall ( output ) ] for i , commit in enumerate ( commits_group ) : dates_paths [ commit ] [ 0 ] = timestamps [ i ] return dates_paths | Get commit Unix timestamps and first matching conf . py path . Exclude commits with no conf . py file . |
37,488 | def fetch_commits ( local_root , remotes ) : command = [ 'git' , 'fetch' , 'origin' ] run_command ( local_root , command ) for sha , name , kind in remotes : try : run_command ( local_root , [ 'git' , 'reflog' , sha ] ) except CalledProcessError : run_command ( local_root , command + [ 'refs/{0}/{1}' . format ( kind , name ) ] ) run_command ( local_root , [ 'git' , 'reflog' , sha ] ) | Fetch from origin . |
37,489 | def export ( local_root , commit , target ) : log = logging . getLogger ( __name__ ) target = os . path . realpath ( target ) mtimes = list ( ) def extract ( stdout ) : queued_links = list ( ) try : with tarfile . open ( fileobj = stdout , mode = 'r|' ) as tar : for info in tar : log . debug ( 'name: %s; mode: %d; size: %s; type: %s' , info . name , info . mode , info . size , info . type ) path = os . path . realpath ( os . path . join ( target , info . name ) ) if not path . startswith ( target ) : log . warning ( 'Ignoring tar object path %s outside of target directory.' , info . name ) elif info . isdir ( ) : if not os . path . exists ( path ) : os . makedirs ( path , mode = info . mode ) elif info . issym ( ) or info . islnk ( ) : queued_links . append ( info ) else : tar . extract ( member = info , path = target ) if os . path . splitext ( info . name ) [ 1 ] . lower ( ) == '.rst' : mtimes . append ( info . name ) for info in ( i for i in queued_links if os . path . exists ( os . path . join ( target , i . linkname ) ) ) : tar . extract ( member = info , path = target ) except tarfile . TarError as exc : log . debug ( 'Failed to extract output from "git archive" command: %s' , str ( exc ) ) run_command ( local_root , [ 'git' , 'archive' , '--format=tar' , commit ] , pipeto = extract ) for file_path in mtimes : last_committed = int ( run_command ( local_root , [ 'git' , 'log' , '-n1' , '--format=%at' , commit , '--' , file_path ] ) ) os . utime ( os . path . join ( target , file_path ) , ( last_committed , last_committed ) ) | Export git commit to directory . Extracts all files at the commit to the target directory . |
37,490 | def clone ( local_root , new_root , remote , branch , rel_dest , exclude ) : log = logging . getLogger ( __name__ ) output = run_command ( local_root , [ 'git' , 'remote' , '-v' ] ) remotes = dict ( ) for match in RE_ALL_REMOTES . findall ( output ) : remotes . setdefault ( match [ 0 ] , [ None , None ] ) if match [ 2 ] == 'fetch' : remotes [ match [ 0 ] ] [ 0 ] = match [ 1 ] else : remotes [ match [ 0 ] ] [ 1 ] = match [ 1 ] if not remotes : raise GitError ( 'Git repo has no remotes.' , output ) if remote not in remotes : raise GitError ( 'Git repo missing remote "{}".' . format ( remote ) , output ) try : run_command ( new_root , [ 'git' , 'clone' , remotes [ remote ] [ 0 ] , '--depth=1' , '--branch' , branch , '.' ] ) except CalledProcessError as exc : raise GitError ( 'Failed to clone from remote repo URL.' , exc . output ) try : run_command ( new_root , [ 'git' , 'symbolic-ref' , 'HEAD' ] ) except CalledProcessError as exc : raise GitError ( 'Specified branch is not a real branch.' , exc . output ) for name , ( fetch , push ) in remotes . items ( ) : try : run_command ( new_root , [ 'git' , 'remote' , 'set-url' if name == 'origin' else 'add' , name , fetch ] , retry = 3 ) run_command ( new_root , [ 'git' , 'remote' , 'set-url' , '--push' , name , push ] , retry = 3 ) except CalledProcessError as exc : raise GitError ( 'Failed to set git remote URL.' , exc . output ) if not exclude : return exclude_joined = [ os . path . relpath ( p , new_root ) for e in exclude for p in glob . glob ( os . path . join ( new_root , rel_dest , e ) ) ] log . debug ( 'Expanded %s to %s' , repr ( exclude ) , repr ( exclude_joined ) ) try : run_command ( new_root , [ 'git' , 'rm' , '-rf' , rel_dest ] ) except CalledProcessError as exc : raise GitError ( '"git rm" failed to remove ' + rel_dest , exc . output ) run_command ( new_root , [ 'git' , 'reset' , 'HEAD' ] + exclude_joined ) run_command ( new_root , [ 'git' , 'checkout' , '--' ] + exclude_joined ) | Clone local_root origin into a new directory and check out a specific branch . Optionally run git rm . |
37,491 | def commit_and_push ( local_root , remote , versions ) : log = logging . getLogger ( __name__ ) current_branch = run_command ( local_root , [ 'git' , 'rev-parse' , '--abbrev-ref' , 'HEAD' ] ) . strip ( ) run_command ( local_root , [ 'git' , 'add' , '.' ] ) try : run_command ( local_root , [ 'git' , 'diff' , 'HEAD' , '--no-ext-diff' , '--quiet' , '--exit-code' ] ) except CalledProcessError : pass else : log . info ( 'No changes to commit.' ) return True output = run_command ( local_root , [ 'git' , 'diff' , 'HEAD' , '--no-ext-diff' , '--name-status' ] ) for status , name in ( l . split ( '\t' , 1 ) for l in output . splitlines ( ) ) : if status != 'M' : break components = name . split ( '/' ) if '.doctrees' not in components and components [ - 1 ] != 'searchindex.js' : break else : log . info ( 'No significant changes to commit.' ) return True latest_commit = sorted ( versions . remotes , key = lambda v : v [ 'date' ] ) [ - 1 ] commit_message_file = os . path . join ( local_root , '_scv_commit_message.txt' ) with open ( commit_message_file , 'w' ) as handle : handle . write ( 'AUTO sphinxcontrib-versioning {} {}\n\n' . format ( datetime . utcfromtimestamp ( latest_commit [ 'date' ] ) . strftime ( '%Y%m%d' ) , latest_commit [ 'sha' ] [ : 11 ] , ) ) for line in ( '{}: {}\n' . format ( v , os . environ [ v ] ) for v in WHITELIST_ENV_VARS if v in os . environ ) : handle . write ( line ) try : run_command ( local_root , [ 'git' , 'commit' , '-F' , commit_message_file ] ) except CalledProcessError as exc : raise GitError ( 'Failed to commit locally.' , exc . output ) os . remove ( commit_message_file ) try : run_command ( local_root , [ 'git' , 'push' , remote , current_branch ] ) except CalledProcessError as exc : if '[rejected]' in exc . output and '(fetch first)' in exc . output : log . debug ( 'Remote has changed since cloning the repo. Must retry.' ) return False raise GitError ( 'Failed to push to remote.' , exc . output ) log . info ( 'Successfully pushed to remote repository.' ) return True | Commit changed new and deleted files in the repo and attempt to push the branch to the remote repository . |
37,492 | def multi_sort ( remotes , sort ) : exploded_alpha = list ( ) exploded_semver = list ( ) if 'alpha' in sort : alpha_max_len = max ( len ( r [ 'name' ] ) for r in remotes ) for name in ( r [ 'name' ] for r in remotes ) : exploded_alpha . append ( [ ord ( i ) for i in name ] + [ 0 ] * ( alpha_max_len - len ( name ) ) ) if 'semver' in sort : exploded_semver = semvers ( r [ 'name' ] for r in remotes ) sort_mapping = dict ( ) for i , remote in enumerate ( remotes ) : key = list ( ) for sort_by in sort : if sort_by == 'alpha' : key . extend ( exploded_alpha [ i ] ) elif sort_by == 'time' : key . append ( - remote [ 'date' ] ) elif sort_by == 'semver' : key . extend ( exploded_semver [ i ] ) sort_mapping [ id ( remote ) ] = key remotes . sort ( key = lambda k : sort_mapping . get ( id ( k ) ) ) | Sort remotes in place . Allows sorting by multiple conditions . |
37,493 | def read_local_conf ( local_conf ) : log = logging . getLogger ( __name__ ) log . info ( 'Reading config from %s...' , local_conf ) try : config = read_config ( os . path . dirname ( local_conf ) , '<local>' ) except HandledError : log . warning ( 'Unable to read file, continuing with only CLI args.' ) return dict ( ) return { k [ 4 : ] : v for k , v in config . items ( ) if k . startswith ( 'scv_' ) and not k [ 4 : ] . startswith ( '_' ) } | Search for conf . py in any rel_source directory in CWD and if found read it and return . |
37,494 | def gather_git_info ( root , conf_rel_paths , whitelist_branches , whitelist_tags ) : log = logging . getLogger ( __name__ ) log . info ( 'Getting list of all remote branches/tags...' ) try : remotes = list_remote ( root ) except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise HandledError log . info ( 'Found: %s' , ' ' . join ( i [ 1 ] for i in remotes ) ) try : try : dates_paths = filter_and_date ( root , conf_rel_paths , ( i [ 0 ] for i in remotes ) ) except GitError : log . info ( 'Need to fetch from remote...' ) fetch_commits ( root , remotes ) try : dates_paths = filter_and_date ( root , conf_rel_paths , ( i [ 0 ] for i in remotes ) ) except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise HandledError except subprocess . CalledProcessError as exc : log . debug ( json . dumps ( dict ( command = exc . cmd , cwd = root , code = exc . returncode , output = exc . output ) ) ) log . error ( 'Failed to get dates for all remote commits.' ) raise HandledError filtered_remotes = [ [ i [ 0 ] , i [ 1 ] , i [ 2 ] , ] + dates_paths [ i [ 0 ] ] for i in remotes if i [ 0 ] in dates_paths ] log . info ( 'With docs: %s' , ' ' . join ( i [ 1 ] for i in filtered_remotes ) ) if not whitelist_branches and not whitelist_tags : return filtered_remotes whitelisted_remotes = list ( ) for remote in filtered_remotes : if remote [ 2 ] == 'heads' and whitelist_branches : if not any ( re . search ( p , remote [ 1 ] ) for p in whitelist_branches ) : continue if remote [ 2 ] == 'tags' and whitelist_tags : if not any ( re . search ( p , remote [ 1 ] ) for p in whitelist_tags ) : continue whitelisted_remotes . append ( remote ) log . info ( 'Passed whitelisting: %s' , ' ' . join ( i [ 1 ] for i in whitelisted_remotes ) ) return whitelisted_remotes | Gather info about the remote git repository . Get list of refs . |
37,495 | def pre_build ( local_root , versions ) : log = logging . getLogger ( __name__ ) exported_root = TempDir ( True ) . name for sha in { r [ 'sha' ] for r in versions . remotes } : target = os . path . join ( exported_root , sha ) log . debug ( 'Exporting %s to temporary directory.' , sha ) export ( local_root , sha , target ) remote = versions [ Config . from_context ( ) . root_ref ] with TempDir ( ) as temp_dir : log . debug ( 'Building root (before setting root_dirs) in temporary directory: %s' , temp_dir ) source = os . path . dirname ( os . path . join ( exported_root , remote [ 'sha' ] , remote [ 'conf_rel_path' ] ) ) build ( source , temp_dir , versions , remote [ 'name' ] , True ) existing = os . listdir ( temp_dir ) for remote in versions . remotes : root_dir = RE_INVALID_FILENAME . sub ( '_' , remote [ 'name' ] ) while root_dir in existing : root_dir += '_' remote [ 'root_dir' ] = root_dir log . debug ( '%s root directory is %s' , remote [ 'name' ] , root_dir ) existing . append ( root_dir ) for remote in list ( versions . remotes ) : log . debug ( 'Partially running sphinx-build to read configuration for: %s' , remote [ 'name' ] ) source = os . path . dirname ( os . path . join ( exported_root , remote [ 'sha' ] , remote [ 'conf_rel_path' ] ) ) try : config = read_config ( source , remote [ 'name' ] ) except HandledError : log . warning ( 'Skipping. Will not be building: %s' , remote [ 'name' ] ) versions . remotes . pop ( versions . remotes . index ( remote ) ) continue remote [ 'found_docs' ] = config [ 'found_docs' ] remote [ 'master_doc' ] = config [ 'master_doc' ] return exported_root | Build docs for all versions to determine root directory and master_doc names . |
37,496 | def build_all ( exported_root , destination , versions ) : log = logging . getLogger ( __name__ ) while True : remote = versions [ Config . from_context ( ) . root_ref ] log . info ( 'Building root: %s' , remote [ 'name' ] ) source = os . path . dirname ( os . path . join ( exported_root , remote [ 'sha' ] , remote [ 'conf_rel_path' ] ) ) build ( source , destination , versions , remote [ 'name' ] , True ) for remote in list ( versions . remotes ) : log . info ( 'Building ref: %s' , remote [ 'name' ] ) source = os . path . dirname ( os . path . join ( exported_root , remote [ 'sha' ] , remote [ 'conf_rel_path' ] ) ) target = os . path . join ( destination , remote [ 'root_dir' ] ) try : build ( source , target , versions , remote [ 'name' ] , False ) except HandledError : log . warning ( 'Skipping. Will not be building %s. Rebuilding everything.' , remote [ 'name' ] ) versions . remotes . pop ( versions . remotes . index ( remote ) ) break else : break | Build all versions . |
37,497 | def _build ( argv , config , versions , current_name , is_root ) : application . Config = ConfigInject if config . show_banner : EventHandlers . BANNER_GREATEST_TAG = config . banner_greatest_tag EventHandlers . BANNER_MAIN_VERSION = config . banner_main_ref EventHandlers . BANNER_RECENT_TAG = config . banner_recent_tag EventHandlers . SHOW_BANNER = True EventHandlers . CURRENT_VERSION = current_name EventHandlers . IS_ROOT = is_root EventHandlers . VERSIONS = versions SC_VERSIONING_VERSIONS [ : ] = [ p for r in versions . remotes for p in sorted ( r . items ( ) ) if p [ 0 ] not in ( 'sha' , 'date' ) ] if config . verbose > 1 : argv += ( '-v' , ) * ( config . verbose - 1 ) if config . no_colors : argv += ( '-N' , ) if config . overflow : argv += config . overflow result = build_main ( argv ) if result != 0 : raise SphinxError | Build Sphinx docs via multiprocessing for isolation . |
37,498 | def _read_config ( argv , config , current_name , queue ) : EventHandlers . ABORT_AFTER_READ = queue _build ( argv , config , Versions ( list ( ) ) , current_name , False ) | Read the Sphinx config via multiprocessing for isolation . |
37,499 | def read_config ( source , current_name ) : log = logging . getLogger ( __name__ ) queue = multiprocessing . Queue ( ) config = Config . from_context ( ) with TempDir ( ) as temp_dir : argv = ( 'sphinx-build' , source , temp_dir ) log . debug ( 'Running sphinx-build for config values with args: %s' , str ( argv ) ) child = multiprocessing . Process ( target = _read_config , args = ( argv , config , current_name , queue ) ) child . start ( ) child . join ( ) if child . exitcode != 0 : log . error ( 'sphinx-build failed for branch/tag while reading config: %s' , current_name ) raise HandledError config = queue . get ( ) return config | Read the Sphinx config for one version . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.