idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
25,500
def __validate_enrollment_periods ( self , enrollments ) : for a , b in itertools . combinations ( enrollments , 2 ) : max_start = max ( a . start , b . start ) min_end = min ( a . end , b . end ) if max_start < min_end : msg = "invalid GrimoireLab enrollment dates. " "Organization dates overlap." raise InvalidFormatError ( cause = msg ) return enrollments
Check for overlapped periods in the enrollments
100
9
25,501
def __parse ( self , stream ) : if not stream : raise InvalidFormatError ( cause = "stream cannot be empty or None" ) json = self . __load_json ( stream ) self . __parse_organizations ( json ) self . __parse_identities ( json ) self . __parse_blacklist ( json )
Parse Sorting Hat stream
70
6
25,502
def __parse_blacklist ( self , json ) : try : for entry in json [ 'blacklist' ] : if not entry : msg = "invalid json format. Blacklist entries cannot be null or empty" raise InvalidFormatError ( cause = msg ) excluded = self . __encode ( entry ) bl = self . _blacklist . get ( excluded , None ) if not bl : bl = MatchingBlacklist ( excluded = excluded ) self . _blacklist [ excluded ] = bl except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse blacklist entries using Sorting Hat format .
138
10
25,503
def __parse_organizations ( self , json ) : try : for organization in json [ 'organizations' ] : name = self . __encode ( organization ) org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) self . _organizations [ name ] = org domains = json [ 'organizations' ] [ organization ] for domain in domains : if type ( domain [ 'is_top' ] ) != bool : msg = "invalid json format. 'is_top' must have a bool value" raise InvalidFormatError ( cause = msg ) dom = Domain ( domain = domain [ 'domain' ] , is_top_domain = domain [ 'is_top' ] ) org . domains . append ( dom ) except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse organizations using Sorting Hat format .
201
9
25,504
def run ( self , * args ) : params = self . parser . parse_args ( args ) with params . infile as infile : try : stream = self . __read_file ( infile ) parser = SortingHatParser ( stream ) except InvalidFormatError as e : self . error ( str ( e ) ) return e . code except ( IOError , TypeError , AttributeError ) as e : raise RuntimeError ( str ( e ) ) if params . identities : self . import_blacklist ( parser ) code = self . import_identities ( parser , matching = params . matching , match_new = params . match_new , no_strict_matching = params . no_strict , reset = params . reset , verbose = params . verbose ) elif params . orgs : self . import_organizations ( parser , params . overwrite ) code = CMD_SUCCESS else : self . import_organizations ( parser , params . overwrite ) self . import_blacklist ( parser ) code = self . import_identities ( parser , matching = params . matching , match_new = params . match_new , no_strict_matching = params . no_strict , reset = params . reset , verbose = params . verbose ) return code
Import data on the registry .
277
6
25,505
def import_blacklist ( self , parser ) : blacklist = parser . blacklist self . log ( "Loading blacklist..." ) n = 0 for entry in blacklist : try : api . add_to_matching_blacklist ( self . db , entry . excluded ) self . display ( 'load_blacklist.tmpl' , entry = entry . excluded ) n += 1 except ValueError as e : raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : msg = "%s. Not added." % str ( e ) self . warning ( msg ) self . log ( "%d/%d blacklist entries loaded" % ( n , len ( blacklist ) ) )
Import blacklist .
143
3
25,506
def import_organizations ( self , parser , overwrite = False ) : orgs = parser . organizations for org in orgs : try : api . add_organization ( self . db , org . name ) except ValueError as e : raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : pass for dom in org . domains : try : api . add_domain ( self . db , org . name , dom . domain , is_top_domain = dom . is_top_domain , overwrite = overwrite ) self . display ( 'load_domains.tmpl' , domain = dom . domain , organization = org . name ) except ( ValueError , NotFoundError ) as e : raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : msg = "%s. Not updated." % str ( e ) self . warning ( msg )
Import organizations .
187
3
25,507
def import_identities ( self , parser , matching = None , match_new = False , no_strict_matching = False , reset = False , verbose = False ) : matcher = None if matching : strict = not no_strict_matching try : blacklist = api . blacklist ( self . db ) matcher = create_identity_matcher ( matching , blacklist , strict = strict ) except MatcherNotSupportedError as e : self . error ( str ( e ) ) return e . code uidentities = parser . identities try : self . __load_unique_identities ( uidentities , matcher , match_new , reset , verbose ) except LoadError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Import identities information on the registry .
171
7
25,508
def __load_unique_identities ( self , uidentities , matcher , match_new , reset , verbose ) : self . new_uids . clear ( ) n = 0 if reset : self . __reset_unique_identities ( ) self . log ( "Loading unique identities..." ) for uidentity in uidentities : self . log ( "\n=====" , verbose ) self . log ( "+ Processing %s" % uidentity . uuid , verbose ) try : stored_uuid = self . __load_unique_identity ( uidentity , verbose ) except LoadError as e : self . error ( "%s Skipping." % str ( e ) ) self . log ( "=====" , verbose ) continue stored_uuid = self . __load_identities ( uidentity . identities , stored_uuid , verbose ) try : self . __load_profile ( uidentity . profile , stored_uuid , verbose ) except Exception as e : self . error ( "%s. Loading %s profile. Skipping profile." % ( str ( e ) , stored_uuid ) ) self . __load_enrollments ( uidentity . enrollments , stored_uuid , verbose ) if matcher and ( not match_new or stored_uuid in self . new_uids ) : stored_uuid = self . _merge_on_matching ( stored_uuid , matcher , verbose ) self . log ( "+ %s (old %s) loaded" % ( stored_uuid , uidentity . uuid ) , verbose ) self . log ( "=====" , verbose ) n += 1 self . log ( "%d/%d unique identities loaded" % ( n , len ( uidentities ) ) )
Load unique identities
392
3
25,509
def __reset_unique_identities ( self ) : self . log ( "Reseting unique identities..." ) self . log ( "Clearing identities relationships" ) nids = 0 uidentities = api . unique_identities ( self . db ) for uidentity in uidentities : for identity in uidentity . identities : api . move_identity ( self . db , identity . id , identity . id ) nids += 1 self . log ( "Relationships cleared for %s identities" % nids ) self . log ( "Clearing enrollments" ) with self . db . connect ( ) as session : enrollments = session . query ( Enrollment ) . all ( ) for enr in enrollments : session . delete ( enr ) self . log ( "Enrollments cleared" )
Clear identities relationships and enrollments data
172
7
25,510
def __load_unique_identity ( self , uidentity , verbose ) : uuid = uidentity . uuid if uuid : try : api . unique_identities ( self . db , uuid ) self . log ( "-- %s already exists." % uuid , verbose ) return uuid except NotFoundError as e : self . log ( "-- %s not found. Generating a new UUID." % uuid , debug = verbose ) # We don't have a unique identity, so we have to create # a new one. if len ( uidentity . identities ) == 0 : msg = "not enough info to load %s unique identity." % uidentity . uuid raise LoadError ( cause = msg ) identity = uidentity . identities . pop ( 0 ) try : stored_uuid = api . add_identity ( self . db , identity . source , identity . email , identity . name , identity . username ) self . new_uids . add ( stored_uuid ) except AlreadyExistsError as e : with self . db . connect ( ) as session : stored_identity = find_identity ( session , e . eid ) stored_uuid = stored_identity . uuid self . warning ( "-- " + str ( e ) , debug = verbose ) except ValueError as e : raise LoadError ( cause = str ( e ) ) self . log ( "-- using %s for %s unique identity." % ( stored_uuid , uuid ) , verbose ) return stored_uuid
Seek or store unique identity
339
6
25,511
def __load_profile ( self , profile , uuid , verbose ) : def is_empty_profile ( prf ) : return not ( prf . name or prf . email or prf . gender or prf . gender_acc or prf . is_bot or prf . country_code ) uid = api . unique_identities ( self . db , uuid ) [ 0 ] if profile : self . __create_profile ( profile , uuid , verbose ) elif is_empty_profile ( uid . profile ) : self . __create_profile_from_identities ( uid . identities , uuid , verbose ) else : self . log ( "-- empty profile given for %s. Not updated" % uuid , verbose )
Create a new profile when the unique identity does not have any .
167
13
25,512
def __create_profile ( self , profile , uuid , verbose ) : # Set parameters to edit kw = profile . to_dict ( ) kw [ 'country_code' ] = profile . country_code # Remove unused keywords kw . pop ( 'uuid' ) kw . pop ( 'country' ) api . edit_profile ( self . db , uuid , * * kw ) self . log ( "-- profile %s updated" % uuid , verbose )
Create profile information from a profile object
106
7
25,513
def __create_profile_from_identities ( self , identities , uuid , verbose ) : import re EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$" NAME_REGEX = r"^\w+\s\w+" name = None email = None username = None for identity in identities : if not name and identity . name : m = re . match ( NAME_REGEX , identity . name ) if m : name = identity . name if not email and identity . email : m = re . match ( EMAIL_ADDRESS_REGEX , identity . email ) if m : email = identity . email if not username : if identity . username and identity . username != 'None' : username = identity . username # We need a name for each profile, so if no one was defined, # use email or username to complete it. if not name : if email : name = email . split ( '@' ) [ 0 ] elif username : # filter email addresses on username fields name = username . split ( '@' ) [ 0 ] else : name = None kw = { 'name' : name , 'email' : email } api . edit_profile ( self . db , uuid , * * kw ) self . log ( "-- profile %s updated" % uuid , verbose )
Create a profile using the data from the identities
314
9
25,514
def _merge_on_matching ( self , uuid , matcher , verbose ) : matches = api . match_identities ( self . db , uuid , matcher ) new_uuid = uuid u = api . unique_identities ( self . db , uuid ) [ 0 ] for m in matches : if m . uuid == uuid : continue self . _merge ( u , m , verbose ) new_uuid = m . uuid # Swap uids to merge with those that could # remain on the list with updated info u = api . unique_identities ( self . db , m . uuid ) [ 0 ] return new_uuid
Merge unique identity with uuid when a match is found
148
12
25,515
def _merge ( self , from_uid , to_uid , verbose ) : if verbose : self . display ( 'match.tmpl' , uid = from_uid , match = to_uid ) api . merge_unique_identities ( self . db , from_uid . uuid , to_uid . uuid ) if verbose : self . display ( 'merge.tmpl' , from_uuid = from_uid . uuid , to_uuid = to_uid . uuid )
Merge unique identity uid on match
114
8
25,516
def __parse ( self , aliases , email_to_employer , domain_to_employer ) : self . __parse_organizations ( domain_to_employer ) self . __parse_identities ( aliases , email_to_employer )
Parse Gitdm streams
55
5
25,517
def __parse_identities ( self , aliases , email_to_employer ) : # Parse streams self . __parse_aliases_stream ( aliases ) self . __parse_email_to_employer_stream ( email_to_employer ) # Create unique identities from aliases list for alias , email in self . __raw_aliases . items ( ) : uid = self . _identities . get ( email , None ) if not uid : uid = UniqueIdentity ( uuid = email ) e = re . match ( self . EMAIL_ADDRESS_REGEX , email , re . UNICODE ) if e : identity = Identity ( email = email , source = self . source ) else : identity = Identity ( username = email , source = self . source ) uid . identities . append ( identity ) self . _identities [ email ] = uid e = re . match ( self . EMAIL_ADDRESS_REGEX , alias , re . UNICODE ) if e : identity = Identity ( email = alias , source = self . source ) else : identity = Identity ( username = alias , source = self . source ) uid . identities . append ( identity ) # Create unique identities from enrollments list for email in self . __raw_identities : # Do we have it from aliases? if email in self . _identities : uid = self . _identities [ email ] elif email in self . __raw_aliases : canonical = self . __raw_aliases [ email ] uid = self . _identities [ canonical ] else : uid = UniqueIdentity ( uuid = email ) identity = Identity ( email = email , source = self . source ) uid . identities . append ( identity ) self . _identities [ email ] = uid # Assign enrollments enrs = self . __raw_identities [ email ] enrs . sort ( key = lambda r : r [ 1 ] ) start_date = MIN_PERIOD_DATE for rol in enrs : name = rol [ 0 ] org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) self . _organizations [ name ] = org end_date = rol [ 1 ] enrollment = Enrollment ( start = start_date , end = end_date , organization = org ) uid . enrollments . append ( enrollment ) if end_date != MAX_PERIOD_DATE : start_date = end_date
Parse Gitdm identities
547
5
25,518
def __parse_organizations ( self , domain_to_employer ) : # Parse streams self . __parse_domain_to_employer_stream ( domain_to_employer ) for org in self . __raw_orgs : o = Organization ( name = org ) for dom in self . __raw_orgs [ org ] : d = Domain ( domain = dom , is_top_domain = False ) o . domains . append ( d ) self . _organizations [ org ] = o
Parse Gitdm organizations
109
5
25,519
def __parse_aliases_stream ( self , stream ) : if not stream : return f = self . __parse_aliases_line for alias_entries in self . __parse_stream ( stream , f ) : alias = alias_entries [ 0 ] username = alias_entries [ 1 ] self . __raw_aliases [ alias ] = username
Parse aliases stream .
78
5
25,520
def __parse_email_to_employer_stream ( self , stream ) : if not stream : return f = self . __parse_email_to_employer_line for rol in self . __parse_stream ( stream , f ) : email = rol [ 0 ] org = rol [ 1 ] rol_date = rol [ 2 ] if org not in self . __raw_orgs : self . __raw_orgs [ org ] = [ ] if email not in self . __raw_identities : self . __raw_identities [ email ] = [ ( org , rol_date ) ] else : self . __raw_identities [ email ] . append ( ( org , rol_date ) )
Parse email to employer stream .
160
7
25,521
def __parse_domain_to_employer_stream ( self , stream ) : if not stream : return f = self . __parse_domain_to_employer_line for o in self . __parse_stream ( stream , f ) : org = o [ 0 ] dom = o [ 1 ] if org not in self . __raw_orgs : self . __raw_orgs [ org ] = [ ] self . __raw_orgs [ org ] . append ( dom )
Parse domain to employer stream .
105
7
25,522
def __parse_stream ( self , stream , parse_line ) : if not stream : raise InvalidFormatError ( cause = 'stream cannot be empty or None' ) nline = 0 lines = stream . split ( '\n' ) for line in lines : nline += 1 # Ignore blank lines and comments m = re . match ( self . LINES_TO_IGNORE_REGEX , line , re . UNICODE ) if m : continue m = re . match ( self . VALID_LINE_REGEX , line , re . UNICODE ) if not m : cause = "line %s: invalid format" % str ( nline ) raise InvalidFormatError ( cause = cause ) try : result = parse_line ( m . group ( 1 ) , m . group ( 2 ) ) yield result except InvalidFormatError as e : cause = "line %s: %s" % ( str ( nline ) , e ) raise InvalidFormatError ( cause = cause )
Generic method to parse gitdm streams
209
7
25,523
def __parse_aliases_line ( self , raw_alias , raw_username ) : alias = self . __encode ( raw_alias ) username = self . __encode ( raw_username ) return alias , username
Parse aliases lines
48
4
25,524
def __parse_email_to_employer_line ( self , raw_email , raw_enrollment ) : e = re . match ( self . EMAIL_ADDRESS_REGEX , raw_email , re . UNICODE ) if not e and self . email_validation : cause = "invalid email format: '%s'" % raw_email raise InvalidFormatError ( cause = cause ) if self . email_validation : email = e . group ( 'email' ) . strip ( ) else : email = raw_email r = re . match ( self . ENROLLMENT_REGEX , raw_enrollment , re . UNICODE ) if not r : cause = "invalid enrollment format: '%s'" % raw_enrollment raise InvalidFormatError ( cause = cause ) org = r . group ( 'organization' ) . strip ( ) date = r . group ( 'date' ) if date : try : dt = dateutil . parser . parse ( r . group ( 'date' ) ) except Exception as e : cause = "invalid date: '%s'" % date else : dt = MAX_PERIOD_DATE email = self . __encode ( email ) org = self . __encode ( org ) return email , org , dt
Parse email to employer lines
283
6
25,525
def __parse_domain_to_employer_line ( self , raw_domain , raw_org ) : d = re . match ( self . DOMAIN_REGEX , raw_domain , re . UNICODE ) if not d : cause = "invalid domain format: '%s'" % raw_domain raise InvalidFormatError ( cause = cause ) dom = d . group ( 'domain' ) . strip ( ) o = re . match ( self . ORGANIZATION_REGEX , raw_org , re . UNICODE ) if not o : cause = "invalid organization format: '%s'" % raw_org raise InvalidFormatError ( cause = cause ) org = o . group ( 'organization' ) . strip ( ) org = self . __encode ( org ) dom = self . __encode ( dom ) return org , dom
Parse domain to employer lines
185
6
25,526
def log ( self , uuid = None , organization = None , from_date = None , to_date = None ) : try : enrollments = api . enrollments ( self . db , uuid , organization , from_date , to_date ) self . display ( 'log.tmpl' , enrollments = enrollments ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
List enrollment information available in the registry .
104
8
25,527
def run ( self , * args ) : params = self . parser . parse_args ( args ) code = self . initialize ( name = params . name , reuse = params . reuse ) return code
Initialize a registry .
41
5
25,528
def initialize ( self , name , reuse = False ) : user = self . _kwargs [ 'user' ] password = self . _kwargs [ 'password' ] host = self . _kwargs [ 'host' ] port = self . _kwargs [ 'port' ] if '-' in name : self . error ( "dabase name '%s' cannot contain '-' characters" % name ) return CODE_VALUE_ERROR try : Database . create ( user , password , name , host , port ) # Try to access and create schema db = Database ( user , password , name , host , port ) # Load countries list self . __load_countries ( db ) except DatabaseExists as e : if not reuse : self . error ( str ( e ) ) return CODE_DATABASE_EXISTS except DatabaseError as e : self . error ( str ( e ) ) return CODE_DATABASE_ERROR except LoadError as e : Database . drop ( user , password , name , host , port ) self . error ( str ( e ) ) return CODE_LOAD_ERROR return CMD_SUCCESS
Create an empty Sorting Hat registry .
241
8
25,529
def __load_countries ( self , db ) : try : countries = self . __read_countries_file ( ) except IOError as e : raise LoadError ( str ( e ) ) try : with db . connect ( ) as session : for country in countries : session . add ( country ) except Exception as e : raise LoadError ( str ( e ) )
Load the list of countries
78
5
25,530
def __read_countries_file ( self ) : import csv import pkg_resources filename = pkg_resources . resource_filename ( 'sortinghat' , 'data/countries.csv' ) with open ( filename , 'r' ) as f : reader = csv . DictReader ( f , fieldnames = [ 'name' , 'code' , 'alpha3' ] ) countries = [ Country ( * * c ) for c in reader ] return countries
Read countries from a CSV file
103
6
25,531
def run ( self , * args ) : params = self . parser . parse_args ( args ) identifier = params . identifier identity = params . identity code = self . remove ( identifier , identity ) return code
Remove unique identities or identities from the registry .
43
9
25,532
def merge_date_ranges ( dates ) : if not dates : return sorted_dates = sorted ( [ sorted ( t ) for t in dates ] ) saved = list ( sorted_dates [ 0 ] ) for st , en in sorted_dates : if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE : raise ValueError ( "start date %s is out of bounds" % str ( st ) ) if en < MIN_PERIOD_DATE or en > MAX_PERIOD_DATE : raise ValueError ( "end date %s is out of bounds" % str ( en ) ) if st <= saved [ 1 ] : if saved [ 0 ] == MIN_PERIOD_DATE : saved [ 0 ] = st if MAX_PERIOD_DATE in ( en , saved [ 1 ] ) : saved [ 1 ] = min ( saved [ 1 ] , en ) else : saved [ 1 ] = max ( saved [ 1 ] , en ) else : yield tuple ( saved ) saved [ 0 ] = st saved [ 1 ] = en yield tuple ( saved )
Merge date ranges .
241
5
25,533
def uuid ( source , email = None , name = None , username = None ) : if source is None : raise ValueError ( "source cannot be None" ) if source == '' : raise ValueError ( "source cannot be an empty string" ) if not ( email or name or username ) : raise ValueError ( "identity data cannot be None or empty" ) s = ':' . join ( ( to_unicode ( source ) , to_unicode ( email ) , to_unicode ( name , unaccent = True ) , to_unicode ( username ) ) ) . lower ( ) sha1 = hashlib . sha1 ( s . encode ( 'UTF-8' , errors = "surrogateescape" ) ) uuid_ = sha1 . hexdigest ( ) return uuid_
Get the UUID related to the identity data .
177
10
25,534
def create_database_engine ( user , password , database , host , port ) : driver = 'mysql+pymysql' url = URL ( driver , user , password , host , port , database , query = { 'charset' : 'utf8mb4' } ) return create_engine ( url , poolclass = QueuePool , pool_size = 25 , pool_pre_ping = True , echo = False )
Create a database engine
94
4
25,535
def create_database_session ( engine ) : try : Session = sessionmaker ( bind = engine ) return Session ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
Connect to the database
58
4
25,536
def close_database_session ( session ) : try : session . close ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
Close connection with the database
50
5
25,537
def reflect_table ( engine , klass ) : try : meta = MetaData ( ) meta . reflect ( bind = engine ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] ) # Try to reflect from any of the supported tables table = None for tb in klass . tables ( ) : if tb in meta . tables : table = meta . tables [ tb ] break if table is None : raise DatabaseError ( error = "Invalid schema. Table not found" , code = "-1" ) # Map table schema into klass mapper ( klass , table , column_prefix = klass . column_prefix ( ) ) return table
Inspect and reflect objects
158
5
25,538
def find_model_by_table_name ( name ) : for model in ModelBase . _decl_class_registry . values ( ) : if hasattr ( model , '__table__' ) and model . __table__ . fullname == name : return model return None
Find a model reference by its table name
60
8
25,539
def handle_database_error ( cls , session , exception ) : session . rollback ( ) if isinstance ( exception , IntegrityError ) : cls . handle_integrity_error ( exception ) elif isinstance ( exception , FlushError ) : cls . handle_flush_error ( exception ) else : raise exception
Rollback changes made and handle any type of error raised by the DBMS .
70
16
25,540
def handle_integrity_error ( cls , exception ) : m = re . match ( cls . MYSQL_INSERT_ERROR_REGEX , exception . statement ) if not m : raise exception model = find_model_by_table_name ( m . group ( 'table' ) ) if not model : raise exception m = re . match ( cls . MYSQL_DUPLICATE_ENTRY_ERROR_REGEX , exception . orig . args [ 1 ] ) if not m : raise exception entity = model . __name__ eid = m . group ( 'value' ) raise AlreadyExistsError ( entity = entity , eid = eid )
Handle integrity error exceptions .
147
5
25,541
def handle_flush_error ( cls , exception ) : trace = exception . args [ 0 ] m = re . match ( cls . MYSQL_FLUSH_ERROR_REGEX , trace ) if not m : raise exception entity = m . group ( 'entity' ) eid = m . group ( 'eid' ) raise AlreadyExistsError ( entity = entity , eid = eid )
Handle flush error exceptions .
88
5
25,542
def run ( self , * args ) : self . parser . parse_args ( args ) code = self . affiliate ( ) return code
Affiliate unique identities to organizations .
28
7
25,543
def affiliate ( self ) : try : uidentities = api . unique_identities ( self . db ) for uid in uidentities : uid . identities . sort ( key = lambda x : x . id ) for identity in uid . identities : # Only check email address to find new affiliations if not identity . email : continue if not EMAIL_ADDRESS_PATTERN . match ( identity . email ) : continue domain = identity . email . split ( '@' ) [ - 1 ] try : doms = api . domains ( self . db , domain = domain , top = True ) except NotFoundError as e : continue if len ( doms ) > 1 : doms . sort ( key = lambda d : len ( d . domain ) , reverse = True ) msg = "multiple top domains for %s sub-domain. Domain %s selected." msg = msg % ( domain , doms [ 0 ] . domain ) self . warning ( msg ) organization = doms [ 0 ] . organization . name # Check enrollments to avoid insert affiliation twice enrollments = api . enrollments ( self . db , uid . uuid , organization ) if enrollments : continue api . add_enrollment ( self . db , uid . uuid , organization ) self . display ( 'affiliate.tmpl' , id = uid . uuid , email = identity . email , organization = organization ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Affiliate unique identities .
335
5
25,544
def run ( self , * args ) : params = self . parser . parse_args ( args ) ct = params . code_or_term if ct and len ( ct ) < 2 : self . error ( 'Code country or term must have 2 or more characters length' ) return CODE_INVALID_FORMAT_ERROR code = ct if ct and len ( ct ) == 2 else None term = ct if ct and len ( ct ) > 2 else None try : countries = api . countries ( self . db , code = code , term = term ) self . display ( 'countries.tmpl' , countries = countries ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Show information about countries .
175
5
25,545
async def _call_async ( self , method_name : str , * args , * * kwargs ) : request = utils . rpc_request ( method_name , * args , * * kwargs ) _log . debug ( "Sending request: %s" , request ) # setup an event to notify us when the reply is received (potentially by a task scheduled by # another call to _async_call). we do this before we send the request to catch the case # where the reply comes back before we re-enter this thread self . _events [ request . id ] = asyncio . Event ( ) # schedule a task to receive the reply to ensure we have a task to receive the reply asyncio . ensure_future ( self . _recv_reply ( ) ) await self . _async_socket . send_multipart ( [ to_msgpack ( request ) ] ) await self . _events [ request . id ] . wait ( ) reply = self . _replies . pop ( request . id ) if isinstance ( reply , RPCError ) : raise utils . RPCError ( reply . error ) else : return reply . result
Sends a request to the socket and then wait for the reply .
256
14
25,546
async def _recv_reply ( self ) : raw_reply , = await self . _async_socket . recv_multipart ( ) reply = from_msgpack ( raw_reply ) _log . debug ( "Received reply: %s" , reply ) self . _replies [ reply . id ] = reply self . _events . pop ( reply . id ) . set ( )
Helper task to recieve a reply store the result and trigger the associated event .
88
16
25,547
def call ( self , method_name : str , * args , rpc_timeout : float = None , * * kwargs ) : request = utils . rpc_request ( method_name , * args , * * kwargs ) _log . debug ( "Sending request: %s" , request ) self . _socket . send_multipart ( [ to_msgpack ( request ) ] ) # if an rpc_timeout override is not specified, use the one set in the Client attributes if rpc_timeout is None : rpc_timeout = self . rpc_timeout start_time = time . time ( ) while True : # Need to keep track of timeout manually in case this loop runs more than once. We subtract off already # elapsed time from the timeout. The call to max is to make sure we don't send a negative value # which would throw an error. timeout = max ( ( start_time + rpc_timeout - time . time ( ) ) * 1000 , 0 ) if rpc_timeout is not None else None if self . _socket . poll ( timeout ) == 0 : raise TimeoutError ( f"Timeout on client {self.endpoint}, method name {method_name}, class info: {self}" ) raw_reply , = self . _socket . recv_multipart ( ) reply = from_msgpack ( raw_reply ) _log . debug ( "Received reply: %s" , reply ) # there's a possibility that the socket will have some leftover replies from a previous # request on it if that .call() was cancelled or timed out. Therefore, we need to discard replies that # don't match the request just like in the call_async case. if reply . id == request . id : break else : _log . debug ( 'Discarding reply: %s' , reply ) for warning in reply . warnings : warn ( f"{warning.kind}: {warning.body}" ) if isinstance ( reply , RPCError ) : raise utils . RPCError ( reply . error ) else : return reply . result
Send JSON RPC request to a backend socket and receive reply Note that this uses the default event loop to run in a blocking manner . If you would rather run in an async fashion or provide your own event loop then use . async_call instead
450
48
25,548
def close ( self ) : self . _socket . close ( ) if self . _async_socket_cache : self . _async_socket_cache . close ( ) self . _async_socket_cache = None
Close the sockets
49
3
25,549
def _connect_to_socket ( self , context : zmq . Context , endpoint : str ) : socket = context . socket ( zmq . DEALER ) socket . connect ( endpoint ) socket . setsockopt ( zmq . LINGER , 0 ) _log . debug ( "Client connected to endpoint %s" , self . endpoint ) return socket
Connect to a DEALER socket at endpoint and turn off lingering .
79
14
25,550
def _async_socket ( self ) : if not self . _async_socket_cache : self . _async_socket_cache = self . _connect_to_socket ( zmq . asyncio . Context ( ) , self . endpoint ) return self . _async_socket_cache
Creates a new async socket if one doesn t already exist for this Client
66
15
25,551
def run ( self , endpoint : str , loop : AbstractEventLoop = None ) : if not loop : loop = asyncio . get_event_loop ( ) try : loop . run_until_complete ( self . run_async ( endpoint ) ) except KeyboardInterrupt : self . _shutdown ( )
Run server main task .
66
5
25,552
def _shutdown ( self ) : for exit_handler in self . _exit_handlers : exit_handler ( ) if self . _socket : self . _socket . close ( ) self . _socket = None
Shut down the server .
46
5
25,553
def _connect ( self , endpoint : str ) : if self . _socket : raise RuntimeError ( 'Cannot run multiple Servers on the same socket' ) context = zmq . asyncio . Context ( ) self . _socket = context . socket ( zmq . ROUTER ) self . _socket . bind ( endpoint ) _log . info ( "Starting server, listening on endpoint {}" . format ( endpoint ) )
Connect the server to an endpoint . Creates a ZMQ ROUTER socket for the given endpoint .
92
21
25,554
async def _process_request ( self , identity : bytes , empty_frame : list , request : RPCRequest ) : try : _log . debug ( "Client %s sent request: %s" , identity , request ) start_time = datetime . now ( ) reply = await self . rpc_spec . run_handler ( request ) if self . announce_timing : _log . info ( "Request {} for {} lasted {} seconds" . format ( request . id , request . method , ( datetime . now ( ) - start_time ) . total_seconds ( ) ) ) _log . debug ( "Sending client %s reply: %s" , identity , reply ) await self . _socket . send_multipart ( [ identity , * empty_frame , to_msgpack ( reply ) ] ) except Exception as e : if self . serialize_exceptions : _log . exception ( 'Exception thrown in _process_request' ) else : raise e
Executes the method specified in a JSON RPC request and then sends the reply to the socket .
210
19
25,555
def add_handler ( self , f ) : if f . __name__ . startswith ( 'rpc_' ) : raise ValueError ( "Server method names cannot start with rpc_." ) self . _json_rpc_methods [ f . __name__ ] = f return f
Adds the function f to a dictionary of JSON RPC methods .
65
12
25,556
def get_handler ( self , request ) : try : f = self . _json_rpc_methods [ request . method ] except ( AttributeError , KeyError ) : # pragma no coverage raise RPCMethodError ( "Received invalid method '{}'" . format ( request . method ) ) return f
Get callable from JSON RPC request
68
7
25,557
async def run_handler ( self , request : RPCRequest ) -> Union [ RPCReply , RPCError ] : with catch_warnings ( record = True ) as warnings : try : rpc_handler = self . get_handler ( request ) except RPCMethodError as e : return rpc_error ( request . id , str ( e ) , warnings = warnings ) try : # Run RPC and get result args , kwargs = get_input ( request . params ) result = rpc_handler ( * args , * * kwargs ) if asyncio . iscoroutine ( result ) : result = await result except Exception as e : if self . serialize_exceptions : _traceback = traceback . format_exc ( ) _log . error ( _traceback ) if self . provide_tracebacks : return rpc_error ( request . id , "{}\n{}" . format ( str ( e ) , _traceback ) , warnings = warnings ) else : return rpc_error ( request . id , str ( e ) , warnings = warnings ) else : raise e return rpc_reply ( request . id , result , warnings = warnings )
Process a JSON RPC request
249
5
25,558
def rpc_request ( method_name : str , * args , * * kwargs ) -> rpcq . messages . RPCRequest : if args : kwargs [ '*args' ] = args return rpcq . messages . RPCRequest ( jsonrpc = '2.0' , id = str ( uuid . uuid4 ( ) ) , method = method_name , params = kwargs )
Create RPC request
91
3
25,559
def rpc_reply ( id : Union [ str , int ] , result : Optional [ object ] , warnings : Optional [ List [ Warning ] ] = None ) -> rpcq . messages . RPCReply : warnings = warnings or [ ] return rpcq . messages . RPCReply ( jsonrpc = '2.0' , id = id , result = result , warnings = [ rpc_warning ( warning ) for warning in warnings ] )
Create RPC reply
94
3
25,560
def rpc_error ( id : Union [ str , int ] , error_msg : str , warnings : List [ Any ] = [ ] ) -> rpcq . messages . RPCError : return rpcq . messages . RPCError ( jsonrpc = '2.0' , id = id , error = error_msg , warnings = [ rpc_warning ( warning ) for warning in warnings ] )
Create RPC error
91
3
25,561
def get_input ( params : Union [ dict , list ] ) -> Tuple [ list , dict ] : # Backwards compatibility for old clients that send params as a list if isinstance ( params , list ) : args = params kwargs = { } elif isinstance ( params , dict ) : args = params . pop ( '*args' , [ ] ) kwargs = params else : # pragma no coverage raise TypeError ( 'Unknown type {} of params, must be list or dict' . format ( type ( params ) ) ) return args , kwargs
Get positional or keyword arguments from JSON RPC params
122
9
25,562
def repr_value ( value ) : if isinstance ( value , list ) and len ( value ) > REPR_LIST_TRUNCATION : return "[{},...]" . format ( ", " . join ( map ( repr , value [ : REPR_LIST_TRUNCATION ] ) ) ) else : return repr ( value )
Represent a value in human readable form . For long list s this truncates the printed representation .
73
19
25,563
def get ( cls , reactor , source = 'graphite' , * * options ) : acls = cls . alerts [ source ] return acls ( reactor , * * options )
Get Alert Class by source .
42
6
25,564
def convert ( self , value ) : try : return convert_to_format ( value , self . _format ) except ( ValueError , TypeError ) : return value
Convert self value .
35
5
25,565
def check ( self , records ) : for value , target in records : LOGGER . info ( "%s [%s]: %s" , self . name , target , value ) if value is None : self . notify ( self . no_data , value , target ) continue for rule in self . rules : if self . evaluate_rule ( rule , value , target ) : self . notify ( rule [ 'level' ] , value , target , rule = rule ) break else : self . notify ( 'normal' , value , target , rule = rule ) self . history [ target ] . append ( value )
Check current value .
128
4
25,566
def evaluate_rule ( self , rule , value , target ) : def evaluate ( expr ) : if expr in LOGICAL_OPERATORS . values ( ) : return expr rvalue = self . get_value_for_expr ( expr , target ) if rvalue is None : return False # ignore this result return expr [ 'op' ] ( value , rvalue ) evaluated = [ evaluate ( expr ) for expr in rule [ 'exprs' ] ] while len ( evaluated ) > 1 : lhs , logical_op , rhs = ( evaluated . pop ( 0 ) for _ in range ( 3 ) ) evaluated . insert ( 0 , logical_op ( lhs , rhs ) ) return evaluated [ 0 ]
Calculate the value .
151
6
25,567
def get_value_for_expr ( self , expr , target ) : if expr in LOGICAL_OPERATORS . values ( ) : return None rvalue = expr [ 'value' ] if rvalue == HISTORICAL : history = self . history [ target ] if len ( history ) < self . history_size : return None rvalue = sum ( history ) / float ( len ( history ) ) rvalue = expr [ 'mod' ] ( rvalue ) return rvalue
I have no idea .
103
5
25,568
def notify ( self , level , value , target = None , ntype = None , rule = None ) : # Did we see the event before? if target in self . state and level == self . state [ target ] : return False # Do we see the event first time? if target not in self . state and level == 'normal' and not self . reactor . options [ 'send_initial' ] : return False self . state [ target ] = level return self . reactor . notify ( level , self , value , target = target , ntype = ntype , rule = rule )
Notify main reactor about event .
123
7
25,569
def load ( self ) : LOGGER . debug ( '%s: start checking: %s' , self . name , self . query ) if self . waiting : self . notify ( 'warning' , 'Process takes too much time' , target = 'waiting' , ntype = 'common' ) else : self . waiting = True try : response = yield self . client . fetch ( self . url , auth_username = self . auth_username , auth_password = self . auth_password , request_timeout = self . request_timeout , connect_timeout = self . connect_timeout , validate_cert = self . validate_cert ) records = ( GraphiteRecord ( line , self . default_nan_value , self . ignore_nan ) for line in response . buffer ) data = [ ( None if record . empty else getattr ( record , self . method ) , record . target ) for record in records ] if len ( data ) == 0 : raise ValueError ( 'No data' ) self . check ( data ) self . notify ( 'normal' , 'Metrics are loaded' , target = 'loading' , ntype = 'common' ) except Exception as e : self . notify ( self . loading_error , 'Loading error: %s' % e , target = 'loading' , ntype = 'common' ) self . waiting = False
Load data from Graphite .
290
6
25,570
def get_graph_url ( self , target , graphite_url = None ) : return self . _graphite_url ( target , graphite_url = graphite_url , raw_data = False )
Get Graphite URL .
46
5
25,571
def _graphite_url ( self , query , raw_data = False , graphite_url = None ) : query = escape . url_escape ( query ) graphite_url = graphite_url or self . reactor . options . get ( 'public_graphite_url' ) url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}" . format ( base = graphite_url , query = query , from_time = self . from_time . as_graphite ( ) , until = self . until . as_graphite ( ) , ) if raw_data : url = "{}&format=raw" . format ( url ) return url
Build Graphite URL .
154
5
25,572
def load ( self ) : LOGGER . debug ( '%s: start checking: %s' , self . name , self . query ) if self . waiting : self . notify ( 'warning' , 'Process takes too much time' , target = 'waiting' , ntype = 'common' ) else : self . waiting = True try : response = yield self . client . fetch ( self . query , method = self . options . get ( 'method' , 'GET' ) , request_timeout = self . request_timeout , connect_timeout = self . connect_timeout , validate_cert = self . options . get ( 'validate_cert' , True ) ) self . check ( [ ( self . get_data ( response ) , self . query ) ] ) self . notify ( 'normal' , 'Metrics are loaded' , target = 'loading' , ntype = 'common' ) except Exception as e : self . notify ( 'critical' , str ( e ) , target = 'loading' , ntype = 'common' ) self . waiting = False
Load URL .
229
3
25,573
def _get_loader ( config ) : if config . endswith ( '.yml' ) or config . endswith ( '.yaml' ) : if not yaml : LOGGER . error ( "pyyaml must be installed to use the YAML loader" ) # TODO: stop reactor if running return None , None return 'yaml' , yaml . load else : return 'json' , json . loads
Determine which config file type and loader to use based on a filename .
92
16
25,574
def start ( self , start_loop = True ) : self . start_alerts ( ) if self . options . get ( 'pidfile' ) : with open ( self . options . get ( 'pidfile' ) , 'w' ) as fpid : fpid . write ( str ( os . getpid ( ) ) ) self . callback . start ( ) LOGGER . info ( 'Reactor starts' ) if start_loop : self . loop . start ( )
Start all the things .
101
5
25,575
def notify ( self , level , alert , value , target = None , ntype = None , rule = None ) : LOGGER . info ( 'Notify %s:%s:%s:%s' , level , alert , value , target or "" ) if ntype is None : ntype = alert . source for handler in self . handlers . get ( level , [ ] ) : handler . notify ( level , alert , value , target = target , ntype = ntype , rule = rule )
Provide the event to the handlers .
107
8
25,576
def write_to_file ( chats , chatfile ) : with open ( chatfile , 'w' ) as handler : handler . write ( '\n' . join ( ( str ( id_ ) for id_ in chats ) ) )
called every time chats are modified
51
6
25,577
def get_chatlist ( chatfile ) : if not chatfile : return set ( ) try : with open ( chatfile ) as file_contents : return set ( int ( chat ) for chat in file_contents ) except ( OSError , IOError ) as exc : LOGGER . error ( 'could not load saved chats:\n%s' , exc ) return set ( )
Try reading ids of saved chats from file . If we fail return empty set
84
16
25,578
def get_data ( upd , bot_ident ) : update_content = json . loads ( upd . decode ( ) ) result = update_content [ 'result' ] data = ( get_fields ( update , bot_ident ) for update in result ) return ( dt for dt in data if dt is not None )
Parse telegram update .
70
6
25,579
def get_fields ( upd , bot_ident ) : msg = upd . get ( 'message' , { } ) text = msg . get ( 'text' ) if not text : return chat_id = msg [ 'chat' ] [ 'id' ] command = filter_commands ( text , chat_id , bot_ident ) if not command : return return ( upd [ 'update_id' ] , chat_id , msg [ 'message_id' ] , command )
In telegram api not every update has message field and not every message has update field . We skip those cases . Rest of fields are mandatory . We also skip if text is not a valid command to handler .
103
42
25,580
def _listen_commands ( self ) : self . _last_update = None update_body = { 'timeout' : 2 } while True : latest = self . _last_update # increase offset to filter out older updates update_body . update ( { 'offset' : latest + 1 } if latest else { } ) update_resp = self . client . get_updates ( update_body ) update_resp . add_done_callback ( self . _respond_commands ) yield gen . sleep ( 5 )
Monitor new updates and send them further to self . _respond_commands where bot actions are decided .
112
21
25,581
def _respond_commands ( self , update_response ) : chatfile = self . chatfile chats = self . chats exc , upd = update_response . exception ( ) , update_response . result ( ) . body if exc : LOGGER . error ( str ( exc ) ) if not upd : return data = get_data ( upd , self . bot_ident ) for update_id , chat_id , message_id , command in data : self . _last_update = update_id chat_is_known = chat_id in chats chats_changed = False reply_text = None if command == '/activate' : if chat_is_known : reply_text = 'This chat is already activated.' else : LOGGER . debug ( 'Adding chat [%s] to notify list.' , chat_id ) reply_text = 'Activated.' chats . add ( chat_id ) chats_changed = True elif command == '/deactivate' : if chat_is_known : LOGGER . debug ( 'Deleting chat [%s] from notify list.' , chat_id ) reply_text = 'Deactivated.' chats . remove ( chat_id ) chats_changed = True if chats_changed and chatfile : write_to_file ( chats , chatfile ) elif command == '/help' : reply_text = HELP_MESSAGE else : LOGGER . warning ( 'Could not parse command: ' 'bot ident is wrong or missing' ) if reply_text : yield self . client . send_message ( { 'chat_id' : chat_id , 'reply_to_message_id' : message_id , 'text' : reply_text , 'parse_mode' : 'Markdown' , } )
Extract commands to bot from update and act accordingly . For description of commands see HELP_MESSAGE variable on top of this module .
376
29
25,582
def notify ( self , level , * args , * * kwargs ) : LOGGER . debug ( 'Handler (%s) %s' , self . name , level ) notify_text = self . get_message ( level , * args , * * kwargs ) for chat in self . chats . copy ( ) : data = { "chat_id" : chat , "text" : notify_text } yield self . client . send_message ( data )
Sends alerts to telegram chats . This method is called from top level module . Do not rename it .
99
22
25,583
def get_message ( self , level , alert , value , * * kwargs ) : target , ntype = kwargs . get ( 'target' ) , kwargs . get ( 'ntype' ) msg_type = 'telegram' if ntype == 'graphite' else 'short' tmpl = TEMPLATES [ ntype ] [ msg_type ] generated = tmpl . generate ( level = level , reactor = self . reactor , alert = alert , value = value , target = target , ) return generated . decode ( ) . strip ( )
Standart alert message . Same format across all graphite - beacon handlers .
125
15
25,584
def fetchmaker ( self , telegram_api_method ) : fetch = self . client . fetch request = self . url ( telegram_api_method ) def _fetcher ( body , method = 'POST' , headers = None ) : """Uses fetch method of tornado http client.""" body = json . dumps ( body ) if not headers : headers = { } headers . update ( { 'Content-Type' : 'application/json' } ) return fetch ( request = request , body = body , method = method , headers = headers ) return _fetcher
Receives api method as string and returns wrapper around AsyncHTTPClient s fetch method
120
18
25,585
def _normalize_value_ms ( cls , value ) : value = round ( value / 1000 ) * 1000 # Ignore fractions of second sorted_units = sorted ( cls . UNITS_IN_MILLISECONDS . items ( ) , key = lambda x : x [ 1 ] , reverse = True ) for unit , unit_in_ms in sorted_units : unit_value = value / unit_in_ms if unit_value . is_integer ( ) : return int ( unit_value ) , unit return value , MILLISECOND
Normalize a value in ms to the largest unit possible without decimal places .
120
15
25,586
def _normalize_unit ( cls , unit ) : if unit in cls . UNITS_IN_SECONDS : return unit return cls . UNIT_ALIASES_REVERSE . get ( unit , None )
Resolve a unit to its real name if it s an alias .
51
14
25,587
def convert ( cls , value , from_unit , to_unit ) : value_ms = value * cls . UNITS_IN_MILLISECONDS [ from_unit ] return value_ms / cls . UNITS_IN_MILLISECONDS [ to_unit ]
Convert a value from one time unit to another .
66
11
25,588
def init_handler ( self ) : assert self . options . get ( 'host' ) and self . options . get ( 'port' ) , "Invalid options" assert self . options . get ( 'to' ) , 'Recipients list is empty. SMTP disabled.' if not isinstance ( self . options [ 'to' ] , ( list , tuple ) ) : self . options [ 'to' ] = [ self . options [ 'to' ] ]
Check self options .
99
4
25,589
def iterator_mix ( * iterators ) : while True : one_left = False for it in iterators : try : yield it . next ( ) except StopIteration : pass else : one_left = True if not one_left : break
Iterating over list of iterators . Bit like zip but zip stops after the shortest iterator is empty abd here we go one until all iterators are empty .
52
33
25,590
def _normalize_path ( self , path ) : norm_path = os . path . normpath ( path ) return os . path . relpath ( norm_path , start = self . _get_working_dir ( ) )
Normalizes a file path so that it returns a path relative to the root repo directory .
50
18
25,591
def translate_github_exception ( func ) : @ functools . wraps ( func ) def _wrapper ( * args , * * kwargs ) : try : return func ( * args , * * kwargs ) except UnknownObjectException as e : logger . exception ( 'GitHub API 404 Exception' ) raise NotFoundError ( str ( e ) ) except GithubException as e : logger . exception ( 'GitHub API Exception' ) raise GitClientError ( str ( e ) ) return _wrapper
Decorator to catch GitHub - specific exceptions and raise them as GitClientError exceptions .
109
18
25,592
def violations ( self ) : return self . _all_violations if self . config . fail_on == FAIL_ON_ANY else self . _diff_violations
Returns either the diff violations or all violations depending on configuration .
37
12
25,593
def execute ( self ) : if not self . config . pr : raise NotPullRequestException logger . debug ( 'Using the following configuration:' ) for name , value in self . config . as_dict ( ) . items ( ) : logger . debug ( ' - {}={}' . format ( name , repr ( value ) ) ) logger . info ( 'Running Lintly against PR #{} for repo {}' . format ( self . config . pr , self . project ) ) parser = PARSERS . get ( self . config . format ) self . _all_violations = parser . parse_violations ( self . linter_output ) logger . info ( 'Lintly found violations in {} files' . format ( len ( self . _all_violations ) ) ) diff = self . get_pr_diff ( ) patch = self . get_pr_patch ( diff ) self . _diff_violations = self . find_diff_violations ( patch ) logger . info ( 'Lintly found diff violations in {} files' . format ( len ( self . _diff_violations ) ) ) self . post_pr_comment ( patch ) self . post_commit_status ( )
Executes a new build on a project .
258
9
25,594
def find_diff_violations ( self , patch ) : violations = collections . defaultdict ( list ) for line in patch . changed_lines : file_violations = self . _all_violations . get ( line [ 'file_name' ] ) if not file_violations : continue line_violations = [ v for v in file_violations if v . line == line [ 'line_number' ] ] for v in line_violations : violations [ line [ 'file_name' ] ] . append ( v ) return violations
Uses the diff for this build to find changed lines that also have violations .
117
16
25,595
def post_pr_comment ( self , patch ) : if self . has_violations : post_pr_comment = True # Attempt to post a PR review. If posting the PR review fails because the bot account # does not have permission to review the PR then simply revert to posting a regular PR # comment. try : logger . info ( 'Deleting old PR review comments' ) self . git_client . delete_pull_request_review_comments ( self . config . pr ) logger . info ( 'Creating PR review' ) self . git_client . create_pull_request_review ( self . config . pr , patch , self . _diff_violations ) post_pr_comment = False except GitClientError as e : # TODO: Make `create_pull_request_review` raise an `UnauthorizedError` # so that we don't have to check for a specific message in the exception if 'Viewer does not have permission to review this pull request' in str ( e ) : logger . warning ( "Could not post PR review (the account didn't have permission)" ) pass else : raise if post_pr_comment : logger . info ( 'Deleting old PR comment' ) self . git_client . delete_pull_request_comments ( self . config . pr ) logger . info ( 'Creating PR comment' ) comment = build_pr_comment ( self . config , self . violations ) self . git_client . create_pull_request_comment ( self . config . pr , comment )
Posts a comment to the GitHub PR if the diff results have issues .
327
14
25,596
def post_commit_status ( self ) : if self . violations : plural = '' if self . introduced_issues_count == 1 else 's' description = 'Pull Request introduced {} linting violation{}' . format ( self . introduced_issues_count , plural ) self . _post_status ( 'failure' , description ) else : self . _post_status ( 'success' , 'Linting detected no new issues.' )
Posts results to a commit status in GitHub if this build is for a pull request .
96
17
25,597
def reg_to_lex ( conditions , wildcards ) : aliases = defaultdict ( set ) n_conds = [ ] # All conditions for i , _ in enumerate ( conditions ) : n_cond = [ ] for char in conditions [ i ] : if char in wildcards : alias = '%s_%s' % ( char , len ( aliases [ char ] ) ) aliases [ char ] . add ( alias ) n_cond . append ( make_token ( alias , reg = wildcards [ char ] ) ) else : n_cond . append ( ~ Literal ( char ) ) n_cond . append ( Eos ( ) ) n_conds . append ( reduce ( operator . and_ , n_cond ) > make_dict ) return tuple ( n_conds ) , aliases
Transform a regular expression into a LEPL object .
171
10
25,598
def main ( * * options ) : configure_logging ( log_all = options . get ( 'log' ) ) stdin_stream = click . get_text_stream ( 'stdin' ) stdin_text = stdin_stream . read ( ) click . echo ( stdin_text ) ci = find_ci_provider ( ) config = Config ( options , ci = ci ) build = LintlyBuild ( config , stdin_text ) try : build . execute ( ) except NotPullRequestException : logger . info ( 'Not a PR. Lintly is exiting.' ) sys . exit ( 0 ) # Exit with the number of files that have violations sys . exit ( len ( build . violations ) )
Slurp up linter output and send it to a GitHub PR review .
159
16
25,599
def translate_gitlab_exception ( func ) : @ functools . wraps ( func ) def _wrapper ( * args , * * kwargs ) : try : return func ( * args , * * kwargs ) except gitlab . GitlabError as e : status_to_exception = { 401 : UnauthorizedError , 404 : NotFoundError , } exc_class = status_to_exception . get ( e . response_code , GitClientError ) raise exc_class ( str ( e ) , status_code = e . response_code ) return _wrapper
Decorator to catch GitLab - specific exceptions and raise them as GitClientError exceptions .
126
19