repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
asifpy/django-crudbuilder | crudbuilder/formset.py | BaseInlineFormset.construct_formset | python | def construct_formset(self):
if not self.inline_model or not self.parent_model:
msg = "Parent and Inline models are required in {}".format(self.__class__.__name__)
raise NotModelException(msg)
return inlineformset_factory(
self.parent_model,
self.inline_m... | Returns an instance of the inline formset | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L18-L29 | [
"def get_factory_kwargs(self):\n \"\"\"\n Returns the keyword arguments for calling the formset factory\n \"\"\"\n kwargs = {}\n kwargs.update({\n 'can_delete': self.can_delete,\n 'extra': self.extra,\n 'exclude': self.exclude,\n 'fields': self.fields,\n 'formfield_... | class BaseInlineFormset(object):
extra = 3
can_delete = True
inline_model = None
parent_model = None
exclude = []
fields = None
formfield_callback = None
fk_name = None
formset_class = None
child_form = None
def get_factory_kwargs(self):
"""
Returns the keyw... |
asifpy/django-crudbuilder | crudbuilder/formset.py | BaseInlineFormset.get_factory_kwargs | python | def get_factory_kwargs(self):
kwargs = {}
kwargs.update({
'can_delete': self.can_delete,
'extra': self.extra,
'exclude': self.exclude,
'fields': self.fields,
'formfield_callback': self.formfield_callback,
'fk_name': self.fk_name,
... | Returns the keyword arguments for calling the formset factory | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/formset.py#L31-L49 | null | class BaseInlineFormset(object):
extra = 3
can_delete = True
inline_model = None
parent_model = None
exclude = []
fields = None
formfield_callback = None
fk_name = None
formset_class = None
child_form = None
def construct_formset(self):
"""
Returns an instanc... |
asifpy/django-crudbuilder | crudbuilder/helpers.py | plural | python | def plural(text):
aberrant = {
'knife': 'knives',
'self': 'selves',
'elf': 'elves',
'life': 'lives',
'hoof': 'hooves',
'leaf': 'leaves',
'echo': 'echoes',
'embargo': 'embargoes',
'hero': 'heroes',
'potato': 'potatoes',
'tomato':... | >>> plural('activity')
'activities' | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L19-L80 | null |
import re
import string
import imp
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
# Django versions < 1.9
from django.utils.importlib import import_module
__all__ = ['plural', 'mixedToUnder', 'capword', 'lowerword', 'underToMixed']
# http://c... |
asifpy/django-crudbuilder | crudbuilder/helpers.py | mixedToUnder | python | def mixedToUnder(s): # pragma: no cover
if s.endswith('ID'):
return mixedToUnder(s[:-2] + "_id")
trans = _mixedToUnderRE.sub(mixedToUnderSub, s)
if trans.startswith('_'):
trans = trans[1:]
return trans | Sample:
>>> mixedToUnder("FooBarBaz")
'foo_bar_baz'
Special case for ID:
>>> mixedToUnder("FooBarID")
'foo_bar_id' | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L88-L103 | [
"def mixedToUnder(s): # pragma: no cover\n \"\"\"\n Sample:\n >>> mixedToUnder(\"FooBarBaz\")\n 'foo_bar_baz'\n\n Special case for ID:\n >>> mixedToUnder(\"FooBarID\")\n 'foo_bar_id'\n \"\"\"\n if s.endswith('ID'):\n return mixedToUnder(s[:-2] + \"_id\")\n trans... |
import re
import string
import imp
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
# Django versions < 1.9
from django.utils.importlib import import_module
__all__ = ['plural', 'mixedToUnder', 'capword', 'lowerword', 'underToMixed']
# http://c... |
asifpy/django-crudbuilder | crudbuilder/helpers.py | underToMixed | python | def underToMixed(name):
if name.endswith('_id'):
return underToMixed(name[:-3] + "ID")
return _underToMixedRE.sub(lambda m: m.group(0)[1].upper(),
name) | >>> underToMixed('some_large_model_name_perhaps')
'someLargeModelNamePerhaps'
>>> underToMixed('exception_for_id')
'exceptionForID' | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L132-L143 | [
"def underToMixed(name):\n \"\"\"\n >>> underToMixed('some_large_model_name_perhaps')\n 'someLargeModelNamePerhaps'\n\n >>> underToMixed('exception_for_id')\n 'exceptionForID'\n \"\"\"\n if name.endswith('_id'):\n return underToMixed(name[:-3] + \"ID\")\n return _underToMixedRE.sub(la... |
import re
import string
import imp
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
# Django versions < 1.9
from django.utils.importlib import import_module
__all__ = ['plural', 'mixedToUnder', 'capword', 'lowerword', 'underToMixed']
# http://c... |
asifpy/django-crudbuilder | crudbuilder/helpers.py | import_crud | python | def import_crud(app):
'''
Import crud module and register all model cruds which it contains
'''
try:
app_path = import_module(app).__path__
except (AttributeError, ImportError):
return None
try:
imp.find_module('crud', app_path)
except ImportError:
return No... | Import crud module and register all model cruds which it contains | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/helpers.py#L162-L179 | null |
import re
import string
import imp
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
# Django versions < 1.9
from django.utils.importlib import import_module
__all__ = ['plural', 'mixedToUnder', 'capword', 'lowerword', 'underToMixed']
# http://c... |
asifpy/django-crudbuilder | crudbuilder/abstract.py | BaseBuilder.get_model_class | python | def get_model_class(self):
try:
c = ContentType.objects.get(app_label=self.app, model=self.model)
except ContentType.DoesNotExist:
# try another kind of resolution
# fixes a situation where a proxy model is defined in some external app.
if django.VERSION >... | Returns model class | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/abstract.py#L53-L63 | null | class BaseBuilder(object):
def __init__(
self,
app,
model,
crud
):
self.model = model
self.app = app
self.crud = crud
self.custom_modelform = self._has_crud_attr('custom_modelform')
self.modelform_excludes = self._has_crud... |
asifpy/django-crudbuilder | crudbuilder/templatetags/crudbuilder.py | get_verbose_field_name | python | def get_verbose_field_name(instance, field_name):
fields = [field.name for field in instance._meta.fields]
if field_name in fields:
return instance._meta.get_field(field_name).verbose_name
else:
return field_name | Returns verbose_name for a field. | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/templatetags/crudbuilder.py#L63-L71 | null | import re
from math import floor
from django import template
from itertools import chain
from django.template.defaultfilters import stringfilter
from collections import namedtuple
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_modelform | python | def generate_modelform(self):
model_class = self.get_model_class
excludes = self.modelform_excludes if self.modelform_excludes else []
_ObjectForm = modelform_factory(model_class, exclude=excludes)
return _ObjectForm | Generate modelform from Django modelform_factory | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L58-L64 | null | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.get_template | python | def get_template(self, tname):
if self.custom_templates and self.custom_templates.get(tname, None):
return self.custom_templates.get(tname)
elif self.inlineformset:
return 'crudbuilder/inline/{}.html'.format(tname)
else:
return 'crudbuilder/instance/{}.html'.... | - Get custom template from CRUD class, if it is defined in it
- No custom template in CRUD class, then use the default template | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L66-L77 | null | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_list_view | python | def generate_list_view(self):
name = model_class_form(self.model + 'ListView')
list_args = dict(
model=self.get_model_class,
context_object_name=plural(self.model),
template_name=self.get_template('list'),
table_class=self.get_actual_table(),
... | Generate class based view for ListView | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L85-L111 | [
"def plural(text):\n \"\"\"\n >>> plural('activity')\n 'activities'\n \"\"\"\n aberrant = {\n 'knife': 'knives',\n 'self': 'selves',\n 'elf': 'elves',\n 'life': 'lives',\n 'hoof': 'hooves',\n 'leaf': 'leaves',\n 'echo': 'echoes',\n 'emba... | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_create_view | python | def generate_create_view(self):
name = model_class_form(self.model + 'CreateView')
create_args = dict(
form_class=self.get_actual_form('create'),
model=self.get_model_class,
template_name=self.get_template('create'),
permissions=self.view_permission('crea... | Generate class based view for CreateView | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L113-L141 | [
"def model_class_form(name):\n \"\"\"\n >>> model_class_form('foo_bar_baz')\n 'FooBarBaz'\n \"\"\"\n return capword(underToMixed(name))\n",
"def view_permission(self, view_type):\n if self.permissions:\n return self.permissions.get(view_type, None)\n else:\n return '{}.{}_{}'.fo... | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_detail_view | python | def generate_detail_view(self):
name = model_class_form(self.model + 'DetailView')
detail_args = dict(
detailview_excludes=self.detailview_excludes,
model=self.get_model_class,
template_name=self.get_template('detail'),
login_required=self.check_login_req... | Generate class based view for DetailView | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L143-L160 | [
"def model_class_form(name):\n \"\"\"\n >>> model_class_form('foo_bar_baz')\n 'FooBarBaz'\n \"\"\"\n return capword(underToMixed(name))\n",
"def view_permission(self, view_type):\n if self.permissions:\n return self.permissions.get(view_type, None)\n else:\n return '{}.{}_{}'.fo... | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_update_view | python | def generate_update_view(self):
name = model_class_form(self.model + 'UpdateView')
update_args = dict(
form_class=self.get_actual_form('update'),
model=self.get_model_class,
template_name=self.get_template('update'),
permissions=self.view_permission('upda... | Generate class based view for UpdateView | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L162-L189 | [
"def model_class_form(name):\n \"\"\"\n >>> model_class_form('foo_bar_baz')\n 'FooBarBaz'\n \"\"\"\n return capword(underToMixed(name))\n",
"def view_permission(self, view_type):\n if self.permissions:\n return self.permissions.get(view_type, None)\n else:\n return '{}.{}_{}'.fo... | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
asifpy/django-crudbuilder | crudbuilder/views.py | ViewBuilder.generate_delete_view | python | def generate_delete_view(self):
name = model_class_form(self.model + 'DeleteView')
delete_args = dict(
model=self.get_model_class,
template_name=self.get_template('delete'),
permissions=self.view_permission('delete'),
permission_required=self.check_permis... | Generate class based view for DeleteView | train | https://github.com/asifpy/django-crudbuilder/blob/9de1c6fa555086673dd7ccc351d4b771c6192489/crudbuilder/views.py#L191-L207 | [
"def model_class_form(name):\n \"\"\"\n >>> model_class_form('foo_bar_baz')\n 'FooBarBaz'\n \"\"\"\n return capword(underToMixed(name))\n",
"def view_permission(self, view_type):\n if self.permissions:\n return self.permissions.get(view_type, None)\n else:\n return '{}.{}_{}'.fo... | class ViewBuilder(BaseBuilder):
"""View builder which returns all the CRUD class based views"""
def __init__(self, *args, **kwargs):
super(ViewBuilder, self).__init__(*args, **kwargs)
self.classes = {}
def generate_crud(self):
self.generate_list_view()
self.generate_create_... |
AlexMathew/scrapple | scrapple/commands/web.py | WebCommand.execute_command | python | def execute_command(self):
print(Back.GREEN + Fore.BLACK + "Scrapple Web Interface")
print(Back.RESET + Fore.RESET)
p1 = Process(target = self.run_flask)
p2 = Process(target = lambda : webbrowser.open('http://127.0.0.1:5000'))
p1.start()
p2.start() | The web command runs the Scrapple web interface through a simple \
`Flask <http://flask.pocoo.org>`_ app.
When the execute_command() method is called from the \
:ref:`runCLI() <implementation-cli>` function, it starts of two simultaneous \
processes :
- Calls the run_flask() ... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/commands/web.py#L39-L67 | null | class WebCommand(command.Command):
"""
Defines the execution of :ref:`web <command-web>`
"""
app = Flask(__name__)
def __init__(self, args):
super(WebCommand, self).__init__(args)
init()
def run_flask(self):
try:
WebCommand.app.run(host="127.0.0.1", port=5... |
AlexMathew/scrapple | scrapple/commands/generate.py | GenerateCommand.execute_command | python | def execute_command(self):
print(Back.GREEN + Fore.BLACK + "Scrapple Generate")
print(Back.RESET + Fore.RESET)
directory = os.path.join(scrapple.__path__[0], 'templates', 'scripts')
with open(os.path.join(directory, 'generate.txt'), 'r') as f:
template_content = f.read()
... | The generate command uses `Jinja2 <http://jinja.pocoo.org/>`_ templates \
to create Python scripts, according to the specification in the configuration \
file. The predefined templates use the extract_content() method of the \
:ref:`selector classes <implementation-selectors>` to implement linea... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/commands/generate.py#L28-L67 | [
"def extract_fieldnames(config):\n \"\"\"\n Function to return a list of unique field names from the config file\n\n :param config: The configuration file that contains the specification of the extractor\n :return: A list of field names from the config file\n\n \"\"\"\n fields = []\n for x in g... | class GenerateCommand(command.Command):
"""
Defines the execution of :ref:`generate <command-generate>`
"""
def __init__(self, args):
super(GenerateCommand, self).__init__(args)
init()
|
AlexMathew/scrapple | scrapple/selectors/selector.py | Selector.extract_content | python | def extract_content(self, selector='', attr='', default='', connector='', *args, **kwargs):
try:
if selector.lower() == "url":
return self.url
if attr.lower() == "text":
tag = self.get_tree_tag(selector=selector, get_one=True)
content = connector.join([make_ascii(x).strip() for x in tag.itertext()])... | Method for performing the content extraction for the particular selector type. \
If the selector is "url", the URL of the current web page is returned.
Otherwise, the selector expression is used to extract content. The particular \
attribute to be extracted ("text", "href", etc.) is specified in the method \
a... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L81-L119 | [
"def get_tree_tag(self, selector='', get_one=False, *args, **kwargs):\n\traise NotImplementedError\n"
] | class Selector(object):
"""
This class defines the basic ``Selector`` object.
"""
__selector_type__ = ''
def __init__(self, url):
"""
The URL of the web page to be loaded is validated - ensuring the schema has \
been specified, and that the URL is valid. A HTTP GET request is made to load \
the web pag... |
AlexMathew/scrapple | scrapple/selectors/selector.py | Selector.extract_links | python | def extract_links(self, selector='', *args, **kwargs):
try:
links = self.get_tree_tag(selector=selector)
for link in links:
next_url = urljoin(self.url, link.get('href'))
yield type(self)(next_url)
except XPathError:
raise Exception("Invalid %s selector - %s" % (self.__selector_type__, selector))
... | Method for performing the link extraction for the crawler. \
The selector passed as the argument is a selector to point to the anchor tags \
that the crawler should pass through. A list of links is obtained, and the links \
are iterated through. The relative paths are converted into absolute paths and \
a ``Xp... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L122-L147 | [
"def get_tree_tag(self, selector='', get_one=False, *args, **kwargs):\n\traise NotImplementedError\n"
] | class Selector(object):
"""
This class defines the basic ``Selector`` object.
"""
__selector_type__ = ''
def __init__(self, url):
"""
The URL of the web page to be loaded is validated - ensuring the schema has \
been specified, and that the URL is valid. A HTTP GET request is made to load \
the web pag... |
AlexMathew/scrapple | scrapple/selectors/selector.py | Selector.extract_tabular | python | def extract_tabular(self, header='', prefix='', suffix='', table_type='', *args, **kwargs):
if type(header) in [str, unicode]:
try:
header_list = self.get_tree_tag(header)
table_headers = [prefix + h.text + suffix for h in header_list]
except XPathError:
raise Exception("Invalid %s selector for tabl... | Method for performing the tabular data extraction. \
:param result: A dictionary containing the extracted data so far
:param table_type: Can be "rows" or "columns". This determines the type of table to be extracted. \
A row extraction is when there is a single row to be extracted and mapped to a set of headers. ... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L150-L187 | [
"def get_tree_tag(self, selector='', get_one=False, *args, **kwargs):\n\traise NotImplementedError\n",
"def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs):\n\t\"\"\"\n\tRow data extraction for extract_tabular\n\t\"\"\"\n\tresult_list =... | class Selector(object):
"""
This class defines the basic ``Selector`` object.
"""
__selector_type__ = ''
def __init__(self, url):
"""
The URL of the web page to be loaded is validated - ensuring the schema has \
been specified, and that the URL is valid. A HTTP GET request is made to load \
the web pag... |
AlexMathew/scrapple | scrapple/selectors/selector.py | Selector.extract_rows | python | def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs):
result_list = []
try:
values = self.get_tree_tag(selector)
if len(table_headers) >= len(values):
from itertools import izip_longest
pairs = izip_longest(table_headers, va... | Row data extraction for extract_tabular | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L190-L224 | [
"def get_tree_tag(self, selector='', get_one=False, *args, **kwargs):\n\traise NotImplementedError\n"
] | class Selector(object):
"""
This class defines the basic ``Selector`` object.
"""
__selector_type__ = ''
def __init__(self, url):
"""
The URL of the web page to be loaded is validated - ensuring the schema has \
been specified, and that the URL is valid. A HTTP GET request is made to load \
the web pag... |
AlexMathew/scrapple | scrapple/selectors/selector.py | Selector.extract_columns | python | def extract_columns(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs):
result_list = []
try:
if type(selector) in [str, unicode]:
selectors = [selector]
elif type(selector) == list:
selectors = selector[:]
else:
raise Exception("Us... | Column data extraction for extract_tabular | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/selectors/selector.py#L227-L271 | [
"def get_tree_tag(self, selector='', get_one=False, *args, **kwargs):\n\traise NotImplementedError\n"
] | class Selector(object):
"""
This class defines the basic ``Selector`` object.
"""
__selector_type__ = ''
def __init__(self, url):
"""
The URL of the web page to be loaded is validated - ensuring the schema has \
been specified, and that the URL is valid. A HTTP GET request is made to load \
the web pag... |
AlexMathew/scrapple | scrapple/cmd.py | runCLI | python | def runCLI():
args = docopt(__doc__, version='0.3.0')
try:
check_arguments(args)
command_list = ['genconfig', 'run', 'generate']
select = itemgetter('genconfig', 'run', 'generate')
selectedCommand = command_list[select(args).index(True)]
cmdClass = get_command_class(selec... | The starting point for the execution of the Scrapple command line tool.
runCLI uses the docstring as the usage description for the scrapple command. \
The class for the required command is selected by a dynamic dispatch, and the \
command is executed through the execute_command() method of the command clas... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/cmd.py#L49-L67 | [
"def get_command_class(command):\n \"\"\"\n Called from runCLI() to select the command class for the selected command.\n\n :param command: The command to be implemented\n :return: The command class corresponding to the selected command\n \"\"\"\n from scrapple.commands import genconfig, generate, ... | """
Usage:
scrapple (-h | --help | --version)
scrapple genconfig <projectname> <url> [--type=<type>] [--selector=<selector>] \
[--levels=<levels>]
scrapple run <projectname> <output_filename> [--output_type=<output_type>] \
[--verbosity=<verbosity>]
scrapple generate <projectname> <output_filename> [--o... |
AlexMathew/scrapple | scrapple/utils/exceptions.py | check_arguments | python | def check_arguments(args):
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise InvalidType("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise InvalidSelector("--selector has to be 'xpath' or '... | Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/exceptions.py#L36-L66 | null | """
scrapple.utils.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to handling exceptions in the input arguments
"""
import re
class InvalidType(ValueError):
"""Exception class for invalid type in arguments."""
pass
class InvalidSelector(ValueError):
"""Exception class for invalid in arguments."""
pass... |
AlexMathew/scrapple | scrapple/utils/dynamicdispatch.py | get_command_class | python | def get_command_class(command):
from scrapple.commands import genconfig, generate, run, web
commandMapping = {
'genconfig': genconfig,
'generate': generate,
'run': run,
'web': web
}
cmdClass = getattr(commandMapping.get(command), command.title() + 'Command')
return cmdClass | Called from runCLI() to select the command class for the selected command.
:param command: The command to be implemented
:return: The command class corresponding to the selected command | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/dynamicdispatch.py#L8-L23 | null | """
scrapple.utils.dynamicdispatch
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Functions related to dynamic dispatch of objects
"""
|
AlexMathew/scrapple | scrapple/utils/form.py | form_to_json | python | def form_to_json(form):
config = dict()
if form['project_name'] == "":
raise Exception('Project name cannot be empty.')
if form['selector_type'] not in ["css", "xpath"]:
raise Exception('Selector type has to css or xpath')
config['project_name'] = form['project_name']
config['selector_type'] = form['selector_t... | Takes the form from the POST request in the web interface, and generates the JSON config\
file
:param form: The form from the POST request
:return: None | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/form.py#L13-L48 | null | """
scrapple.utils.form
~~~~~~~~~~~~~~~~~~~
Functions related to form handling.
"""
import itertools
import json
import os
|
AlexMathew/scrapple | scrapple/commands/run.py | RunCommand.execute_command | python | def execute_command(self):
try:
self.args['--verbosity'] = int(self.args['--verbosity'])
if self.args['--verbosity'] not in [0, 1, 2]:
raise ValueError
if self.args['--verbosity'] > 0:
print(Back.GREEN + Fore.BLACK + "Scrapple Run")
... | The run command implements the web content extractor corresponding to the given \
configuration file.
The execute_command() validates the input project name and opens the JSON \
configuration file. The run() method handles the execution of the extractor run.
The extractor implementati... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/commands/run.py#L29-L74 | [
"def validate_config(config):\n \"\"\"\n Validates the extractor configuration file. Ensures that there are no duplicate field names, etc.\n\n :param config: The configuration file that contains the specification of the extractor\n :return: True if config is valid, else raises a exception that specifies... | class RunCommand(command.Command):
"""
Defines the execution of :ref:`run <command-run>`
"""
def __init__(self, args):
super(RunCommand, self).__init__(args)
init()
def run(self):
selectorClassMapping = {
'xpath': XpathSelector,
'css': CssSelector
... |
AlexMathew/scrapple | scrapple/utils/config.py | traverse_next | python | def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0):
for link in page.extract_links(selector=nextx['follow_link']):
if verbosity > 0:
print('\n')
print(Back.YELLOW + Fore.BLUE + "Loading page ", link.url + Back.RESET + Fore.RESET, end='')
r = results... | Recursive generator to traverse through the next attribute and \
crawl through the links to be followed.
:param page: The current page being parsed
:param next: The next attribute of the current scraping dict
:param results: The current extracted content, stored in a dict
:return: The extracted con... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L20-L58 | [
"def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0):\n \"\"\"\n Recursive generator to traverse through the next attribute and \\\n crawl through the links to be followed.\n\n :param page: The current page being parsed\n :param next: The next attribute of the current scrapi... | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
from colorama import Back, Fore, init
init()
class InvalidConfigException(Exception):
"""Exception class for invalid config file. Example: duplicate field names"""
... |
AlexMathew/scrapple | scrapple/utils/config.py | validate_config | python | def validate_config(config):
fields = [f for f in get_fields(config)]
if len(fields) != len(set(fields)):
raise InvalidConfigException(
"Invalid configuration file - %d duplicate field names" % len(fields) - len(set(fields))
)
return True | Validates the extractor configuration file. Ensures that there are no duplicate field names, etc.
:param config: The configuration file that contains the specification of the extractor
:return: True if config is valid, else raises a exception that specifies the correction to be made | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L61-L74 | [
"def get_fields(config):\n \"\"\"\n Recursive generator that yields the field names in the config file\n\n :param config: The configuration file that contains the specification of the extractor\n :return: The field names in the config file, through a generator\n\n \"\"\"\n for data in config['scra... | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
from colorama import Back, Fore, init
init()
class InvalidConfigException(Exception):
"""Exception class for invalid config file. Example: duplicate field names"""
... |
AlexMathew/scrapple | scrapple/utils/config.py | get_fields | python | def get_fields(config):
for data in config['scraping']['data']:
if data['field'] != '':
yield data['field']
if 'next' in config['scraping']:
for n in config['scraping']['next']:
for f in get_fields(n):
yield f | Recursive generator that yields the field names in the config file
:param config: The configuration file that contains the specification of the extractor
:return: The field names in the config file, through a generator | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L77-L91 | [
"def get_fields(config):\n \"\"\"\n Recursive generator that yields the field names in the config file\n\n :param config: The configuration file that contains the specification of the extractor\n :return: The field names in the config file, through a generator\n\n \"\"\"\n for data in config['scra... | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
from colorama import Back, Fore, init
init()
class InvalidConfigException(Exception):
"""Exception class for invalid config file. Example: duplicate field names"""
... |
AlexMathew/scrapple | scrapple/utils/config.py | extract_fieldnames | python | def extract_fieldnames(config):
fields = []
for x in get_fields(config):
if x in fields:
fields.append(x + '_' + str(fields.count(x) + 1))
else:
fields.append(x)
return fields | Function to return a list of unique field names from the config file
:param config: The configuration file that contains the specification of the extractor
:return: A list of field names from the config file | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/utils/config.py#L94-L108 | [
"def get_fields(config):\n \"\"\"\n Recursive generator that yields the field names in the config file\n\n :param config: The configuration file that contains the specification of the extractor\n :return: The field names in the config file, through a generator\n\n \"\"\"\n for data in config['scra... | """
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~
Functions related to traversing the configuration file
"""
from __future__ import print_function
from colorama import Back, Fore, init
init()
class InvalidConfigException(Exception):
"""Exception class for invalid config file. Example: duplicate field names"""
... |
AlexMathew/scrapple | scrapple/commands/genconfig.py | GenconfigCommand.execute_command | python | def execute_command(self):
print(Back.GREEN + Fore.BLACK + "Scrapple Genconfig")
print(Back.RESET + Fore.RESET)
directory = os.path.join(scrapple.__path__[0], 'templates', 'configs')
with open(os.path.join(directory, self.args['--type'] + '.txt'), 'r') as f:
template_content ... | The genconfig command depends on predefined `Jinja2 <http://jinja.pocoo.org/>`_ \
templates for the skeleton configuration files. Taking the --type argument from the \
CLI input, the corresponding template file is used.
Settings for the configuration file, like project name, selector type and ... | train | https://github.com/AlexMathew/scrapple/blob/eeb604601b155d6cc7e035855ff4d3f48f8bed74/scrapple/commands/genconfig.py#L28-L57 | null | class GenconfigCommand(command.Command):
"""
Defines the execution of :ref:`genconfig <command-genconfig>`
"""
def __init__(self, args):
super(GenconfigCommand, self).__init__(args)
init()
def execute_command(self):
"""
The genconfig command depends on predefined `J... |
brettcannon/gidgethub | gidgethub/sansio.py | _parse_content_type | python | def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:
if not content_type:
return None, "utf-8"
else:
type_, parameters = cgi.parse_header(content_type)
encoding = parameters.get("charset", "utf-8")
return type_, encoding | Tease out the content-type and character encoding.
A default character encoding of UTF-8 is used, so the content-type
must be used to determine if any decoding is necessary to begin
with. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L24-L36 | null | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | _decode_body | python | def _decode_body(content_type: Optional[str], body: bytes,
*, strict: bool = False) -> Any:
type_, encoding = _parse_content_type(content_type)
if not len(body) or not content_type:
return None
decoded_body = body.decode(encoding)
if type_ == "application/json":
return j... | Decode an HTTP body based on the specified content type.
If 'strict' is true, then raise ValueError if the content type
is not recognized. Otherwise simply returned the body as a decoded
string. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L39-L57 | [
"def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:\n \"\"\"Tease out the content-type and character encoding.\n\n A default character encoding of UTF-8 is used, so the content-type\n must be used to determine if any decoding is necessary to begin\n with.\n \"\"\"\n ... | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | validate_event | python | def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
# https://developer.github.com/webhooks/securing/#validating-payloads-from-github
signature_prefix = "sha1="
if not signature.startswith(signature_prefix):
raise ValidationFailure("signature does not start with "
... | Validate the signature of a webhook event. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L60-L71 | null | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | accept_format | python | def accept_format(*, version: str = "v3", media: Optional[str] = None,
json: bool = True) -> str:
# https://developer.github.com/v3/media/
# https://developer.github.com/v3/#current-version
accept = f"application/vnd.github.{version}"
if media is not None:
accept += f".{media}"... | Construct the specification of the format that a request should return.
The version argument defaults to v3 of the GitHub API and is applicable to
all requests. The media argument along with 'json' specifies what format
the request should return, e.g. requesting the rendered HTML of a comment.
Do note ... | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L125-L145 | null | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | create_headers | python | def create_headers(requester: str, *, accept: str = accept_format(),
oauth_token: Optional[str] = None,
jwt: Optional[str] = None) -> Dict[str, str]:
# user-agent: https://developer.github.com/v3/#user-agent-required
# accept: https://developer.github.com/v3/#current-versio... | Create a dict representing GitHub-specific header fields.
The user agent is set according to who the requester is. GitHub asks it be
either a username or project name.
The 'accept' argument corresponds to the 'accept' field and defaults to the
default result of accept_format(). You should only need to... | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L148-L186 | null | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | decipher_response | python | def decipher_response(status_code: int, headers: Mapping[str, str],
body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]:
data = _decode_body(headers.get("content-type"), body)
if status_code in {200, 201, 204}:
return data, RateLimit.from_http(headers), _next_link(header... | Decipher an HTTP response for a GitHub API request.
The mapping providing the headers is expected to support lowercase keys.
The parameters of this function correspond to the three main parts
of an HTTP response: the status code, headers, and body. Assuming
no errors which lead to an exception being r... | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L269-L326 | [
"def _decode_body(content_type: Optional[str], body: bytes,\n *, strict: bool = False) -> Any:\n \"\"\"Decode an HTTP body based on the specified content type.\n\n If 'strict' is true, then raise ValueError if the content type\n is not recognized. Otherwise simply returned the body as a dec... | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | format_url | python | def format_url(url: str, url_vars: Mapping[str, Any]) -> str:
url = urllib.parse.urljoin(DOMAIN, url) # Works even if 'url' is fully-qualified.
expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
return expanded_url | Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L331-L342 | null | """Code to help with HTTP requests, responses, and events from GitHub's developer API.
This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifyin... |
brettcannon/gidgethub | gidgethub/sansio.py | Event.from_http | python | def from_http(cls, headers: Mapping[str, str], body: bytes,
*, secret: Optional[str] = None) -> "Event":
if "x-hub-signature" in headers:
if secret is None:
raise ValidationFailure("secret not provided")
validate_event(body, signature=headers... | Construct an event from HTTP headers and JSON body data.
The mapping providing the headers is expected to support lowercase keys.
Since this method assumes the body of the HTTP request is JSON, a check
is performed for a content-type of "application/json" (GitHub does
support other con... | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L90-L122 | [
"def _decode_body(content_type: Optional[str], body: bytes,\n *, strict: bool = False) -> Any:\n \"\"\"Decode an HTTP body based on the specified content type.\n\n If 'strict' is true, then raise ValueError if the content type\n is not recognized. Otherwise simply returned the body as a dec... | class Event:
"""Details of a GitHub webhook event."""
def __init__(self, data: Any, *, event: str, delivery_id: str) -> None:
# https://developer.github.com/v3/activity/events/types/
# https://developer.github.com/webhooks/#delivery-headers
self.data = data
# Event is not an en... |
brettcannon/gidgethub | gidgethub/sansio.py | RateLimit.from_http | python | def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
try:
limit = int(headers["x-ratelimit-limit"])
remaining = int(headers["x-ratelimit-remaining"])
reset_epoch = float(headers["x-ratelimit-reset"])
except KeyError:
return None
... | Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L237-L250 | null | class RateLimit:
"""The rate limit imposed upon the requester.
The 'limit' attribute specifies the rate of requests per hour the client is
limited to.
The 'remaining' attribute specifies how many requests remain within the
current rate limit that the client can make.
The reset_datetime attri... |
brettcannon/gidgethub | gidgethub/routing.py | Router.add | python | def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None:
if len(data_detail) > 1:
msg = ()
raise TypeError("dispatching based on data details is only "
"supported up to one level deep; "
f"{len(data_detail)} ... | Add a new route.
After registering 'func' for the specified event_type, an
optional data_detail may be provided. By providing an extra
keyword argument, dispatching can occur based on a top-level
key of the data in the event being dispatched. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L29-L50 | null | class Router:
"""Route webhook events to registered functions."""
def __init__(self, *other_routers: "Router") -> None:
"""Instantiate a new router (possibly from other routers)."""
self._shallow_routes: Dict[str, List[AsyncCallback]] = {}
# event type -> data key -> data value -> call... |
brettcannon/gidgethub | gidgethub/routing.py | Router.register | python | def register(self, event_type: str,
**data_detail: Any) -> Callable[[AsyncCallback], AsyncCallback]:
def decorator(func: AsyncCallback) -> AsyncCallback:
self.add(func, event_type, **data_detail)
return func
return decorator | Decorator to apply the add() method to a function. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L52-L58 | null | class Router:
"""Route webhook events to registered functions."""
def __init__(self, *other_routers: "Router") -> None:
"""Instantiate a new router (possibly from other routers)."""
self._shallow_routes: Dict[str, List[AsyncCallback]] = {}
# event type -> data key -> data value -> call... |
brettcannon/gidgethub | gidgethub/routing.py | Router.dispatch | python | async def dispatch(self, event: sansio.Event, *args: Any,
**kwargs: Any) -> None:
found_callbacks = []
try:
found_callbacks.extend(self._shallow_routes[event.event])
except KeyError:
pass
try:
details = self._deep_routes[event.e... | Dispatch an event to all registered function(s). | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L60-L80 | null | class Router:
"""Route webhook events to registered functions."""
def __init__(self, *other_routers: "Router") -> None:
"""Instantiate a new router (possibly from other routers)."""
self._shallow_routes: Dict[str, List[AsyncCallback]] = {}
# event type -> data key -> data value -> call... |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI._request | python | async def _request(self, method: str, url: str, headers: Mapping[str, str],
body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]:
"""Make an HTTP request.""" | Make an HTTP request. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L26-L28 | null | class GitHubAPI(abc.ABC):
"""Provide an idiomatic API for making calls to GitHub's API."""
def __init__(self, requester: str, *, oauth_token: Opt[str] = None,
cache: Opt[CACHE_TYPE] = None) -> None:
self.requester = requester
self.oauth_token = oauth_token
self._cache ... |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI._make_request | python | async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],
data: Any, accept: str,
jwt: Opt[str] = None,
oauth_token: Opt[str] = None,
) -> Tuple[bytes, Opt[str]]:
if oauth_token i... | Construct and make an HTTP request. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L34-L89 | [
"def format_url(url: str, url_vars: Mapping[str, Any]) -> str:\n \"\"\"Construct a URL for the GitHub API.\n\n The URL may be absolute or relative. In the latter case the appropriate\n domain will be added. This is to help when copying the relative URL directly\n from the GitHub developer documentation.... | class GitHubAPI(abc.ABC):
"""Provide an idiomatic API for making calls to GitHub's API."""
def __init__(self, requester: str, *, oauth_token: Opt[str] = None,
cache: Opt[CACHE_TYPE] = None) -> None:
self.requester = requester
self.oauth_token = oauth_token
self._cache ... |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI.getitem | python | async def getitem(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> Any:
data, _ = await self._make_request("GET", url, url_vars,... | Send a GET request for a single item to the specified endpoint. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L91-L100 | [
"async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],\n data: Any, accept: str,\n jwt: Opt[str] = None,\n oauth_token: Opt[str] = None,\n ) -> Tuple[bytes, Opt[str]]:\n \"\"\"Construct and make a... | class GitHubAPI(abc.ABC):
"""Provide an idiomatic API for making calls to GitHub's API."""
def __init__(self, requester: str, *, oauth_token: Opt[str] = None,
cache: Opt[CACHE_TYPE] = None) -> None:
self.requester = requester
self.oauth_token = oauth_token
self._cache ... |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI.getiter | python | async def getiter(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> AsyncGenerator[Any, None]:
data, more = await self._make_reque... | Return an async iterable for all the items at a specified endpoint. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L102-L120 | [
"async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],\n data: Any, accept: str,\n jwt: Opt[str] = None,\n oauth_token: Opt[str] = None,\n ) -> Tuple[bytes, Opt[str]]:\n \"\"\"Construct and make a... | class GitHubAPI(abc.ABC):
"""Provide an idiomatic API for making calls to GitHub's API."""
def __init__(self, requester: str, *, oauth_token: Opt[str] = None,
cache: Opt[CACHE_TYPE] = None) -> None:
self.requester = requester
self.oauth_token = oauth_token
self._cache ... |
brettcannon/gidgethub | gidgethub/tornado.py | GitHubAPI._request | python | async def _request(self, method: str, url: str, headers: Mapping[str, str],
body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]:
if method == "GET" and not body:
real_body = None
else:
real_body = body
request = httpclient.HTTPRequest(url, me... | Make an HTTP request. | train | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/tornado.py#L11-L23 | null | class GitHubAPI(gh_abc.GitHubAPI):
async def sleep(self, seconds: float) -> None:
"""Sleep for the specified number of seconds."""
await gen.sleep(seconds)
|
sarugaku/vistir | src/vistir/compat.py | is_bytes | python | def is_bytes(string):
if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa
return True
elif six.PY2 and isinstance(string, (buffer, bytearray)): # noqa
return True
return False | Check if a string is a bytes instance
:param Union[str, bytes] string: A string that may be string or bytes like
:return: Whether the provided string is a bytes type or not
:rtype: bool | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/compat.py#L205-L216 | null | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import codecs
import errno
import os
import sys
import warnings
from tempfile import mkdtemp
import six
from .backports.tempfile import NamedTemporaryFile as _NamedTemporaryFile
__all__ = [
"Path",
"get_terminal_... |
sarugaku/vistir | src/vistir/compat.py | fs_encode | python | def fs_encode(path):
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to encode")
if isinstance(path, six.text_type):
if six.PY2:
return b"".join(
(
_byte(ord(c) - 0xDC00)
if 0xDC00 <= ord(c) <... | Encode a filesystem path to the proper filesystem encoding
:param Union[str, bytes] path: A string-like path
:returns: A bytes-encoded filesystem path representation | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/compat.py#L316-L338 | [
"def _get_path(path):\n \"\"\"\n Fetch the string value from a path-like object\n\n Returns **None** if there is no string value.\n \"\"\"\n\n if isinstance(path, (six.string_types, bytes)):\n return path\n path_type = type(path)\n try:\n path_repr = path_type.__fspath__(path)\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import codecs
import errno
import os
import sys
import warnings
from tempfile import mkdtemp
import six
from .backports.tempfile import NamedTemporaryFile as _NamedTemporaryFile
__all__ = [
"Path",
"get_terminal_... |
sarugaku/vistir | src/vistir/compat.py | fs_decode | python | def fs_decode(path):
path = _get_path(path)
if path is None:
raise TypeError("expected a valid path to decode")
if isinstance(path, six.binary_type):
if six.PY2:
from array import array
indexes = _invalid_utf8_indexes(array(str("B"), path))
return "".joi... | Decode a filesystem path using the proper filesystem encoding
:param path: The filesystem path to decode from bytes or string
:return: The filesystem path, decoded with the determined encoding
:rtype: Text | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/compat.py#L341-L363 | [
"def _get_path(path):\n \"\"\"\n Fetch the string value from a path-like object\n\n Returns **None** if there is no string value.\n \"\"\"\n\n if isinstance(path, (six.string_types, bytes)):\n return path\n path_type = type(path)\n try:\n path_repr = path_type.__fspath__(path)\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import codecs
import errno
import os
import sys
import warnings
from tempfile import mkdtemp
import six
from .backports.tempfile import NamedTemporaryFile as _NamedTemporaryFile
__all__ = [
"Path",
"get_terminal_... |
sarugaku/vistir | src/vistir/termcolors.py | colored | python | def colored(text, color=None, on_color=None, attrs=None):
return colorize(text, fg=color, bg=on_color, attrs=attrs) | Colorize text using a reimplementation of the colorizer from
https://github.com/pavdmyt/yaspin so that it works on windows.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/termcolors.py#L57-L74 | [
"def colorize(text, fg=None, bg=None, attrs=None):\n if os.getenv(\"ANSI_COLORS_DISABLED\") is None:\n style = \"NORMAL\"\n if attrs is not None and not isinstance(attrs, list):\n _attrs = []\n if isinstance(attrs, six.string_types):\n _attrs.append(attrs)\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
import colorama
import six
from .compat import to_native_string
DISABLE_COLORS = os.getenv("CI", False) or os.getenv(
"ANSI_COLORS_DISABLED", os.getenv("VISTIR_DISABLE_COLORS", False)
)
ATTRIBUT... |
sarugaku/vistir | src/vistir/misc.py | partialclass | python | def partialclass(cls, *args, **kwargs):
name_attrs = [
n
for n in (getattr(cls, name, str(cls)) for name in ("__name__", "__qualname__"))
if n is not None
]
name_attrs = name_attrs[0]
type_ = type(
name_attrs, (cls,), {"__init__": partialmethod(cls.__init__, *args, **kwa... | Returns a partially instantiated class
:return: A partial class instance
:rtype: cls
>>> source = partialclass(Source, url="https://pypi.org/simple")
>>> source
<class '__main__.Source'>
>>> source(name="pypi")
>>> source.__dict__
mappingproxy({'__module__': '__main__', '__dict__': <at... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L371-L404 | null | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | to_bytes | python | def to_bytes(string, encoding="utf-8", errors=None):
unicode_name = get_canonical_encoding_name("utf-8")
if not errors:
if get_canonical_encoding_name(encoding) == unicode_name:
if six.PY3 and os.name == "nt":
errors = "surrogatepass"
else:
errors... | Force a value to bytes.
:param string: Some input that can be converted to a bytes.
:type string: str or bytes unicode or a memoryview subclass
:param encoding: The encoding to use for conversions, defaults to "utf-8"
:param encoding: str, optional
:return: Corresponding byte representation (for us... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L409-L447 | [
"def get_canonical_encoding_name(name):\n # type: (str) -> str\n \"\"\"\n Given an encoding name, get the canonical name from a codec lookup.\n\n :param str name: The name of the codec to lookup\n :return: The canonical version of the codec name\n :rtype: str\n \"\"\"\n\n import codecs\n\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | to_text | python | def to_text(string, encoding="utf-8", errors=None):
unicode_name = get_canonical_encoding_name("utf-8")
if not errors:
if get_canonical_encoding_name(encoding) == unicode_name:
if six.PY3 and os.name == "nt":
errors = "surrogatepass"
else:
errors ... | Force a value to a text-type.
:param string: Some input that can be converted to a unicode representation.
:type string: str or bytes unicode
:param encoding: The encoding to use for conversions, defaults to "utf-8"
:param encoding: str, optional
:return: The unicode representation of the string
... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L450-L487 | [
"def get_canonical_encoding_name(name):\n # type: (str) -> str\n \"\"\"\n Given an encoding name, get the canonical name from a codec lookup.\n\n :param str name: The name of the codec to lookup\n :return: The canonical version of the codec name\n :rtype: str\n \"\"\"\n\n import codecs\n\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | get_wrapped_stream | python | def get_wrapped_stream(stream, encoding=None, errors="replace"):
if stream is None:
raise TypeError("must provide a stream to wrap")
stream = _get_binary_buffer(stream)
if stream is not None and encoding is None:
encoding = "utf-8"
if not encoding:
encoding = get_output_encoding... | Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream.
:param stream: A stream instance to wrap
:param str encoding: The encoding to use for the stream
:param str errors: The error handler to use, default "replace"
:returns: A new, wrapped stream
:rtype: :class:`Stream... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L660-L680 | [
"def get_canonical_encoding_name(name):\n # type: (str) -> str\n \"\"\"\n Given an encoding name, get the canonical name from a codec lookup.\n\n :param str name: The name of the codec to lookup\n :return: The canonical version of the codec name\n :rtype: str\n \"\"\"\n\n import codecs\n\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | get_text_stream | python | def get_text_stream(stream="stdout", encoding=None):
stream_map = {"stdin": sys.stdin, "stdout": sys.stdout, "stderr": sys.stderr}
if os.name == "nt" or sys.platform.startswith("win"):
from ._winconsole import _get_windows_console_stream, _wrap_std_stream
else:
_get_windows_console_stream ... | Retrieve a unicode stream wrapper around **sys.stdout** or **sys.stderr**.
:param str stream: The name of the stream to wrap from the :mod:`sys` module.
:param str encoding: An optional encoding to use.
:return: A new :class:`~vistir.misc.StreamWrapper` instance around the stream
:rtype: `vistir.misc.S... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L863-L886 | [
"def get_wrapped_stream(stream, encoding=None, errors=\"replace\"):\n \"\"\"\n Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream.\n\n :param stream: A stream instance to wrap\n :param str encoding: The encoding to use for the stream\n :param str errors: The error han... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | replace_with_text_stream | python | def replace_with_text_stream(stream_name):
new_stream = TEXT_STREAMS.get(stream_name)
if new_stream is not None:
new_stream = new_stream()
setattr(sys, stream_name, new_stream)
return None | Given a stream name, replace the target stream with a text-converted equivalent
:param str stream_name: The name of a target stream, such as **stdout** or **stderr**
:return: None | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L913-L923 | null | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/misc.py | echo | python | def echo(text, fg=None, bg=None, style=None, file=None, err=False, color=None):
if file and not hasattr(file, "write"):
raise TypeError("Expected a writable stream, received {0!r}".format(file))
if not file:
if err:
file = _text_stderr()
else:
file = _text_stdout... | Write the given text to the provided stream or **sys.stdout** by default.
Provides optional foreground and background colors from the ansi defaults:
**grey**, **red**, **green**, **yellow**, **blue**, **magenta**, **cyan**
or **white**.
Available styles include **bold**, **dark**, **underline**, **bli... | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L938-L987 | [
"def is_bytes(string):\n \"\"\"Check if a string is a bytes instance\n\n :param Union[str, bytes] string: A string that may be string or bytes like\n :return: Whether the provided string is a bytes type or not\n :rtype: bool\n \"\"\"\n if six.PY3 and isinstance(string, (bytes, memoryview, bytearra... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import io
import json
import locale
import logging
import os
import subprocess
import sys
from collections import OrderedDict
from functools import partial
from itertools import islice, tee
from weakref import WeakKeyDictio... |
sarugaku/vistir | src/vistir/cursor.py | get_stream_handle | python | def get_stream_handle(stream=sys.stdout):
handle = stream
if os.name == "nt":
from ._winconsole import get_stream_handle as get_win_stream_handle
return get_win_stream_handle(stream)
return handle | Get the OS appropriate handle for the corresponding output stream.
:param str stream: The the stream to get the handle for
:return: A handle to the appropriate stream, either a ctypes buffer
or **sys.stdout** or **sys.stderr**. | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/cursor.py#L10-L23 | null | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function
import os
import sys
__all__ = ["hide_cursor", "show_cursor", "get_stream_handle"]
def hide_cursor(stream=sys.stdout):
"""
Hide the console cursor on the given stream
:param stream: The name of the stream to get the handle f... |
sarugaku/vistir | src/vistir/cursor.py | hide_cursor | python | def hide_cursor(stream=sys.stdout):
handle = get_stream_handle(stream=stream)
if os.name == "nt":
from ._winconsole import hide_cursor
hide_cursor()
else:
handle.write("\033[?25l")
handle.flush() | Hide the console cursor on the given stream
:param stream: The name of the stream to get the handle for
:return: None
:rtype: None | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/cursor.py#L26-L42 | [
"def get_stream_handle(stream=sys.stdout):\n \"\"\"\n Get the OS appropriate handle for the corresponding output stream.\n\n :param str stream: The the stream to get the handle for\n :return: A handle to the appropriate stream, either a ctypes buffer\n or **sys.stdout** or **sys.stderr**.\n ... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function
import os
import sys
__all__ = ["hide_cursor", "show_cursor", "get_stream_handle"]
def get_stream_handle(stream=sys.stdout):
"""
Get the OS appropriate handle for the corresponding output stream.
:param str stream: The the st... |
sarugaku/vistir | tasks/__init__.py | clean | python | def clean(ctx):
ctx.run(f"python setup.py clean")
dist = ROOT.joinpath("dist")
print(f"[clean] Removing {dist}")
if dist.exists():
shutil.rmtree(str(dist)) | Clean previously built package artifacts. | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/tasks/__init__.py#L26-L33 | null | import pathlib
import re
import shutil
import subprocess
import invoke
import parver
from towncrier._builder import find_fragments, render_fragments, split_fragments
from towncrier._settings import load_config
def _get_git_root(ctx):
return pathlib.Path(
ctx.run("git rev-parse --show-toplevel", hide=True... |
sarugaku/vistir | src/vistir/backports/tempfile.py | _sanitize_params | python | def _sanitize_params(prefix, suffix, dir):
output_type = _infer_return_type(prefix, suffix, dir)
if suffix is None:
suffix = output_type()
if prefix is None:
if output_type is str:
prefix = "tmp"
else:
prefix = os.fsencode("tmp")
if dir is None:
if... | Common parameter processing for most APIs in this module. | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/backports/tempfile.py#L55-L70 | [
"def fs_encode(path):\n try:\n return os.fsencode(path)\n except AttributeError:\n from ..compat import fs_encode\n\n return fs_encode(path)\n",
"def _infer_return_type(*args):\n _types = set()\n for arg in args:\n if isinstance(type(arg), six.string_types):\n _t... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, unicode_literals
import functools
import io
import os
import sys
from tempfile import _bin_openflags, _mkstemp_inner, gettempdir
import six
try:
from weakref import finalize
except ImportError:
from backports.weakref import finalize
def fs_enco... |
sarugaku/vistir | src/vistir/backports/surrogateescape.py | register_surrogateescape | python | def register_surrogateescape():
if six.PY3:
return
try:
codecs.lookup_error(FS_ERRORS)
except LookupError:
codecs.register_error(FS_ERRORS, surrogateescape_handler) | Registers the surrogateescape error handler on Python 2 (only) | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/backports/surrogateescape.py#L183-L192 | null | """
This is Victor Stinner's pure-Python implementation of PEP 383: the "surrogateescape" error
handler of Python 3.
Source: misc/python/surrogateescape.py in https://bitbucket.org/haypo/misc
"""
# This code is released under the Python license and the BSD 2-clause license
import codecs
import sys
import six
FS_ERR... |
sarugaku/vistir | src/vistir/path.py | set_write_bit | python | def set_write_bit(fn):
# type: (str) -> None
fn = fs_encode(fn)
if not os.path.exists(fn):
return
file_stat = os.stat(fn).st_mode
os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
if os.name == "nt":
from ._winconsole import get_current_user
user_sid ... | Set read-write permissions for the current user on the target path. Fail silently
if the path doesn't exist.
:param str fn: The target filename or path
:return: None | train | https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/path.py#L325-L362 | [
"def fs_encode(path):\n \"\"\"\n Encode a filesystem path to the proper filesystem encoding\n\n :param Union[str, bytes] path: A string-like path\n :returns: A bytes-encoded filesystem path representation\n \"\"\"\n\n path = _get_path(path)\n if path is None:\n raise TypeError(\"expected... | # -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import atexit
import errno
import functools
import os
import posixpath
import shutil
import stat
import time
import warnings
import six
from six.moves import urllib_parse
from six.moves.urllib import request as urllib_requ... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/variable_name_normalizer.py | normalize_variable_name | python | def normalize_variable_name(node, reachability_tester):
# type: (Dict[str, Any], ReferenceReachabilityTester) -> Optional[str]
node_type = NodeType(node['type'])
if not is_analyzable_identifier(node):
return None
if node_type is NodeType.IDENTIFIER:
return _normalize_identifier_value(... | Returns normalized variable name.
Normalizing means that variable names get explicit visibility by
visibility prefix such as: "g:", "s:", ...
Returns None if the specified node is unanalyzable.
A node is unanalyzable if:
- the node is not identifier-like
- the node is named dynamically | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/variable_name_normalizer.py#L21-L45 | [
"def is_analyzable_identifier(node): # type: (Dict[str, Any]) -> bool\n \"\"\" Whether the specified node is an analyzable identifier.\n\n Node declarative-identifier-like is analyzable if it is not dynamic\n and not a member variable, because we can do static scope analysis.\n\n Analyzable cases:\n ... | from typing import Dict, Any, Optional # noqa: F401
from vint.ast.node_type import NodeType
from vint.ast.plugin.scope_plugin.scope import (
ScopeVisibility,
ExplicityOfScopeVisibility,
)
from vint.ast.plugin.scope_plugin.scope_detector import (
is_analyzable_identifier,
IdentifierLikeNodeTypes,
)
from... |
Kuniwak/vint | vint/ast/traversing.py | traverse | python | def traverse(node, on_enter=None, on_leave=None):
node_type = NodeType(node['type'])
if node_type not in ChildNodeAccessorMap:
raise UnknownNodeTypeException(node_type)
if on_enter:
should_traverse_children = on_enter(node) is not SKIP_CHILDREN
else:
should_traverse_children = ... | Traverses the specified Vim script AST node (depth first order).
The on_enter/on_leave handler will be called with the specified node and
the children. You can skip traversing child nodes by returning
SKIP_CHILDREN. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/traversing.py#L226-L254 | [
"def prettify_node_type(node):\n node['type'] = NodeType(node['type'])\n",
"def prettify_node_type(node):\n node['type'] = NodeType(node['type'])\n",
"def _check_scriptencoding(self, node):\n # TODO: Use BREAK when implemented\n if self.has_scriptencoding:\n return SKIP_CHILDREN\n\n node_t... | from vint.ast.node_type import NodeType
SKIP_CHILDREN = 'SKIP_CHILDREN'
def for_each(func, nodes):
""" Calls func for each the specified nodes. """
for node in nodes:
call_if_def(func, node)
def for_each_deeply(func, node_lists):
""" Calls func for each the specified nodes. """
for nodes in... |
Kuniwak/vint | vint/linting/policy_set.py | PolicySet.update_by_config | python | def update_by_config(self, config_dict):
policy_enabling_map = self._get_enabling_map(config_dict)
self.enabled_policies = []
for policy_name, is_policy_enabled in policy_enabling_map.items():
if not self._is_policy_exists(policy_name):
self._warn_unexistent_policy(p... | Update policies set by the config dictionary.
Expect the policy_enabling_map structure to be (represented by YAML):
- PolicyFoo:
enabled: True
- PolicyBar:
enabled: False
additional_field: 'is_ok' | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/linting/policy_set.py#L48-L68 | [
"def _is_policy_exists(self, name):\n return name in self._all_policies_map\n",
"def _get_enabling_map(self, config_dict):\n severity = config_dict['cmdargs']['severity']\n policy_enabling_map = {}\n\n for policy_name, policy in self._all_policies_map.items():\n policy_enabling_map[policy_name]... | class PolicySet(object):
def __init__(self, policy_classes):
self._all_policies_map = PolicySet.create_all_policies_map(policy_classes)
self.enabled_policies = []
@classmethod
def create_all_policies_map(cls, policy_classes):
policy_map = {PolicyClass.__name__: PolicyClass() for Po... |
Kuniwak/vint | vint/linting/cli.py | _build_cmdargs | python | def _build_cmdargs(argv):
parser = _build_arg_parser()
namespace = parser.parse_args(argv[1:])
cmdargs = vars(namespace)
return cmdargs | Build command line arguments dict to use;
- displaying usages
- vint.linting.env.build_environment
This method take an argv parameter to make function pure. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/linting/cli.py#L79-L90 | null | from typing import Dict, Any, List # noqa: F401
import sys
from argparse import ArgumentParser
from pathlib import Path
import pkg_resources
import logging
from vint.linting.linter import Linter
from vint.linting.env import build_environment
from vint.linting.config.config_container import ConfigContainer
from vint.l... |
Kuniwak/vint | vint/ast/parsing.py | Parser.parse | python | def parse(self, lint_target): # type: (AbstractLintTarget) -> Dict[str, Any]
decoder = Decoder(default_decoding_strategy)
decoded = decoder.decode(lint_target.read())
decoded_and_lf_normalized = decoded.replace('\r\n', '\n')
return self.parse_string(decoded_and_lf_normalized) | Parse vim script file and return the AST. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/parsing.py#L19-L25 | [
"def decode(self, bytes_seq):\n # type: (bytes) -> str\n strings = []\n\n for (loc, hunk) in _split_by_scriptencoding(bytes_seq):\n debug_hint_for_the_loc = dict()\n self.debug_hint[loc] = debug_hint_for_the_loc\n\n string = self.strategy.decode(hunk, debug_hint=debug_hint_for_the_loc)... | class Parser(object):
def __init__(self, plugins=None, enable_neovim=False):
""" Initialize Parser with the specified plugins.
The plugins can add attributes to the AST.
"""
self.plugins = plugins if plugins else []
self._enable_neovim = enable_neovim
def parse_string(... |
Kuniwak/vint | vint/ast/parsing.py | Parser.parse_string | python | def parse_string(self, string): # type: (str) -> Dict[str, Any]
lines = string.split('\n')
reader = vimlparser.StringReader(lines)
parser = vimlparser.VimLParser(self._enable_neovim)
ast = parser.parse(reader)
# TOPLEVEL does not have a pos, but we need pos for all nodes
... | Parse vim script string and return the AST. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/parsing.py#L28-L42 | [
"def parse(self, reader):\n self.reader = reader\n self.context = []\n toplevel = Node(NODE_TOPLEVEL)\n toplevel.pos = self.reader.getpos()\n toplevel.body = []\n self.push_context(toplevel)\n while self.reader.peek() != \"<EOF>\":\n self.parse_one_cmd()\n self.check_missing_endfuncti... | class Parser(object):
def __init__(self, plugins=None, enable_neovim=False):
""" Initialize Parser with the specified plugins.
The plugins can add attributes to the AST.
"""
self.plugins = plugins if plugins else []
self._enable_neovim = enable_neovim
def parse(self, li... |
Kuniwak/vint | vint/ast/parsing.py | Parser.parse_redir | python | def parse_redir(self, redir_cmd):
redir_cmd_str = redir_cmd['str']
matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str)
if matched:
redir_cmd_op = matched.group(1)
redir_cmd_body = matched.group(2)
arg_pos = redir_cmd['ea']['argpos']
... | Parse a command :redir content. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/parsing.py#L45-L84 | [
"def traverse(node, on_enter=None, on_leave=None):\n \"\"\" Traverses the specified Vim script AST node (depth first order).\n The on_enter/on_leave handler will be called with the specified node and\n the children. You can skip traversing child nodes by returning\n SKIP_CHILDREN.\n \"\"\"\n node_... | class Parser(object):
def __init__(self, plugins=None, enable_neovim=False):
""" Initialize Parser with the specified plugins.
The plugins can add attributes to the AST.
"""
self.plugins = plugins if plugins else []
self._enable_neovim = enable_neovim
def parse(self, li... |
Kuniwak/vint | vint/ast/parsing.py | Parser.parse_string_expr | python | def parse_string_expr(self, string_expr_node):
string_expr_node_value = string_expr_node['value']
string_expr_str = string_expr_node_value[1:-1]
# Care escaped string literals
if string_expr_node_value[0] == "'":
string_expr_str = string_expr_str.replace("''", "'")
e... | Parse a string node content. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/parsing.py#L87-L121 | [
"def traverse(node, on_enter=None, on_leave=None):\n \"\"\" Traverses the specified Vim script AST node (depth first order).\n The on_enter/on_leave handler will be called with the specified node and\n the children. You can skip traversing child nodes by returning\n SKIP_CHILDREN.\n \"\"\"\n node_... | class Parser(object):
def __init__(self, plugins=None, enable_neovim=False):
""" Initialize Parser with the specified plugins.
The plugins can add attributes to the AST.
"""
self.plugins = plugins if plugins else []
self._enable_neovim = enable_neovim
def parse(self, li... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/scope_detector.py | is_builtin_variable | python | def is_builtin_variable(id_node): # type: (Dict[str, Any]) -> bool
# Builtin variables are always IDENTIFIER.
if NodeType(id_node['type']) is not NodeType.IDENTIFIER:
return False
id_value = id_node['value']
if id_value.startswith('v:'):
# It is an explicit builtin variable such as: "... | Whether the specified node is a builtin identifier. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/scope_detector.py#L69-L90 | null | from typing import Dict, Any, Optional # noqa: F401
from vint.ast.plugin.scope_plugin.scope import (
ScopeVisibility,
ExplicityOfScopeVisibility,
Scope,
)
from vint.ast.node_type import NodeType
from vint.ast.dictionary.builtins import (
BuiltinVariablesCanHaveImplicitScope,
BuiltinFunctions,
)
fro... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/scope_detector.py | is_builtin_function | python | def is_builtin_function(id_node): # type: (Dict[str, Any]) -> bool
# Builtin functions are always IDENTIFIER.
if NodeType(id_node['type']) is not NodeType.IDENTIFIER:
return False
id_value = id_node['value']
if not is_function_identifier(id_node):
return False
# There are differe... | Whether the specified node is a builtin function name identifier.
The given identifier should be a child node of NodeType.CALL. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/scope_detector.py#L93-L112 | null | from typing import Dict, Any, Optional # noqa: F401
from vint.ast.plugin.scope_plugin.scope import (
ScopeVisibility,
ExplicityOfScopeVisibility,
Scope,
)
from vint.ast.node_type import NodeType
from vint.ast.dictionary.builtins import (
BuiltinVariablesCanHaveImplicitScope,
BuiltinFunctions,
)
fro... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/scope_detector.py | detect_possible_scope_visibility | python | def detect_possible_scope_visibility(node, context_scope): # type: (Dict[str, Any], Scope) -> ScopeVisibilityHint
node_type = NodeType(node['type'])
if not is_analyzable_identifier(node):
return ScopeVisibilityHint(
ScopeVisibility.UNANALYZABLE,
ExplicityOfScopeVisibility.UNANA... | Returns a *possible* variable visibility by the specified node.
The "possible" means that we can not determine a scope visibility of lambda arguments until reachability check. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/scope_detector.py#L150-L174 | [
"def is_analyzable_identifier(node): # type: (Dict[str, Any]) -> bool\n \"\"\" Whether the specified node is an analyzable identifier.\n\n Node declarative-identifier-like is analyzable if it is not dynamic\n and not a member variable, because we can do static scope analysis.\n\n Analyzable cases:\n ... | from typing import Dict, Any, Optional # noqa: F401
from vint.ast.plugin.scope_plugin.scope import (
ScopeVisibility,
ExplicityOfScopeVisibility,
Scope,
)
from vint.ast.node_type import NodeType
from vint.ast.dictionary.builtins import (
BuiltinVariablesCanHaveImplicitScope,
BuiltinFunctions,
)
fro... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/identifier_classifier.py | IdentifierClassifier.attach_identifier_attributes | python | def attach_identifier_attributes(self, ast): # type: (Dict[str, Any]) -> Dict[str, Any]
redir_assignment_parser = RedirAssignmentParser()
ast_with_parsed_redir = redir_assignment_parser.process(ast)
map_and_filter_parser = CallNodeParser()
ast_with_parse_map_and_filter_and_redir = \
... | Attach 5 flags to the AST.
- is dynamic: True if the identifier name can be determined by static analysis.
- is member: True if the identifier is a member of a subscription/dot/slice node.
- is declaring: True if the identifier is used to declare.
- is autoload: True if the identifier i... | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/identifier_classifier.py#L118-L150 | [
"def traverse(node, on_enter=None, on_leave=None):\n \"\"\" Traverses the specified Vim script AST node (depth first order).\n The on_enter/on_leave handler will be called with the specified node and\n the children. You can skip traversing child nodes by returning\n SKIP_CHILDREN.\n \"\"\"\n node_... | class IdentifierClassifier(object):
""" A class for identifier classifiers.
This class classify nodes by 5 flags:
- is dynamic: True if the identifier name can be determined by static analysis.
- is member: True if the identifier is a member of a subscription/dot/slice node.
- is declaring: True if... |
Kuniwak/vint | vint/linting/policy/abstract_policy.py | AbstractPolicy.create_violation_report | python | def create_violation_report(self, node, lint_context):
return {
'name': self.name,
'level': self.level,
'description': self.description,
'reference': self.reference,
'position': {
'line': node['pos']['lnum'],
'column': n... | Returns a violation report for the node. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/linting/policy/abstract_policy.py#L22-L34 | null | class AbstractPolicy(object):
description = None
reference = None
level = None
def __init__(self):
self.name = self.__class__.__name__
def listen_node_types(self):
""" Listening node type.
is_valid will be called when a linter visit the listening node type.
"""
... |
Kuniwak/vint | vint/linting/policy/abstract_policy.py | AbstractPolicy.get_policy_config | python | def get_policy_config(self, lint_context):
policy_config = lint_context['config']\
.get('policies', {})\
.get(self.__class__.__name__, {})
return policy_config | Returns a config of the concrete policy. For example, a config of ProhibitSomethingEvil is located on
config.policies.ProhibitSomethingEvil. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/linting/policy/abstract_policy.py#L37-L46 | null | class AbstractPolicy(object):
description = None
reference = None
level = None
def __init__(self):
self.name = self.__class__.__name__
def listen_node_types(self):
""" Listening node type.
is_valid will be called when a linter visit the listening node type.
"""
... |
Kuniwak/vint | vint/linting/policy/abstract_policy.py | AbstractPolicy.get_violation_if_found | python | def get_violation_if_found(self, node, lint_context):
if self.is_valid(node, lint_context):
return None
return self.create_violation_report(node, lint_context) | Returns a violation if the node is invalid. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/linting/policy/abstract_policy.py#L49-L54 | [
"def is_valid(self, node, lint_context):\n \"\"\" Whether the specified node is valid for the policy. \"\"\"\n return True\n"
] | class AbstractPolicy(object):
description = None
reference = None
level = None
def __init__(self):
self.name = self.__class__.__name__
def listen_node_types(self):
""" Listening node type.
is_valid will be called when a linter visit the listening node type.
"""
... |
Kuniwak/vint | vint/bootstrap.py | import_all_policies | python | def import_all_policies():
pkg_name = _get_policy_package_name_for_test()
pkg_path_list = pkg_name.split('.')
pkg_path = str(Path(_get_vint_root(), *pkg_path_list).resolve())
for _, module_name, is_pkg in pkgutil.iter_modules([pkg_path]):
if not is_pkg:
module_fqn = pkg_name + '.' ... | Import all policies that were registered by vint.linting.policy_registry.
Dynamic policy importing is comprised of the 3 steps
1. Try to import all policy modules (then we can't know what policies exist)
2. In policy module, register itself by using vint.linting.policy_registry
3. After all polic... | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/bootstrap.py#L24-L41 | [
"def _get_policy_package_name_for_test():\n \"\"\" Test hook method that returns a package name for policy modules. \"\"\"\n return 'vint.linting.policy'\n",
"def _get_vint_root():\n return Path(__file__).parent.parent\n"
] | import importlib
import pkgutil
from pathlib import Path
from vint.linting.cli import start_cli
import logging
LOG_FORMAT = 'vint %(levelname)s: %(message)s'
def init_logger():
logging.basicConfig(format=LOG_FORMAT)
def init_linter():
import_all_policies()
def init_cli():
start_cli()
def _get_vi... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/scope_linker.py | ScopeLinker.process | python | def process(self, ast): # type: (Dict[str, Any]) -> None
id_classifier = IdentifierClassifier()
attached_ast = id_classifier.attach_identifier_attributes(ast)
# We are already in script local scope.
self._scope_tree_builder.enter_new_scope(ScopeVisibility.SCRIPT_LOCAL)
travers... | Build a scope tree and links between scopes and identifiers by the
specified ast. You can access the built scope tree and the built links
by .scope_tree and .link_registry. | train | https://github.com/Kuniwak/vint/blob/db29337d859d88239c282c2e9d84c858f23a4a09/vint/ast/plugin/scope_plugin/scope_linker.py#L326-L342 | [
"def traverse(node, on_enter=None, on_leave=None):\n \"\"\" Traverses the specified Vim script AST node (depth first order).\n The on_enter/on_leave handler will be called with the specified node and\n the children. You can skip traversing child nodes by returning\n SKIP_CHILDREN.\n \"\"\"\n node_... | class ScopeLinker(object):
""" A class for scope linkers.
The class link identifiers in the given AST node and the scopes where the
identifier will be declared or referenced.
"""
class ScopeTreeBuilder(object):
""" A class for event-driven builders to build a scope tree.
The class i... |
emre/storm | storm/kommandr.py | prog.command | python | def command(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], collections.Callable):
return self._generate_command(args[0])
else:
def _command(func):
return self._generate_command(func, *args, **kwargs)
return _command | Convenient decorator simply creates corresponding command | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L96-L103 | null | class prog(object):
"""Class to hold an isolated command namespace"""
_COMMAND_FLAG = '_command'
_POSITIONAL = type('_positional', (object,), {})
def __init__(self, **kwargs):
"""Constructor
:param version: program version
:param type: str
:param **kwargs: keyword arg... |
emre/storm | storm/kommandr.py | prog.arg | python | def arg(self, arg_name, *args, **kwargs):
def wrapper(func):
if not getattr(func, 'argopts', None):
func.argopts = {}
func.argopts[arg_name] = (args, kwargs)
return func
return wrapper | Decorator function configures any arg by given ``arg_name`` with
supplied ``args`` and ``kwargs`` passing them transparently to
:py:func:``argparse.ArgumentParser.add_argument`` function
:param arg_name: arg name to configure
:param type: str | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L105-L119 | null | class prog(object):
"""Class to hold an isolated command namespace"""
_COMMAND_FLAG = '_command'
_POSITIONAL = type('_positional', (object,), {})
def __init__(self, **kwargs):
"""Constructor
:param version: program version
:param type: str
:param **kwargs: keyword arg... |
emre/storm | storm/kommandr.py | prog._generate_command | python | def _generate_command(self, func, name=None, **kwargs):
func_pointer = name or func.__name__
storm_config = get_storm_config()
aliases, additional_kwarg = None, None
if 'aliases' in storm_config:
for command, alias_list in \
six.iteritems(storm_config.get(... | Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed through to
:py:class:``argparse.ArgumentPar... | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L121-L177 | null | class prog(object):
"""Class to hold an isolated command namespace"""
_COMMAND_FLAG = '_command'
_POSITIONAL = type('_positional', (object,), {})
def __init__(self, **kwargs):
"""Constructor
:param version: program version
:param type: str
:param **kwargs: keyword arg... |
emre/storm | storm/kommandr.py | prog.execute | python | def execute(self, arg_list):
arg_map = self.parser.parse_args(arg_list).__dict__
command = arg_map.pop(self._COMMAND_FLAG)
return command(**arg_map) | Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L179-L188 | null | class prog(object):
"""Class to hold an isolated command namespace"""
_COMMAND_FLAG = '_command'
_POSITIONAL = type('_positional', (object,), {})
def __init__(self, **kwargs):
"""Constructor
:param version: program version
:param type: str
:param **kwargs: keyword arg... |
emre/storm | storm/parsers/ssh_uri_parser.py | parse | python | def parse(uri, user=None, port=22):
uri = uri.strip()
if not user:
user = getpass.getuser()
# get user
if '@' in uri:
user = uri.split("@")[0]
# get port
if ':' in uri:
port = uri.split(":")[-1]
try:
port = int(port)
except ValueError:
raise V... | parses ssh connection uri-like sentences.
ex:
- root@google.com -> (root, google.com, 22)
- noreply@facebook.com:22 -> (noreply, facebook.com, 22)
- facebook.com:3306 -> ($USER, facebook.com, 3306)
- twitter.com -> ($USER, twitter.com, 22)
default port: 22
default user: $USE... | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/parsers/ssh_uri_parser.py#L7-L47 | null | # -*- coding: utf-8 -*-
import getpass
import re
|
emre/storm | storm/__main__.py | add | python | def add(name, connection_uri, id_file="", o=[], config=None):
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
user, host, port = parse(
connection_uri,
user=get_... | Adds a new entry to sshconfig. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L34-L63 | [
"def parse(uri, user=None, port=22):\n \"\"\"\n parses ssh connection uri-like sentences.\n ex:\n - root@google.com -> (root, google.com, 22)\n - noreply@facebook.com:22 -> (noreply, facebook.com, 22)\n - facebook.com:3306 -> ($USER, facebook.com, 3306)\n - twitter.com -> ($USER... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | clone | python | def clone(name, clone_name, config=None):
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, clone_name)
print(
get_formatted_message(
... | Clone an entry to the sshconfig. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L67-L90 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | move | python | def move(name, entry_name, config=None):
storm_ = get_storm_instance(config)
try:
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, entry_name, keep_original=False)
print(
get_formatted_message(
... | Move an entry to the sshconfig. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L93-L117 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | edit | python | def edit(name, connection_uri, id_file="", o=[], config=None):
storm_ = get_storm_instance(config)
try:
if ',' in name:
name = " ".join(name.split(","))
user, host, port = parse(
connection_uri,
user=get_default("user", storm_.defaults),
port=get... | Edits the related entry in ssh config. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L120-L143 | [
"def parse(uri, user=None, port=22):\n \"\"\"\n parses ssh connection uri-like sentences.\n ex:\n - root@google.com -> (root, google.com, 22)\n - noreply@facebook.com:22 -> (noreply, facebook.com, 22)\n - facebook.com:3306 -> ($USER, facebook.com, 3306)\n - twitter.com -> ($USER... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | update | python | def update(name, connection_uri="", id_file="", o=[], config=None):
storm_ = get_storm_instance(config)
settings = {}
if id_file != "":
settings['identityfile'] = id_file
for option in o:
k, v = option.split("=")
settings[k] = v
try:
storm_.update_entry(name, **se... | Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L146-L169 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | delete | python | def delete(name, config=None):
storm_ = get_storm_instance(config)
try:
storm_.delete_entry(name)
print(
get_formatted_message(
'hostname "{0}" deleted successfully.'.format(name),
'success')
)
except ValueError as error:
print(get_for... | Deletes a single host. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L172-L187 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | list | python | def list(config=None):
storm_ = get_storm_instance(config)
try:
result = colored('Listing entries:', 'white', attrs=["bold", ]) + "\n\n"
result_stack = ""
for host in storm_.list_entries(True):
if host.get("type") == 'entry':
if not host.get("host") == "*":
... | Lists all hosts from ssh config. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L190-L258 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | search | python | def search(search_text, config=None):
storm_ = get_storm_instance(config)
try:
results = storm_.search_host(search_text)
if len(results) == 0:
print ('no results found.')
if len(results) > 0:
message = 'Listing results for {0}:\n'.format(search_text)
... | Searches entries by given search text. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L261-L278 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | delete_all | python | def delete_all(config=None):
storm_ = get_storm_instance(config)
try:
storm_.delete_all_entries()
print(get_formatted_message('all entries deleted.', 'success'))
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | Deletes all hosts from ssh config. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L281-L292 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | backup | python | def backup(target_file, config=None):
storm_ = get_storm_instance(config)
try:
storm_.backup(target_file)
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | Backups the main ssh configuration into target file. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L295-L304 | [
"def get_formatted_message(message, format_type):\n\n # required for CLI test suite. see tests.py\n if 'TESTMODE' in os.environ and not isinstance(message, ValueError):\n for color_code in COLOR_CODES:\n message = message.replace(color_code, \"\")\n\n return \"{0} {1}\".format(format_... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/__main__.py | web | python | def web(port, debug=False, theme="modern", ssh_config=None):
from storm import web as _web
_web.run(port, debug, theme, ssh_config) | Starts the web UI. | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L310-L313 | [
"def run(port, debug, theme, ssh_config=None):\n global __THEME__\n port = int(port)\n debug = bool(debug)\n __THEME__ = theme\n\n def get_storm():\n return Storm(ssh_config)\n\n app.get_storm = get_storm\n\n app.run(port=port, debug=debug)\n"
] | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
import __builtin__ as builtins
except ImportError:
import builtins
from storm import Storm
from storm.parsers.ssh_uri_parser import parse
from storm.utils import (get_formatted_message, colored)
from storm.kommandr import *... |
emre/storm | storm/parsers/ssh_config_parser.py | StormConfig.parse | python | def parse(self, file_obj):
order = 1
host = {"host": ['*'], "config": {}, }
for line in file_obj:
line = line.rstrip('\n').lstrip()
if line == '':
self._config.append({
'type': 'empty_line',
'value': line,
... | Read an OpenSSH config from the given file object.
@param file_obj: a file-like object to read the config file from
@type file_obj: file | train | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/parsers/ssh_config_parser.py#L16-L82 | null | class StormConfig(SSHConfig):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.