INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
returns a registry component for anything that s a valid package name ( this does not guarantee that the component actually exists in the registry: use availableVersions () for that ). | def createFromSource(cls, vs, name, registry):
''' returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that).
'''
# we deliberately allow only lowerc... |
Read a list of files. Their configuration values are merged with preference to values from files earlier in the list. | def read(self, filenames):
'''' Read a list of files. Their configuration values are merged, with
preference to values from files earlier in the list.
'''
for fn in filenames:
try:
self.configs[fn] = ordered_json.load(fn)
except IOError:
... |
return a configuration value | def get(self, path):
''' return a configuration value
usage:
get('section.property')
Note that currently array indexes are not supported. You must
get the whole array.
returns None if any path element or the property is missing
'''
... |
Set a configuration value. If no filename is specified the property is set in the first configuration file. Note that if a filename is specified and the property path is present in an earlier filename then set property will be hidden. | def set(self, path, value=None, filename=None):
''' Set a configuration value. If no filename is specified, the
property is set in the first configuration file. Note that if a
filename is specified and the property path is present in an
earlier filename then set property will... |
indicate whether the current item is the last one in a generator | def islast(generator):
''' indicate whether the current item is the last one in a generator
'''
next_x = None
first = True
for x in generator:
if not first:
yield (next_x, False)
next_x = x
first = False
if not first:
yield (next_x, True) |
Return a RemoteComponent sublclass for the specified component name and source url ( or version specification ) Raises an exception if any arguments are invalid. | def remoteComponentFor(name, version_required, registry='modules'):
''' Return a RemoteComponent sublclass for the specified component name and
source url (or version specification)
Raises an exception if any arguments are invalid.
'''
try:
vs = sourceparse.parseSourceURL(version_re... |
returns a Component/ Target for the specified version if found in the list of search paths. If update is True then also check for newer versions of the found component and update it in - place ( unless it was installed via a symlink ). | def satisfyVersionFromSearchPaths(name, version_required, search_paths, update=False, type='module', inherit_shrinkwrap=None):
''' returns a Component/Target for the specified version, if found in the
list of search paths. If `update' is True, then also check for newer
versions of the found componen... |
installs and returns a Component/ Target for the specified name + version requirement into a subdirectory of working_directory | def satisfyVersionByInstalling(name, version_required, working_directory, type='module', inherit_shrinkwrap=None):
''' installs and returns a Component/Target for the specified name+version
requirement, into a subdirectory of `working_directory'
'''
v = latestSuitableVersion(name, version_required, ... |
installs and returns a Component/ Target for the specified version requirement into working_directory using the provided remote version object. This function is not normally called via satisfyVersionByInstalling which looks up a suitable remote version object. | def _satisfyVersionByInstallingVersion(name, version_required, working_directory, version, type='module', inherit_shrinkwrap=None):
''' installs and returns a Component/Target for the specified version requirement into
'working_directory' using the provided remote version object.
This function is no... |
returns a Component/ Target for the specified version ( either to an already installed copy ( from the available list or from disk ) or to a newly downloaded one ) or None if the version could not be satisfied. | def satisfyVersion(
name,
version_required,
available,
search_paths,
working_directory,
update_installed=None,
type='module', # or 'target'
inherit_shrinkwrap=None
):
''' returns a Component/Target for the specified version (either to an already
... |
validate source directory names in components | def sourceDirValidationError(dirname, component_name):
''' validate source directory names in components '''
if dirname == component_name:
return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)
elif dirname.lower() in ('source', 'src') and dirname ... |
print information about outdated modules return 0 if there is nothing to be done and nonzero otherwise | def displayOutdated(modules, dependency_specs, use_colours):
''' print information about outdated modules,
return 0 if there is nothing to be done and nonzero otherwise
'''
if use_colours:
DIM = colorama.Style.DIM #pylint: disable=no-member
NORMAL = colorama.Style.NORMAL ... |
Read the. yotta_origin. json file ( if present ) and return the value of the url property | def origin(self):
''' Read the .yotta_origin.json file (if present), and return the value
of the 'url' property '''
if self.origin_info is None:
self.origin_info = {}
try:
self.origin_info = ordered_json.load(os.path.join(self.path, Origin_Info_Fname))... |
Return a truthy object if a newer suitable version is available otherwise return None. ( in fact the object returned is a ComponentVersion that can be used to get the newer version ) | def outdated(self):
''' Return a truthy object if a newer suitable version is available,
otherwise return None.
(in fact the object returned is a ComponentVersion that can be used
to get the newer version)
'''
if self.latest_suitable_version and self.latest_s... |
Commit the current working directory state ( or do nothing if the working directory is not version controlled ) | def commitVCS(self, tag=None):
''' Commit the current working directory state (or do nothing if the
working directory is not version controlled)
'''
if not self.vcs:
return
self.vcs.commit(message='version %s' % tag, tag=tag) |
Test if this module ignores the file at path which must be a path relative to the root of the module. | def ignores(self, path):
''' Test if this module ignores the file at "path", which must be a
path relative to the root of the module.
If a file is within a directory that is ignored, the file is also
ignored.
'''
test_path = PurePath('/', path)
# als... |
Write the current ( possibly modified ) component description to a package description file in the component directory. | def writeDescription(self):
''' Write the current (possibly modified) component description to a
package description file in the component directory.
'''
ordered_json.dump(os.path.join(self.path, self.description_filename), self.description)
if self.vcs:
self.vcs.... |
Write a tarball of the current component/ target to the file object file_object which must already be open for writing at position 0 | def generateTarball(self, file_object):
''' Write a tarball of the current component/target to the file object
"file_object", which must already be open for writing at position 0
'''
archive_name = '%s-%s' % (self.getName(), self.getVersion())
def filterArchive(tarinfo):
... |
Publish to the appropriate registry return a description of any errors that occured or None if successful. No VCS tagging is performed. | def publish(self, registry=None):
''' Publish to the appropriate registry, return a description of any
errors that occured, or None if successful.
No VCS tagging is performed.
'''
if (registry is None) or (registry == registry_access.Registry_Base_URL):
if 'pr... |
Try to un - publish the current version. Return a description of any errors that occured or None if successful. | def unpublish(self, registry=None):
''' Try to un-publish the current version. Return a description of any
errors that occured, or None if successful.
'''
return registry_access.unpublish(
self.getRegistryNamespace(),
self.getName(),
self.getVersio... |
Return the specified script command. If the first part of the command is a. py file then the current python interpreter is prepended. | def getScript(self, scriptname):
''' Return the specified script command. If the first part of the
command is a .py file, then the current python interpreter is
prepended.
If the script is a single string, rather than an array, it is
shlex-split.
'''
... |
Run the specified script from the scripts section of the module. json file in the directory of this module. | def runScript(self, scriptname, additional_environment=None):
''' Run the specified script from the scripts section of the
module.json file in the directory of this module.
'''
import subprocess
import shlex
command = self.getScript(scriptname)
if command is ... |
Determine yotta - config truthiness. In yotta config land truthiness is different to python or json truthiness ( in order to map nicely only preprocessor and CMake definediness ): | def _truthyConfValue(v):
''' Determine yotta-config truthiness. In yotta config land truthiness is
different to python or json truthiness (in order to map nicely only
preprocessor and CMake definediness):
json -> python -> truthy/falsey
false -> False -> Falsey
... |
Returns [ DependencySpec ] | def getDependencySpecs(self, target=None):
''' Returns [DependencySpec]
These are returned in the order that they are listed in the
component description file: this is so that dependency resolution
proceeds in a predictable way.
'''
deps = []
def spe... |
Check if this module has any dependencies with the specified name in its dependencies list or in target dependencies for the specified target | def hasDependency(self, name, target=None, test_dependencies=False):
''' Check if this module has any dependencies with the specified name
in its dependencies list, or in target dependencies for the
specified target
'''
if name in self.description.get('dependencies', {}).... |
Check if this module or any of its dependencies have a dependencies with the specified name in their dependencies or in their targetDependencies corresponding to the specified target. | def hasDependencyRecursively(self, name, target=None, test_dependencies=False):
''' Check if this module, or any of its dependencies, have a
dependencies with the specified name in their dependencies, or in
their targetDependencies corresponding to the specified target.
Note... |
Returns { component_name: component } | def getDependencies(self,
available_components = None,
search_dirs = None,
target = None,
available_only = False,
test = False,
warnings = True
):
''' Returns {component_name:component}
'''
... |
Get installed components using provider to find ( and possibly install ) components. | def __getDependenciesWithProvider(self,
available_components = None,
search_dirs = None,
target = None,
update_installed = False,
provider = None,
... |
Get installed components using provider to find ( and possibly install ) components. | def __getDependenciesRecursiveWithProvider(self,
available_components = None,
search_dirs = None,
target = None,
traverse_links = False,
... |
Get available and already installed components don t check for remotely available components. See also satisfyDependenciesRecursive () | def getDependenciesRecursive(self,
available_components = None,
processed = None,
search_dirs = None,
target = None,
available_only = False,
test = False
... |
Retrieve and install all the dependencies of this component and its dependencies recursively or satisfy them from a collection of available_components or from disk. | def satisfyDependenciesRecursive(
self,
available_components = None,
search_dirs = None,
update_installed = False,
traverse_links = False,
target = None,
test = False
... |
Ensure that the specified target name ( and optionally version github ref or URL ) is installed in the targets directory of the current component | def satisfyTarget(self, target_name_and_version, update_installed=False, additional_config=None, install_missing=True):
''' Ensure that the specified target name (and optionally version,
github ref or URL) is installed in the targets directory of the
current component
return... |
Return a derived target object representing the selected target: if the target is not installed or is invalid then the returned object will test false in a boolean context. | def getTarget(self, target_name_and_version, additional_config=None):
''' Return a derived target object representing the selected target: if
the target is not installed, or is invalid then the returned object
will test false in a boolean context.
Returns derived_target
... |
Return a dictionary of binaries to compile: { dirname: exename } this is used when automatically generating CMakeLists | def getBinaries(self):
''' Return a dictionary of binaries to compile: {"dirname":"exename"},
this is used when automatically generating CMakeLists
Note that currently modules may define only a single executable
binary or library to be built by the automatic build system, by... |
Return a dictionary of libraries to compile: { dirname: libname } this is used when automatically generating CMakeLists. | def getLibs(self, explicit_only=False):
''' Return a dictionary of libraries to compile: {"dirname":"libname"},
this is used when automatically generating CMakeLists.
If explicit_only is not set, then in the absence of both 'lib' and
'bin' sections in the module.json file, t... |
Return a list of licenses that apply to this module. ( Strings which may be SPDX identifiers ) | def licenses(self):
''' Return a list of licenses that apply to this module. (Strings,
which may be SPDX identifiers)
'''
if 'license' in self.description:
return [self.description['license']]
else:
return [x['type'] for x in self.description['licenses... |
Some components must export whole directories full of headers into the search path. This is really really bad and they shouldn t do it but support is provided as a concession to compatibility. | def getExtraIncludes(self):
''' Some components must export whole directories full of headers into
the search path. This is really really bad, and they shouldn't do
it, but support is provided as a concession to compatibility.
'''
if 'extraIncludes' in self.description:
... |
Some components ( e. g. libc ) must export directories of header files into the system include search path. They do this by adding a extraSysIncludes: [ array of directories ] field in their package description. This function returns the list of directories ( or an empty list ) if it doesn t exist. | def getExtraSysIncludes(self):
''' Some components (e.g. libc) must export directories of header files
into the system include search path. They do this by adding a
'extraSysIncludes' : [ array of directories ] field in their
package description. This function returns the lis... |
return a list of errors encountered ( e. g. dependency missing or specification not met | def checkDependenciesForShrinkwrap(dependency_list):
''' return a list of errors encountered (e.g. dependency missing or
specification not met
'''
# sourceparse, , parse version specifications, internall
from yotta.lib import sourceparse
errors = []
# first gather the available versions ... |
return a list of GitCloneVersion objects for tags which are valid semantic version idenfitifiers. | def availableVersions(self):
''' return a list of GitCloneVersion objects for tags which are valid
semantic version idenfitifiers.
'''
r = []
for t in self.vcs.tags():
logger.debug("available version tag: %s", t)
# ignore empty tags:
if not... |
return a GithubComponentVersion object for a specific commit if valid | def commitVersion(self, spec):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', spec, re.I)
if commit_match:
return GitCloneVersion('', spec, self)
return None |
returns a git component for any git:// url or None if this is not a git component. | def createFromSource(cls, vs, name=None):
''' returns a git component for any git:// url, or None if this is not
a git component.
Normally version will be empty, unless the original url was of the
form 'git://...#version', which can be used to grab a particular
t... |
merge dictionaries of dictionaries recursively with elements from dictionaries earlier in the argument sequence taking precedence | def _mergeDictionaries(*args):
''' merge dictionaries of dictionaries recursively, with elements from
dictionaries earlier in the argument sequence taking precedence
'''
# to support merging of OrderedDicts, copy the result type from the first
# argument:
result = type(args[0])()
for k, ... |
create a new nested dictionary object with the same structure as dictionary but with all scalar values replaced with value | def _mirrorStructure(dictionary, value):
''' create a new nested dictionary object with the same structure as
'dictionary', but with all scalar values replaced with 'value'
'''
result = type(dictionary)()
for k in dictionary.keys():
if isinstance(dictionary[k], dict):
result[... |
returns ( error config ) | def loadAdditionalConfig(config_path):
''' returns (error, config)
'''
error = None
config = {}
if not config_path:
return (error, config)
if os.path.isfile(config_path):
try:
config = ordered_json.load(config_path)
except Exception as e:
error = "... |
Get the specified target description optionally ensuring that it ( and all dependencies ) are installed in targets_path. | def getDerivedTarget(
target_name_and_version,
targets_path,
application_dir = None,
install_missing = True,
update_installed = False,
additional_config = None,
shrinkwrap = None
):
# access, , get compo... |
returns pack. DependencySpec for the base target of this target ( or None if this target does not inherit from another target. | def baseTargetSpec(self):
''' returns pack.DependencySpec for the base target of this target (or
None if this target does not inherit from another target.
'''
inherits = self.description.get('inherits', {})
if len(inherits) == 1:
name, version_req = list(inherits.... |
return the specified script if one exists ( possibly inherited from a base target ) | def getScript(self, scriptname):
''' return the specified script if one exists (possibly inherited from
a base target)
'''
for t in self.hierarchy:
s = t.getScript(scriptname)
if s:
return s
return None |
load the configuration information from the target hierarchy | def _loadConfig(self):
''' load the configuration information from the target hierarchy '''
config_dicts = [self.additional_config, self.app_config] + [t.getConfig() for t in self.hierarchy]
# create an identical set of dictionaries, but with the names of the
# sources in place of the va... |
return a list of toolchain file paths in override order ( starting at the bottom/ leaf of the hierarchy and ending at the base ). The list is returned in the order they should be included ( most - derived last ). | def getToolchainFiles(self):
''' return a list of toolchain file paths in override order (starting
at the bottom/leaf of the hierarchy and ending at the base).
The list is returned in the order they should be included
(most-derived last).
'''
return reversed([... |
Return the list of cmake files which are to be included by yotta in every module built. The list is returned in the order they should be included ( most - derived last ). | def getAdditionalIncludes(self):
''' Return the list of cmake files which are to be included by yotta in
every module built. The list is returned in the order they should
be included (most-derived last).
'''
return reversed([
os.path.join(t.path, include_file)... |
Return true if this target inherits from the named target ( directly or indirectly. Also returns true if this target is the named target. Otherwise return false. | def inheritsFrom(self, target_name):
''' Return true if this target inherits from the named target (directly
or indirectly. Also returns true if this target is the named
target. Otherwise return false.
'''
for t in self.hierarchy:
if t and t.getName() == targe... |
Execute the given command returning an error message if an error occured or None if the command was succesful. | def exec_helper(self, cmd, builddir):
''' Execute the given command, returning an error message if an error occured
or None if the command was succesful.'''
try:
child = subprocess.Popen(cmd, cwd=builddir)
child.wait()
except OSError as e:
if e.err... |
Execute the commands necessary to build this component and all of its dependencies. | def build(self, builddir, component, args, release_build=False, build_args=None, targets=None,
release_no_debug_info_build=False):
''' Execute the commands necessary to build this component, and all of
its dependencies. '''
if build_args is None:
build_args = []
... |
Return the builddir - relative path of program if only a partial path is specified. Returns None and logs an error message if the program is ambiguous or not found | def findProgram(self, builddir, program):
''' Return the builddir-relative path of program, if only a partial
path is specified. Returns None and logs an error message if the
program is ambiguous or not found
'''
# if this is an exact match, do no further checking:
if os... |
Launch the specified program. Uses the start script if specified by the target attempts to run it natively if that script is not defined. | def start(self, builddir, program, forward_args):
''' Launch the specified program. Uses the `start` script if specified
by the target, attempts to run it natively if that script is not
defined.
'''
child = None
try:
prog_path = self.findProgram(buildd... |
Launch a debugger for the specified program. Uses the debug script if specified by the target falls back to the debug and debugServer commands if not. program is inserted into the $program variable in commands. | def debug(self, builddir, program):
''' Launch a debugger for the specified program. Uses the `debug`
script if specified by the target, falls back to the `debug` and
`debugServer` commands if not. `program` is inserted into the
$program variable in commands.
'''
... |
look for program in PATH ( respecting PATHEXT ) and return the path to it or None if it was not found | def which(program):
''' look for "program" in PATH (respecting PATHEXT), and return the path to
it, or None if it was not found
'''
# current directory / absolute paths:
if os.path.exists(program) and os.access(program, os.X_OK):
return program
# PATH:
for path in os.environ['PAT... |
Prune the cache | def pruneCache():
''' Prune the cache '''
cache_dir = folders.cacheDirectory()
def fullpath(f):
return os.path.join(cache_dir, f)
def getMTimeSafe(f):
# it's possible that another process removed the file before we stat
# it, handle this gracefully
try:
return... |
return decorator to prune cache after calling fn with a probability of p | def sometimesPruneCache(p):
''' return decorator to prune cache after calling fn with a probability of p'''
def decorator(fn):
@functools.wraps(fn)
def wrapped(*args, **kwargs):
r = fn(*args, **kwargs)
if random.random() < p:
pruneCache()
retur... |
If the specified cache key exists unpack the tarball into the specified directory otherwise raise NotInCache ( a KeyError subclass ). | def unpackFromCache(cache_key, to_directory):
''' If the specified cache key exists, unpack the tarball into the
specified directory, otherwise raise NotInCache (a KeyError subclass).
'''
if cache_key is None:
raise NotInCache('"None" is never in cache')
cache_key = _encodeCacheKey(cach... |
Download the specified stream to a temporary cache directory and returns a cache key that can be used to access/ remove the file. You should use either removeFromCache ( cache_key ) or _moveCachedFile to move the downloaded file to a known key after downloading. | def _downloadToCache(stream, hashinfo={}, origin_info=dict()):
''' Download the specified stream to a temporary cache directory, and
returns a cache key that can be used to access/remove the file.
You should use either removeFromCache(cache_key) or _moveCachedFile to
move the downloaded file... |
Move a file atomically within the cache: used to make cached files available at known keys so they can be used by other processes. | def _moveCachedFile(from_key, to_key):
''' Move a file atomically within the cache: used to make cached files
available at known keys, so they can be used by other processes.
'''
cache_dir = folders.cacheDirectory()
from_path = os.path.join(cache_dir, from_key)
to_path = os.path.join(cache... |
Unpack a responses stream that contains a tarball into a directory. If a hash is provided then it will be used as a cache key ( for future requests you can try to retrieve the key value from the cache first before making the request ) | def unpackTarballStream(stream, into_directory, hash={}, cache_key=None, origin_info=dict()):
''' Unpack a responses stream that contains a tarball into a directory. If
a hash is provided, then it will be used as a cache key (for future
requests you can try to retrieve the key value from the cache f... |
Parse the specified version source URL ( or version spec ) and return an instance of VersionSource | def parseSourceURL(source_url):
''' Parse the specified version source URL (or version spec), and return an
instance of VersionSource
'''
name, spec = _getNonRegistryRef(source_url)
if spec:
return spec
try:
url_is_spec = version.Spec(source_url)
except ValueError:
... |
Parse targetname [ @versionspec ] and return a tuple ( target_name_string version_spec_string ). | def parseTargetNameAndSpec(target_name_and_spec):
''' Parse targetname[@versionspec] and return a tuple
(target_name_string, version_spec_string).
targetname[,versionspec] is also supported (this is how target names
and specifications are stored internally, and was the documented way of
... |
Parse modulename [ @versionspec ] and return a tuple ( module_name_string version_spec_string ). | def parseModuleNameAndSpec(module_name_and_spec):
''' Parse modulename[@versionspec] and return a tuple
(module_name_string, version_spec_string).
Also accepts raw github version specs (Owner/reponame#whatever), as the
name can be deduced from these.
Note that the specification spl... |
Fit empirical Bayes prior in the hierarchical model [ Efron2014 ] _. | def gfit(X, sigma, p=5, nbin=200, unif_fraction=0.1):
"""
Fit empirical Bayes prior in the hierarchical model [Efron2014]_.
.. math::
mu ~ G, X ~ N(mu, sigma^2)
Parameters
----------
X: ndarray
A 1D array of observations.
sigma: float
Noise estimate on X.
p: in... |
Estimate Bayes posterior with Gaussian noise [ Efron2014 ] _. | def gbayes(x0, g_est, sigma):
"""
Estimate Bayes posterior with Gaussian noise [Efron2014]_.
Parameters
----------
x0: ndarray
an observation
g_est: float
a prior density, as returned by gfit
sigma: int
noise estimate
Returns
-------
An array of the post... |
Calibrate noisy variance estimates with empirical Bayes. | def calibrateEB(variances, sigma2):
"""
Calibrate noisy variance estimates with empirical Bayes.
Parameters
----------
vars: ndarray
List of variance estimates.
sigma2: int
Estimate of the Monte Carlo noise in vars.
Returns
-------
An array of the calibrated varianc... |
Derive samples used to create trees in scikit - learn RandomForest objects. | def calc_inbag(n_samples, forest):
"""
Derive samples used to create trees in scikit-learn RandomForest objects.
Recovers the samples in each tree from the random state of that tree using
:func:`forest._generate_sample_indices`.
Parameters
----------
n_samples : int
The number of s... |
Helper function that performs the core computation | def _core_computation(X_train, X_test, inbag, pred_centered, n_trees,
memory_constrained=False, memory_limit=None,
test_mode=False):
"""
Helper function, that performs the core computation
Parameters
----------
X_train : ndarray
An array with shap... |
Helper functions that implements bias correction | def _bias_correction(V_IJ, inbag, pred_centered, n_trees):
"""
Helper functions that implements bias correction
Parameters
----------
V_IJ : ndarray
Intermediate result in the computation.
inbag : ndarray
The inbag matrix that fit the data. If set to `None` (default) it
... |
Calculate error bars from scikit - learn RandomForest estimators. | def random_forest_error(forest, X_train, X_test, inbag=None,
calibrate=True, memory_constrained=False,
memory_limit=None):
"""
Calculate error bars from scikit-learn RandomForest estimators.
RandomForest is a regressor or classifier object
this variance c... |
Generates a self - signed certificate for use in an internal development environment for testing SSL pages. | def generate_self_signed_certificate(self, domain='', r=None):
"""
Generates a self-signed certificate for use in an internal development
environment for testing SSL pages.
http://almostalldigital.wordpress.com/2013/03/07/self-signed-ssl-certificate-for-ec2-load-balancer/
"""
... |
Creates a certificate signing request to be submitted to a formal certificate authority to generate a certificate. | def generate_csr(self, domain='', r=None):
"""
Creates a certificate signing request to be submitted to a formal
certificate authority to generate a certificate.
Note, the provider may say the CSR must be created on the target server,
but this is not necessary.
"""
... |
Reads the expiration date of a local crt file. | def get_expiration_date(self, fn):
"""
Reads the expiration date of a local crt file.
"""
r = self.local_renderer
r.env.crt_fn = fn
with hide('running'):
ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True)
matches = re.findall('n... |
Scans through all local. crt files and displays the expiration dates. | def list_expiration_dates(self, base='roles/all/ssl'):
"""
Scans through all local .crt files and displays the expiration dates.
"""
max_fn_len = 0
max_date_len = 0
data = []
for fn in os.listdir(base):
fqfn = os.path.join(base, fn)
if not ... |
Confirms the key CSR and certificate files all match. | def verify_certificate_chain(self, base=None, crt=None, csr=None, key=None):
"""
Confirms the key, CSR, and certificate files all match.
"""
from burlap.common import get_verbose, print_fail, print_success
r = self.local_renderer
if base:
crt = base + '.crt'... |
Dynamically creates a Fabric task for each configuration role. | def _get_environ_handler(name, d):
"""
Dynamically creates a Fabric task for each configuration role.
"""
def func(site=None, **kwargs):
from fabric import state
# We can't auto-set default_site, because that break tasks that have
# to operate over multiple sites.
# If ... |
Recursively merges two dictionaries. | def update_merge(d, u):
"""
Recursively merges two dictionaries.
Uses fabric's AttributeDict so you can reference values via dot-notation.
e.g. env.value1.value2.value3...
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
"""
import collections... |
Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available. | def check_version():
"""
Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available.
This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.
"""
global CHECK_VERSION
if not CHECK_VERSION:
... |
Automatically includes all submodules and role selectors in the top - level fabfile using spooky - scary black magic. | def populate_fabfile():
"""
Automatically includes all submodules and role selectors
in the top-level fabfile using spooky-scary black magic.
This allows us to avoid manually declaring imports for every module, e.g.
import burlap.pip
import burlap.vm
import burlap...
which... |
Decorator declaring the wrapped function to be a new - style task. | def task_or_dryrun(*args, **kwargs):
"""
Decorator declaring the wrapped function to be a new-style task.
May be invoked as a simple, argument-less decorator (i.e. ``@task``) or
with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).
Please see the :ref:`new-style task <task-dec... |
Decorator for registering a satchel method as a Fabric task. | def task(*args, **kwargs):
"""
Decorator for registering a satchel method as a Fabric task.
Can be used like:
@task
def my_method(self):
...
@task(precursors=['other_satchel'])
def my_method(self):
...
"""
precursors = kwargs.pop('precursor... |
A wrapper around Fabric s runs_once () to support our dryrun feature. | def runs_once(meth):
"""
A wrapper around Fabric's runs_once() to support our dryrun feature.
"""
from burlap.common import get_dryrun, runs_once_methods
if get_dryrun():
pass
else:
runs_once_methods.append(meth)
_runs_once(meth)
return meth |
Check if a path exists and is a file. | def is_file(self, path, use_sudo=False):
"""
Check if a path exists, and is a file.
"""
if self.is_local and not use_sudo:
return os.path.isfile(path)
else:
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), warn_... |
Check if a path exists and is a directory. | def is_dir(self, path, use_sudo=False):
"""
Check if a path exists, and is a directory.
"""
if self.is_local and not use_sudo:
return os.path.isdir(path)
else:
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), wa... |
Check if a path exists and is a symbolic link. | def is_link(self, path, use_sudo=False):
"""
Check if a path exists, and is a symbolic link.
"""
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), warn_only=True):
return func('[ -L "%(path)s" ]' % locals()).succeeded |
Get the owner name of a file or directory. | def get_owner(self, path, use_sudo=False):
"""
Get the owner name of a file or directory.
"""
func = use_sudo and run_as_root or self.run
# I'd prefer to use quiet=True, but that's not supported with older
# versions of Fabric.
with self.settings(hide('running', '... |
Get the user s umask. | def umask(self, use_sudo=False):
"""
Get the user's umask.
Returns a string such as ``'0002'``, representing the user's umask
as an octal number.
If `use_sudo` is `True`, this function returns root's umask.
"""
func = use_sudo and run_as_root or self.run
... |
Upload a template file. | def upload_template(self, filename, destination, context=None, use_jinja=False,
template_dir=None, use_sudo=False, backup=True,
mirror_local_mode=False, mode=None,
mkdir=False, chown=False, user=None):
"""
Upload a template file.
... |
Compute the MD5 sum of a file. | def md5sum(self, filename, use_sudo=False):
"""
Compute the MD5 sum of a file.
"""
func = use_sudo and run_as_root or self.run
with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
# Linux (LSB)
if exists(u'/usr/bin/md5sum'):... |
Get the lines of a remote file ignoring empty or commented ones | def uncommented_lines(self, filename, use_sudo=False):
"""
Get the lines of a remote file, ignoring empty or commented ones
"""
func = run_as_root if use_sudo else self.run
res = func('cat %s' % quote(filename), quiet=True)
if res.succeeded:
return [line for l... |
Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch | def getmtime(self, path, use_sudo=False):
"""
Return the time of last modification of path.
The return value is a number giving the number of seconds since the epoch
Same as :py:func:`os.path.getmtime()`
"""
func = use_sudo and run_as_root or self.run
with self.s... |
Copy a file or directory | def copy(self, source, destination, recursive=False, use_sudo=False):
"""
Copy a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination))) |
Move a file or directory | def move(self, source, destination, use_sudo=False):
"""
Move a file or directory
"""
func = use_sudo and run_as_root or self.run
func('/bin/mv {0} {1}'.format(quote(source), quote(destination))) |
Remove a file or directory | def remove(self, path, recursive=False, use_sudo=False):
"""
Remove a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/rm {0}{1}'.format(options, quote(path))) |
Require a file to exist and have specific contents and properties. | def require(self, path=None, contents=None, source=None, url=None, md5=None,
use_sudo=False, owner=None, group='', mode=None, verify_remote=True,
temp_dir='/tmp'):
"""
Require a file to exist and have specific contents and properties.
You can provide either:
- *conten... |
Determines if a new release has been made. | def check_for_change(self):
"""
Determines if a new release has been made.
"""
r = self.local_renderer
lm = self.last_manifest
last_fingerprint = lm.fingerprint
current_fingerprint = self.get_target_geckodriver_version_number()
self.vprint('last_fingerprin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.