text
stringlengths
81
112k
A property returning the url of the recipe with ``{version}`` replaced by the :attr:`url`. If accessing the url, you should use this property, *not* access the url directly. def versioned_url(self): '''A property returning the url of the recipe with ``{version}`` replaced by the :attr:`...
(internal) Download an ``url`` to a ``target``. def download_file(self, url, target, cwd=None): """ (internal) Download an ``url`` to a ``target``. """ if not url: return info('Downloading {} from {}'.format(self.name, url)) if cwd: target = join...
Apply a patch from the current recipe directory into the current build directory. .. versionchanged:: 0.6.0 Add ability to apply patch from any dir via kwarg `build_dir`''' def apply_patch(self, filename, arch, build_dir=None): """ Apply a patch from the current recipe dire...
Return archs of self.ctx that are valid build archs for the Recipe. def filtered_archs(self): '''Return archs of self.ctx that are valid build archs for the Recipe.''' result = [] for arch in self.ctx.archs: if not self.archs or (arch.arch in self.archs): ...
Checks what recipes are being built to see which of the alternative and optional dependencies are being used, and returns a list of these. def check_recipe_choices(self): '''Checks what recipes are being built to see which of the alternative and optional dependencies are being used, ...
Given the arch name, returns the directory where it will be built. This returns a different directory depending on what alternative or optional dependencies are being built. def get_build_container_dir(self, arch): '''Given the arch name, returns the directory where it will be ...
Returns the local recipe directory or defaults to the core recipe directory. def get_recipe_dir(self): """ Returns the local recipe directory or defaults to the core recipe directory. """ if self.ctx.local_recipes is not None: local_recipe_dir = join(self.ctx...
Return the env specialized for the recipe def get_recipe_env(self, arch=None, with_flags_in_cc=True, clang=False): """Return the env specialized for the recipe """ if arch is None: arch = self.filtered_archs[0] return arch.get_env(with_flags_in_cc=with_flags_in_cc, clang=cla...
Run any pre-build tasks for the Recipe. By default, this checks if any prebuild_archname methods exist for the archname of the current architecture, and runs them if so. def prebuild_arch(self, arch): '''Run any pre-build tasks for the Recipe. By default, this checks if any prebuild_arc...
Apply any patches for the Recipe. .. versionchanged:: 0.6.0 Add ability to apply patches from any dir via kwarg `build_dir` def apply_patches(self, arch, build_dir=None): '''Apply any patches for the Recipe. .. versionchanged:: 0.6.0 Add ability to apply patches from a...
Run any build tasks for the Recipe. By default, this checks if any build_archname methods exist for the archname of the current architecture, and runs them if so. def build_arch(self, arch): '''Run any build tasks for the Recipe. By default, this checks if any build_archname methods exi...
Run any post-build tasks for the Recipe. By default, this checks if any postbuild_archname methods exist for the archname of the current architecture, and runs them if so. def postbuild_arch(self, arch): '''Run any post-build tasks for the Recipe. By default, this checks if any postbuil...
Deletes all the build information of the recipe. If arch is not None, only this arch dir is deleted. Otherwise (the default) all builds for all archs are deleted. By default, this just deletes the main build dir. If the recipe has e.g. object files biglinked, or .so files stored ...
Returns the Recipe with the given name, if it exists. def get_recipe(cls, name, ctx): '''Returns the Recipe with the given name, if it exists.''' name = name.lower() if not hasattr(cls, "recipes"): cls.recipes = {} if name in cls.recipes: return cls.recipes[name]...
The name of the build folders containing this recipe. def folder_name(self): '''The name of the build folders containing this recipe.''' name = self.site_packages_name if name is None: name = self.name return name
Install the Python module by calling setup.py install with the target Python dir. def build_arch(self, arch): '''Install the Python module by calling setup.py install with the target Python dir.''' super(PythonRecipe, self).build_arch(arch) self.install_python_package(arch)
Automate the installation of a Python package (or a cython package where the cython components are pre-built). def install_python_package(self, arch, name=None, env=None, is_dir=True): '''Automate the installation of a Python package (or a cython package where the cython components are pre-buil...
Build any cython components, then install the Python module by calling setup.py install with the target Python dir. def build_arch(self, arch): '''Build any cython components, then install the Python module by calling setup.py install with the target Python dir. ''' Recipe.build...
Build any cython components, then install the Python module by calling setup.py install with the target Python dir. def build_arch(self, arch): '''Build any cython components, then install the Python module by calling setup.py install with the target Python dir. ''' Recipe.build...
Recursively renames all files named XXX.cpython-...-linux-gnu.so" to "XXX.so", i.e. removing the erroneous architecture name coming from the local system. def reduce_object_file_names(self, dirn): """Recursively renames all files named XXX.cpython-...-linux-gnu.so" to "XXX.so", i.e. rem...
Decorator to create automatically a :class:`Runnable` object with the function. The function will be delayed and call into the Activity thread. def run_on_ui_thread(f): '''Decorator to create automatically a :class:`Runnable` object with the function. The function will be delayed and call into the Activity...
Gets the channel with the given number. def Channel(n): """ Gets the channel with the given number. """ rv = channels.get(n, None) if rv is None: rv = ChannelImpl(n) channels[n] = rv return rv
Generate the python source for a node tree. def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = CodeGe...
Register a special name like `loop`. def add_special(self, name): """Register a special name like `loop`.""" self.undeclared.discard(name) self.declared.add(name)
Check if a name is declared in this or an outer scope. def is_declared(self, name, local_only=False): """Check if a name is declared in this or an outer scope.""" if name in self.declared_locally or name in self.declared_parameter: return True if local_only: return False...
Create a copy of the current one. def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) ...
Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. ...
Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically unless the force_generator parameter is set to False. def blockvisit(self, nodes, frame): """Visit a list of nodes as block in a frame. If the current frame ...
Pull all the references identifiers into the local scope. def pull_locals(self, frame): """Pull all the references identifiers into the local scope.""" for name in frame.identifiers.undeclared: self.writeline('l_%s = context.resolve(%r)' % (name, name))
Disable Python optimizations for the frame. def unoptimize_scope(self, frame): """Disable Python optimizations for the frame.""" # XXX: this is not that nice but it has no real overhead. It # mainly works because python finds the locals before dead code # is removed. If that breaks we...
This function returns all the shadowed variables in a dict in the form name: alias and will write the required assignments into the current scope. No indentation takes place. This also predefines locally declared variables from the loop body because under some circumstances it may be t...
Restore all aliases and delete unused variables. def pop_scope(self, aliases, frame): """Restore all aliases and delete unused variables.""" for name, alias in aliases.iteritems(): self.writeline('l_%s = %s' % (name, alias)) to_delete = set() for name in frame.identifiers.de...
In Jinja a few statements require the help of anonymous functions. Those are currently macros and call blocks and in the future also recursive loops. As there is currently technical limitation that doesn't allow reading and writing a variable in a scope where the initial value is comin...
Dump the function def of a macro or call block. def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check ...
Dump the macro definition for the def created by macro_body. def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: ...
Call a block and register it for the template. def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 1 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.h...
Visit regular imports. def visit_Import(self, node, frame): """Visit regular imports.""" if node.with_context: self.unoptimize_scope(frame) self.writeline('l_%s = ' % node.target, node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) se...
A range that can't generate ranges with a length of more than MAX_RANGE items. def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items. """ rng = xrange(*args) if len(rng) > MAX_RANGE: raise OverflowError('range too big, maximum size for r...
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden. >>> from jinja2.sandbox import is_internal_attr...
Subscribe an object from sandboxed code. def getitem(self, obj, argument): """Subscribe an object from sandboxed code.""" try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, basestring): try: attr = str(a...
Call an object from sandboxed code. def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" # the double prefixes are to avoid double keyword argument # errors when proxying the call. if not __self.is_safe_callable(__obj): raise Securit...
Returns a file descriptor for the filename if that file exists, otherwise `None`. def open_if_exists(filename, mode='rb'): """Returns a file descriptor for the filename if that file exists, otherwise `None`. """ try: return open(filename, mode) except IOError, e: if e.errno not ...
Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). def object_type_repr(obj): """Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (F...
Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text will be limite...
Generate some lorem impsum for the template. def generate_lorem_ipsum(n=5, html=True, min=20, max=100): """Generate some lorem impsum for the template.""" from jinja2.constants import LOREM_IPSUM_WORDS from random import choice, randrange words = LOREM_IPSUM_WORDS.split() result = [] for _ in ...
r"""Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' def unescape(self): r"""Unescape markup again into an unicode string. This also resolves known...
r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' def striptags(self): r"""Unescape markup into an unicod...
Python 2.4 compatibility. def _remove(self, obj): """Python 2.4 compatibility.""" for idx, item in enumerate(self._queue): if item == obj: del self._queue[idx] break
Goes one item ahead and returns it. def next(self): """Goes one item ahead and returns it.""" rv = self.current self.pos = (self.pos + 1) % len(self.items) return rv
Scan directories recursively until find any file with the given extension. The default extension to search is ``.so``. def get_lib_from(search_directory, lib_extension='.so'): '''Scan directories recursively until find any file with the given extension. The default extension to search is ``.so``.''' fo...
Parse an assign statement. def parse_set(self): """Parse an assign statement.""" lineno = next(self.stream).lineno target = self.parse_assign_target() self.stream.expect('assign') expr = self.parse_tuple() return nodes.Assign(target, expr, lineno=lineno)
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only`...
Works like `parse_expression` but if multiple expressions are delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created. This method could also return a regular expression instead of a tuple if no commas where found. The default parsing mode is a full tuple. If `simplified` i...
Takes information about the distribution, and decides what kind of distribution it will be. If parameters conflict (e.g. a dist with that name already exists, but doesn't have the right set of recipes), an error is thrown. Parameters ---------- name : str ...
Returns all the distributions found locally. def get_distributions(cls, ctx, extra_dist_dirs=[]): '''Returns all the distributions found locally.''' if extra_dist_dirs: raise BuildInterruptingException( 'extra_dist_dirs argument to get_distributions ' 'is not...
Save information about the distribution in its dist_dir. def save_info(self, dirn): ''' Save information about the distribution in its dist_dir. ''' with current_directory(dirn): info('Saving distribution info') with open('dist_info.json', 'w') as fileh: ...
Loads bytecode from a file or file like object. def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source ...
Dump the bytecode into the file or file like object passed. def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) ...
Automate the installation of a Python package (or a cython package where the cython components are pre-built). def install_python_package(self, arch, name=None, env=None, is_dir=True): '''Automate the installation of a Python package (or a cython package where the cython components are pre-buil...
If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. "...
Helper for `translate_exception`. def fake_exc_info(exc_info, filename, lineno): """Helper for `translate_exception`.""" exc_type, exc_value, tb = exc_info # figure the real context out if tb is not None: real_locals = tb.tb_frame.f_locals.copy() ctx = real_locals.get('context') ...
This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returne...
Chains the frames. Requires ctypes or the speedups extension. def chain_frames(self): """Chains the frames. Requires ctypes or the speedups extension.""" prev_tb = None for tb in self.frames: if prev_tb is not None: prev_tb.tb_next = tb prev_tb = tb ...
Compiles all the rules from the environment into a list of rules. def compile_rules(environment): """Compiles all the rules from the environment into a list of rules.""" e = re.escape rules = [ (len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), ...
Look at the next token. def look(self): """Look at the next token.""" old_token = next(self) result = self.current self.push(result) self.current = old_token return result
Go one token ahead and return the old one def next(self): """Go one token ahead and return the old one""" rv = self.current if self._pushed: self.current = self._pushed.popleft() elif self.current.type is not TOKEN_EOF: try: self.current = self._n...
Close the stream. def close(self): """Close the stream.""" self.current = Token(self.current.lineno, TOKEN_EOF, '') self._next = None self.closed = True
Expect a given token type and return it. This accepts the same argument as :meth:`jinja2.lexer.Token.test`. def expect(self, expr): """Expect a given token type and return it. This accepts the same argument as :meth:`jinja2.lexer.Token.test`. """ if not self.current.test(expr)...
This method tokenizes the text and returns the tokens in a generator. Use this method if you just want to tokenize a template. def tokeniter(self, source, name, filename=None, state=None): """This method tokenizes the text and returns the tokens in a generator. Use this method if you just wan...
Add libgeos headers to path def get_recipe_env(self, arch, with_flags_in_cc=True): """ Add libgeos headers to path """ env = super(ShapelyRecipe, self).get_recipe_env(arch, with_flags_in_cc) libgeos_dir = Recipe.get_recipe('libgeos', self.ctx).get_build_dir(arch.arch) env['CFLAGS'] += "...
Read the NDK version from the NDK dir, if possible def read_ndk_version(ndk_dir): """Read the NDK version from the NDK dir, if possible""" try: with open(join(ndk_dir, 'source.properties')) as fileh: ndk_data = fileh.read() except IOError: info('Could not determine NDK version, ...
Warn if the user's target API is less than the current minimum recommendation def check_target_api(api, arch): """Warn if the user's target API is less than the current minimum recommendation """ if api >= ARMEABI_MAX_TARGET_API and arch == 'armeabi': raise BuildInterruptingException( ...
Warn if the user's NDK is too high or low. def check_ndk_api(ndk_api, android_api): """Warn if the user's NDK is too high or low.""" if ndk_api > android_api: raise BuildInterruptingException( 'Target NDK API is {}, higher than the target Android API {}.'.format( ndk_api, an...
Eliminate dead code. def visit_If(self, node): """Eliminate dead code.""" # do not optimize ifs that have a block inside so that it doesn't # break super(). if node.find(nodes.Block) is not None: return self.generic_visit(node) try: val = self.visit(node....
Do constant folding. def fold(self, node): """Do constant folding.""" node = self.generic_visit(node) try: return nodes.Const.from_untrusted(node.as_const(), lineno=node.lineno, environment=s...
Enforce HTML escaping. This will probably double escape variables. def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(unicode(value))
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcec...
Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja <ul{{ {'class': 'my_list', 'missing': none, 'id': 'list-%d'|format(variable)}|xmlattr }}> ... <...
Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} def do_sort(value, case_sensitive=Fal...
If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if the variable was defined, otherwise ``'my_variable is not defi...
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} ->...
Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega, giga, etc.), if the second parameter is set to `True` the binary prefixes are used (mebi, gibi). def do_filesizeformat(value, binary=False): """Format the value like a ...
Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars ...
Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja {{ mytext|indent(2, true) }} indent by...
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will try to save the last word. If the text was in fact truncated it will append an ellipsis sign (`...
Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`. def do_wordwrap(s, width=79, break_long_words=True): ...
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. def do_int(value, default=0): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default usi...
Strip SGML/XML tags and replace adjacent whitespace by one space. def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(unicode(value)).striptags()
Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja...
Extracts metdata files from the given package to the given folder, which may be referenced in any way that is permitted in a requirements.txt file or install_requires=[] listing. Current supported metadata files that will be extracted: - pytoml.yml (only if package wasn't obtained as ...
Returns the path the system-wide python binary. (In case we're running in a virtualenv or venv) def _get_system_python_executable(): """ Returns the path the system-wide python binary. (In case we're running in a virtualenv or venv) """ # This function is required by get_package_as_folder()...
This function downloads the given package / dependency and extracts the raw contents into a folder. Afterwards, it returns a tuple with the type of distribution obtained, and the temporary folder it extracted to. It is the caller's responsibility to delete the returned temp folder after...
See if a dependency reference refers to a folder path. If it does, return the folder path (which parses and resolves file:// urls in the process). If it doesn't, return None. def parse_as_folder_reference(dep): """ See if a dependency reference refers to a folder path. If it does, r...
Internal function to extract metainfo from a package. Currently supported info types: - name - dependencies (a list of dependencies) def _extract_info_from_package(dependency, extract_type=None, debug=False, ...
Obtain the dependencies from a package. Please note this function is possibly SLOW, especially if you enable the recursive mode. def get_package_dependencies(package, recursive=False, verbose=False, include_build_req...
Gets the dependencies from the package in the given folder, then attempts to deduce the actual package name resulting from each dependency line, stripping away everything else. def get_dep_names_of_package( package, keep_version_pins=False, recursive=False, verbose=False...
This function will take care of all non-recipe things, by: 1. Processing them from --requirements (the modules argument) and installing them 2. Installing the user project/app itself via setup.py if ignore_setup_py=True def run_pymodules_install(ctx, modules, project_dir, ignore...
Calculates all the storage and build dirs, and makes sure the directories exist where necessary. def setup_dirs(self, storage_dir): '''Calculates all the storage and build dirs, and makes sure the directories exist where necessary.''' self.storage_dir = expanduser(storage_dir) i...
Checks that build dependencies exist and sets internal variables for the Android SDK etc. ..warning:: This *must* be called before trying any build stuff def prepare_build_environment(self, user_sdk_dir, user_ndk_dir, ...
Returns the location of site-packages in the python-install build dir. def get_site_packages_dir(self, arch=None): '''Returns the location of site-packages in the python-install build dir. ''' if self.python_recipe.name == 'python2legacy': return join(self.get_python...