Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function:def get_binfo(self):
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(executor)
binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
if self._specific_sources:
sources = [ s for s in self.sources if not s in ignore_set]
else:
sources = executor.get_unignored_sources(self, self.ignore)
seen = set()
binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)]
binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources]
binfo.bdepends = self.depends
binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set]
binfo.bimplicit = self.implicit or []
binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set]
return binfo | [
"\n Fetch a node's build information.\n\n node - the node whose sources will be collected\n cache - alternate node to use for the signature cache\n returns - the build signature\n\n This no longer handles the recursive descent of the\n node's children's signatures. We expect that they're\n already built and updated by someone else, if that's\n what's wanted.\n "
] |
Please provide a description of the function:def add_dependency(self, depend):
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"Adds dependencies."
] |
Please provide a description of the function:def add_prerequisite(self, prerequisite):
if self.prerequisites is None:
self.prerequisites = SCons.Util.UniqueList()
self.prerequisites.extend(prerequisite)
self._children_reset() | [
"Adds prerequisites"
] |
Please provide a description of the function:def add_ignore(self, depend):
try:
self._add_child(self.ignore, self.ignore_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"Adds dependencies to ignore."
] |
Please provide a description of the function:def add_source(self, source):
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e))) | [
"Adds sources."
] |
Please provide a description of the function:def _add_child(self, collection, set, child):
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
if added:
self._children_reset() | [
"Adds 'child' to 'collection', first checking 'set' to see if it's\n already present."
] |
Please provide a description of the function:def all_children(self, scan=1):
if scan:
self.scan()
# The return list may contain duplicate Nodes, especially in
# source trees where there are a lot of repeated #includes
# of a tangle of .h files. Profiling shows, however, that
# eliminating the duplicates with a brute-force approach that
# preserves the order (that is, something like:
#
# u = []
# for n in list:
# if n not in u:
# u.append(n)"
#
# takes more cycles than just letting the underlying methods
# hand back cached values if a Node's information is requested
# multiple times. (Other methods of removing duplicates, like
# using dictionary keys, lose the order, and the only ordered
# dictionary patterns I found all ended up using "not in"
# internally anyway...)
return list(chain.from_iterable([_f for _f in [self.sources, self.depends, self.implicit] if _f])) | [
"Return a list of all the node's direct children."
] |
Please provide a description of the function:def Tag(self, key, value):
if not self._tags:
self._tags = {}
self._tags[key] = value | [
" Add a user-defined tag. "
] |
Please provide a description of the function:def changed(self, node=None, allowcache=False):
t = 0
if t: Trace('changed(%s [%s], %s)' % (self, classname(self), node))
if node is None:
node = self
result = False
bi = node.get_stored_info().binfo
then = bi.bsourcesigs + bi.bdependsigs + bi.bimplicitsigs
children = self.children()
diff = len(children) - len(then)
if diff:
# The old and new dependency lists are different lengths.
# This always indicates that the Node must be rebuilt.
# We also extend the old dependency list with enough None
# entries to equal the new dependency list, for the benefit
# of the loop below that updates node information.
then.extend([None] * diff)
if t: Trace(': old %s new %s' % (len(then), len(children)))
result = True
for child, prev_ni in zip(children, then):
if _decider_map[child.changed_since_last_build](child, self, prev_ni):
if t: Trace(': %s changed' % child)
result = True
contents = self.get_executor().get_contents()
if self.has_builder():
import SCons.Util
newsig = SCons.Util.MD5signature(contents)
if bi.bactsig != newsig:
if t: Trace(': bactsig %s != newsig %s' % (bi.bactsig, newsig))
result = True
if not result:
if t: Trace(': up to date')
if t: Trace('\n')
return result | [
"\n Returns if the node is up-to-date with respect to the BuildInfo\n stored last time it was built. The default behavior is to compare\n it against our own previously stored BuildInfo, but the stored\n BuildInfo from another Node (typically one in a Repository)\n can be used instead.\n\n Note that we now *always* check every dependency. We used to\n short-circuit the check by returning as soon as we detected\n any difference, but we now rely on checking every dependency\n to make sure that any necessary Node information (for example,\n the content signature of an #included .h file) is updated.\n\n The allowcache option was added for supporting the early\n release of the executor/builder structures, right after\n a File target was built. When set to true, the return\n value of this changed method gets cached for File nodes.\n Like this, the executor isn't needed any longer for subsequent\n calls to changed().\n\n @see: FS.File.changed(), FS.File.release_target_info()\n "
] |
Please provide a description of the function:def children_are_up_to_date(self):
# Allow the children to calculate their signatures.
self.binfo = self.get_binfo()
if self.always_build:
return None
state = 0
for kid in self.children(None):
s = kid.get_state()
if s and (not state or s > state):
state = s
return (state == 0 or state == SCons.Node.up_to_date) | [
"Alternate check for whether the Node is current: If all of\n our children were up-to-date, then this Node was up-to-date, too.\n\n The SCons.Node.Alias and SCons.Node.Python.Value subclasses\n rebind their current() method to this method."
] |
Please provide a description of the function:def render_include_tree(self):
if self.is_derived():
env = self.get_build_env()
if env:
for s in self.sources:
scanner = self.get_source_scanner(s)
if scanner:
path = self.get_build_scanner_path(scanner)
else:
path = None
def f(node, env=env, scanner=scanner, path=path):
return node.get_found_includes(env, scanner, path)
return SCons.Util.render_tree(s, f, 1)
else:
return None | [
"\n Return a text representation, suitable for displaying to the\n user, of the include tree for the sources of this node.\n "
] |
Please provide a description of the function:def get_next(self):
while self.stack:
if self.stack[-1].wkids:
node = self.stack[-1].wkids.pop(0)
if not self.stack[-1].wkids:
self.stack[-1].wkids = None
if node in self.history:
self.cycle_func(node, self.stack)
else:
node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
self.stack.append(node)
self.history[node] = None
else:
node = self.stack.pop()
del self.history[node]
if node:
if self.stack:
parent = self.stack[-1]
else:
parent = None
self.eval_func(node, parent)
return node
return None | [
"Return the next node for this walk of the tree.\n\n This function is intentionally iterative, not recursive,\n to sidestep any issues of stack size limitations.\n "
] |
Please provide a description of the function:def sign_report(self, device_id, root, data, **kwargs):
AuthProvider.VerifyRoot(root)
if root != AuthProvider.NoKey:
raise NotFoundError('unsupported root key in BasicAuthProvider', root_key=root)
result = bytearray(hashlib.sha256(data).digest())
return {'signature': result, 'root_key': root} | [
"Sign a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should sign\n **kwargs: There are additional specific keyword args that are required\n depending on the root key used. Typically, you must specify\n - report_id (int): The report id\n - sent_timestamp (int): The sent timestamp of the report\n\n These two bits of information are used to construct the per report\n signing and encryption key from the specific root key type.\n\n Returns:\n dict: The signature and any associated metadata about the signature.\n The signature itself must always be a bytearray stored under the\n 'signature' key, however additional keys may be present depending\n on the signature method used.\n\n Raises:\n NotFoundError: If the auth provider is not able to sign the data.\n "
] |
Please provide a description of the function:def verify_report(self, device_id, root, data, signature, **kwargs):
AuthProvider.VerifyRoot(root)
if root != AuthProvider.NoKey:
raise NotFoundError('unsupported root key in BasicAuthProvider', root_key=root)
result = bytearray(hashlib.sha256(data).digest())
if len(signature) == 0:
verified = False
elif len(signature) > len(result):
verified = False
elif len(signature) < len(result):
trunc_result = result[:len(signature)]
verified = hmac.compare_digest(signature, trunc_result)
else:
verified = hmac.compare_digest(signature, result)
return {'verified': verified, 'bit_length': 8*len(signature)} | [
"Verify a buffer of report data on behalf of a device.\n\n Args:\n device_id (int): The id of the device that we should encrypt for\n root (int): The root key type that should be used to generate the report\n data (bytearray): The data that we should verify\n signature (bytearray): The signature attached to data that we should verify\n **kwargs: There are additional specific keyword args that are required\n depending on the root key used. Typically, you must specify\n - report_id (int): The report id\n - sent_timestamp (int): The sent timestamp of the report\n\n These two bits of information are used to construct the per report\n signing and encryption key from the specific root key type.\n\n Returns:\n dict: The result of the verification process must always be a bool under the\n 'verified' key, however additional keys may be present depending on the\n signature method used.\n\n Raises:\n NotFoundError: If the auth provider is not able to verify the data due to\n an error. If the data is simply not valid, then the function returns\n normally.\n "
] |
Please provide a description of the function:def execute(self, sensor_graph, scope_stack):
parent = scope_stack[-1]
alloc = parent.allocator
trigger_stream, trigger_cond = parent.trigger_chain()
rpc_const = alloc.allocate_stream(DataStream.ConstantType, attach=True)
rpc_val = (self.slot_id.address << 16) | self.rpc_id
stream = self.stream
if stream is None:
stream = alloc.allocate_stream(DataStream.UnbufferedType)
sensor_graph.add_node(u"({} {} && {} always) => {} using call_rpc".format(trigger_stream, trigger_cond, rpc_const, stream))
sensor_graph.add_constant(rpc_const, rpc_val) | [
"Execute this statement on the sensor_graph given the current scope tree.\n\n This adds a single node to the sensor graph with the call_rpc function\n as is processing function.\n\n Args:\n sensor_graph (SensorGraph): The sensor graph that we are building or\n modifying\n scope_stack (list(Scope)): A stack of nested scopes that may influence\n how this statement allocates clocks or other stream resources.\n "
] |
Please provide a description of the function:def timeout_thread_handler(timeout, stop_event):
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2) | [
"A background thread to kill the process if it takes too long.\n\n Args:\n timeout (float): The number of seconds to wait before killing\n the process.\n stop_event (Event): An optional event to cleanly stop the background\n thread if required during testing.\n "
] |
Please provide a description of the function:def create_parser():
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)")
parser.add_argument('-l', '--logfile', help="The file where we should log all logging messages")
parser.add_argument('-i', '--include', action="append", default=[], help="Only include the specified loggers")
parser.add_argument('-e', '--exclude', action="append", default=[], help="Exclude the specified loggers, including all others")
parser.add_argument('-q', '--quit', action="store_true", help="Do not spawn a shell after executing any commands")
parser.add_argument('-t', '--timeout', type=float, help="Do not allow this process to run for more than a specified number of seconds.")
parser.add_argument('commands', nargs=argparse.REMAINDER, help="The command(s) to execute")
return parser | [
"Create the argument parser for iotile."
] |
Please provide a description of the function:def parse_global_args(argv):
parser = create_parser()
args = parser.parse_args(argv)
should_log = args.include or args.exclude or (args.verbose > 0)
verbosity = args.verbose
root = logging.getLogger()
if should_log:
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname).3s %(name)s %(message)s',
'%y-%m-%d %H:%M:%S')
if args.logfile:
handler = logging.FileHandler(args.logfile)
else:
handler = logging.StreamHandler()
handler.setFormatter(formatter)
if args.include and args.exclude:
print("You cannot combine whitelisted (-i) and blacklisted (-e) loggers, you must use one or the other.")
sys.exit(1)
loglevels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if verbosity >= len(loglevels):
verbosity = len(loglevels) - 1
level = loglevels[verbosity]
if args.include:
for name in args.include:
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
root.addHandler(logging.NullHandler())
else:
# Disable propagation of log events from disabled loggers
for name in args.exclude:
logger = logging.getLogger(name)
logger.disabled = True
root.setLevel(level)
root.addHandler(handler)
else:
root.addHandler(logging.NullHandler())
return args | [
"Parse all global iotile tool arguments.\n\n Any flag based argument at the start of the command line is considered as\n a global flag and parsed. The first non flag argument starts the commands\n that are passed to the underlying hierarchical shell.\n\n Args:\n argv (list): The command line for this command\n\n Returns:\n Namespace: The parsed arguments, with all of the commands that should\n be executed in an iotile shell as the attribute 'commands'\n "
] |
Please provide a description of the function:def setup_completion(shell):
# Handle special case of importing pyreadline on Windows
# See: http://stackoverflow.com/questions/6024952/readline-functionality-on-windows-with-python-2-7
import glob
try:
import readline
except ImportError:
import pyreadline as readline
def _complete(text, state):
buf = readline.get_line_buffer()
if buf.startswith('help ') or " " not in buf:
return [x for x in shell.valid_identifiers() if x.startswith(text)][state]
return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]
readline.set_completer_delims(' \t\n;')
# Handle Mac OS X special libedit based readline
# See: http://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion
if readline.__doc__ is not None and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
readline.set_completer(_complete) | [
"Setup readline to tab complete in a cross platform way."
] |
Please provide a description of the function:def main(argv=None):
if argv is None:
argv = sys.argv[1:]
args = parse_global_args(argv)
type_system.interactive = True
line = args.commands
timeout_thread = None
timeout_stop_event = threading.Event()
if args.timeout:
timeout_thread = threading.Thread(target=timeout_thread_handler, args=(args.timeout, timeout_stop_event))
timeout_thread.daemon = True
timeout_thread.start()
shell = HierarchicalShell('iotile')
shell.root_add("registry", "iotile.core.dev.annotated_registry,registry")
shell.root_add("config", "iotile.core.dev.config,ConfigManager")
shell.root_add('hw', "iotile.core.hw.hwmanager,HardwareManager")
reg = ComponentRegistry()
plugins = reg.list_plugins()
for key, val in plugins.items():
shell.root_add(key, val)
finished = False
try:
if len(line) > 0:
finished = shell.invoke(line)
except IOTileException as exc:
print(exc.format())
# if the command passed on the command line fails, then we should
# just exit rather than drop the user into a shell.
SharedLoop.stop()
return 1
except Exception: # pylint:disable=broad-except; We need to make sure we always call cmdstream.do_final_close()
# Catch all exceptions because otherwise we won't properly close cmdstreams
# since the program will be said to except 'abnormally'
traceback.print_exc()
SharedLoop.stop()
return 1
# If the user tells us to never spawn a shell, make sure we don't
# Also, if we finished our command and there is no context, quit now
if args.quit or finished:
SharedLoop.stop()
return 0
setup_completion(shell)
# We ended the initial command with a context, start a shell
try:
while True:
try:
linebuf = input("(%s) " % shell.context_name())
# Skip comments automatically
if len(linebuf) > 0 and linebuf[0] == '#':
continue
except KeyboardInterrupt:
print("")
continue
# Catch exception outside the loop so we stop invoking submethods if a parent
# fails because then the context and results would be unpredictable
try:
finished = shell.invoke_string(linebuf)
except KeyboardInterrupt:
print("")
if timeout_stop_event.is_set():
break
except IOTileException as exc:
print(exc.format())
except Exception: #pylint:disable=broad-except;
# We want to make sure the iotile tool never crashes when in interactive shell mode
traceback.print_exc()
if shell.finished():
break
# Make sure to catch ^C and ^D so that we can cleanly dispose of subprocess resources if
# there are any.
except EOFError:
print("")
except KeyboardInterrupt:
print("")
finally:
# Make sure we close any open CMDStream communication channels so that we don't lockup at exit
SharedLoop.stop()
# Make sure we cleanly join our timeout thread before exiting
if timeout_thread is not None:
timeout_stop_event.set()
timeout_thread.join() | [
"Run the iotile shell tool.\n\n You can optionally pass the arguments that should be run\n in the argv parameter. If nothing is passed, the args\n are pulled from sys.argv.\n\n The return value of this function is the return value\n of the shell command.\n "
] |
Please provide a description of the function:def do_build(self, argv):
import SCons.Node
import SCons.SConsign
import SCons.Script.Main
options = copy.deepcopy(self.options)
options, targets = self.parser.parse_args(argv[1:], values=options)
SCons.Script.COMMAND_LINE_TARGETS = targets
if targets:
SCons.Script.BUILD_TARGETS = targets
else:
# If the user didn't specify any targets on the command line,
# use the list of default targets.
SCons.Script.BUILD_TARGETS = SCons.Script._build_plus_default
nodes = SCons.Script.Main._build_targets(self.fs,
options,
targets,
self.target_top)
if not nodes:
return
# Call each of the Node's alter_targets() methods, which may
# provide additional targets that ended up as part of the build
# (the canonical example being a VariantDir() when we're building
# from a source directory) and which we therefore need their
# state cleared, too.
x = []
for n in nodes:
x.extend(n.alter_targets()[0])
nodes.extend(x)
# Clean up so that we can perform the next build correctly.
#
# We do this by walking over all the children of the targets,
# and clearing their state.
#
# We currently have to re-scan each node to find their
# children, because built nodes have already been partially
# cleared and don't remember their children. (In scons
# 0.96.1 and earlier, this wasn't the case, and we didn't
# have to re-scan the nodes.)
#
# Because we have to re-scan each node, we can't clear the
# nodes as we walk over them, because we may end up rescanning
# a cleared node as we scan a later node. Therefore, only
# store the list of nodes that need to be cleared as we walk
# the tree, and clear them in a separate pass.
#
# XXX: Someone more familiar with the inner workings of scons
# may be able to point out a more efficient way to do this.
SCons.Script.Main.progress_display("scons: Clearing cached node information ...")
seen_nodes = {}
def get_unseen_children(node, parent, seen_nodes=seen_nodes):
def is_unseen(node, seen_nodes=seen_nodes):
return node not in seen_nodes
return [child for child in node.children(scan=1) if is_unseen(child)]
def add_to_seen_nodes(node, parent, seen_nodes=seen_nodes):
seen_nodes[node] = 1
# If this file is in a VariantDir and has a
# corresponding source file in the source tree, remember the
# node in the source tree, too. This is needed in
# particular to clear cached implicit dependencies on the
# source file, since the scanner will scan it if the
# VariantDir was created with duplicate=0.
try:
rfile_method = node.rfile
except AttributeError:
return
else:
rfile = rfile_method()
if rfile != node:
seen_nodes[rfile] = 1
for node in nodes:
walker = SCons.Node.Walker(node,
kids_func=get_unseen_children,
eval_func=add_to_seen_nodes)
n = walker.get_next()
while n:
n = walker.get_next()
for node in list(seen_nodes.keys()):
# Call node.clear() to clear most of the state
node.clear()
# node.clear() doesn't reset node.state, so call
# node.set_state() to reset it manually
node.set_state(SCons.Node.no_state)
node.implicit = None
# Debug: Uncomment to verify that all Taskmaster reference
# counts have been reset to zero.
#if node.ref_count != 0:
# from SCons.Debug import Trace
# Trace('node %s, ref_count %s !!!\n' % (node, node.ref_count))
SCons.SConsign.Reset()
SCons.Script.Main.progress_display("scons: done clearing node information.") | [
"\\\n build [TARGETS] Build the specified TARGETS and their\n dependencies. 'b' is a synonym.\n "
] |
Please provide a description of the function:def do_help(self, argv):
if argv[1:]:
for arg in argv[1:]:
if self._do_one_help(arg):
break
else:
# If bare 'help' is called, print this class's doc
# string (if it has one).
doc = self._doc_to_help(self.__class__)
if doc:
sys.stdout.write(doc + '\n')
sys.stdout.flush() | [
"\\\n help [COMMAND] Prints help for the specified COMMAND. 'h'\n and '?' are synonyms.\n "
] |
Please provide a description of the function:def do_shell(self, argv):
import subprocess
argv = argv[1:]
if not argv:
argv = os.environ[self.shell_variable]
try:
# Per "[Python-Dev] subprocess insufficiently platform-independent?"
# http://mail.python.org/pipermail/python-dev/2008-August/081979.html "+
# Doing the right thing with an argument list currently
# requires different shell= values on Windows and Linux.
p = subprocess.Popen(argv, shell=(sys.platform=='win32'))
except EnvironmentError as e:
sys.stderr.write('scons: %s: %s\n' % (argv[0], e.strerror))
else:
p.wait() | [
"\\\n shell [COMMANDLINE] Execute COMMANDLINE in a subshell. 'sh' and\n '!' are synonyms.\n "
] |
Please provide a description of the function:def build(args):
# Do some sleuthing work to find scons if it's not installed into an importable
# place, as it is usually not.
scons_path = "Error"
try:
scons_path = resource_path('scons-local-{}'.format(SCONS_VERSION), expect='folder')
sys.path.insert(0, scons_path)
import SCons.Script
except ImportError:
raise BuildError("Couldn't find internal scons packaged w/ iotile-build. This is a bug that should be reported",
scons_path=scons_path)
site_path = resource_path('site_scons', expect='folder')
all_args = ['iotile', '--site-dir=%s' % site_path, '-Q']
sys.argv = all_args + list(args)
SCons.Script.main() | [
"\n Invoke the scons build system from the current directory, exactly as if\n the scons tool had been invoked.\n "
] |
Please provide a description of the function:def merge_dicts(a, b):
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key])
else:
a[key] = b[key]
else:
a[key] = b[key]
return a | [
"\"merges b into a"
] |
Please provide a description of the function:def archs(self, as_list=False):
archs = self.arch_list().split('/')
if as_list:
return archs
return set(archs) | [
"Return all of the architectures for this target.\n\n Args:\n as_list (bool): Return a list instead of the default set object.\n\n Returns:\n set or list: All of the architectures used in this TargetSettings object.\n "
] |
Please provide a description of the function:def retarget(self, remove=[], add=[]):
archs = self.arch_list().split('/')
for r in remove:
if r in archs:
archs.remove(r)
archs.extend(add)
archstr = "/".join(archs)
return self.family.find(archstr, self.module_name()) | [
"Return a TargetSettings object for the same module but with some of the architectures\n removed and others added.\n "
] |
Please provide a description of the function:def build_dirs(self):
arch = self.arch_name()
build_path = os.path.join('build', arch)
output = os.path.join('build', 'output')
test = os.path.join('build', 'test', arch)
return {'build': build_path, 'output': output, 'test': test} | [
"Return the build directory hierarchy:\n Defines:\n - build: build/chip\n - output: build/output\n - test: build/test/chip\n where chip is the canonical name for the chip passed in\n "
] |
Please provide a description of the function:def property(self, name, default=MISSING):
if name in self.settings:
return self.settings[name]
if default is not MISSING:
return default
raise ArgumentError("property %s not found for target '%s' and no default given" % (name, self.name)) | [
"Get the value of the given property for this chip, using the default\n value if not found and one is provided. If not found and default is None,\n raise an Exception.\n "
] |
Please provide a description of the function:def combined_properties(self, suffix):
props = [y for x, y in self.settings.items() if x.endswith(suffix)]
properties = itertools.chain(*props)
processed_props = [x for x in properties]
return processed_props | [
"Get the value of all properties whose name ends with suffix and join them\n together into a list.\n "
] |
Please provide a description of the function:def includes(self):
incs = self.combined_properties('includes')
processed_incs = []
for prop in incs:
if isinstance(prop, str):
processed_incs.append(prop)
else:
processed_incs.append(os.path.join(*prop))
# All include paths are relative to base directory of the
fullpaths = [os.path.normpath(os.path.join('.', x)) for x in processed_incs]
fullpaths.append(os.path.normpath(os.path.abspath(self.build_dirs()['build'])))
return fullpaths | [
"Return all of the include directories for this chip as a list."
] |
Please provide a description of the function:def arch_prefixes(self):
archs = self.archs(as_list=True)
prefixes = []
for i in range(1, len(archs)+1):
prefixes.append(archs[:i])
return prefixes | [
"Return the initial 1, 2, ..., N architectures as a prefix list\n\n For arch1/arch2/arch3, this returns\n [arch1],[arch1/arch2],[arch1/arch2/arch3]\n "
] |
Please provide a description of the function:def _load_dependency(cls, tile, dep, family):
depname = dep['unique_id']
depdir = os.path.join(tile.folder, 'build', 'deps', depname)
deppath = os.path.join(depdir, 'module_settings.json')
if not os.path.exists(deppath):
raise BuildError("Could not find dependency", dependency=dep)
try:
deptile = IOTile(depdir)
except DataError as exc:
raise BuildError("Could not find dependency", dependency=dep, error=exc)
merge_dicts(family['architectures'], deptile.architectures.copy()) | [
"Load a dependency from build/deps/<unique_id>."
] |
Please provide a description of the function:def targets(self, module):
if module not in self.module_targets:
raise BuildError("Could not find module in targets()", module=module)
return [self.find(x, module) for x in self.module_targets[module]] | [
"Find the targets for a given module.\n\n Returns:\n list: A sequence of all of the targets for the specified module.\n "
] |
Please provide a description of the function:def for_all_targets(self, module, func, filter_func=None):
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | [
"Call func once for all of the targets of this module."
] |
Please provide a description of the function:def validate_target(self, target):
archs = target.split('/')
for arch in archs:
if not arch in self.archs:
return False
return True | [
"Make sure that the specified target only contains architectures that we know about."
] |
Please provide a description of the function:def _load_target(self, target, module=None):
mod = ModuleSettings({}, {})
if not self.validate_target(target):
raise ArgumentError("Target %s is invalid, check to make sure every architecture in it is defined" % target)
if module is not None:
if module not in self.modules:
raise ArgumentError("Unknown module name passed: %s" % module)
mod = self.modules[module]
settings = {}
archs = target.split('/')
for arch in archs:
arch_settings = deepcopy(self.archs[arch])
if arch in mod.overlays:
arch_settings = merge_dicts(arch_settings, mod.overlays[arch])
# Allow this architecture to overlay previous architectures as well
if "overlays" in arch_settings:
for arch2 in archs:
if arch2 == arch:
break
if arch2 in arch_settings["overlays"]:
arch_settings = merge_dicts(arch_settings, arch_settings["overlays"][arch2])
del arch_settings["overlays"]
# Allow the module to overlay included architectures as well
if "overlays" in mod.settings and arch in mod.settings['overlays']:
arch_settings = merge_dicts(arch_settings, mod.settings['overlays'][arch])
settings = merge_dicts(settings, arch_settings)
settings = merge_dicts(settings, mod.settings)
targetname = "%s:%s" % (str(module), target)
return TargetSettings(targetname, settings, self) | [
"Given a string specifying a series of architectural overlays as:\n <arch 1>/<arch 2>/... and optionally a module name to pull in\n module specific settings, return a TargetSettings object that\n encapsulates all of the settings for this target.\n "
] |
Please provide a description of the function:def _load_architectures(self, family):
if "architectures" not in family:
raise InternalError("required architectures key not in build_settings.json for desired family")
for key, val in family['architectures'].items():
if not isinstance(val, dict):
raise InternalError("All entries under chip_settings must be dictionaries")
self.archs[key] = deepcopy(val) | [
"Load in all of the architectural overlays for this family. An architecture adds configuration\n information that is used to build a common set of source code for a particular hardware and situation.\n They are stackable so that you can specify a chip and a configuration for that chip, for example.\n "
] |
Please provide a description of the function:def generate(env):
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
# C
c_file.add_action(".l", LexAction)
c_file.add_emitter(".l", lexEmitter)
c_file.add_action(".lex", LexAction)
c_file.add_emitter(".lex", lexEmitter)
# Objective-C
cxx_file.add_action(".lm", LexAction)
cxx_file.add_emitter(".lm", lexEmitter)
# C++
cxx_file.add_action(".ll", LexAction)
cxx_file.add_emitter(".ll", lexEmitter)
env["LEX"] = env.Detect("flex") or "lex"
env["LEXFLAGS"] = SCons.Util.CLVar("")
env["LEXCOM"] = "$LEX $LEXFLAGS -t $SOURCES > $TARGET" | [
"Add Builders and construction variables for lex to an Environment."
] |
Please provide a description of the function:def clear_to_reset(self, config_vars):
super(ClockManagerSubsystem, self).clear_to_reset(config_vars)
self.tick_counters = dict(fast=0, user1=0, user2=0, normal=0)
self.is_utc = False
self.time_offset = 0
if self.has_rtc and self.stored_offset is not None:
self.time_offset = self.stored_offset + self.uptime
self.uptime = 0
self.ticks['fast'] = config_vars.get('fast_tick', 0)
self.ticks['user1'] = config_vars.get('user_tick_1', 0)
self.ticks['user2'] = config_vars.get('user_tick_2', 0) | [
"Clear all volatile information across a reset.\n\n The reset behavior is that:\n - uptime is reset to 0\n - is `has_rtc` is True, the utc_offset is preserved\n - otherwise the utc_offset is cleared to none\n "
] |
Please provide a description of the function:def handle_tick(self):
self.uptime += 1
for name, interval in self.ticks.items():
if interval == 0:
continue
self.tick_counters[name] += 1
if self.tick_counters[name] == interval:
self.graph_input(self.TICK_STREAMS[name], self.uptime)
self.tick_counters[name] = 0 | [
"Internal callback every time 1 second has passed."
] |
Please provide a description of the function:def set_tick(self, index, interval):
name = self.tick_name(index)
if name is None:
return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY)
self.ticks[name] = interval
return Error.NO_ERROR | [
"Update the a tick's interval.\n\n Args:\n index (int): The index of the tick that you want to fetch.\n interval (int): The number of seconds between ticks.\n Setting this to 0 will disable the tick.\n\n Returns:\n int: An error code.\n "
] |
Please provide a description of the function:def get_tick(self, index):
name = self.tick_name(index)
if name is None:
return [pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY), 0]
return [Error.NO_ERROR, self.ticks[name]] | [
"Get a tick's interval.\n\n Args:\n index (int): The index of the tick that you want to fetch.\n\n Returns:\n int, int: Error code and The tick's interval in seconds.\n\n A value of 0 means that the tick is disabled.\n "
] |
Please provide a description of the function:def get_time(self, force_uptime=False):
if force_uptime:
return self.uptime
time = self.uptime + self.time_offset
if self.is_utc:
time |= (1 << 31)
return time | [
"Get the current UTC time or uptime.\n\n By default, this method will return UTC time if possible and fall back\n to uptime if not. If you specify, force_uptime=True, it will always\n return uptime even if utc time is available.\n\n Args:\n force_uptime (bool): Always return uptime, defaults to False.\n\n Returns:\n int: The current uptime or encoded utc time.\n "
] |
Please provide a description of the function:def synchronize_clock(self, offset):
self.time_offset = offset - self.uptime
self.is_utc = True
if self.has_rtc:
self.stored_offset = self.time_offset | [
"Persistently synchronize the clock to UTC time.\n\n Args:\n offset (int): The number of seconds since 1/1/2000 00:00Z\n "
] |
Please provide a description of the function:def get_user_timer(self, index):
err, tick = self.clock_manager.get_tick(index)
return [err, tick] | [
"Get the current value of a user timer."
] |
Please provide a description of the function:def set_user_timer(self, value, index):
err = self.clock_manager.set_tick(index, value)
return [err] | [
"Set the current value of a user timer."
] |
Please provide a description of the function:def set_time_offset(self, offset, is_utc):
is_utc = bool(is_utc)
self.clock_manager.time_offset = offset
self.clock_manager.is_utc = is_utc
return [Error.NO_ERROR] | [
"Temporarily set the current time offset."
] |
Please provide a description of the function:def device_slug_to_id(slug):
if not isinstance(slug, str):
raise ArgumentError("Invalid device slug that is not a string", slug=slug)
try:
device_slug = IOTileDeviceSlug(slug, allow_64bits=False)
except ValueError:
raise ArgumentError("Unable to recognize {} as a device id".format(slug))
return device_slug.get_id() | [
"Convert a d-- device slug to an integer.\n\n Args:\n slug (str): A slug in the format d--XXXX-XXXX-XXXX-XXXX\n\n Returns:\n int: The device id as an integer\n\n Raises:\n ArgumentError: if there is a malformed slug\n "
] |
Please provide a description of the function:def device_id_to_slug(did):
try:
device_slug = IOTileDeviceSlug(did, allow_64bits=False)
except ValueError:
raise ArgumentError("Unable to recognize {} as a device id".format(did))
return str(device_slug) | [
" Converts a device id into a correct device slug.\n\n Args:\n did (long) : A device id\n did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, d--XXXX, d--XXXX-XXXX-XXXX-XXXX\n Returns:\n str: The device slug in the d--XXXX-XXXX-XXXX-XXXX format\n Raises:\n ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string\n "
] |
Please provide a description of the function:def fleet_id_to_slug(did):
try:
fleet_slug = IOTileFleetSlug(did)
except ValueError:
raise ArgumentError("Unable to recognize {} as a fleet id".format(did))
return str(fleet_slug) | [
" Converts a fleet id into a correct fleet slug.\n\n Args:\n did (long) : A fleet id\n did (string) : A device slug in the form of XXXX, XXXX-XXXX-XXXX, g--XXXX, g--XXXX-XXXX-XXXX\n Returns:\n str: The device slug in the g--XXXX-XXXX-XXX format\n Raises:\n ArgumentError: if the ID is not in the [1, 16**12] range, or if not a valid string\n "
] |
Please provide a description of the function:def get_program_files_dir():
# Now see if we can look in the registry...
val = ''
if SCons.Util.can_read_reg:
try:
# Look for Windows Program Files directory
k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE,
'Software\\Microsoft\\Windows\\CurrentVersion')
val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir')
except SCons.Util.RegError:
val = ''
pass
if val == '':
# A reasonable default if we can't read the registry
# (Actually, it's pretty reasonable even if we can :-)
val = os.path.join(os.path.dirname(get_system_root()),"Program Files")
return val | [
"\n Get the location of the program files directory\n Returns\n -------\n\n "
] |
Please provide a description of the function:def get_architecture(arch=None):
if arch is None:
arch = os.environ.get('PROCESSOR_ARCHITEW6432')
if not arch:
arch = os.environ.get('PROCESSOR_ARCHITECTURE')
return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) | [
"Returns the definition for the specified architecture string.\n\n If no string is specified, the system default is returned (as defined\n by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment\n variables).\n "
] |
Please provide a description of the function:def generate(env):
try:
bld = env['BUILDERS']['Rpm']
except KeyError:
bld = RpmBuilder
env['BUILDERS']['Rpm'] = bld
env.SetDefault(RPM = 'LC_ALL=C rpmbuild')
env.SetDefault(RPMFLAGS = SCons.Util.CLVar('-ta'))
env.SetDefault(RPMCOM = rpmAction)
env.SetDefault(RPMSUFFIX = '.rpm') | [
"Add Builders and construction variables for rpm to an Environment."
] |
Please provide a description of the function:def next_id(self, channel):
if channel not in self.topics:
self.topics[channel] = 0
return 0
self.topics[channel] += 1
return self.topics[channel] | [
"Get the next sequence number for a named channel or topic\n\n If channel has not been sent to next_id before, 0 is returned\n otherwise next_id returns the last id returned + 1.\n\n Args:\n channel (string): The name of the channel to get a sequential\n id for.\n\n Returns:\n int: The next id for this channel\n "
] |
Please provide a description of the function:def escape(arg):
"escape shell special characters"
slash = '\\'
special = '"$'
arg = arg.replace(slash, slash+slash)
for c in special:
arg = arg.replace(c, slash+c)
# print("ESCAPE RESULT: %s" % arg)
return '"' + arg + '"' | [] |
Please provide a description of the function:def MatchQuality(cls, record_data, record_count=1):
if record_count > 1:
return MatchQuality.NoMatch
cmd, _address, _resp_length, payload = cls._parse_rpc_info(record_data)
if cmd == cls.RPC_ID:
try:
_os_info, _app_info, update_os, update_app = struct.unpack("<LLBB", payload)
update_os = bool(update_os)
update_app = bool(update_app)
except ValueError:
return MatchQuality.NoMatch
return MatchQuality.PerfectMatch
return MatchQuality.NoMatch | [
"Check how well this record matches the given binary data.\n\n This function will only be called if the record matches the type code\n given by calling MatchType() and this function should check how well\n this record matches and return a quality score between 0 and 100, with\n higher quality matches having higher scores. The default value should\n be MatchQuality.GenericMatch which is 50. If this record does not\n match at all, it should return MatchQuality.NoMatch.\n\n Many times, only a single record type will match a given binary record\n but there are times when multiple different logical records produce\n the same type of record in a script, such as set_version and\n set_userkey both producing a call_rpc record with different RPC\n values. The MatchQuality method is used to allow for rich decoding\n of such scripts back to the best possible record that created them.\n\n Args:\n record_data (bytearay): The raw record that we should check for\n a match.\n record_count (int): The number of binary records that are included\n in record_data.\n\n Returns:\n int: The match quality between 0 and 100. You should use the\n constants defined in MatchQuality as much as possible.\n "
] |
Please provide a description of the function:def FromBinary(cls, record_data, record_count=1):
_cmd, _address, _resp_length, payload = cls._parse_rpc_info(record_data)
try:
os_info, app_info, update_os, update_app = struct.unpack("<LLBB", payload)
update_os = bool(update_os)
update_app = bool(update_app)
if update_app and not update_os:
tag, version = _parse_info(app_info)
return SetDeviceTagRecord(app_tag=tag, app_version=version)
elif update_os and not update_app:
tag, version = _parse_info(os_info)
return SetDeviceTagRecord(os_tag=tag, os_version=version)
elif update_os and update_app:
os_tag, os_version = _parse_info(os_info)
app_tag, app_version = _parse_info(app_info)
return SetDeviceTagRecord(app_tag=app_tag, app_version=app_version,
os_tag=os_tag, os_version=os_version)
else:
raise ArgumentError("Neither update_os nor update_app is set True")
except ValueError:
raise ArgumentError("Could not parse set device version payload", payload=payload) | [
"Create an UpdateRecord subclass from binary record data.\n\n This should be called with a binary record blob (NOT including the\n record type header) and it will decode it into a SetDeviceTagRecord.\n\n Args:\n record_data (bytearray): The raw record data that we wish to parse\n into an UpdateRecord subclass NOT including its 8 byte record header.\n record_count (int): The number of records included in record_data.\n\n Raises:\n ArgumentError: If the record_data is malformed and cannot be parsed.\n\n Returns:\n SetDeviceTagRecord: The decoded reflash tile record.\n "
] |
Please provide a description of the function:def verify(self, obj):
if not isinstance(obj, str):
raise ValidationError("Object is not a string", reason='object is not a string',
object=obj, type=type(obj), str_type=str)
return obj | [
"Verify that the object conforms to this verifier's schema\n\n Args:\n obj (object): A python object to verify\n\n Raises:\n ValidationError: If there is a problem verifying the dictionary, a\n ValidationError is thrown with at least the reason key set indicating\n the reason for the lack of validation.\n "
] |
Please provide a description of the function:def format(self, indent_level, indent_size=4):
desc = self.format_name('String')
return self.wrap_lines(desc, indent_level, indent_size=indent_size) | [
"Format this verifier\n\n Returns:\n string: A formatted string\n "
] |
Please provide a description of the function:def clear_to_reset(self, config_vars):
super(BasicStreamingSubsystem, self).clear_to_reset(config_vars)
self._in_progress_streamers = set() | [
"Clear all volatile information across a reset."
] |
Please provide a description of the function:def process_streamer(self, streamer, callback=None):
index = streamer.index
if index in self._in_progress_streamers:
raise InternalError("You cannot add a streamer again until it has finished streaming.")
queue_item = QueuedStreamer(streamer, callback)
self._in_progress_streamers.add(index)
self._logger.debug("Streamer %d: queued to send %d readings", index, queue_item.initial_count)
self._queue.put_nowait(queue_item) | [
"Start streaming a streamer.\n\n Args:\n streamer (DataStreamer): The streamer itself.\n callback (callable): An optional callable that will be called as:\n callable(index, success, highest_id_received_from_other_side)\n "
] |
Please provide a description of the function:def pack_rpc_response(response=None, exception=None):
if response is None:
response = bytes()
if exception is None:
status = (1 << 6)
if len(response) > 0:
status |= (1 << 7)
elif isinstance(exception, (RPCInvalidIDError, RPCNotFoundError)):
status = 2
elif isinstance(exception, BusyRPCResponse):
status = 0
elif isinstance(exception, TileNotFoundError):
status = 0xFF
elif isinstance(exception, RPCErrorCode):
status = (1 << 6) | (exception.params['code'] & ((1 << 6) - 1))
else:
status = 3
return status, response | [
"Convert a response payload or exception to a status code and payload.\n\n This function will convert an Exception raised by an RPC implementation\n to the corresponding status code.\n "
] |
Please provide a description of the function:def unpack_rpc_response(status, response=None, rpc_id=0, address=0):
status_code = status & ((1 << 6) - 1)
if address == 8:
status_code &= ~(1 << 7)
if status == 0:
raise BusyRPCResponse()
elif status == 2:
raise RPCNotFoundError("rpc %d:%04X not found" % (address, rpc_id))
elif status == 3:
raise RPCErrorCode(status_code)
elif status == 0xFF:
raise TileNotFoundError("tile %d not found" % address)
elif status_code != 0:
raise RPCErrorCode(status_code)
if response is None:
response = b''
return response | [
"Unpack an RPC status back in to payload or exception."
] |
Please provide a description of the function:def pack_rpc_payload(arg_format, args):
code = _create_respcode(arg_format, args)
packed_result = struct.pack(code, *args)
unpacked_validation = struct.unpack(code, packed_result)
if tuple(args) != unpacked_validation:
raise RPCInvalidArgumentsError("Passed values would be truncated, please validate the size of your string",
code=code, args=args)
return packed_result | [
"Pack an RPC payload according to arg_format.\n\n Args:\n arg_format (str): a struct format code (without the <) for the\n parameter format for this RPC. This format code may include the final\n character V, which means that it expects a variable length bytearray.\n args (list): A list of arguments to pack according to arg_format.\n\n Returns:\n bytes: The packed argument buffer.\n "
] |
Please provide a description of the function:def unpack_rpc_payload(resp_format, payload):
code = _create_argcode(resp_format, payload)
return struct.unpack(code, payload) | [
"Unpack an RPC payload according to resp_format.\n\n Args:\n resp_format (str): a struct format code (without the <) for the\n parameter format for this RPC. This format code may include the final\n character V, which means that it expects a variable length bytearray.\n payload (bytes): The binary payload that should be unpacked.\n\n Returns:\n list: A list of the unpacked payload items.\n "
] |
Please provide a description of the function:def rpc(address, rpc_id, arg_format, resp_format=None):
if rpc_id < 0 or rpc_id > 0xFFFF:
raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))
def _rpc_wrapper(func):
if inspect.iscoroutinefunction(func):
async def _rpc_executor(self, payload):
try:
args = unpack_rpc_payload(arg_format, payload)
except struct.error as exc:
raise RPCInvalidArgumentsError(str(exc), arg_format=arg_format, payload=binascii.hexlify(payload))
resp = await func(self, *args)
if resp is None:
resp = []
if resp_format is not None:
try:
return pack_rpc_payload(resp_format, resp)
except struct.error as exc:
raise RPCInvalidReturnValueError(str(exc), resp_format=resp_format, resp=repr(resp))
return resp
_rpc_executor.rpc_id = rpc_id
_rpc_executor.rpc_addr = address
_rpc_executor.is_rpc = True
return _rpc_executor
else:
def _rpc_executor(self, payload):
try:
args = unpack_rpc_payload(arg_format, payload)
except struct.error as exc:
raise RPCInvalidArgumentsError(str(exc), arg_format=arg_format, payload=binascii.hexlify(payload))
resp = func(self, *args)
if resp is None:
resp = []
if resp_format is not None:
try:
return pack_rpc_payload(resp_format, resp)
except struct.error as exc:
raise RPCInvalidReturnValueError(address, rpc_id, resp_format, resp, error=exc) from exc
return resp
_rpc_executor.rpc_id = rpc_id
_rpc_executor.rpc_addr = address
_rpc_executor.is_rpc = True
return _rpc_executor
return _rpc_wrapper | [
"Decorator to denote that a function implements an RPC with the given ID and address.\n\n The underlying function should be a member function that will take\n individual parameters after the RPC payload has been decoded according\n to arg_format.\n\n Arguments to the function are decoded from the 20 byte RPC argument payload according\n to arg_format, which should be a format string that can be passed to struct.unpack.\n\n Similarly, the function being decorated should return an iterable of results that\n will be encoded into a 20 byte response buffer by struct.pack using resp_format as\n the format string.\n\n The RPC will respond as if it were implemented by a tile at address ``address`` and\n the 16-bit RPC id ``rpc_id``.\n\n Args:\n address (int): The address of the mock tile this RPC is for\n rpc_id (int): The number of the RPC\n arg_format (string): a struct format code (without the <) for the\n parameter format for this RPC. This format code may include the final\n character V, which means that it expects a variable length bytearray.\n resp_format (string): an optional format code (without the <) for\n the response format for this RPC. This format code may include the final\n character V, which means that it expects a variable length bytearray.\n "
] |
Please provide a description of the function:def call_rpc(self, rpc_id, payload=bytes()):
if rpc_id < 0 or rpc_id > 0xFFFF:
raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))
if rpc_id not in self._rpcs:
raise RPCNotFoundError("rpc_id: {}".format(rpc_id))
return self._rpcs[rpc_id](payload) | [
"Call an RPC by its ID.\n\n Args:\n rpc_id (int): The number of the RPC\n payload (bytes): A byte string of payload parameters up to 20 bytes\n\n Returns:\n bytes: The response payload from the RPC\n "
] |
Please provide a description of the function:def isfortran(env, source):
try:
fsuffixes = env['FORTRANSUFFIXES']
except KeyError:
# If no FORTRANSUFFIXES, no fortran tool, so there is no need to look
# for fortran sources.
return 0
if not source:
# Source might be None for unusual cases like SConf.
return 0
for s in source:
if s.sources:
ext = os.path.splitext(str(s.sources[0]))[1]
if ext in fsuffixes:
return 1
return 0 | [
"Return 1 if any of code in source has fortran files in it, 0\n otherwise."
] |
Please provide a description of the function:def ComputeFortranSuffixes(suffixes, ppsuffixes):
assert len(suffixes) > 0
s = suffixes[0]
sup = s.upper()
upper_suffixes = [_.upper() for _ in suffixes]
if SCons.Util.case_sensitive_suffixes(s, sup):
ppsuffixes.extend(upper_suffixes)
else:
suffixes.extend(upper_suffixes) | [
"suffixes are fortran source files, and ppsuffixes the ones to be\n pre-processed. Both should be sequences, not strings."
] |
Please provide a description of the function:def CreateDialectActions(dialect):
CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect)
CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect)
ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR' % dialect)
ShCompPPAction = SCons.Action.Action('$SH%sPPCOM ' % dialect, '$SH%sPPCOMSTR' % dialect)
return CompAction, CompPPAction, ShCompAction, ShCompPPAction | [
"Create dialect specific actions."
] |
Please provide a description of the function:def DialectAddToEnv(env, dialect, suffixes, ppsuffixes, support_module = 0):
ComputeFortranSuffixes(suffixes, ppsuffixes)
fscan = SCons.Scanner.Fortran.FortranScan("%sPATH" % dialect)
for suffix in suffixes + ppsuffixes:
SCons.Tool.SourceFileScanner.add_scanner(suffix, fscan)
env.AppendUnique(FORTRANSUFFIXES = suffixes + ppsuffixes)
compaction, compppaction, shcompaction, shcompppaction = \
CreateDialectActions(dialect)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in suffixes:
static_obj.add_action(suffix, compaction)
shared_obj.add_action(suffix, shcompaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
for suffix in ppsuffixes:
static_obj.add_action(suffix, compppaction)
shared_obj.add_action(suffix, shcompppaction)
static_obj.add_emitter(suffix, FortranEmitter)
shared_obj.add_emitter(suffix, ShFortranEmitter)
if '%sFLAGS' % dialect not in env:
env['%sFLAGS' % dialect] = SCons.Util.CLVar('')
if 'SH%sFLAGS' % dialect not in env:
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect)
# If a tool does not define fortran prefix/suffix for include path, use C ones
if 'INC%sPREFIX' % dialect not in env:
env['INC%sPREFIX' % dialect] = '$INCPREFIX'
if 'INC%sSUFFIX' % dialect not in env:
env['INC%sSUFFIX' % dialect] = '$INCSUFFIX'
env['_%sINCFLAGS' % dialect] = '$( ${_concat(INC%sPREFIX, %sPATH, INC%sSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' % (dialect, dialect, dialect)
if support_module == 1:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $_FORTRANMODFLAG $SOURCES' % (dialect, dialect, dialect)
else:
env['%sCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['%sPPCOM' % dialect] = '$%s -o $TARGET -c $%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect)
env['SH%sPPCOM' % dialect] = '$SH%s -o $TARGET -c $SH%sFLAGS $CPPFLAGS $_CPPDEFFLAGS $_%sINCFLAGS $SOURCES' % (dialect, dialect, dialect) | [
"Add dialect specific construction variables."
] |
Please provide a description of the function:def add_fortran_to_env(env):
try:
FortranSuffixes = env['FORTRANFILESUFFIXES']
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
#print("Adding %s to fortran suffixes" % FortranSuffixes)
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
FortranPPSuffixes = ['.fpp', '.FPP']
DialectAddToEnv(env, "FORTRAN", FortranSuffixes,
FortranPPSuffixes, support_module = 1)
env['FORTRANMODPREFIX'] = '' # like $LIBPREFIX
env['FORTRANMODSUFFIX'] = '.mod' # like $LIBSUFFIX
env['FORTRANMODDIR'] = '' # where the compiler should place .mod files
env['FORTRANMODDIRPREFIX'] = '' # some prefix to $FORTRANMODDIR - similar to $INCPREFIX
env['FORTRANMODDIRSUFFIX'] = '' # some suffix to $FORTRANMODDIR - similar to $INCSUFFIX
env['_FORTRANMODFLAG'] = '$( ${_concat(FORTRANMODDIRPREFIX, FORTRANMODDIR, FORTRANMODDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)' | [
"Add Builders and construction variables for Fortran to an Environment."
] |
Please provide a description of the function:def add_f77_to_env(env):
try:
F77Suffixes = env['F77FILESUFFIXES']
except KeyError:
F77Suffixes = ['.f77']
#print("Adding %s to f77 suffixes" % F77Suffixes)
try:
F77PPSuffixes = env['F77PPFILESUFFIXES']
except KeyError:
F77PPSuffixes = []
DialectAddToEnv(env, "F77", F77Suffixes, F77PPSuffixes) | [
"Add Builders and construction variables for f77 to an Environment."
] |
Please provide a description of the function:def add_f90_to_env(env):
try:
F90Suffixes = env['F90FILESUFFIXES']
except KeyError:
F90Suffixes = ['.f90']
#print("Adding %s to f90 suffixes" % F90Suffixes)
try:
F90PPSuffixes = env['F90PPFILESUFFIXES']
except KeyError:
F90PPSuffixes = []
DialectAddToEnv(env, "F90", F90Suffixes, F90PPSuffixes,
support_module = 1) | [
"Add Builders and construction variables for f90 to an Environment."
] |
Please provide a description of the function:def add_f95_to_env(env):
try:
F95Suffixes = env['F95FILESUFFIXES']
except KeyError:
F95Suffixes = ['.f95']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F95PPSuffixes = env['F95PPFILESUFFIXES']
except KeyError:
F95PPSuffixes = []
DialectAddToEnv(env, "F95", F95Suffixes, F95PPSuffixes,
support_module = 1) | [
"Add Builders and construction variables for f95 to an Environment."
] |
Please provide a description of the function:def add_f03_to_env(env):
try:
F03Suffixes = env['F03FILESUFFIXES']
except KeyError:
F03Suffixes = ['.f03']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F03PPSuffixes = env['F03PPFILESUFFIXES']
except KeyError:
F03PPSuffixes = []
DialectAddToEnv(env, "F03", F03Suffixes, F03PPSuffixes,
support_module = 1) | [
"Add Builders and construction variables for f03 to an Environment."
] |
Please provide a description of the function:def add_f08_to_env(env):
try:
F08Suffixes = env['F08FILESUFFIXES']
except KeyError:
F08Suffixes = ['.f08']
try:
F08PPSuffixes = env['F08PPFILESUFFIXES']
except KeyError:
F08PPSuffixes = []
DialectAddToEnv(env, "F08", F08Suffixes, F08PPSuffixes,
support_module = 1) | [
"Add Builders and construction variables for f08 to an Environment."
] |
Please provide a description of the function:def add_all_to_env(env):
add_fortran_to_env(env)
add_f77_to_env(env)
add_f90_to_env(env)
add_f95_to_env(env)
add_f03_to_env(env)
add_f08_to_env(env) | [
"Add builders and construction variables for all supported fortran\n dialects."
] |
Please provide a description of the function:def _delete_duplicates(l, keep_last):
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen.add(i)
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result | [
"Delete duplicates from a sequence, keeping the first or last."
] |
Please provide a description of the function:def NoSubstitutionProxy(subject):
class _NoSubstitutionProxy(Environment):
def __init__(self, subject):
self.__dict__['__subject'] = subject
def __getattr__(self, name):
return getattr(self.__dict__['__subject'], name)
def __setattr__(self, name, value):
return setattr(self.__dict__['__subject'], name, value)
def executor_to_lvars(self, kwdict):
if 'executor' in kwdict:
kwdict['lvars'] = kwdict['executor'].get_lvars()
del kwdict['executor']
else:
kwdict['lvars'] = {}
def raw_to_mode(self, dict):
try:
raw = dict['raw']
except KeyError:
pass
else:
del dict['raw']
dict['mode'] = raw
def subst(self, string, *args, **kwargs):
return string
def subst_kw(self, kw, *args, **kwargs):
return kw
def subst_list(self, string, *args, **kwargs):
nargs = (string, self,) + args
nkw = kwargs.copy()
nkw['gvars'] = {}
self.executor_to_lvars(nkw)
self.raw_to_mode(nkw)
return SCons.Subst.scons_subst_list(*nargs, **nkw)
def subst_target_source(self, string, *args, **kwargs):
nargs = (string, self,) + args
nkw = kwargs.copy()
nkw['gvars'] = {}
self.executor_to_lvars(nkw)
self.raw_to_mode(nkw)
return SCons.Subst.scons_subst(*nargs, **nkw)
return _NoSubstitutionProxy(subject) | [
"\n An entry point for returning a proxy subclass instance that overrides\n the subst*() methods so they don't actually perform construction\n variable substitution. This is specifically intended to be the shim\n layer in between global function calls (which don't want construction\n variable substitution) and the DefaultEnvironment() (which would\n substitute variables if left to its own devices).\n\n We have to wrap this in a function that allows us to delay definition of\n the class until it's necessary, so that when it subclasses Environment\n it will pick up whatever Environment subclass the wrapper interface\n might have assigned to SCons.Environment.Environment.\n "
] |
Please provide a description of the function:def clone(self, new_object):
return self.__class__(new_object, self.method, self.name) | [
"\n Returns an object that re-binds the underlying \"method\" to\n the specified new object.\n "
] |
Please provide a description of the function:def _init_special(self):
self._special_del = {}
self._special_del['SCANNERS'] = _del_SCANNERS
self._special_set = {}
for key in reserved_construction_var_names:
self._special_set[key] = _set_reserved
for key in future_reserved_construction_var_names:
self._special_set[key] = _set_future_reserved
self._special_set['BUILDERS'] = _set_BUILDERS
self._special_set['SCANNERS'] = _set_SCANNERS
# Freeze the keys of self._special_set in a list for use by
# methods that need to check. (Empirically, list scanning has
# gotten better than dict.has_key() in Python 2.5.)
self._special_set_keys = list(self._special_set.keys()) | [
"Initial the dispatch tables for special handling of\n special construction variables."
] |
Please provide a description of the function:def subst(self, string, raw=0, target=None, source=None, conv=None, executor=None):
gvars = self.gvars()
lvars = self.lvars()
lvars['__env__'] = self
if executor:
lvars.update(executor.get_lvars())
return SCons.Subst.scons_subst(string, self, raw, target, source, gvars, lvars, conv) | [
"Recursively interpolates construction variables from the\n Environment into the specified string, returning the expanded\n result. Construction variables are specified by a $ prefix\n in the string and begin with an initial underscore or\n alphabetic character followed by any number of underscores\n or alphanumeric characters. The construction variable names\n may be surrounded by curly braces to separate the name from\n trailing characters.\n "
] |
Please provide a description of the function:def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None):
gvars = self.gvars()
lvars = self.lvars()
lvars['__env__'] = self
if executor:
lvars.update(executor.get_lvars())
return SCons.Subst.scons_subst_list(string, self, raw, target, source, gvars, lvars, conv) | [
"Calls through to SCons.Subst.scons_subst_list(). See\n the documentation for that function."
] |
Please provide a description of the function:def subst_path(self, path, target=None, source=None):
if not SCons.Util.is_List(path):
path = [path]
def s(obj):
try:
get = obj.get
except AttributeError:
obj = SCons.Util.to_String_for_subst(obj)
else:
obj = get()
return obj
r = []
for p in path:
if SCons.Util.is_String(p):
p = self.subst(p, target=target, source=source, conv=s)
if SCons.Util.is_List(p):
if len(p) == 1:
p = p[0]
else:
# We have an object plus a string, or multiple
# objects that we need to smush together. No choice
# but to make them into a string.
p = ''.join(map(SCons.Util.to_String_for_subst, p))
else:
p = s(p)
r.append(p)
return r | [
"Substitute a path list, turning EntryProxies into Nodes\n and leaving Nodes (and other objects) as-is.",
"This is the \"string conversion\" routine that we have our\n substitutions use to return Nodes, not strings. This relies\n on the fact that an EntryProxy object has a get() method that\n returns the underlying Node that it wraps, which is a bit of\n architectural dependence that we might need to break or modify\n in the future in response to additional requirements."
] |
Please provide a description of the function:def AddMethod(self, function, name=None):
method = MethodWrapper(self, function, name)
self.added_methods.append(method) | [
"\n Adds the specified function as a method of this construction\n environment with the specified name. If the name is omitted,\n the default name is the name of the function itself.\n "
] |
Please provide a description of the function:def RemoveMethod(self, function):
self.added_methods = [dm for dm in self.added_methods if not dm.method is function] | [
"\n Removes the specified function's MethodWrapper from the\n added_methods list, so we don't re-bind it when making a clone.\n "
] |
Please provide a description of the function:def Override(self, overrides):
if not overrides: return self
o = copy_non_reserved_keywords(overrides)
if not o: return self
overrides = {}
merges = None
for key, value in o.items():
if key == 'parse_flags':
merges = value
else:
overrides[key] = SCons.Subst.scons_subst_once(value, self, key)
env = OverrideEnvironment(self, overrides)
if merges: env.MergeFlags(merges)
return env | [
"\n Produce a modified environment whose variables are overridden by\n the overrides dictionaries. \"overrides\" is a dictionary that\n will override the variables of this environment.\n\n This function is much more efficient than Clone() or creating\n a new Environment because it doesn't copy the construction\n environment dictionary, it just wraps the underlying construction\n environment, and doesn't even create a wrapper object if there\n are no overrides.\n "
] |
Please provide a description of the function:def ParseFlags(self, *flags):
dict = {
'ASFLAGS' : SCons.Util.CLVar(''),
'CFLAGS' : SCons.Util.CLVar(''),
'CCFLAGS' : SCons.Util.CLVar(''),
'CXXFLAGS' : SCons.Util.CLVar(''),
'CPPDEFINES' : [],
'CPPFLAGS' : SCons.Util.CLVar(''),
'CPPPATH' : [],
'FRAMEWORKPATH' : SCons.Util.CLVar(''),
'FRAMEWORKS' : SCons.Util.CLVar(''),
'LIBPATH' : [],
'LIBS' : [],
'LINKFLAGS' : SCons.Util.CLVar(''),
'RPATH' : [],
}
def do_parse(arg):
# if arg is a sequence, recurse with each element
if not arg:
return
if not SCons.Util.is_String(arg):
for t in arg: do_parse(t)
return
# if arg is a command, execute it
if arg[0] == '!':
arg = self.backtick(arg[1:])
# utility function to deal with -D option
def append_define(name, dict = dict):
t = name.split('=')
if len(t) == 1:
dict['CPPDEFINES'].append(name)
else:
dict['CPPDEFINES'].append([t[0], '='.join(t[1:])])
# Loop through the flags and add them to the appropriate option.
# This tries to strike a balance between checking for all possible
# flags and keeping the logic to a finite size, so it doesn't
# check for some that don't occur often. It particular, if the
# flag is not known to occur in a config script and there's a way
# of passing the flag to the right place (by wrapping it in a -W
# flag, for example) we don't check for it. Note that most
# preprocessor options are not handled, since unhandled options
# are placed in CCFLAGS, so unless the preprocessor is invoked
# separately, these flags will still get to the preprocessor.
# Other options not currently handled:
# -iqoutedir (preprocessor search path)
# -u symbol (linker undefined symbol)
# -s (linker strip files)
# -static* (linker static binding)
# -shared* (linker dynamic binding)
# -symbolic (linker global binding)
# -R dir (deprecated linker rpath)
# IBM compilers may also accept -qframeworkdir=foo
params = shlex.split(arg)
append_next_arg_to = None # for multi-word args
for arg in params:
if append_next_arg_to:
if append_next_arg_to == 'CPPDEFINES':
append_define(arg)
elif append_next_arg_to == '-include':
t = ('-include', self.fs.File(arg))
dict['CCFLAGS'].append(t)
elif append_next_arg_to == '-isysroot':
t = ('-isysroot', arg)
dict['CCFLAGS'].append(t)
dict['LINKFLAGS'].append(t)
elif append_next_arg_to == '-isystem':
t = ('-isystem', arg)
dict['CCFLAGS'].append(t)
elif append_next_arg_to == '-arch':
t = ('-arch', arg)
dict['CCFLAGS'].append(t)
dict['LINKFLAGS'].append(t)
else:
dict[append_next_arg_to].append(arg)
append_next_arg_to = None
elif not arg[0] in ['-', '+']:
dict['LIBS'].append(self.fs.File(arg))
elif arg == '-dylib_file':
dict['LINKFLAGS'].append(arg)
append_next_arg_to = 'LINKFLAGS'
elif arg[:2] == '-L':
if arg[2:]:
dict['LIBPATH'].append(arg[2:])
else:
append_next_arg_to = 'LIBPATH'
elif arg[:2] == '-l':
if arg[2:]:
dict['LIBS'].append(arg[2:])
else:
append_next_arg_to = 'LIBS'
elif arg[:2] == '-I':
if arg[2:]:
dict['CPPPATH'].append(arg[2:])
else:
append_next_arg_to = 'CPPPATH'
elif arg[:4] == '-Wa,':
dict['ASFLAGS'].append(arg[4:])
dict['CCFLAGS'].append(arg)
elif arg[:4] == '-Wl,':
if arg[:11] == '-Wl,-rpath=':
dict['RPATH'].append(arg[11:])
elif arg[:7] == '-Wl,-R,':
dict['RPATH'].append(arg[7:])
elif arg[:6] == '-Wl,-R':
dict['RPATH'].append(arg[6:])
else:
dict['LINKFLAGS'].append(arg)
elif arg[:4] == '-Wp,':
dict['CPPFLAGS'].append(arg)
elif arg[:2] == '-D':
if arg[2:]:
append_define(arg[2:])
else:
append_next_arg_to = 'CPPDEFINES'
elif arg == '-framework':
append_next_arg_to = 'FRAMEWORKS'
elif arg[:14] == '-frameworkdir=':
dict['FRAMEWORKPATH'].append(arg[14:])
elif arg[:2] == '-F':
if arg[2:]:
dict['FRAMEWORKPATH'].append(arg[2:])
else:
append_next_arg_to = 'FRAMEWORKPATH'
elif arg in ['-mno-cygwin',
'-pthread',
'-openmp',
'-fopenmp']:
dict['CCFLAGS'].append(arg)
dict['LINKFLAGS'].append(arg)
elif arg == '-mwindows':
dict['LINKFLAGS'].append(arg)
elif arg[:5] == '-std=':
if arg[5:].find('++')!=-1:
key='CXXFLAGS'
else:
key='CFLAGS'
dict[key].append(arg)
elif arg[0] == '+':
dict['CCFLAGS'].append(arg)
dict['LINKFLAGS'].append(arg)
elif arg in ['-include', '-isysroot', '-isystem', '-arch']:
append_next_arg_to = arg
else:
dict['CCFLAGS'].append(arg)
for arg in flags:
do_parse(arg)
return dict | [
"\n Parse the set of flags and return a dict with the flags placed\n in the appropriate entry. The flags are treated as a typical\n set of command-line flags for a GNU-like toolchain and used to\n populate the entries in the dict immediately below. If one of\n the flag strings begins with a bang (exclamation mark), it is\n assumed to be a command and the rest of the string is executed;\n the result of that evaluation is then added to the dict.\n "
] |
Please provide a description of the function:def MergeFlags(self, args, unique=1, dict=None):
if dict is None:
dict = self
if not SCons.Util.is_Dict(args):
args = self.ParseFlags(args)
if not unique:
self.Append(**args)
return self
for key, value in args.items():
if not value:
continue
try:
orig = self[key]
except KeyError:
orig = value
else:
if not orig:
orig = value
elif value:
# Add orig and value. The logic here was lifted from
# part of env.Append() (see there for a lot of comments
# about the order in which things are tried) and is
# used mainly to handle coercion of strings to CLVar to
# "do the right thing" given (e.g.) an original CCFLAGS
# string variable like '-pipe -Wall'.
try:
orig = orig + value
except (KeyError, TypeError):
try:
add_to_orig = orig.append
except AttributeError:
value.insert(0, orig)
orig = value
else:
add_to_orig(value)
t = []
if key[-4:] == 'PATH':
### keep left-most occurence
for v in orig:
if v not in t:
t.append(v)
else:
### keep right-most occurence
orig.reverse()
for v in orig:
if v not in t:
t.insert(0, v)
self[key] = t
return self | [
"\n Merge the dict in args into the construction variables of this\n env, or the passed-in dict. If args is not a dict, it is\n converted into a dict using ParseFlags. If unique is not set,\n the flags are appended rather than merged.\n "
] |
Please provide a description of the function:def get_factory(self, factory, default='File'):
name = default
try:
is_node = issubclass(factory, SCons.Node.FS.Base)
except TypeError:
# The specified factory isn't a Node itself--it's
# most likely None, or possibly a callable.
pass
else:
if is_node:
# The specified factory is a Node (sub)class. Try to
# return the FS method that corresponds to the Node's
# name--that is, we return self.fs.Dir if they want a Dir,
# self.fs.File for a File, etc.
try: name = factory.__name__
except AttributeError: pass
else: factory = None
if not factory:
# They passed us None, or we picked up a name from a specified
# class, so return the FS method. (Note that we *don't*
# use our own self.{Dir,File} methods because that would
# cause env.subst() to be called twice on the file name,
# interfering with files that have $$ in them.)
factory = getattr(self.fs, name)
return factory | [
"Return a factory function for creating Nodes for this\n construction environment.\n "
] |
Please provide a description of the function:def get_scanner(self, skey):
if skey and self['PLATFORM'] == 'win32':
skey = skey.lower()
return self._gsm().get(skey) | [
"Find the appropriate scanner given a key (usually a file suffix).\n "
] |
Please provide a description of the function:def Append(self, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we finish processing an item,
# but Python 1.5.2 apparently doesn't let you use "continue"
# within try:-except: blocks, so we have to nest our code.
try:
if key == 'CPPDEFINES' and SCons.Util.is_String(self._dict[key]):
self._dict[key] = [self._dict[key]]
orig = self._dict[key]
except KeyError:
# No existing variable in the environment, so just set
# it to the new value.
if key == 'CPPDEFINES' and SCons.Util.is_String(val):
self._dict[key] = [val]
else:
self._dict[key] = val
else:
try:
# Check if the original looks like a dictionary.
# If it is, we can't just try adding the value because
# dictionaries don't have __add__() methods, and
# things like UserList will incorrectly coerce the
# original dict to a list (which we don't want).
update_dict = orig.update
except AttributeError:
try:
# Most straightforward: just try to add them
# together. This will work in most cases, when the
# original and new values are of compatible types.
self._dict[key] = orig + val
except (KeyError, TypeError):
try:
# Check if the original is a list.
add_to_orig = orig.append
except AttributeError:
# The original isn't a list, but the new
# value is (by process of elimination),
# so insert the original in the new value
# (if there's one to insert) and replace
# the variable with it.
if orig:
val.insert(0, orig)
self._dict[key] = val
else:
# The original is a list, so append the new
# value to it (if there's a value to append).
if val:
add_to_orig(val)
else:
# The original looks like a dictionary, so update it
# based on what we think the value looks like.
if SCons.Util.is_List(val):
if key == 'CPPDEFINES':
tmp = []
for (k, v) in orig.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
orig = tmp
orig += val
self._dict[key] = orig
else:
for v in val:
orig[v] = None
else:
try:
update_dict(val)
except (AttributeError, TypeError, ValueError):
if SCons.Util.is_Dict(val):
for k, v in val.items():
orig[k] = v
else:
orig[val] = None
self.scanner_map_delete(kw) | [
"Append values to existing construction variables\n in an Environment.\n "
] |
Please provide a description of the function:def AppendENVPath(self, name, newpath, envname = 'ENV',
sep = os.pathsep, delete_existing=1):
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | [
"Append path elements to the path 'name' in the 'ENV'\n dictionary for this environment. Will only add any particular\n path once, and will normpath and normcase all paths to help\n assure this. This can also handle the case where the env\n variable is a list instead of a string.\n\n If delete_existing is 0, a newpath which is already in the path\n will not be moved to the end (it will be left where it is).\n "
] |
Please provide a description of the function:def AppendUnique(self, delete_existing=0, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
if SCons.Util.is_List(val):
val = _delete_duplicates(val, delete_existing)
if key not in self._dict or self._dict[key] in ('', None):
self._dict[key] = val
elif SCons.Util.is_Dict(self._dict[key]) and \
SCons.Util.is_Dict(val):
self._dict[key].update(val)
elif SCons.Util.is_List(val):
dk = self._dict[key]
if key == 'CPPDEFINES':
tmp = []
for i in val:
if SCons.Util.is_List(i):
if len(i) >= 2:
tmp.append((i[0], i[1]))
else:
tmp.append((i[0],))
elif SCons.Util.is_Tuple(i):
tmp.append(i)
else:
tmp.append((i,))
val = tmp
# Construct a list of (key, value) tuples.
if SCons.Util.is_Dict(dk):
tmp = []
for (k, v) in dk.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
dk = tmp
elif SCons.Util.is_String(dk):
dk = [(dk,)]
else:
tmp = []
for i in dk:
if SCons.Util.is_List(i):
if len(i) >= 2:
tmp.append((i[0], i[1]))
else:
tmp.append((i[0],))
elif SCons.Util.is_Tuple(i):
tmp.append(i)
else:
tmp.append((i,))
dk = tmp
else:
if not SCons.Util.is_List(dk):
dk = [dk]
if delete_existing:
dk = [x for x in dk if x not in val]
else:
val = [x for x in val if x not in dk]
self._dict[key] = dk + val
else:
dk = self._dict[key]
if SCons.Util.is_List(dk):
if key == 'CPPDEFINES':
tmp = []
for i in dk:
if SCons.Util.is_List(i):
if len(i) >= 2:
tmp.append((i[0], i[1]))
else:
tmp.append((i[0],))
elif SCons.Util.is_Tuple(i):
tmp.append(i)
else:
tmp.append((i,))
dk = tmp
# Construct a list of (key, value) tuples.
if SCons.Util.is_Dict(val):
tmp = []
for (k, v) in val.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
val = tmp
elif SCons.Util.is_String(val):
val = [(val,)]
if delete_existing:
dk = list(filter(lambda x, val=val: x not in val, dk))
self._dict[key] = dk + val
else:
dk = [x for x in dk if x not in val]
self._dict[key] = dk + val
else:
# By elimination, val is not a list. Since dk is a
# list, wrap val in a list first.
if delete_existing:
dk = list(filter(lambda x, val=val: x not in val, dk))
self._dict[key] = dk + [val]
else:
if not val in dk:
self._dict[key] = dk + [val]
else:
if key == 'CPPDEFINES':
if SCons.Util.is_String(dk):
dk = [dk]
elif SCons.Util.is_Dict(dk):
tmp = []
for (k, v) in dk.items():
if v is not None:
tmp.append((k, v))
else:
tmp.append((k,))
dk = tmp
if SCons.Util.is_String(val):
if val in dk:
val = []
else:
val = [val]
elif SCons.Util.is_Dict(val):
tmp = []
for i,j in val.items():
if j is not None:
tmp.append((i,j))
else:
tmp.append(i)
val = tmp
if delete_existing:
dk = [x for x in dk if x not in val]
self._dict[key] = dk + val
self.scanner_map_delete(kw) | [
"Append values to existing construction variables\n in an Environment, if they're not already there.\n If delete_existing is 1, removes existing values first, so\n values move to end.\n "
] |
Please provide a description of the function:def Clone(self, tools=[], toolpath=None, parse_flags = None, **kw):
builders = self._dict.get('BUILDERS', {})
clone = copy.copy(self)
# BUILDERS is not safe to do a simple copy
clone._dict = semi_deepcopy_dict(self._dict, ['BUILDERS'])
clone._dict['BUILDERS'] = BuilderDict(builders, clone)
# Check the methods added via AddMethod() and re-bind them to
# the cloned environment. Only do this if the attribute hasn't
# been overwritten by the user explicitly and still points to
# the added method.
clone.added_methods = []
for mw in self.added_methods:
if mw == getattr(self, mw.name):
clone.added_methods.append(mw.clone(clone))
clone._memo = {}
# Apply passed-in variables before the tools
# so the tools can use the new variables
kw = copy_non_reserved_keywords(kw)
new = {}
for key, value in kw.items():
new[key] = SCons.Subst.scons_subst_once(value, self, key)
clone.Replace(**new)
apply_tools(clone, tools, toolpath)
# apply them again in case the tools overwrote them
clone.Replace(**new)
# Finally, apply any flags to be merged in
if parse_flags: clone.MergeFlags(parse_flags)
if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.EnvironmentClone')
return clone | [
"Return a copy of a construction Environment. The\n copy is like a Python \"deep copy\"--that is, independent\n copies are made recursively of each objects--except that\n a reference is copied when an object is not deep-copyable\n (like a function). There are no references to any mutable\n objects in the original Environment.\n "
] |
Please provide a description of the function:def Detect(self, progs):
if not SCons.Util.is_List(progs):
progs = [ progs ]
for prog in progs:
path = self.WhereIs(prog)
if path: return prog
return None | [
"Return the first available program in progs.\n "
] |
Please provide a description of the function:def Dump(self, key = None):
import pprint
pp = pprint.PrettyPrinter(indent=2)
if key:
dict = self.Dictionary(key)
else:
dict = self.Dictionary()
return pp.pformat(dict) | [
"\n Using the standard Python pretty printer, return the contents of the\n scons build environment as a string.\n\n If the key passed in is anything other than None, then that will\n be used as an index into the build environment dictionary and\n whatever is found there will be fed into the pretty printer. Note\n that this key is case sensitive.\n "
] |
Please provide a description of the function:def FindIxes(self, paths, prefix, suffix):
suffix = self.subst('$'+suffix)
prefix = self.subst('$'+prefix)
for path in paths:
dir,name = os.path.split(str(path))
if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix:
return path | [
"\n Search a list of paths for something that matches the prefix and suffix.\n\n paths - the list of paths or nodes.\n prefix - construction variable for the prefix.\n suffix - construction variable for the suffix.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.