signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def packet_queue(self, pkt):
|
pkt.pos = <NUM_LIT:0><EOL>pkt.to_process = pkt.packet_length<EOL>self.out_packet.append(pkt)<EOL>return NC.ERR_SUCCESS<EOL>
|
Enqueue packet to out_packet queue.
|
f3688:c0:m5
|
def packet_write(self):
|
bytes_written = <NUM_LIT:0><EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN, bytes_written<EOL><DEDENT>while len(self.out_packet) > <NUM_LIT:0>:<EOL><INDENT>pkt = self.out_packet[<NUM_LIT:0>]<EOL>write_length, status = nyamuk_net.write(self.sock, pkt.payload)<EOL>if write_length > <NUM_LIT:0>:<EOL><INDENT>pkt.to_process -= write_length<EOL>pkt.pos += write_length<EOL>bytes_written += write_length<EOL>if pkt.to_process > <NUM_LIT:0>:<EOL><INDENT>return NC.ERR_SUCCESS, bytes_written<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if status == errno.EAGAIN or status == errno.EWOULDBLOCK:<EOL><INDENT>return NC.ERR_SUCCESS, bytes_written<EOL><DEDENT>elif status == errno.ECONNRESET:<EOL><INDENT>return NC.ERR_CONN_LOST, bytes_written<EOL><DEDENT>else:<EOL><INDENT>return NC.ERR_UNKNOWN, bytes_written<EOL><DEDENT><DEDENT>"""<STR_LIT>"""<EOL>del self.out_packet[<NUM_LIT:0>]<EOL>self.last_msg_out = time.time()<EOL><DEDENT>return NC.ERR_SUCCESS, bytes_written<EOL>
|
Write packet to network.
|
f3688:c0:m6
|
def packet_read(self):
|
bytes_received = <NUM_LIT:0><EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>if self.in_packet.command == <NUM_LIT:0>:<EOL><INDENT>ba_data, errnum, errmsg = nyamuk_net.read(self.sock, <NUM_LIT:1>)<EOL>if errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:1>:<EOL><INDENT>bytes_received += <NUM_LIT:1><EOL>byte = ba_data[<NUM_LIT:0>]<EOL>self.in_packet.command = byte<EOL>if self.as_broker:<EOL><INDENT>if self.bridge is None and self.state == NC.CS_NEW and (byte & <NUM_LIT>) != NC.CMD_CONNECT:<EOL><INDENT>print("<STR_LIT>")<EOL>return NC.ERR_PROTOCOL, bytes_received<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if errnum == errno.EAGAIN or errnum == errno.EWOULDBLOCK:<EOL><INDENT>return NC.ERR_SUCCESS, bytes_received<EOL><DEDENT>elif errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:0> or errnum == errno.ECONNRESET:<EOL><INDENT>return NC.ERR_CONN_LOST, bytes_received<EOL><DEDENT>else:<EOL><INDENT>evt = event.EventNeterr(errnum, errmsg)<EOL>self.push_event(evt)<EOL>return NC.ERR_UNKNOWN, bytes_received<EOL><DEDENT><DEDENT><DEDENT>if not self.in_packet.have_remaining:<EOL><INDENT>loop_flag = True<EOL>while loop_flag:<EOL><INDENT>ba_data, errnum, errmsg = nyamuk_net.read(self.sock, <NUM_LIT:1>)<EOL>if errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:1>: <EOL><INDENT>byte = ba_data[<NUM_LIT:0>]<EOL>bytes_received += <NUM_LIT:1><EOL>self.in_packet.remaining_count += <NUM_LIT:1><EOL>if self.in_packet.remaining_count > <NUM_LIT:4>:<EOL><INDENT>return NC.ERR_PROTOCOL, bytes_received<EOL><DEDENT>self.in_packet.remaining_length += (byte & <NUM_LIT>) * self.in_packet.remaining_mult<EOL>self.in_packet.remaining_mult *= <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>if errnum == errno.EAGAIN or errnum == errno.EWOULDBLOCK:<EOL><INDENT>return NC.ERR_SUCCESS, bytes_received<EOL><DEDENT>elif errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:0> or errnum == errno.ECONNRESET:<EOL><INDENT>return NC.ERR_CONN_LOST, bytes_received<EOL><DEDENT>else:<EOL><INDENT>evt = event.EventNeterr(errnum, errmsg)<EOL>self.push_event(evt)<EOL>return NC.ERR_UNKNOWN, bytes_received<EOL><DEDENT><DEDENT>if (byte & <NUM_LIT>) == <NUM_LIT:0>:<EOL><INDENT>loop_flag = False<EOL><DEDENT><DEDENT>if self.in_packet.remaining_length > <NUM_LIT:0>:<EOL><INDENT>self.in_packet.payload = bytearray(self.in_packet.remaining_length)<EOL>if self.in_packet.payload is None:<EOL><INDENT>return NC.ERR_NO_MEM, bytes_received<EOL><DEDENT>self.in_packet.to_process = self.in_packet.remaining_length<EOL><DEDENT>self.in_packet.have_remaining = True<EOL><DEDENT>if self.in_packet.to_process > <NUM_LIT:0>:<EOL><INDENT>ba_data, errnum, errmsg = nyamuk_net.read(self.sock, self.in_packet.to_process)<EOL>if errnum == <NUM_LIT:0> and len(ba_data) > <NUM_LIT:0>:<EOL><INDENT>readlen = len(ba_data)<EOL>bytes_received += readlen<EOL>for idx in range(<NUM_LIT:0>, readlen):<EOL><INDENT>self.in_packet.payload[self.in_packet.pos] = ba_data[idx]<EOL>self.in_packet.pos += <NUM_LIT:1><EOL>self.in_packet.to_process -= <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if errnum == errno.EAGAIN or errnum == errno.EWOULDBLOCK:<EOL><INDENT>return NC.ERR_SUCCESS, bytes_received<EOL><DEDENT>elif errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:0> or errnum == errno.ECONNRESET:<EOL><INDENT>return NC.ERR_CONN_LOST, bytes_received<EOL><DEDENT>else:<EOL><INDENT>evt = event.EventNeterr(errnum, errmsg)<EOL>self.push_event(evt)<EOL>return NC.ERR_UNKNOWN, bytes_received<EOL><DEDENT><DEDENT><DEDENT>self.in_packet.pos = <NUM_LIT:0><EOL>ret = self.packet_handle()<EOL>self.in_packet.packet_cleanup()<EOL>self.last_msg_in = time.time()<EOL>return ret, bytes_received<EOL>
|
Read packet from network.
|
f3688:c0:m7
|
def socket_close(self):
|
if self.sock != NC.INVALID_SOCKET:<EOL><INDENT>self.sock.close()<EOL><DEDENT>self.sock = NC.INVALID_SOCKET<EOL>
|
Close our socket.
|
f3688:c0:m8
|
def build_publish_pkt(self, mid, topic, payload, qos, retain, dup):
|
pkt = MqttPkt()<EOL>payloadlen = len(payload)<EOL>packetlen = <NUM_LIT:2> + len(topic) + payloadlen<EOL>if qos > <NUM_LIT:0>:<EOL><INDENT>packetlen += <NUM_LIT:2><EOL><DEDENT>pkt.mid = mid<EOL>pkt.command = NC.CMD_PUBLISH | ((dup & <NUM_LIT>) << <NUM_LIT:3>) | (qos << <NUM_LIT:1>) | retain<EOL>pkt.remaining_length = packetlen<EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret, None<EOL><DEDENT>pkt.write_string(topic)<EOL>if qos > <NUM_LIT:0>:<EOL><INDENT>pkt.write_uint16(mid)<EOL><DEDENT>if payloadlen > <NUM_LIT:0>:<EOL><INDENT>pkt.write_bytes(payload, payloadlen)<EOL><DEDENT>return NC.ERR_SUCCESS, pkt<EOL>
|
Build PUBLISH packet.
|
f3688:c0:m10
|
def send_simple_command(self, cmd):
|
pkt = MqttPkt()<EOL>pkt.command = cmd<EOL>pkt.remaining_length = <NUM_LIT:0><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>return self.packet_queue(pkt)<EOL>
|
Send simple mqtt commands.
|
f3688:c0:m11
|
def register(model):
|
moderator.register(model, Akismet)<EOL>
|
Just a wrapper around django_comments.moderation.register.
It's only argument is the model for comment moderation.
|
f3690:m0
|
def allow(self, comment, content_object, request):
|
POST = urlencode({<EOL>"<STR_LIT>": settings.AKISMET_BLOG.encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.ip_address,<EOL>"<STR_LIT>": request.META.get('<STR_LIT>', "<STR_LIT>").<EOL>encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": request.META.get('<STR_LIT>', "<STR_LIT>").<EOL>encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.user_name.encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.user_email.encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.user_url.encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.comment.encode("<STR_LIT:utf-8>")})<EOL>connection = HTTPConnection(AKISMET_URL, AKISMET_PORT)<EOL>connection.request("<STR_LIT:POST>", AKISMET_PATH, POST,<EOL>{"<STR_LIT>": AKISMET_USERAGENT,<EOL>"<STR_LIT>":"<STR_LIT>"<EOL>})<EOL>response = connection.getresponse()<EOL>status, result = response.status, response.read()<EOL>if result == "<STR_LIT:false>":<EOL><INDENT>return True<EOL><DEDENT>elif result == "<STR_LIT:true>" and settings.DISCARD_SPAM:<EOL><INDENT>return False<EOL><DEDENT>elif result == "<STR_LIT:true>":<EOL><INDENT>comment.is_removed = True<EOL>comment.is_public = False<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>raise AkismetError(status, result)<EOL><DEDENT>
|
Moderates comments.
|
f3690:c1:m0
|
def spammer_view(request):
|
<EOL>context = RequestContext(request, {})<EOL>template = Template("<STR_LIT>")<EOL>response = HttpResponse(template.render(context))<EOL>response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True,<EOL>expires=datetime.now()+timedelta(days=<NUM_LIT>))<EOL>if DJANGOSPAM_LOG:<EOL><INDENT>log("<STR_LIT>", request.method, request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>"))<EOL><DEDENT>return response<EOL>
|
View for setting cookies on spammers.
|
f3693:m0
|
def process_request(self, request):
|
if COOKIE_KEY in request.COOKIES andrequest.COOKIES[COOKIE_KEY] == COOKIE_SPAM:<EOL><INDENT>response = HttpResponse("<STR_LIT>")<EOL>response.status_code = <NUM_LIT><EOL>if DJANGOSPAM_LOG:<EOL><INDENT>logger.log("<STR_LIT>", request.method,<EOL>request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>"))<EOL><DEDENT>return response<EOL><DEDENT>if DJANGOSPAM_LOG:<EOL><INDENT>logger.log("<STR_LIT>", request.method, request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>"))<EOL><DEDENT>return None<EOL>
|
Discovers if a request is from a knwon spam bot and denies access.
|
f3694:c0:m0
|
def process_response(self, request, response):
|
if COOKIE_KEY not in request.COOKIES:<EOL><INDENT>response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True,<EOL>expires=datetime.now()+timedelta(days=<NUM_LIT:30>))<EOL>if DJANGOSPAM_LOG:<EOL><INDENT>logger.log("<STR_LIT>", request.method, request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>")) <EOL><DEDENT><DEDENT>return response<EOL>
|
Sets "Ok" cookie on unknown users.
|
f3694:c0:m1
|
def register(model):
|
moderator.register(model, CookieModerator)<EOL>
|
Just a wrapper around django_comments.moderation.register.
It's only argument is the model for comment moderation.
|
f3695:m0
|
def allow(self, comment, content_object, request):
|
<EOL>if settings.COOKIE_KEY not in request.COOKIESand (settings.DISCARD_SPAM or settings.DISCARD_NO_COOKIE):<EOL><INDENT>return False<EOL><DEDENT>elif settings.COOKIE_KEY not in request.COOKIES:<EOL><INDENT>comment.is_removed = True<EOL>comment.is_public = False<EOL>return True<EOL><DEDENT>return True<EOL>
|
Tests comment post requests for the djangospam cookie.
|
f3695:c0:m0
|
def log(ltype, method, page, user_agent):
|
try:<EOL><INDENT>f = open(settings.DJANGOSPAM_LOG, "<STR_LIT:a>")<EOL>f.write("<STR_LIT>" %(datetime.datetime.now(), ltype, method, page, user_agent))<EOL>f.close()<EOL><DEDENT>except:<EOL><INDENT>if settings.DJANGOSPAM_FAIL_ON_LOG:<EOL><INDENT>exc_type, exc_value = sys.exc_info()[:<NUM_LIT:2>]<EOL>raise LogError(exc_type, exc_value)<EOL><DEDENT><DEDENT>
|
Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>"
|
f3698:m0
|
def __init__(self, data):
|
self.data = data<EOL>
|
: param data: :type list of lists
Example usage:
data = [
['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
['2004', 1000, 400, 100, 600],
['2005', 1170, 460, 120, 310],
['2006', 660, 1120, 50, -460],
['2007', 1030, 540, 100, 200],
]
sd = SimpleDataSource(data)
|
f3701:c0:m0
|
def get_first_column(self):
|
data_not_header = self.data[<NUM_LIT:1>:]<EOL>return [el[<NUM_LIT:0>] for el in data_not_header]<EOL>
|
Get the first column. Generally would be the x axis.
: return: :type list of strings
Example:
For the example shown in __init__, it would return the following:
['2004', '2005', '2006', '2007']
|
f3701:c0:m3
|
def __init__(self, queryset, fields=None):
|
self.queryset = queryset<EOL>if fields:<EOL><INDENT>self.fields = fields<EOL><DEDENT>else:<EOL><INDENT>self.fields = [el.name for el in self.queryset.model._meta.fields]<EOL><DEDENT>self.data = self.create_data()<EOL>
|
: param queryset: :type Django ORM queryset
: param fields: :type list of strings
Example usage:
queryset = Account.objects.all()
mds = ModelDataSource(queryset, fields=['year', 'sales', 'expenses'])
# This assumes the following model Account:
class Account(models.Model):
year = models.IntegerField()
sales = models.DecimalField()
expenses = models.DecimalField()
profit = models.DecimalField()
|
f3702:c0:m0
|
def get_data(self):
|
raise GraphosException("<STR_LIT>")<EOL>
|
Get all the data. Subclasses should override this
|
f3703:c0:m1
|
def get_header(self):
|
raise GraphosException("<STR_LIT>")<EOL>
|
Get the header - First row. Subclasses should override this
|
f3703:c0:m2
|
def get_first_column(self):
|
raise GraphosException("<STR_LIT>")<EOL>
|
Get the first column. Generally would be the x axis.
Subclasses should override this
|
f3703:c0:m3
|
def __init__(self, csv_file, fields=None):
|
reader = csv.reader(csv_file)<EOL>data =[row for row in reader]<EOL>self.data = data<EOL>self.fields = fields<EOL>
|
csv_file: A file like object which should be charted
|
f3704:c0:m0
|
def get_series(self):
|
data = self.get_data()<EOL>series_names = data[<NUM_LIT:0>][<NUM_LIT:1>:]<EOL>serieses = []<EOL>options = self.get_options()<EOL>if '<STR_LIT>' in options:<EOL><INDENT>data = self.get_data()<EOL>annotation_list = options['<STR_LIT>']<EOL>for i, name in enumerate(series_names):<EOL><INDENT>new_data = []<EOL>if name in annotation_list:<EOL><INDENT>data_list = column(data, i + <NUM_LIT:1>)[<NUM_LIT:1>:]<EOL>for k in data_list:<EOL><INDENT>temp_data = {}<EOL>for j in annotation_list[name]:<EOL><INDENT>if k == j['<STR_LIT:id>']:<EOL><INDENT>temp_data['<STR_LIT:y>'] = k<EOL>temp_data['<STR_LIT>'] = {'<STR_LIT>': True, '<STR_LIT>': j['<STR_LIT:value>']}<EOL><DEDENT>else:<EOL><INDENT>temp_data['<STR_LIT:y>'] = k<EOL><DEDENT><DEDENT>new_data.append(temp_data)<EOL><DEDENT>series = {"<STR_LIT:name>": name, "<STR_LIT:data>": new_data}<EOL><DEDENT>else:<EOL><INDENT>series = {"<STR_LIT:name>": name, "<STR_LIT:data>": column(data, i + <NUM_LIT:1>)[<NUM_LIT:1>:]}<EOL><DEDENT>if '<STR_LIT>' in options and len(options['<STR_LIT>']) > i:<EOL><INDENT>series['<STR_LIT>'] = options['<STR_LIT>'][i]<EOL><DEDENT>serieses.append(series)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for i, name in enumerate(series_names):<EOL><INDENT>series = {"<STR_LIT:name>": name, "<STR_LIT:data>": column(data, i+<NUM_LIT:1>)[<NUM_LIT:1>:]}<EOL>if '<STR_LIT>' in options and len(options['<STR_LIT>']) > i:<EOL><INDENT>series['<STR_LIT>'] = options['<STR_LIT>'][i]<EOL><DEDENT>serieses.append(series)<EOL><DEDENT><DEDENT>serieses = self.add_series_options(serieses)<EOL>return serieses<EOL>
|
Example usage:
data = [
['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
['2004', 1000, 400, 100, 600],
['2005', 1170, 460, 120, 310],
['2006', 660, 1120, 50, -460],
['2007', 1030, 540, 100, 200],
]
sd = SimpleDataSource(data)
hc = BaseHighCharts(sd)
hc.get_series() would be [{"name": "Sales", "data": [1000, 1170, 660, 1030]}, {"name": "Expenses", "data": [400, 460, 1120, 540]} ....]
|
f3710:c0:m2
|
def get_categories(self):
|
return column(self.get_data(), <NUM_LIT:0>)[<NUM_LIT:1>:]<EOL>
|
This would return ['2004', '2005', '2006', '2007']
|
f3710:c0:m5
|
def get_series(self):
|
if self.series_type == '<STR_LIT>':<EOL><INDENT>serieses = self.calculate_single_series()<EOL><DEDENT>else:<EOL><INDENT>serieses = self.calculate_multi_series()<EOL><DEDENT>return serieses<EOL>
|
Different serieses should come up based on different data formats passed.
1. Single series
This would be a choropleth map where the color intensity of different regions/polygons
differ based on the integer values in series. Two things are important here
a: It works with a colorAxis
b: First series i.e second column of tabular data must be integer.
2. Multiple series
Example
State Winner Seats
Orissa BJP 5
Bihar RJD 10
Assam BJP 7
Meghalaya AAP 12
Manipur AAP 4
Punjab AAP 4
In this case all states won by AAP make up one series and will be colored in a particular color.
Then all states won by BJP will be colored in a particular color. This color will be different from AAP color.
But colorAxis doesn't make sense here. It's not a choropleth map. But colorAxes(not colorAxis) could make senese here, i.e set color intensities for different serieses. But highcharts doesn't allow setting colorAxes, i.e color intensities for different serieses.
Graphos internally finds out all the distinct entries of second column of tabular data and created different serieses for different states.
|
f3710:c11:m1
|
def __init__(self, data_source, html_id=None,<EOL>width=None, height=None,<EOL>options=None, encoder=GraphosEncoder,<EOL>*args, **kwargs):
|
self.data_source = data_source<EOL>self.html_id = html_id or get_random_string()<EOL>self.height = height or DEFAULT_HEIGHT<EOL>self.width = width or DEFAULT_WIDTH<EOL>self.options = options or {}<EOL>self.header = data_source.get_header()<EOL>self.encoder = encoder<EOL>self.context_data = kwargs<EOL>
|
: param data_source: :type graphos.sources.base.BaseDataSource subclass instance.
: param html_id: :type string: Id of the div where you would like chart to be rendered
: param width: :type integer: Width of the chart div
: param height: :type integer: Height of the chart div
|
f3712:c0:m0
|
def get_default_options(graph_type="<STR_LIT>"):
|
options = {"<STR_LIT>": {"<STR_LIT:%s>" % graph_type: {"<STR_LIT>": "<STR_LIT:true>"}},<EOL>"<STR_LIT>": {"<STR_LIT>": '<STR_LIT>'},<EOL>"<STR_LIT:title>": "<STR_LIT>"}<EOL>return options<EOL>
|
default options
|
f3717:m1
|
def get_db(db_name=None):
|
import pymongo<EOL>return pymongo.Connection(host=DB_HOST,<EOL>port=DB_PORT)[db_name]<EOL>
|
GetDB - simple function to wrap getting a database
connection from the connection pool.
|
f3717:m2
|
def find_package_data(<EOL>where='<STR_LIT:.>', package='<STR_LIT>',<EOL>exclude=standard_exclude,<EOL>exclude_directories=standard_exclude_directories,<EOL>only_in_packages=True,<EOL>show_ignored=True):
|
out = {}<EOL>stack = [(convert_path(where), '<STR_LIT>', package, only_in_packages)]<EOL>while stack:<EOL><INDENT>where, prefix, package, only_in_packages = stack.pop(<NUM_LIT:0>)<EOL>for name in os.listdir(where):<EOL><INDENT>fn = os.path.join(where, name)<EOL>if os.path.isdir(fn):<EOL><INDENT>bad_name = False<EOL>for pattern in exclude_directories:<EOL><INDENT>if (fnmatchcase(name, pattern)<EOL>or fn.lower() == pattern.lower()):<EOL><INDENT>bad_name = True<EOL>if show_ignored:<EOL><INDENT>print("<STR_LIT>" % (fn, pattern), file=sys.stderr)<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if bad_name:<EOL><INDENT>continue<EOL><DEDENT>if (os.path.isfile(os.path.join(fn, '<STR_LIT>'))<EOL>and not prefix):<EOL><INDENT>if not package:<EOL><INDENT>new_package = name<EOL><DEDENT>else:<EOL><INDENT>new_package = package + '<STR_LIT:.>' + name<EOL><DEDENT>stack.append((fn, '<STR_LIT>', new_package, False))<EOL><DEDENT>else:<EOL><INDENT>stack.append((fn, prefix + name + '<STR_LIT:/>', package, only_in_packages))<EOL><DEDENT><DEDENT>elif package or not only_in_packages:<EOL><INDENT>bad_name = False<EOL>for pattern in exclude:<EOL><INDENT>if (fnmatchcase(name, pattern)<EOL>or fn.lower() == pattern.lower()):<EOL><INDENT>bad_name = True<EOL>if show_ignored:<EOL><INDENT>print("<STR_LIT>" % (fn, pattern), file=sys.stderr)<EOL><DEDENT>break<EOL><DEDENT><DEDENT>if bad_name:<EOL><INDENT>continue<EOL><DEDENT>out.setdefault(package, []).append(prefix+name)<EOL><DEDENT><DEDENT><DEDENT>return out<EOL>
|
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won't be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren't
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
|
f3733:m2
|
def setUp(self):
|
self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL>
|
SetUp.
|
f3735:c0:m0
|
def setUp(self):
|
self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL>
|
SetUp.
|
f3735:c1:m0
|
def setUp(self):
|
self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL>self.start_date = '<STR_LIT>'<EOL>self.end_date = '<STR_LIT>'<EOL>self.keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>
|
SetUp.
|
f3735:c2:m0
|
def setUp(self):
|
self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>self.fields = ['<STR_LIT:Name>', '<STR_LIT>']<EOL>
|
SetUp.
|
f3736:c0:m0
|
def setUp(self):
|
self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>self.start_date = '<STR_LIT>'<EOL>self.end_date = '<STR_LIT>'<EOL>self.keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>
|
SetUp.
|
f3736:c1:m0
|
def setUp(self):
|
self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>os.makedirs('<STR_LIT>')<EOL>self.output_folder = '<STR_LIT>'<EOL>
|
SetUp.
|
f3736:c2:m0
|
def tearDown(self):
|
for root, dirs, files in os.walk(self.output_folder, topdown=False):<EOL><INDENT>for name in files:<EOL><INDENT>os.remove(os.path.join(root, name))<EOL><DEDENT>for name in dirs:<EOL><INDENT>os.rmdir(os.path.join(root, name))<EOL><DEDENT><DEDENT>os.rmdir(self.output_folder)<EOL>
|
Cleaning up.
|
f3736:c2:m3
|
def load_key(pubkey):
|
try:<EOL><INDENT>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT>except ValueError:<EOL><INDENT>pubkey = pubkey.replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT>
|
Load public RSA key, with work-around for keys using
incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
|
f3737:m0
|
def encrypt(pubkey, password):
|
key = load_key(pubkey)<EOL>encrypted_password = key.encrypt(password, PKCS1v15())<EOL>return base64.b64encode(encrypted_password)<EOL>
|
Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
|
f3737:m1
|
def fetch_public_key(repo):
|
keyurl = '<STR_LIT>'.format(repo)<EOL>data = json.loads(urlopen(keyurl).read().decode())<EOL>if '<STR_LIT:key>' not in data:<EOL><INDENT>errmsg = "<STR_LIT>".format(repo)<EOL>errmsg += "<STR_LIT>"<EOL>raise ValueError(errmsg)<EOL><DEDENT>return data['<STR_LIT:key>']<EOL>
|
Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
|
f3737:m2
|
def prepend_line(filepath, line):
|
with open(filepath) as f:<EOL><INDENT>lines = f.readlines()<EOL><DEDENT>lines.insert(<NUM_LIT:0>, line)<EOL>with open(filepath, '<STR_LIT:w>') as f:<EOL><INDENT>f.writelines(lines)<EOL><DEDENT>
|
Rewrite a file adding a line to its beginning.
|
f3737:m3
|
def update_travis_deploy_password(encrypted_password):
|
config = load_yaml_config(TRAVIS_CONFIG_FILE)<EOL>config['<STR_LIT>']['<STR_LIT:password>'] = dict(secure=encrypted_password)<EOL>save_yaml_config(TRAVIS_CONFIG_FILE, config)<EOL>line = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>prepend_line(TRAVIS_CONFIG_FILE, line)<EOL>
|
Update the deploy section of the .travis.yml file
to use the given encrypted password.
|
f3737:m6
|
def __validate_list(list_to_validate):
|
if not type(list_to_validate) is list:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" +<EOL>type(list_to_validate).__name__ + "<STR_LIT>"<EOL>)<EOL><DEDENT>
|
Validate list.
|
f3739:m0
|
def __validate_dates(start_date, end_date):
|
try:<EOL><INDENT>start_date = datetime.datetime.strptime(start_date, '<STR_LIT>')<EOL>end_date = datetime.datetime.strptime(end_date, '<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (end_date - start_date).days > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if (end_date - start_date).days < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>
|
Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year.
|
f3739:m1
|
def __yahoo_request(query):
|
query = quote(query)<EOL>url = '<STR_LIT>' + query +'<STR_LIT>'<EOL>response = urlopen(url).read()<EOL>return json.loads(response.decode('<STR_LIT:utf-8>'))['<STR_LIT>']['<STR_LIT>']<EOL>
|
Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL.
|
f3739:m2
|
def request_quotes(tickers_list, selected_columns=['<STR_LIT:*>']):
|
__validate_list(tickers_list)<EOL>__validate_list(selected_columns)<EOL>query = '<STR_LIT>'<EOL>query = query.format(<EOL>cols='<STR_LIT:U+002CU+0020>'.join(selected_columns),<EOL>vals='<STR_LIT:U+002CU+0020>'.join('<STR_LIT>'.format(s) for s in tickers_list)<EOL>)<EOL>response = __yahoo_request(query)<EOL>if not response:<EOL><INDENT>raise RequestError('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>if not type(response['<STR_LIT>']) is list:<EOL><INDENT>return [response['<STR_LIT>']]<EOL><DEDENT>return response['<STR_LIT>']<EOL>
|
Request Yahoo Finance recent quotes.
Returns quotes information from YQL. The columns to be requested are
listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more
information on YQL.
>>> request_quotes(['AAPL'], ['Name', 'PreviousClose'])
{
'PreviousClose': '95.60',
'Name': 'Apple Inc.'
}
:param table: Table name.
:type table: string
:param tickers_list: List of tickers that will be returned.
:type tickers_list: list of strings
:param selected_columns: List of columns to be returned, defaults to ['*']
:type selected_columns: list of strings, optional
:returns: Requested quotes.
:rtype: json
:raises: TypeError, TypeError
|
f3739:m3
|
def request_historical(ticker, start_date, end_date):
|
__validate_dates(start_date, end_date)<EOL>cols = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>query = '<STR_LIT>' +'<STR_LIT>' +'<STR_LIT>'<EOL>query = query.format(<EOL>cols='<STR_LIT:U+002CU+0020>'.join(cols),<EOL>ticker=ticker,<EOL>start_date=start_date,<EOL>end_date=end_date<EOL>)<EOL>response = __yahoo_request(query)<EOL>if not response:<EOL><INDENT>raise RequestError('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>if not type(response['<STR_LIT>']) is list:<EOL><INDENT>return [response['<STR_LIT>']]<EOL><DEDENT>return response['<STR_LIT>']<EOL>
|
Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retrieved. Information provided by YQL platform.
Check `here <http://goo.gl/8AROUD>`_ for more information on YQL.
.. warning:: Request limited to a period not greater than 366 days.
Use download_historical() to download the full historical data.
>>> request_historical('AAPL', '2016-03-01', '2016-03-02')
[
{
'Close': '100.75',
'Low': '99.639999',
'High': '100.889999',
'Adj_Close': '100.140301',
'Date': '2016-03-02',
'Open': '100.510002',
'Volume': '33169600'
},
{
'Close': '100.529999',
'Low': '97.419998',
'High': '100.769997',
'Adj_Close': '99.921631',
'Date': '2016-03-01',
'Open': '97.650002',
'Volume': '50407100'
}
]
:param start_date: Start date
:type start_date: string on the format of "yyyy-mm-dd"
:param end_date: End date
:type end_date: string on the format of "yyyy-mm-dd"
:returns: Daily historical information.
:rtype: list of dictionaries
|
f3739:m4
|
def download_historical(tickers_list, output_folder):
|
__validate_list(tickers_list)<EOL>for ticker in tickers_list:<EOL><INDENT>file_name = os.path.join(output_folder, ticker + '<STR_LIT>')<EOL>with open(file_name, '<STR_LIT:wb>') as f:<EOL><INDENT>base_url = '<STR_LIT>'<EOL>try:<EOL><INDENT>urlopen(base_url + ticker)<EOL>urlretrieve(base_url + ticker, f.name)<EOL><DEDENT>except:<EOL><INDENT>os.remove(file_name)<EOL>raise RequestError('<STR_LIT>' +<EOL>ticker + '<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>
|
Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:param tickers_list: List of tickers that will be returned.
:type tickers_list: list of strings
:param output_folder: Output folder path
:type output_folder: string
|
f3739:m5
|
def __init__(self, ticker):
|
self.__ticker = ticker<EOL>
|
Instantiate Stock class.
|
f3741:c0:m0
|
def __repr__(self):
|
return '<STR_LIT>'.format(ticker=self.__ticker)<EOL>
|
An unambiguous representation of a Stock's instance.
|
f3741:c0:m1
|
def __eq__(self, other):
|
if isinstance(other, Stock):<EOL><INDENT>return self.__repr__() == other.__repr__()<EOL><DEDENT>return False<EOL>
|
Equality comparison operator.
|
f3741:c0:m2
|
def __ne__(self, other):
|
return not self.__eq__() == other.__repr__()<EOL>
|
Inquality comparison operator.
|
f3741:c0:m3
|
def __hash__(self):
|
return hash(self.__repr__())<EOL>
|
Hash representation of a Stock's instance.
|
f3741:c0:m4
|
def get_ticker(self):
|
return self.__ticker<EOL>
|
Get stock's ticker.
>>> stock.get_ticker()
'AAPL'
:returns: Ticker.
:rtype: string
|
f3741:c0:m5
|
def set_ticker(self, ticker):
|
self.__ticker = ticker<EOL>
|
Set stock's ticker.
>>> stock.set_ticker('YHOO')
>>> print(stock)
<Stock YHOO>
:param ticker: Stock ticker in Yahoo Finances format.
:type ticker: string
|
f3741:c0:m6
|
def get_info(self):
|
keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:Name>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']<EOL>response = request_quotes([self.__ticker], keys)<EOL>return response<EOL>
|
Get all stock's information provided by Yahoo Finance.
There is no guarantee that all the fields will be available for all
stocks. That being said, the following fields will be retrieved by
this method as a python dictionary from YQL platform:
- Ask
- AverageDailyVolume
- Bid
- BookValue
- Change
- Change_PercentChange
- ChangeFromFiftydayMovingAverage
- ChangeFromTwoHundreddayMovingAverage
- ChangeFromYearHigh
- ChangeFromYearLow
- ChangeinPercent
- Currency
- DaysHigh
- DaysLow
- DaysRange
- DividendPayDate
- DividendShare
- DividendYield
- EarningsShare
- EBITDA
- EPSEstimateCurrentYear
- EPSEstimateNextQuarter
- EPSEstimateNextYear
- ExDividendDate
- FiftydayMovingAverage
- LastTradeDate
- LastTradePriceOnly
- LastTradeTime
- LastTradeWithTime
- MarketCapitalization
- Name
- OneyrTargetPrice
- Open
- PEGRatio
- PERatio
- PercebtChangeFromYearHigh
- PercentChange
- PercentChangeFromFiftydayMovingAverage
- PercentChangeFromTwoHundreddayMovingAverage
- PercentChangeFromYearLow
- PreviousClose
- PriceBook
- PriceEPSEstimateCurrentYear
- PriceEPSEstimateNextYear
- PriceSales
- ShortRatio
- StockExchange
- Symbol
- TwoHundreddayMovingAverage
- Volume
- YearHigh
- YearLow
- YearRange
Check `here <http://goo.gl/8AROUD>`_ for more information on YQL.
:returns: Dictionary with all the available information.
:rtype: dictionary
|
f3741:c0:m8
|
def get_historical(self, start_date, end_date):
|
return request_historical(self.__ticker, start_date, end_date)<EOL>
|
Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retrieved. Information provided by YQL platform.
Check `here <http://goo.gl/8AROUD>`_ for more information on YQL.
.. warning:: Request limited to a period not greater than 366 days.
Use download_historical() to download the full historical data.
>>> stock.get_historical('2016-03-01', '2016-03-02')
[
{
'Close': '100.75',
'Low': '99.639999',
'High': '100.889999',
'Adj_Close': '100.140301',
'Date': '2016-03-02',
'Open': '100.510002',
'Volume': '33169600'
},
{
'Close': '100.529999',
'Low': '97.419998',
'High': '100.769997',
'Adj_Close': '99.921631',
'Date': '2016-03-01',
'Open': '97.650002',
'Volume': '50407100'
}
]
:param start_date: Start date
:type start_date: string on the format of "yyyy-mm-dd"
:param end_date: End date
:type end_date: string on the format of "yyyy-mm-dd"
:returns: Daily historical information.
:rtype: list of dictionaries
|
f3741:c0:m9
|
def save_historical(self, output_folder):
|
download_historical([self.__ticker], output_folder)<EOL>
|
Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume.
Files will be saved to output_folder as <ticker>.csv.
:param output_folder: Output folder path
:type output_folder: string
|
f3741:c0:m10
|
def setUp(self):
|
base_dir = os.path.join(os.path.dirname(__file__), "<STR_LIT>",<EOL>"<STR_LIT>")<EOL>self.legacy_regex_1 = ['<STR_LIT>']<EOL>self.legacy_regex_2 = ['<STR_LIT>', '<STR_LIT>']<EOL>self.file_1 = base_dir + '<STR_LIT>'<EOL>self.file_2 = base_dir + '<STR_LIT>'<EOL>self.file_3 = base_dir + '<STR_LIT>'<EOL>
|
Setup.
|
f3747:c0:m0
|
def __init__(self):
|
self.queue = []<EOL>
|
Initialize an empty queue.
|
f3753:c0:m0
|
def __len__(self):
|
return len(self.queue)<EOL>
|
Length of the queue.
|
f3753:c0:m1
|
def dequeue(self):
|
return self.queue.pop()<EOL>
|
Remove one item from the queue.
|
f3753:c0:m2
|
def enqueue(self, *args, **kwargs):
|
self.queue.insert(<NUM_LIT:0>, args)<EOL>
|
Add items to the queue.
:param args: tuple is appended to list
:param kwargs: are ignored.
|
f3753:c0:m3
|
def _get_files_modified():
|
cmd = "<STR_LIT>"<EOL>_, files_modified, _ = run(cmd)<EOL>extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + ["<STR_LIT>"]]<EOL>test = "<STR_LIT>".format("<STR_LIT:|>".join(extensions))<EOL>return list(filter(lambda f: re.search(test, f), files_modified))<EOL>
|
Get the list of modified files that are Python or Jinja2.
|
f3756:m0
|
def _get_git_author():
|
_, stdout, _ = run("<STR_LIT>")<EOL>git_author = stdout[<NUM_LIT:0>]<EOL>return git_author[:git_author.find("<STR_LIT:>>") + <NUM_LIT:1>]<EOL>
|
Return the git author from the git variables.
|
f3756:m1
|
def _get_component(filename, default="<STR_LIT>"):
|
if hasattr(filename, "<STR_LIT>"):<EOL><INDENT>filename = filename.decode()<EOL><DEDENT>parts = filename.split(os.path.sep)<EOL>if len(parts) >= <NUM_LIT:3>:<EOL><INDENT>if parts[<NUM_LIT:1>] in "<STR_LIT>".split():<EOL><INDENT>return parts[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>if len(parts) >= <NUM_LIT:2>:<EOL><INDENT>if parts[<NUM_LIT:1>] in "<STR_LIT>".split():<EOL><INDENT>return parts[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if len(parts) >= <NUM_LIT:1>:<EOL><INDENT>if parts[<NUM_LIT:0>] in "<STR_LIT>".split():<EOL><INDENT>return parts[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>return default<EOL>
|
Get component name from filename.
|
f3756:m2
|
def _get_components(files):
|
return tuple(set(_get_component(f) for f in files))<EOL>
|
Compile the components list from the given files.
|
f3756:m3
|
def _prepare_commit_msg(tmp_file, author, files_modified=None, template=None):
|
files_modified = files_modified or []<EOL>template = template or "<STR_LIT>"<EOL>if hasattr(template, "<STR_LIT>"):<EOL><INDENT>template = template.decode()<EOL><DEDENT>with open(tmp_file, "<STR_LIT:r>", "<STR_LIT:utf-8>") as fh:<EOL><INDENT>contents = fh.readlines()<EOL>msg = filter(lambda x: not (x.startswith("<STR_LIT:#>") or x.isspace()),<EOL>contents)<EOL>if len(list(msg)):<EOL><INDENT>return<EOL><DEDENT><DEDENT>component = "<STR_LIT>"<EOL>components = _get_components(files_modified)<EOL>if len(components) == <NUM_LIT:1>:<EOL><INDENT>component = components[<NUM_LIT:0>]<EOL><DEDENT>elif len(components) > <NUM_LIT:1>:<EOL><INDENT>component = "<STR_LIT:/>".join(components)<EOL>contents.append(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>with open(tmp_file, "<STR_LIT:w>", "<STR_LIT:utf-8>") as fh:<EOL><INDENT>fh.write(template.format(component=component,<EOL>author=author,<EOL>extra="<STR_LIT>".join(contents)))<EOL><DEDENT>
|
Prepare the commit message in tmp_file.
It will build the commit message prefilling the component line, as well
as the signature using the git author and the modified files.
The file remains untouched if it is not empty.
|
f3756:m4
|
def _check_message(message, options):
|
options = options or dict()<EOL>options.update(get_options())<EOL>options.update(_read_local_kwalitee_configuration())<EOL>errors = check_message(message, **options)<EOL>if errors:<EOL><INDENT>for error in errors:<EOL><INDENT>print(error, file=sys.stderr)<EOL><DEDENT>return False<EOL><DEDENT>return True<EOL>
|
Checking the message and printing the errors.
|
f3756:m5
|
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def prepare_commit_msg_hook(argv):
|
options = get_options()<EOL>options.update(_read_local_kwalitee_configuration())<EOL>_prepare_commit_msg(argv[<NUM_LIT:1>],<EOL>_get_git_author(),<EOL>_get_files_modified(),<EOL>options.get('<STR_LIT>'))<EOL>return <NUM_LIT:0><EOL>
|
Hook: prepare a commit message.
|
f3756:m6
|
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def commit_msg_hook(argv):
|
with open(argv[<NUM_LIT:1>], "<STR_LIT:r>", "<STR_LIT:utf-8>") as fh:<EOL><INDENT>message = "<STR_LIT:\n>".join(filter(lambda x: not x.startswith("<STR_LIT:#>"),<EOL>fh.readlines()))<EOL><DEDENT>options = {"<STR_LIT>": True}<EOL>if not _check_message(message, options):<EOL><INDENT>click.echo(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>return <NUM_LIT:0><EOL>
|
Hook: for checking commit message (prevent commit).
|
f3756:m7
|
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def post_commit_hook(argv):
|
_, stdout, _ = run("<STR_LIT>")<EOL>message = "<STR_LIT:\n>".join(stdout)<EOL>options = {"<STR_LIT>": True}<EOL>if not _check_message(message, options):<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>return <NUM_LIT:1> <EOL><DEDENT>return <NUM_LIT:0><EOL>
|
Hook: for checking commit message.
|
f3756:m8
|
def _read_local_kwalitee_configuration(directory="<STR_LIT:.>"):
|
filepath = os.path.abspath(os.path.join(directory, '<STR_LIT>'))<EOL>data = {}<EOL>if os.path.exists(filepath):<EOL><INDENT>with open(filepath, '<STR_LIT:r>') as file_read:<EOL><INDENT>data = yaml.load(file_read.read())<EOL><DEDENT><DEDENT>return data<EOL>
|
Check if the repo has a ``.kwalitee.yaml`` file.
|
f3756:m9
|
def _pre_commit(files, options):
|
errors = []<EOL>tmpdir = mkdtemp()<EOL>files_to_check = []<EOL>try:<EOL><INDENT>for (file_, content) in files:<EOL><INDENT>dirname, filename = os.path.split(os.path.abspath(file_))<EOL>prefix = os.path.commonprefix([dirname, tmpdir])<EOL>dirname = os.path.relpath(dirname, start=prefix)<EOL>dirname = os.path.join(tmpdir, dirname)<EOL>if not os.path.isdir(dirname):<EOL><INDENT>os.makedirs(dirname)<EOL><DEDENT>filename = os.path.join(dirname, filename)<EOL>with open(filename, "<STR_LIT:wb>") as fh:<EOL><INDENT>fh.write(content)<EOL><DEDENT>files_to_check.append((file_, filename))<EOL><DEDENT>for (file_, filename) in files_to_check:<EOL><INDENT>errors += list(map(lambda x: "<STR_LIT>".format(file_, x),<EOL>check_file(filename, **options) or []))<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>shutil.rmtree(tmpdir, ignore_errors=True)<EOL><DEDENT>return errors<EOL>
|
Run the check on files of the added version.
They might be different than the one on disk. Equivalent than doing a git
stash, check, and git stash pop.
|
f3756:m10
|
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def pre_commit_hook(argv):
|
options = get_options()<EOL>options.update(_read_local_kwalitee_configuration())<EOL>files = []<EOL>for filename in _get_files_modified():<EOL><INDENT>_, stdout, _ = run("<STR_LIT>".format(filename), raw_output=True)<EOL>files.append((filename, stdout))<EOL><DEDENT>errors = _pre_commit(files, options)<EOL>for error in errors:<EOL><INDENT>if hasattr(error, "<STR_LIT>"):<EOL><INDENT>error = error.decode()<EOL><DEDENT>click.echo(error, file=sys.stderr)<EOL><DEDENT>if errors:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>return <NUM_LIT:0><EOL>
|
Hook: checking the staged files.
|
f3756:m11
|
def run(command, raw_output=False):
|
p = Popen(command.split(), stdout=PIPE, stderr=PIPE)<EOL>(stdout, stderr) = p.communicate()<EOL>if not raw_output:<EOL><INDENT>return (<EOL>p.returncode,<EOL>[line.rstrip() for line in stdout.decode("<STR_LIT:utf-8>").splitlines()],<EOL>[line.rstrip() for line in stderr.decode("<STR_LIT:utf-8>").splitlines()]<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return (p.returncode, stdout, stderr)<EOL><DEDENT>
|
Run a command using subprocess.
:param command: command line to be run
:type command: str
:param raw_output: does not attempt to convert the output as unicode
:type raw_output: bool
:return: error code, output (``stdout``) and error (``stderr``)
:rtype: tuple
|
f3756:m12
|
@click.group()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', envvar='<STR_LIT>', default='<STR_LIT:.>')<EOL>@click.pass_context<EOL>def prepare(ctx, repository):
|
ctx.obj = Repo(repository=repository)<EOL>
|
Assist with release process.
|
f3758:m0
|
def analyse_body_paragraph(body_paragraph, labels=None):
|
<EOL>for label, dummy in labels:<EOL><INDENT>if body_paragraph.startswith('<STR_LIT>' + label):<EOL><INDENT>return (label, body_paragraph[len(label) + <NUM_LIT:3>:].replace('<STR_LIT>',<EOL>'<STR_LIT:U+0020>'))<EOL><DEDENT><DEDENT>if body_paragraph.startswith('<STR_LIT>'):<EOL><INDENT>return (None, body_paragraph[<NUM_LIT:2>:].replace('<STR_LIT>', '<STR_LIT:U+0020>'))<EOL><DEDENT>return (None, None)<EOL>
|
Analyse commit body paragraph and return (label, message).
>>> analyse_body_paragraph('* BETTER Foo and bar.',
>>> ... {'BETTER': 'Improvements'})
('BETTER', 'Foo and bar.')
>>> analyse_body_paragraph('* Foo and bar.')
(None, 'Foo and bar.')
>>> analyse_body_paragraph('Foo and bar.')
(None, None)
|
f3758:m1
|
def remove_ticket_directives(message):
|
if message:<EOL><INDENT>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL><DEDENT>return message<EOL>
|
Remove ticket directives like "(closes #123).
>>> remove_ticket_directives('(closes #123)')
'(#123)'
>>> remove_ticket_directives('(foo #123)')
'(foo #123)'
|
f3758:m2
|
def amended_commits(commits):
|
<EOL>amended_sha1s = []<EOL>for message in commits.values():<EOL><INDENT>amended_sha1s.extend(re.findall(r'<STR_LIT>', message))<EOL><DEDENT>return amended_sha1s<EOL>
|
Return those git commit sha1s that have been amended later.
|
f3758:m3
|
def enrich_git_log_dict(messages, labels):
|
for commit_sha1, message in messages.items():<EOL><INDENT>component = None<EOL>title = message.split('<STR_LIT:\n>')[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>component, title = title.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>component = component.strip()<EOL><DEDENT>except ValueError:<EOL><INDENT>pass <EOL><DEDENT>paragraphs = [analyse_body_paragraph(p, labels)<EOL>for p in message.split('<STR_LIT>')]<EOL>yield {<EOL>'<STR_LIT>': commit_sha1,<EOL>'<STR_LIT>': component,<EOL>'<STR_LIT:title>': title.strip(),<EOL>'<STR_LIT>': re.findall(r'<STR_LIT>', message),<EOL>'<STR_LIT>': [<EOL>(label, remove_ticket_directives(message))<EOL>for label, message in paragraphs<EOL>],<EOL>}<EOL><DEDENT>
|
Enrich git log with related information on tickets.
|
f3758:m4
|
@prepare.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT:-c>', '<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>@pass_repo<EOL>def release(obj, commit='<STR_LIT>', components=False):
|
options = obj.options<EOL>repository = obj.repository<EOL>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _pygit2_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _git_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>click.echo('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', file=sys.stderr)<EOL>return <NUM_LIT:2><EOL><DEDENT><DEDENT>messages = OrderedDict([(getattr(c, sha), c.message) for c in commits])<EOL>for commit_sha1 in amended_commits(messages):<EOL><INDENT>if commit_sha1 in messages:<EOL><INDENT>del messages[commit_sha1]<EOL><DEDENT><DEDENT>full_messages = list(<EOL>enrich_git_log_dict(messages, options.get('<STR_LIT>'))<EOL>)<EOL>indent = '<STR_LIT:U+0020>' if components else '<STR_LIT>'<EOL>wrapper = textwrap.TextWrapper(<EOL>width=<NUM_LIT>,<EOL>initial_indent=indent + '<STR_LIT>',<EOL>subsequent_indent=indent + '<STR_LIT:U+0020>',<EOL>)<EOL>for label, section in options.get('<STR_LIT>'):<EOL><INDENT>if section is None:<EOL><INDENT>continue<EOL><DEDENT>bullets = []<EOL>for commit in full_messages:<EOL><INDENT>bullets += [<EOL>{'<STR_LIT:text>': bullet, '<STR_LIT>': commit['<STR_LIT>']}<EOL>for lbl, bullet in commit['<STR_LIT>']<EOL>if lbl == label and bullet is not None<EOL>]<EOL><DEDENT>if len(bullets) > <NUM_LIT:0>:<EOL><INDENT>click.echo(section)<EOL>click.echo('<STR_LIT>' * len(section))<EOL>click.echo()<EOL>if components:<EOL><INDENT>def key(cmt):<EOL><INDENT>return cmt['<STR_LIT>']<EOL><DEDENT>for component, bullets in itertools.groupby(<EOL>sorted(bullets, key=key), key):<EOL><INDENT>bullets = list(bullets)<EOL>if len(bullets) > <NUM_LIT:0>:<EOL><INDENT>click.echo('<STR_LIT>'.format(component))<EOL>click.echo()<EOL><DEDENT>for bullet in bullets:<EOL><INDENT>click.echo(wrapper.fill(bullet['<STR_LIT:text>']))<EOL><DEDENT>click.echo()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for bullet in bullets:<EOL><INDENT>click.echo(wrapper.fill(bullet['<STR_LIT:text>']))<EOL><DEDENT><DEDENT>click.echo()<EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL>
|
Generate release notes.
|
f3758:m5
|
@click.group()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', envvar='<STR_LIT>', default='<STR_LIT:.>')<EOL>@click.option('<STR_LIT:-c>', '<STR_LIT>', type=click.File('<STR_LIT:rb>'), default=None)<EOL>@click.pass_context<EOL>def check(ctx, repository, config):
|
ctx.obj = Repo(repository=repository, config=config)<EOL>
|
Check commits.
|
f3759:m0
|
def _is_merge_commit(commit):
|
if len(commit.parents) > <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
|
Test whether the commit is a merge commit or not.
|
f3759:m3
|
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def message(obj, commit='<STR_LIT>', skip_merge_commits=False):
|
from ..kwalitee import check_message<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.Fore.GREEN<EOL>red = colorama.Fore.RED<EOL><DEDENT>else:<EOL><INDENT>reset = yellow = green = red = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _pygit2_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _git_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>click.echo('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>file=sys.stderr)<EOL>return <NUM_LIT:2><EOL><DEDENT><DEDENT>template = '<STR_LIT>'.format(yellow, sha, reset)<EOL>template += '<STR_LIT>'<EOL>count = <NUM_LIT:0><EOL>ident = '<STR_LIT:U+0020>'<EOL>re_line = re.compile('<STR_LIT>', re.MULTILINE)<EOL>for commit in commits:<EOL><INDENT>if skip_merge_commits and _is_merge_commit(commit):<EOL><INDENT>continue<EOL><DEDENT>message = commit.message<EOL>errors = check_message(message, **options)<EOL>message = re.sub(re_line, ident, message)<EOL>if errors:<EOL><INDENT>count += <NUM_LIT:1><EOL>errors.insert(<NUM_LIT:0>, red)<EOL><DEDENT>else:<EOL><INDENT>errors = [green, '<STR_LIT>']<EOL><DEDENT>errors.append(reset)<EOL>click.echo(template.format(commit=commit,<EOL>message=message.encode('<STR_LIT:utf-8>'),<EOL>errors='<STR_LIT:\n>'.join(errors)))<EOL><DEDENT>if min(count, <NUM_LIT:1>):<EOL><INDENT>raise click.Abort<EOL><DEDENT>
|
Check the messages of the commits.
|
f3759:m4
|
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def files(obj, commit='<STR_LIT>', skip_merge_commits=False):
|
from ..kwalitee import check_file, SUPPORTED_FILES<EOL>from ..hooks import run<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.Fore.GREEN<EOL>red = colorama.Fore.RED<EOL><DEDENT>else:<EOL><INDENT>reset = yellow = green = red = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _pygit2_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _git_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>click.echo(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>file=sys.stderr)<EOL>click.exit(<NUM_LIT:2>)<EOL><DEDENT><DEDENT>template = '<STR_LIT>'.format(yellow, sha, reset)<EOL>template += '<STR_LIT>'<EOL>error_template = '<STR_LIT>'.format(reset, red)<EOL>no_errors = ['<STR_LIT>'.format(green, reset)]<EOL>msg_file_excluded = '<STR_LIT>'.format(yellow, reset)<EOL>def _get_files_modified(commit):<EOL><INDENT>"""<STR_LIT>"""<EOL>cmd = "<STR_LIT>"<EOL>_, files_modified, _ = run(cmd.format(commit))<EOL>extensions = [re.escape(ext)<EOL>for ext in list(SUPPORTED_FILES) + ["<STR_LIT>"]]<EOL>test = "<STR_LIT>".format("<STR_LIT:|>".join(extensions))<EOL>return list(filter(lambda f: re.search(test, f), files_modified))<EOL><DEDENT>def _ensure_directory(filename):<EOL><INDENT>dir_ = os.path.dirname(filename)<EOL>if not os.path.exists(dir_):<EOL><INDENT>os.makedirs(dir_)<EOL><DEDENT><DEDENT>def _format_errors(args):<EOL><INDENT>filename, errors = args<EOL>if errors is None:<EOL><INDENT>return msg_file_excluded.format(filename=filename)<EOL><DEDENT>else:<EOL><INDENT>return error_template.format(filename=filename, errors='<STR_LIT:\n>'.join(<EOL>errors if len(errors) else no_errors))<EOL><DEDENT><DEDENT>count = <NUM_LIT:0><EOL>ident = '<STR_LIT:U+0020>'<EOL>re_line = re.compile('<STR_LIT>', re.MULTILINE)<EOL>for commit in commits:<EOL><INDENT>if skip_merge_commits and _is_merge_commit(commit):<EOL><INDENT>continue<EOL><DEDENT>message = commit.message<EOL>commit_sha = getattr(commit, sha)<EOL>tmpdir = mkdtemp()<EOL>errors = {}<EOL>try:<EOL><INDENT>for filename in _get_files_modified(commit):<EOL><INDENT>cmd = "<STR_LIT>"<EOL>_, out, _ = run(cmd.format(commit_sha=commit_sha,<EOL>filename=filename),<EOL>raw_output=True)<EOL>destination = os.path.join(tmpdir, filename)<EOL>_ensure_directory(destination)<EOL>with open(destination, '<STR_LIT>') as f:<EOL><INDENT>f.write(out)<EOL><DEDENT>errors[filename] = check_file(destination, **options)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>shutil.rmtree(tmpdir, ignore_errors=True)<EOL><DEDENT>message = re.sub(re_line, ident, message)<EOL>if len(errors):<EOL><INDENT>count += <NUM_LIT:1><EOL>errors = map(_format_errors, errors.items())<EOL><DEDENT>else:<EOL><INDENT>errors = no_errors<EOL><DEDENT>click.echo(template.format(commit=commit,<EOL>message=message.encode('<STR_LIT:utf-8>'),<EOL>errors='<STR_LIT:\n>'.join(errors)))<EOL><DEDENT>if min(count, <NUM_LIT:1>):<EOL><INDENT>raise click.Abort<EOL><DEDENT>
|
Check the files of the commits.
|
f3759:m5
|
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def authors(obj, commit='<STR_LIT>', skip_merge_commits=False):
|
from ..kwalitee import check_author<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.Fore.GREEN<EOL>red = colorama.Fore.RED<EOL><DEDENT>else:<EOL><INDENT>reset = yellow = green = red = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _pygit2_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _git_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>click.echo('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>file=sys.stderr)<EOL>return <NUM_LIT:2><EOL><DEDENT><DEDENT>template = '<STR_LIT>'.format(yellow, sha, reset)<EOL>template += '<STR_LIT>'<EOL>count = <NUM_LIT:0><EOL>ident = '<STR_LIT:U+0020>'<EOL>re_line = re.compile('<STR_LIT>', re.MULTILINE)<EOL>for commit in commits:<EOL><INDENT>if skip_merge_commits and _is_merge_commit(commit):<EOL><INDENT>continue<EOL><DEDENT>message = commit.message<EOL>author = u'<STR_LIT>'.format(<EOL>commit).encode('<STR_LIT:utf-8>')<EOL>errors = check_author(author, **options)<EOL>message = re.sub(re_line, ident, message)<EOL>if errors:<EOL><INDENT>count += <NUM_LIT:1><EOL>errors.insert(<NUM_LIT:0>, red)<EOL><DEDENT>else:<EOL><INDENT>errors = [green, '<STR_LIT>']<EOL><DEDENT>errors.append(reset)<EOL>click.echo(template.format(commit=commit,<EOL>message=message.encode('<STR_LIT:utf-8>'),<EOL>errors='<STR_LIT:\n>'.join(errors)))<EOL><DEDENT>if min(count, <NUM_LIT:1>):<EOL><INDENT>raise click.Abort<EOL><DEDENT>
|
Check the authors of the commits.
|
f3759:m6
|
def __init__(self, repository='<STR_LIT:.>', config=None):
|
self.repository = repository<EOL>self.options = get_options()<EOL>self.options.update(_read_local_kwalitee_configuration(<EOL>directory=repository))<EOL>if config:<EOL><INDENT>self.options.update(<EOL>yaml.load(config.read())<EOL>)<EOL><DEDENT>
|
Store information about repository and get kwalitee options.
|
f3759:c0:m0
|
@click.group()<EOL>def main():
|
Perform various checks on a Git repository.
It eases developers life by automatizing boring stuff like commit message
checks or release notes generations.
|
f3760:m0
|
|
@click.group()<EOL>def githooks():
|
Install githooks for kwalitee checks.
|
f3761:m0
|
|
@githooks.command()<EOL>@click.option("<STR_LIT>", "<STR_LIT>", is_flag=True,<EOL>help="<STR_LIT>", default=False)<EOL>def install(force=False):
|
ret, git_dir, _ = run("<STR_LIT>")<EOL>if ret != <NUM_LIT:0>:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>git_dir = git_dir[<NUM_LIT:0>]<EOL>hooks_dir = os.path.join(git_dir, HOOK_PATH)<EOL>for hook in HOOKS:<EOL><INDENT>hook_path = os.path.join(hooks_dir, hook)<EOL>if os.path.exists(hook_path):<EOL><INDENT>if not force:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>".format(hook_path),<EOL>file=sys.stderr)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>os.unlink(hook_path)<EOL><DEDENT><DEDENT>source = os.path.join(sys.prefix, "<STR_LIT>", "<STR_LIT>" + hook)<EOL>os.symlink(os.path.normpath(source), hook_path)<EOL><DEDENT>return True<EOL>
|
Install git hooks.
|
f3761:m1
|
@githooks.command()<EOL>def uninstall():
|
ret, git_dir, _ = run("<STR_LIT>")<EOL>if ret != <NUM_LIT:0>:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>git_dir = git_dir[<NUM_LIT:0>]<EOL>hooks_dir = os.path.join(git_dir, HOOK_PATH)<EOL>for hook in HOOKS:<EOL><INDENT>hook_path = os.path.join(hooks_dir, hook)<EOL>if os.path.exists(hook_path):<EOL><INDENT>os.remove(hook_path)<EOL><DEDENT><DEDENT>return True<EOL>
|
Uninstall git hooks.
|
f3761:m2
|
def _check_1st_line(line, **kwargs):
|
components = kwargs.get("<STR_LIT>", ())<EOL>max_first_line = kwargs.get("<STR_LIT>", <NUM_LIT:50>)<EOL>errors = []<EOL>lineno = <NUM_LIT:1><EOL>if len(line) > max_first_line:<EOL><INDENT>errors.append(("<STR_LIT>", lineno, max_first_line, len(line)))<EOL><DEDENT>if line.endswith("<STR_LIT:.>"):<EOL><INDENT>errors.append(("<STR_LIT>", lineno))<EOL><DEDENT>if '<STR_LIT::>' not in line:<EOL><INDENT>errors.append(("<STR_LIT>", lineno))<EOL><DEDENT>else:<EOL><INDENT>component, msg = line.split('<STR_LIT::>', <NUM_LIT:1>)<EOL>if component not in components:<EOL><INDENT>errors.append(("<STR_LIT>", lineno, component))<EOL><DEDENT><DEDENT>return errors<EOL>
|
First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the first line
:type max_first_line: int
:return: errors as in (code, line number, *args)
:rtype: list
|
f3762:m0
|
def _check_bullets(lines, **kwargs):
|
max_length = kwargs.get("<STR_LIT:max_length>", <NUM_LIT>)<EOL>labels = {l for l, _ in kwargs.get("<STR_LIT>", tuple())}<EOL>def _strip_ticket_directives(line):<EOL><INDENT>return re.sub(r'<STR_LIT>', '<STR_LIT>', line)<EOL><DEDENT>errors = []<EOL>missed_lines = []<EOL>skipped = []<EOL>for (i, line) in enumerate(lines[<NUM_LIT:1>:]):<EOL><INDENT>if line.startswith('<STR_LIT:*>'):<EOL><INDENT>dot_found = False<EOL>if len(missed_lines) > <NUM_LIT:0>:<EOL><INDENT>errors.append(("<STR_LIT>", i + <NUM_LIT:2>))<EOL><DEDENT>if lines[i].strip() != '<STR_LIT>':<EOL><INDENT>errors.append(("<STR_LIT>", i + <NUM_LIT:2>))<EOL><DEDENT>if _strip_ticket_directives(line).endswith('<STR_LIT:.>'):<EOL><INDENT>dot_found = True<EOL><DEDENT>label = _re_bullet_label.search(line)<EOL>if label and label.group('<STR_LIT:label>') not in labels:<EOL><INDENT>errors.append(("<STR_LIT>", i + <NUM_LIT:2>, label.group('<STR_LIT:label>')))<EOL><DEDENT>for (j, indented) in enumerate(lines[i + <NUM_LIT:2>:]):<EOL><INDENT>if indented.strip() == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>if not re.search(r"<STR_LIT>", indented):<EOL><INDENT>errors.append(("<STR_LIT>", i + j + <NUM_LIT:3>))<EOL><DEDENT>else:<EOL><INDENT>skipped.append(i + j + <NUM_LIT:1>)<EOL>stripped_line = _strip_ticket_directives(indented)<EOL>if stripped_line.endswith('<STR_LIT:.>'):<EOL><INDENT>dot_found = True<EOL><DEDENT>elif stripped_line.strip():<EOL><INDENT>dot_found = False<EOL><DEDENT><DEDENT><DEDENT>if not dot_found:<EOL><INDENT>errors.append(("<STR_LIT>", i + <NUM_LIT:2>))<EOL><DEDENT><DEDENT>elif i not in skipped and line.strip():<EOL><INDENT>missed_lines.append((i + <NUM_LIT:2>, line))<EOL><DEDENT>if len(line) > max_length:<EOL><INDENT>errors.append(("<STR_LIT>", i + <NUM_LIT:2>, max_length, len(line)))<EOL><DEDENT><DEDENT>return errors, missed_lines<EOL>
|
Check that the bullet point list is well formatted.
Each bullet point shall have one space before and after it. The bullet
character is the "*" and there is no space before it but one after it
meaning the next line are starting with two blanks spaces to respect the
indentation.
:param lines: all the lines of the message
:type lines: list
:param max_lengths: maximum length of any line. (Default 72)
:return: errors as in (code, line number, *args)
:rtype: list
|
f3762:m1
|
def _check_signatures(lines, **kwargs):
|
trusted = kwargs.get("<STR_LIT>", ())<EOL>signatures = tuple(kwargs.get("<STR_LIT>", ()))<EOL>alt_signatures = tuple(kwargs.get("<STR_LIT>", ()))<EOL>min_reviewers = kwargs.get("<STR_LIT>", <NUM_LIT:3>)<EOL>matching = []<EOL>errors = []<EOL>signatures += alt_signatures<EOL>test_signatures = re.compile("<STR_LIT>".format("<STR_LIT:|>".join(signatures)))<EOL>test_alt_signatures = re.compile("<STR_LIT>".format("<STR_LIT:|>".join(alt_signatures)))<EOL>for i, line in lines:<EOL><INDENT>if signatures and test_signatures.search(line):<EOL><INDENT>if line.endswith("<STR_LIT:.>"):<EOL><INDENT>errors.append(("<STR_LIT>", i))<EOL><DEDENT>if not alt_signatures or not test_alt_signatures.search(line):<EOL><INDENT>matching.append(line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>errors.append(("<STR_LIT>", i))<EOL><DEDENT><DEDENT>if not matching:<EOL><INDENT>errors.append(("<STR_LIT>", <NUM_LIT:1>))<EOL>errors.append(("<STR_LIT>", <NUM_LIT:1>))<EOL><DEDENT>elif len(matching) < min_reviewers:<EOL><INDENT>pattern = re.compile('<STR_LIT:|>'.join(map(lambda x: '<STR_LIT:<>' + re.escape(x) + '<STR_LIT:>>',<EOL>trusted)))<EOL>trusted_matching = list(filter(None, map(pattern.search, matching)))<EOL>if len(trusted_matching) == <NUM_LIT:0>:<EOL><INDENT>errors.append(("<STR_LIT>", <NUM_LIT:1>))<EOL><DEDENT><DEDENT>return errors<EOL>
|
Check that the signatures are valid.
There should be at least three signatures. If not, one of them should be a
trusted developer/reviewer.
Formatting supported being: [signature] full name <email@address>
:param lines: lines (lineno, content) to verify.
:type lines: list
:param signatures: list of supported signature
:type signatures: list
:param alt_signatures: list of alternative signatures, not counted
:type alt_signatures: list
:param trusted: list of trusted reviewers, the e-mail address.
:type trusted: list
:param min_reviewers: minimal number of reviewers needed. (Default 3)
:type min_reviewers: int
:return: errors as in (code, line number, *args)
:rtype: list
|
f3762:m2
|
def check_message(message, **kwargs):
|
if kwargs.pop("<STR_LIT>", False):<EOL><INDENT>if not message or message.isspace():<EOL><INDENT>return []<EOL><DEDENT><DEDENT>lines = re.split(r"<STR_LIT>", message)<EOL>errors = _check_1st_line(lines[<NUM_LIT:0>], **kwargs)<EOL>err, signature_lines = _check_bullets(lines, **kwargs)<EOL>errors += err<EOL>errors += _check_signatures(signature_lines, **kwargs)<EOL>def _format(code, lineno, args):<EOL><INDENT>return "<STR_LIT>".format(lineno,<EOL>code,<EOL>_messages_codes[code].format(*args))<EOL><DEDENT>return list(map(lambda x: _format(x[<NUM_LIT:0>], x[<NUM_LIT:1>], x[<NUM_LIT:2>:]),<EOL>sorted(errors, key=lambda x: x[<NUM_LIT:0>])))<EOL>
|
Check the message format.
Rules:
- the first line must start by a component name
- and a short description (52 chars),
- then bullet points are expected
- and finally signatures.
:param components: compontents, e.g. ``('auth', 'utils', 'misc')``
:type components: `list`
:param signatures: signatures, e.g. ``('Signed-off-by', 'Reviewed-by')``
:type signatures: `list`
:param alt_signatures: alternative signatures, e.g. ``('Tested-by',)``
:type alt_signatures: `list`
:param trusted: optional list of reviewers, e.g. ``('john.doe@foo.org',)``
:type trusted: `list`
:param max_length: optional maximum line length (by default: 72)
:type max_length: int
:param max_first_line: optional maximum first line length (by default: 50)
:type max_first_line: int
:param allow_empty: optional way to allow empty message (by default: False)
:type allow_empty: bool
:return: errors sorted by line number
:rtype: `list`
|
f3762:m3
|
def _register_pyflakes_check():
|
from flake8_isort import Flake8Isort<EOL>from flake8_blind_except import check_blind_except<EOL>codes = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>}<EOL>for name, obj in vars(pyflakes.messages).items():<EOL><INDENT>if name[<NUM_LIT:0>].isupper() and obj.message:<EOL><INDENT>obj.tpl = "<STR_LIT>".format(codes.get(name, "<STR_LIT>"), obj.message)<EOL><DEDENT><DEDENT>pep8.register_check(_PyFlakesChecker, codes=['<STR_LIT:F>'])<EOL>parser = pep8.get_parser('<STR_LIT>', '<STR_LIT>')<EOL>Flake8Isort.add_options(parser)<EOL>options, args = parser.parse_args([])<EOL>pep8.register_check(Flake8Isort, codes=['<STR_LIT:I>'])<EOL>pep8.register_check(check_blind_except, codes=['<STR_LIT>'])<EOL>
|
Register the pyFlakes checker into PEP8 set of checks.
|
f3762:m4
|
def is_file_excluded(filename, excludes):
|
<EOL>return any([exclude and re.match(exclude, filename) is not None<EOL>for exclude in excludes])<EOL>
|
Check if the file should be excluded.
:param filename: file name
:param excludes: list of regex to match
:return: True if the file should be excluded
|
f3762:m5
|
def check_pep8(filename, **kwargs):
|
options = {<EOL>"<STR_LIT:ignore>": kwargs.get("<STR_LIT:ignore>"),<EOL>"<STR_LIT>": kwargs.get("<STR_LIT>"),<EOL>}<EOL>if not _registered_pyflakes_check and kwargs.get("<STR_LIT>", True):<EOL><INDENT>_register_pyflakes_check()<EOL><DEDENT>checker = pep8.Checker(filename, reporter=_Report, **options)<EOL>checker.check_all()<EOL>errors = []<EOL>for error in sorted(checker.report.errors, key=lambda x: x[<NUM_LIT:0>]):<EOL><INDENT>errors.append("<STR_LIT>".format(*error))<EOL><DEDENT>return errors<EOL>
|
Perform static analysis on the given file.
:param filename: path of file to check.
:type filename: str
:param ignore: codes to ignore, e.g. ``('E111', 'E123')``
:type ignore: `list`
:param select: codes to explicitly select.
:type select: `list`
:param pyflakes: run the pyflakes checks too (default ``True``)
:type pyflakes: bool
:return: errors
:rtype: `list`
.. seealso:: :py:class:`pycodestyle.Checker`
|
f3762:m6
|
def check_pydocstyle(filename, **kwargs):
|
ignore = kwargs.get("<STR_LIT:ignore>")<EOL>match = kwargs.get("<STR_LIT>", None)<EOL>match_dir = kwargs.get("<STR_LIT>", None)<EOL>errors = []<EOL>if match and not re.match(match, os.path.basename(filename)):<EOL><INDENT>return errors<EOL><DEDENT>if match_dir:<EOL><INDENT>path = os.path.split(os.path.abspath(filename))[<NUM_LIT:0>]<EOL>while path != "<STR_LIT:/>":<EOL><INDENT>path, dirname = os.path.split(path)<EOL>if not re.match(match_dir, dirname):<EOL><INDENT>return errors<EOL><DEDENT><DEDENT><DEDENT>checker = pydocstyle.PEP257Checker()<EOL>with open(filename) as fp:<EOL><INDENT>try:<EOL><INDENT>for error in checker.check_source(fp.read(), filename):<EOL><INDENT>if ignore is None or error.code not in ignore:<EOL><INDENT>message = re.sub("<STR_LIT>",<EOL>r"<STR_LIT>",<EOL>error.message)<EOL>errors.append("<STR_LIT>".format(error.line, message))<EOL><DEDENT><DEDENT><DEDENT>except tokenize.TokenError as e:<EOL><INDENT>errors.append("<STR_LIT>".format(e.args[<NUM_LIT:0>], *e.args[<NUM_LIT:1>]))<EOL><DEDENT>except pydocstyle.AllError as e:<EOL><INDENT>errors.append(str(e))<EOL><DEDENT><DEDENT>return errors<EOL>
|
Perform static analysis on the given file docstrings.
:param filename: path of file to check.
:type filename: str
:param ignore: codes to ignore, e.g. ('D400',)
:type ignore: `list`
:param match: regex the filename has to match to be checked
:type match: str
:param match_dir: regex everydir in path should match to be checked
:type match_dir: str
:return: errors
:rtype: `list`
.. seealso::
`PyCQA/pydocstyle <https://github.com/GreenSteam/pydocstyle/>`_
|
f3762:m7
|
def check_license(filename, **kwargs):
|
year = kwargs.pop("<STR_LIT>", datetime.now().year)<EOL>python_style = kwargs.pop("<STR_LIT>", True)<EOL>ignores = kwargs.get("<STR_LIT:ignore>")<EOL>template = "<STR_LIT>"<EOL>if python_style:<EOL><INDENT>re_comment = re.compile(r"<STR_LIT>")<EOL>starter = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>re_comment = re.compile(r"<STR_LIT>")<EOL>starter = "<STR_LIT>"<EOL><DEDENT>errors = []<EOL>lines = []<EOL>file_is_empty = False<EOL>license = "<STR_LIT>"<EOL>lineno = <NUM_LIT:0><EOL>try:<EOL><INDENT>with codecs.open(filename, "<STR_LIT:r>", "<STR_LIT:utf-8>") as fp:<EOL><INDENT>line = fp.readline()<EOL>blocks = []<EOL>while re_comment.match(line):<EOL><INDENT>if line.startswith(starter):<EOL><INDENT>line = line[len(starter):].lstrip()<EOL>blocks.append(line)<EOL>lines.append((lineno, line.strip()))<EOL><DEDENT>lineno, line = lineno + <NUM_LIT:1>, fp.readline()<EOL><DEDENT>file_is_empty = line == "<STR_LIT>"<EOL>license = "<STR_LIT>".join(blocks)<EOL><DEDENT><DEDENT>except UnicodeDecodeError:<EOL><INDENT>errors.append((lineno + <NUM_LIT:1>, "<STR_LIT>", "<STR_LIT:utf-8>"))<EOL>license = "<STR_LIT>"<EOL><DEDENT>if file_is_empty and not license.strip():<EOL><INDENT>return errors<EOL><DEDENT>match_year = _re_copyright_year.search(license)<EOL>if match_year is None:<EOL><INDENT>errors.append((lineno + <NUM_LIT:1>, "<STR_LIT>"))<EOL><DEDENT>elif int(match_year.group("<STR_LIT>")) != year:<EOL><INDENT>theline = match_year.group(<NUM_LIT:0>)<EOL>lno = lineno<EOL>for no, l in lines:<EOL><INDENT>if theline.strip() == l:<EOL><INDENT>lno = no<EOL>break<EOL><DEDENT><DEDENT>errors.append((lno + <NUM_LIT:1>, "<STR_LIT>", year, match_year.group("<STR_LIT>")))<EOL><DEDENT>else:<EOL><INDENT>program_match = _re_program.search(license)<EOL>program_2_match = _re_program_2.search(license)<EOL>program_3_match = _re_program_3.search(license)<EOL>if program_match is None:<EOL><INDENT>errors.append((lineno, "<STR_LIT>"))<EOL><DEDENT>elif (program_2_match is None or<EOL>program_3_match is None or<EOL>(program_match.group("<STR_LIT>").upper() !=<EOL>program_2_match.group("<STR_LIT>").upper() !=<EOL>program_3_match.group("<STR_LIT>").upper())):<EOL><INDENT>errors.append((lineno, "<STR_LIT>"))<EOL><DEDENT><DEDENT>def _format_error(lineno, code, *args):<EOL><INDENT>return template.format(lineno, code,<EOL>_licenses_codes[code].format(*args))<EOL><DEDENT>def _filter_codes(error):<EOL><INDENT>if not ignores or error[<NUM_LIT:1>] not in ignores:<EOL><INDENT>return error<EOL><DEDENT><DEDENT>return list(map(lambda x: _format_error(*x),<EOL>filter(_filter_codes, errors)))<EOL>
|
Perform a license check on the given file.
The license format should be commented using # and live at the top of the
file. Also, the year should be the current one.
:param filename: path of file to check.
:type filename: str
:param year: default current year
:type year: int
:param ignore: codes to ignore, e.g. ``('L100', 'L101')``
:type ignore: `list`
:param python_style: False for JavaScript or CSS files
:type python_style: bool
:return: errors
:rtype: `list`
|
f3762:m8
|
def check_file(filename, **kwargs):
|
excludes = kwargs.get("<STR_LIT>", [])<EOL>errors = []<EOL>if is_file_excluded(filename, excludes):<EOL><INDENT>return None<EOL><DEDENT>if filename.endswith("<STR_LIT>"):<EOL><INDENT>if kwargs.get("<STR_LIT>", True):<EOL><INDENT>errors += check_pep8(filename, **kwargs)<EOL><DEDENT>if kwargs.get("<STR_LIT>", True):<EOL><INDENT>errors += check_pydocstyle(filename, **kwargs)<EOL><DEDENT>if kwargs.get("<STR_LIT>", True):<EOL><INDENT>errors += check_license(filename, **kwargs)<EOL><DEDENT><DEDENT>elif re.search("<STR_LIT>", filename):<EOL><INDENT>errors += check_license(filename, **kwargs)<EOL><DEDENT>elif re.search("<STR_LIT>", filename):<EOL><INDENT>errors += check_license(filename, python_style=False, **kwargs)<EOL><DEDENT>def try_to_int(value):<EOL><INDENT>try:<EOL><INDENT>return int(value.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>])<EOL><DEDENT>except ValueError:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT><DEDENT>return sorted(errors, key=try_to_int)<EOL>
|
Perform static analysis on the given file.
.. seealso::
- :data:`.SUPPORTED_FILES`
- :func:`.check_pep8`
- :func:`.check_pydocstyle`
- and :func:`.check_license`
:param filename: path of file to check.
:type filename: str
:return: errors sorted by line number or None if file is excluded
:rtype: `list`
|
f3762:m9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.