INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Returns the function signature string for memberdef nodes. | def get_function_signature(self, node):
"""Returns the function signature string for memberdef nodes."""
name = self.extract_text(self.get_specific_subnodes(node, 'name'))
if self.with_type_info:
argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))
e... |
Produces the "Constructors" section and the constructor signatures
(since swig does not do so for classes) for class docstrings. | def make_constructor_list(self, constructor_nodes, classname):
"""Produces the "Constructors" section and the constructor signatures
(since swig does not do so for classes) for class docstrings."""
if constructor_nodes == []:
return
self.add_text(['\n', 'Constructors',
... |
Produces the "Attributes" section in class docstrings for public
member variables (attributes). | def make_attribute_list(self, node):
"""Produces the "Attributes" section in class docstrings for public
member variables (attributes).
"""
atr_nodes = []
for n in self.get_specific_subnodes(node, 'memberdef', recursive=2):
if n.attributes['kind'].value == 'variable' ... |
Collects the memberdef nodes and corresponding signatures that
correspond to public function entries that are at most depth 2 deeper
than the current (compounddef) node. Returns a dictionary with
function signatures (what swig expects after the %feature directive)
as keys, and a list of... | def get_memberdef_nodes_and_signatures(self, node, kind):
"""Collects the memberdef nodes and corresponding signatures that
correspond to public function entries that are at most depth 2 deeper
than the current (compounddef) node. Returns a dictionary with
function signatures (what swig... |
Produce standard documentation for memberdef_nodes. | def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes):
"""Produce standard documentation for memberdef_nodes."""
for n in memberdef_nodes:
self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n'])
if self.with_function_signature:
... |
Produces docstring entries containing an "Overloaded function"
section with the documentation for each overload, if the function is
overloaded and self.with_overloaded_functions is set. Else, produce
normal documentation. | def handle_typical_memberdefs(self, signature, memberdef_nodes):
"""Produces docstring entries containing an "Overloaded function"
section with the documentation for each overload, if the function is
overloaded and self.with_overloaded_functions is set. Else, produce
normal documentation... |
This is the only place where text wrapping is automatically performed.
Generally, this function parses the node (locally), wraps the text, and
then adds the result to self.pieces. However, it may be convenient to
allow the previous content of self.pieces to be included in the text
wrappi... | def do_para(self, node):
"""This is the only place where text wrapping is automatically performed.
Generally, this function parses the node (locally), wraps the text, and
then adds the result to self.pieces. However, it may be convenient to
allow the previous content of self.pieces to be... |
This produces %feature("docstring") entries for classes, and handles
class, namespace and file memberdef entries specially to allow for
overloaded functions. For other cases, passes parsing on to standard
handlers (which may produce unexpected results). | def do_compounddef(self, node):
"""This produces %feature("docstring") entries for classes, and handles
class, namespace and file memberdef entries specially to allow for
overloaded functions. For other cases, passes parsing on to standard
handlers (which may produce unexpected results)... |
Handle cases outside of class, struct, file or namespace. These are
now dealt with by `handle_overloaded_memberfunction`.
Do these even exist??? | def do_memberdef(self, node):
"""Handle cases outside of class, struct, file or namespace. These are
now dealt with by `handle_overloaded_memberfunction`.
Do these even exist???
"""
prot = node.attributes['prot'].value
id = node.attributes['id'].value
kind = node.... |
For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output. | def do_header(self, node):
"""For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output."""
data = self.extract_text(node)
self.add_text('\n/*\n %s \n*/\n' % data)
# If our immediate sibling is a 'descript... |
Decide whether to show documentation on a variable. | def visiblename(name, all=None, obj=None):
"""Decide whether to show documentation on a variable."""
# Certain special names are redundant or internal.
# XXX Remove __initializing__?
if name in {'__author__', '__builtins__', '__cached__', '__credits__',
'__date__', '__doc__', '__fil... |
Download the bulk API result file for a single batch | def _download_file(uri, bulk_api):
"""Download the bulk API result file for a single batch"""
resp = requests.get(uri, headers=bulk_api.headers(), stream=True)
with tempfile.TemporaryFile("w+b") as f:
for chunk in resp.iter_content(chunk_size=None):
f.write(chunk)
f.seek(0)
... |
Yield successive n-sized chunks from l. | def _split_batches(self, data, batch_size):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(data), batch_size):
yield data[i : i + batch_size] |
Load data for a single step. | def _load_mapping(self, mapping):
"""Load data for a single step."""
mapping["oid_as_pk"] = bool(mapping.get("fields", {}).get("Id"))
job_id, local_ids_for_batch = self._create_job(mapping)
result = self._wait_for_job(job_id)
# We store inserted ids even if some batches failed
... |
Initiate a bulk insert and upload batches to run in parallel. | def _create_job(self, mapping):
"""Initiate a bulk insert and upload batches to run in parallel."""
job_id = self.bulk.create_insert_job(mapping["sf_object"], contentType="CSV")
self.logger.info(" Created bulk job {}".format(job_id))
# Upload batches
local_ids_for_batch = {}
... |
Get data from the local db | def _get_batches(self, mapping, batch_size=10000):
"""Get data from the local db"""
action = mapping.get("action", "insert")
fields = mapping.get("fields", {}).copy()
static = mapping.get("static", {})
lookups = mapping.get("lookups", {})
record_type = mapping.get("record... |
Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining to the id tables to get real SF ids
for lookups. | def _query_db(self, mapping):
"""Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining to the id tables to get real SF ids
for lookups.
"""
model = self.models[mapping.get("table")]
# Use primary key instead of th... |
Get the job results and store inserted SF Ids in a new table | def _store_inserted_ids(self, mapping, job_id, local_ids_for_batch):
"""Get the job results and store inserted SF Ids in a new table"""
id_table_name = self._reset_id_table(mapping)
conn = self.session.connection()
for batch_id, local_ids in local_ids_for_batch.items():
try:
... |
Create an empty table to hold the inserted SF Ids | def _reset_id_table(self, mapping):
"""Create an empty table to hold the inserted SF Ids"""
if not hasattr(self, "_initialized_id_tables"):
self._initialized_id_tables = set()
id_table_name = "{}_sf_ids".format(mapping["table"])
if id_table_name not in self._initialized_id_ta... |
Returns the first mapping for a table name | def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping |
Loads the configuration from YAML, if no override config was passed in initially. | def _load_config(self):
""" Loads the configuration from YAML, if no override config was passed in initially. """
if (
self.config
): # any config being pre-set at init will short circuit out, but not a plain {}
return
# Verify that we're in a project
r... |
Initializes sentry.io error logging for this session | def init_sentry(self,):
""" Initializes sentry.io error logging for this session """
if not self.use_sentry:
return
sentry_config = self.keychain.get_service("sentry")
tags = {
"repo": self.repo_name,
"branch": self.repo_branch,
"commit":... |
Query GitHub releases to find the previous production release | def get_previous_version(self):
"""Query GitHub releases to find the previous production release"""
gh = self.get_github_api()
repo = gh.repository(self.repo_owner, self.repo_name)
most_recent = None
for release in repo.releases():
# Return the second release that mat... |
location of the user local directory for the project
e.g., ~/.cumulusci/NPSP-Extension-Test/ | def project_local_dir(self):
""" location of the user local directory for the project
e.g., ~/.cumulusci/NPSP-Extension-Test/ """
# depending on where we are in bootstrapping the BaseGlobalConfig
# the canonical projectname could be located in one of two places
if self.project__... |
Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a list of dependencies to resolve
:param include_beta: when tru... | def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param d... |
Initializes self.logger | def _init_logger(self):
""" Initializes self.logger """
if self.flow:
self.logger = self.flow.logger.getChild(self.__class__.__name__)
else:
self.logger = logging.getLogger(__name__) |
Initializes self.options | def _init_options(self, kwargs):
""" Initializes self.options """
self.options = self.task_config.options
if self.options is None:
self.options = {}
if kwargs:
self.options.update(kwargs)
# Handle dynamic lookup of project_config values via $project_confi... |
Log the beginning of the task execution | def _log_begin(self):
""" Log the beginning of the task execution """
self.logger.info("Beginning task: %s", self.__class__.__name__)
if self.salesforce_task and not self.flow:
self.logger.info("%15s %s", "As user:", self.org_config.username)
self.logger.info("%15s %s", "... |
poll for a result in a loop | def _poll(self):
""" poll for a result in a loop """
while True:
self.poll_count += 1
self._poll_action()
if self.poll_complete:
break
time.sleep(self.poll_interval_s)
self._poll_update_interval() |
update the polling interval to be used next iteration | def _poll_update_interval(self):
""" update the polling interval to be used next iteration """
# Increase by 1 second every 3 polls
if old_div(self.poll_count, 3) > self.poll_interval_level:
self.poll_interval_level += 1
self.poll_interval_s += 1
self.logger.i... |
Returns a ProjectConfig for the given project | def get_project_config(self, *args, **kwargs):
""" Returns a ProjectConfig for the given project """
warnings.warn(
"BaseGlobalConfig.get_project_config is pending deprecation",
DeprecationWarning,
)
return self.project_config_class(self, *args, **kwargs) |
Loads the local configuration | def _load_config(self):
""" Loads the local configuration """
# load the global config
with open(self.config_global_path, "r") as f_config:
config = ordered_yaml_load(f_config)
self.config_global = config
# Load the local config
if self.config_global_local_pa... |
Username for the org connection. | def username(self):
""" Username for the org connection. """
username = self.config.get("username")
if not username:
username = self.userinfo__preferred_username
return username |
Opens a file for tracking the time of the last version check | def timestamp_file():
"""Opens a file for tracking the time of the last version check"""
config_dir = os.path.join(
os.path.expanduser("~"), BaseGlobalConfig.config_local_dir
)
if not os.path.exists(config_dir):
os.mkdir(config_dir)
timestamp_file = os.path.join(config_dir, "cumulu... |
Decorator which passes the CCI config object as the first arg to a click command. | def pass_config(func=None, **config_kw):
"""Decorator which passes the CCI config object as the first arg to a click command."""
def decorate(func):
def new_func(*args, **kw):
config = load_config(**config_kw)
func(config, *args, **kw)
return functools.update_wrapper(ne... |
list the services that can be configured | def list_commands(self, ctx):
""" list the services that can be configured """
config = load_config(**self.load_config_kwargs)
services = self._get_services_config(config)
return sorted(services.keys()) |
parse a datetime returned from the salesforce API.
in python 3 we should just use a strptime %z, but until then we're just going
to assert that its a fixed offset of +0000 since thats the observed behavior. getting
python 2 to support fixed offset parsing is too complicated for what we need imo. | def parse_api_datetime(value):
""" parse a datetime returned from the salesforce API.
in python 3 we should just use a strptime %z, but until then we're just going
to assert that its a fixed offset of +0000 since thats the observed behavior. getting
python 2 to support fixed offset parsing is too compl... |
Recursively walk a directory and remove XML elements | def removeXmlElement(name, directory, file_pattern, logger=None):
""" Recursively walk a directory and remove XML elements """
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, file_pattern):
filepath = os.path.join(path, filename)
... |
Remove XML elements from a single file | def remove_xml_element_file(name, path):
""" Remove XML elements from a single file """
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = elementtree_parse_file(path)
tree = remove_xml_element(name, tree)
return tree.write(path, encoding=UTF8, xml_declaration=True) |
Remove XML elements from a string | def remove_xml_element_string(name, content):
""" Remove XML elements from a string """
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = ET.fromstring(content)
tree = remove_xml_element(name, tree)
clean_content = ET.tostring(tree, encoding=UTF8)
return clean_content |
Removes XML elements from an ElementTree content tree | def remove_xml_element(name, tree):
""" Removes XML elements from an ElementTree content tree """
# root = tree.getroot()
remove = tree.findall(
".//{{http://soap.sforce.com/2006/04/metadata}}{}".format(name)
)
if not remove:
return tree
parent_map = {c: p for p in tree.iter() f... |
Replaces %%%NAMESPACE%%% for all files and ___NAMESPACE___ in all
filenames in the zip with the either '' if no namespace is provided
or 'namespace__' if provided. | def zip_inject_namespace(
zip_src,
namespace=None,
managed=None,
filename_token=None,
namespace_token=None,
namespaced_org=None,
logger=None,
):
""" Replaces %%%NAMESPACE%%% for all files and ___NAMESPACE___ in all
filenames in the zip with the either '' if no namespace is provid... |
Given a namespace, strips 'namespace__' from all files and filenames
in the zip | def zip_strip_namespace(zip_src, namespace, logger=None):
""" Given a namespace, strips 'namespace__' from all files and filenames
in the zip
"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZI... |
Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%% for all
files and ___NAMESPACE___ in all filenames in the zip | def zip_tokenize_namespace(zip_src, namespace, logger=None):
""" Given a namespace, replaces 'namespace__' with %%%NAMESPACE%%% for all
files and ___NAMESPACE___ in all filenames in the zip
"""
if not namespace:
return zip_src
namespace_prefix = "{}__".format(namespace)
lightning_na... |
Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements | def zip_clean_metaxml(zip_src, logger=None):
""" Given a zipfile, cleans all *-meta.xml files in the zip for
deployment by stripping all <packageVersions/> elements
"""
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED)
changed = []
for name in zip_src.namelist():
co... |
Document a (project specific) task configuration in RST format. | def doc_task(task_name, task_config, project_config=None, org_config=None):
""" Document a (project specific) task configuration in RST format. """
from cumulusci.core.utils import import_class
doc = []
doc.append("{}\n==========================================\n".format(task_name))
doc.append("**D... |
Context manager that creates a temporary directory and chdirs to it.
When the context manager exits it returns to the previous cwd
and deletes the temporary directory. | def temporary_dir():
"""Context manager that creates a temporary directory and chdirs to it.
When the context manager exits it returns to the previous cwd
and deletes the temporary directory.
"""
d = tempfile.mkdtemp()
try:
with cd(d):
yield d
finally:
if os.path... |
Returns a boolean for whether filepath is contained in dirpath.
Normalizes the paths (e.g. resolving symlinks and ..)
so this is the safe way to make sure a user-configured path
is located inside the user's project repo. | def in_directory(filepath, dirpath):
"""Returns a boolean for whether filepath is contained in dirpath.
Normalizes the paths (e.g. resolving symlinks and ..)
so this is the safe way to make sure a user-configured path
is located inside the user's project repo.
"""
filepath = os.path.realpath(fi... |
Log progress while iterating. | def log_progress(
iterable,
logger,
batch_size=10000,
progress_message="Processing... ({})",
done_message="Done! (Total: {})",
):
"""Log progress while iterating.
"""
i = 0
for x in iterable:
yield x
i += 1
if not i % batch_size:
logger.info(progre... |
Returns the login url which will automatically log into the target
Salesforce org. By default, the org_name passed to the library
constructor is used but this can be overridden with the org option
to log into a different org. | def login_url(self, org=None):
""" Returns the login url which will automatically log into the target
Salesforce org. By default, the org_name passed to the library
constructor is used but this can be overridden with the org option
to log into a different org.
"""
... |
Runs a named CumulusCI task for the current project with optional
support for overriding task options via kwargs.
Examples:
| =Keyword= | =task_name= | =task_options= | =comment= |
| Run Task | deploy | ... | def run_task(self, task_name, **options):
""" Runs a named CumulusCI task for the current project with optional
support for overriding task options via kwargs.
Examples:
| =Keyword= | =task_name= | =task_options= | =comment= |
|... |
Returns the namespace prefix (including __) for the specified package name.
(Defaults to project__package__name_managed from the current project config.)
Returns an empty string if the package is not installed as a managed package. | def get_namespace_prefix(self, package=None):
""" Returns the namespace prefix (including __) for the specified package name.
(Defaults to project__package__name_managed from the current project config.)
Returns an empty string if the package is not installed as a managed package.
"""
... |
Runs a CumulusCI task class with task options via kwargs.
Use this keyword to run logic from CumulusCI tasks which have not
been configured in the project's cumulusci.yml file. This is
most useful in cases where a test needs to use task logic for
logic unique to the tes... | def run_task_class(self, class_path, **options):
""" Runs a CumulusCI task class with task options via kwargs.
Use this keyword to run logic from CumulusCI tasks which have not
been configured in the project's cumulusci.yml file. This is
most useful in cases where a test ne... |
Returns a TaskConfig | def get_task(self, name):
""" Returns a TaskConfig """
config = getattr(self, "tasks__{}".format(name))
if not config:
raise TaskNotFoundError("Task not found: {}".format(name))
return TaskConfig(config) |
Returns a FlowConfig | def get_flow(self, name):
""" Returns a FlowConfig """
config = getattr(self, "flows__{}".format(name))
if not config:
raise FlowNotFoundError("Flow not found: {}".format(name))
return FlowConfig(config) |
Returns the rendered release notes from all parsers as a string | def render(self):
""" Returns the rendered release notes from all parsers as a string """
release_notes = []
for parser in self.parsers:
parser_content = parser.render()
if parser_content is not None:
release_notes.append(parser_content)
return u"\... |
Merge existing and new release content. | def _update_release_content(self, release, content):
"""Merge existing and new release content."""
if release.body:
new_body = []
current_parser = None
is_start_line = False
for parser in self.parsers:
parser.replaced = False
#... |
Get a primed and readytogo flow coordinator. | def get_flow(self, name, options=None):
""" Get a primed and readytogo flow coordinator. """
config = self.project_config.get_flow(name)
callbacks = self.callback_class()
coordinator = FlowCoordinator(
self.project_config,
config,
name=name,
... |
loads the environment variables as unicode if ascii | def _get_env(self):
""" loads the environment variables as unicode if ascii """
env = {}
for k, v in os.environ.items():
k = k.decode() if isinstance(k, bytes) else k
v = v.decode() if isinstance(v, bytes) else v
env[k] = v
return list(env.items()) |
Import a class from a string module class path | def import_class(path):
""" Import a class from a string module class path """
components = path.split(".")
module = components[:-1]
module = ".".join(module)
mod = __import__(module, fromlist=[native_str(components[-1])])
return getattr(mod, native_str(components[-1])) |
Create a timezone-aware datetime object from a datetime string. | def parse_datetime(dt_str, format):
"""Create a timezone-aware datetime object from a datetime string."""
t = time.strptime(dt_str, format)
return datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], pytz.UTC) |
Determine True/False from argument | def process_bool_arg(arg):
""" Determine True/False from argument """
if isinstance(arg, bool):
return arg
elif isinstance(arg, basestring):
if arg.lower() in ["true", "1"]:
return True
elif arg.lower() in ["false", "0"]:
return False |
Parse a string into a list separated by commas with whitespace stripped | def process_list_arg(arg):
""" Parse a string into a list separated by commas with whitespace stripped """
if isinstance(arg, list):
return arg
elif isinstance(arg, basestring):
args = []
for part in arg.split(","):
args.append(part.strip())
return args |
decode ISO-8859-1 to unicode, when using sf api | def decode_to_unicode(content):
""" decode ISO-8859-1 to unicode, when using sf api """
if content and not isinstance(content, str):
try:
# Try to decode ISO-8859-1 to unicode
return content.decode("ISO-8859-1")
except UnicodeEncodeError:
# Assume content is u... |
recursively deep-merge the configs into one another (highest priority comes first) | def merge_config(configs):
""" recursively deep-merge the configs into one another (highest priority comes first) """
new_config = {}
for name, config in configs.items():
new_config = dictmerge(new_config, config, name)
return new_config |
Deeply merge two ``dict``s that consist of lists, dicts, and scalars.
This function (recursively) merges ``b`` INTO ``a``, does not copy any values, and returns ``a``.
based on https://stackoverflow.com/a/15836901/5042831
NOTE: tuples and arbitrary objects are NOT handled and will raise TypeError | def dictmerge(a, b, name=None):
""" Deeply merge two ``dict``s that consist of lists, dicts, and scalars.
This function (recursively) merges ``b`` INTO ``a``, does not copy any values, and returns ``a``.
based on https://stackoverflow.com/a/15836901/5042831
NOTE: tuples and arbitrary objects are NOT ha... |
Create a Version in MetaDeploy if it doesn't already exist | def _find_or_create_version(self, product):
"""Create a Version in MetaDeploy if it doesn't already exist
"""
tag = self.options["tag"]
label = self.project_config.get_version_for_tag(tag)
result = self._call_api(
"GET", "/versions", params={"product": product["id"],... |
Generate the html. `libraries` is a list of LibraryDocumentation objects | def _render_html(self, libraries):
"""Generate the html. `libraries` is a list of LibraryDocumentation objects"""
title = self.options.get("title", "Keyword Documentation")
date = time.strftime("%A %B %d, %I:%M %p")
cci_version = cumulusci.__version__
stylesheet_path = os.path.... |
Uses sfdx force:org:create to create the org | def create_org(self):
""" Uses sfdx force:org:create to create the org """
if not self.config_file:
# FIXME: raise exception
return
if not self.scratch_org_type:
self.config["scratch_org_type"] = "workspace"
# If the scratch org definition itself cont... |
Generates an org password with the sfdx utility. | def generate_password(self):
"""Generates an org password with the sfdx utility. """
if self.password_failed:
self.logger.warning("Skipping resetting password since last attempt failed")
return
# Set a random password so it's available via cci org info
command =... |
Uses sfdx force:org:delete to delete the org | def delete_org(self):
""" Uses sfdx force:org:delete to delete the org """
if not self.created:
self.logger.info(
"Skipping org deletion: the scratch org has not been created"
)
return
command = sarge.shell_format("sfdx force:org:delete -p -u ... |
Use sfdx force:org:describe to refresh token instead of built in OAuth handling | def refresh_oauth_token(self, keychain):
""" Use sfdx force:org:describe to refresh token instead of built in OAuth handling """
if hasattr(self, "_scratch_info"):
# Cache the scratch_info for 1 hour to avoid unnecessary calls out
# to sfdx CLI
delta = datetime.dateti... |
returns the time (in seconds) that the batch took, if complete | def delta(self):
""" returns the time (in seconds) that the batch took, if complete """
completed_date = parse_api_datetime(self.batch["CompletedDate"])
created_date = parse_api_datetime(self.batch["CreatedDate"])
td = completed_date - created_date
return td.total_seconds() |
Convert Connected App to service | def _convert_connected_app(self):
"""Convert Connected App to service"""
if self.services and "connected_app" in self.services:
# already a service
return
connected_app = self.get_connected_app()
if not connected_app:
# not configured
retur... |
Creates all scratch org configs for the project in the keychain if
a keychain org doesn't already exist | def _load_scratch_orgs(self):
""" Creates all scratch org configs for the project in the keychain if
a keychain org doesn't already exist """
current_orgs = self.list_orgs()
if not self.project_config.orgs__scratch:
return
for config_name in self.project_config.or... |
Adds/Updates a scratch org config to the keychain from a named config | def create_scratch_org(self, org_name, config_name, days=None, set_password=True):
""" Adds/Updates a scratch org config to the keychain from a named config """
scratch_config = getattr(
self.project_config, "orgs__scratch__{}".format(config_name)
)
if days is not None:
... |
re-encrypt stored services and orgs with the new key | def change_key(self, key):
""" re-encrypt stored services and orgs with the new key """
services = {}
for service_name in self.list_services():
services[service_name] = self.get_service(service_name)
orgs = {}
for org_name in self.list_orgs():
orgs[org_n... |
retrieve the name and configuration of the default org | def get_default_org(self):
""" retrieve the name and configuration of the default org """
for org in self.list_orgs():
org_config = self.get_org(org)
if org_config.default:
return org, org_config
return None, None |
set the default org for tasks by name key | def set_default_org(self, name):
""" set the default org for tasks by name key """
org = self.get_org(name)
self.unset_default_org()
org.config["default"] = True
self.set_org(org) |
unset the default orgs for tasks | def unset_default_org(self):
""" unset the default orgs for tasks """
for org in self.list_orgs():
org_config = self.get_org(org)
if org_config.default:
del org_config.config["default"]
self.set_org(org_config) |
retrieve an org configuration by name key | def get_org(self, name):
""" retrieve an org configuration by name key """
if name not in self.orgs:
self._raise_org_not_found(name)
return self._get_org(name) |
list the orgs configured in the keychain | def list_orgs(self):
""" list the orgs configured in the keychain """
orgs = list(self.orgs.keys())
orgs.sort()
return orgs |
Store a ServiceConfig in the keychain | def set_service(self, name, service_config, project=False):
""" Store a ServiceConfig in the keychain """
if not self.project_config.services or name not in self.project_config.services:
self._raise_service_not_valid(name)
self._validate_service(name, service_config)
self._se... |
Retrieve a stored ServiceConfig from the keychain or exception
:param name: the service name to retrieve
:type name: str
:rtype ServiceConfig
:return the configured Service | def get_service(self, name):
""" Retrieve a stored ServiceConfig from the keychain or exception
:param name: the service name to retrieve
:type name: str
:rtype ServiceConfig
:return the configured Service
"""
self._convert_connected_app()
if not self.pr... |
list the services configured in the keychain | def list_services(self):
""" list the services configured in the keychain """
services = list(self.services.keys())
services.sort()
return services |
Start the Python debugger when robotframework is running.
This makes sure that pdb can use stdin/stdout even though
robotframework has redirected I/O. | def set_pdb_trace(pm=False):
"""Start the Python debugger when robotframework is running.
This makes sure that pdb can use stdin/stdout even though
robotframework has redirected I/O.
"""
import sys
import pdb
for attr in ("stdin", "stdout", "stderr"):
setattr(sys, attr, getattr(sys... |
Decorator to turn on automatic retries of flaky selenium failures.
Decorate a robotframework library class to turn on retries for all
selenium calls from that library:
@selenium_retry
class MyLibrary(object):
# Decorate a method to turn it back off for that method
@sel... | def selenium_retry(target=None, retry=True):
"""Decorator to turn on automatic retries of flaky selenium failures.
Decorate a robotframework library class to turn on retries for all
selenium calls from that library:
@selenium_retry
class MyLibrary(object):
# Decorate a method ... |
Run a single selenium command and retry once.
The retry happens for certain errors that are likely to be resolved
by retrying. | def selenium_execute_with_retry(self, execute, command, params):
"""Run a single selenium command and retry once.
The retry happens for certain errors that are likely to be resolved
by retrying.
"""
try:
return execute(command, params)
except Exception as e:
... |
Gets the last release tag before self.current_tag | def _get_last_tag(self):
""" Gets the last release tag before self.current_tag """
current_version = LooseVersion(
self._get_version_from_tag(self.release_notes_generator.current_tag)
)
versions = []
for tag in self.repo.tags():
if not tag.name.startswit... |
Gets all pull requests from the repo since we can't do a filtered
date merged search | def _get_pull_requests(self):
""" Gets all pull requests from the repo since we can't do a filtered
date merged search """
for pull in self.repo.pull_requests(
state="closed", base=self.github_info["master_branch"], direction="asc"
):
if self._include_pull_request... |
Checks if the given pull_request was merged to the default branch
between self.start_date and self.end_date | def _include_pull_request(self, pull_request):
""" Checks if the given pull_request was merged to the default branch
between self.start_date and self.end_date """
merged_date = pull_request.merged_at
if not merged_date:
return False
if self.last_tag:
last... |
Monkey patch robotframework to do postmortem debugging | def patch_statusreporter():
"""Monkey patch robotframework to do postmortem debugging
"""
from robot.running.statusreporter import StatusReporter
orig_exit = StatusReporter.__exit__
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val and isinstance(exc_val, Exception):
se... |
Returns the value of the first name element found inside of element | def get_item_name(self, item, parent):
""" Returns the value of the first name element found inside of element """
names = self.get_name_elements(item)
if not names:
raise MissingNameElementError
name = names[0].text
prefix = self.item_name_prefix(parent)
if ... |
Step details formatted for logging output. | def for_display(self):
""" Step details formatted for logging output. """
skip = ""
if self.skip:
skip = " [SKIP]"
result = "{step_num}: {path}{skip}".format(
step_num=self.step_num, path=self.path, skip=skip
)
description = self.task_config.get("d... |
Run a step.
:return: StepResult | def run_step(self):
"""
Run a step.
:return: StepResult
"""
# Resolve ^^task_name.return_value style option syntax
task_config = self.step.task_config.copy()
task_config["options"] = task_config["options"].copy()
self.flow.resolve_return_value_options(ta... |
Given the flow config and everything else, create a list of steps to run, sorted by step number.
:return: List[StepSpec] | def _init_steps(self,):
"""
Given the flow config and everything else, create a list of steps to run, sorted by step number.
:return: List[StepSpec]
"""
self._check_old_yaml_format()
config_steps = self.flow_config.steps
self._check_infinite_flows(config_steps)
... |
for each step (as defined in the flow YAML), _visit_step is called with only
the first two parameters. this takes care of validating the step, collating the
option overrides, and if it is a task, creating a StepSpec for it.
If it is a flow, we recursively call _visit_step with the rest of the p... | def _visit_step(
self,
number,
step_config,
visited_steps=None,
parent_options=None,
parent_ui_options=None,
from_flow=None,
):
"""
for each step (as defined in the flow YAML), _visit_step is called with only
the first two parameters. t... |
Recursively loop through the flow_config and check if there are any cycles.
:param steps: Set of step definitions to loop through
:param flows: Flows already visited.
:return: None | def _check_infinite_flows(self, steps, flows=None):
"""
Recursively loop through the flow_config and check if there are any cycles.
:param steps: Set of step definitions to loop through
:param flows: Flows already visited.
:return: None
"""
if flows is None:
... |
Test and refresh credentials to the org specified. | def _init_org(self):
""" Test and refresh credentials to the org specified. """
self.logger.info(
"Verifying and refreshing credentials for the specified org: {}.".format(
self.org_config.name
)
)
orig_config = self.org_config.config.copy()
... |
Handle dynamic option value lookups in the format ^^task_name.attr | def resolve_return_value_options(self, options):
"""Handle dynamic option value lookups in the format ^^task_name.attr"""
for key, value in options.items():
if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX):
path, name = value[len(RETURN_VALUE_OPTION_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.